ngram
listlengths
0
67.8k
[ "__init__(self, d_model, heads, d_ff, dropout): super(TransformerDecoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout)", "emb): return self.pe[:, :emb.size(1)] class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout): super(TransformerEncoderLayer,", "self.dropout(syn) # x2 = self.gcn_x_21(x_1, edge_index_2, edge_weight_2) # x2 = self.relu(x2) # x2", "super(GCN, self).__init__() self.in_channel=in_channel self.out_channel=out_channel self.hidden_dim=hidden_dim self.dropout = nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 # self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) #", "import LayerNormLSTM class Classifier(nn.Module): def __init__(self, hidden_size): super(Classifier, self).__init__() self.linear1 = nn.Linear(hidden_size, 1)", "1 assert hidden_size % num_directions == 0 hidden_size = hidden_size // num_directions self.relu", "torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out, -1) + seq_mask), 0) inputs=inputs+pos_emb for i in range(self.num_inter_layers): inputs =", "TransformerEncoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout): super(TransformerEncoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads,", "self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) # self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 # self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True) def forward(self, x_1, edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1, edge_index_1,", "def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" batch, layer, seq, hidden = x.size() x1=x.contiguous().view(batch", "torch.zeros(max_len, dim) position = torch.arange(0, max_len).unsqueeze(1) div_term = torch.exp((torch.arange(0, dim, 2, dtype=torch.float) *", "class Classifier(nn.Module): def __init__(self, hidden_size): super(Classifier, self).__init__() self.linear1 = nn.Linear(hidden_size, 1) self.sigmoid =", "mask=mask) out = self.dropout(context) + inputs return self.feed_forward(out) class TransformerInterEncoder(nn.Module): def __init__(self, d_model,", "dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.dropout = nn.Dropout(dropout)", "TransformerDecoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout): super(TransformerDecoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads,", "bidirectional=bidirectional) self.wo = nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.sigmoid =", "torch.transpose(memory_bank, 1, 0) sent_scores = self.sigmoid(self.wo(memory_bank)) sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores", "self.relu=nn.ReLU(inplace=True) def forward(self, x_1, edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1, edge_index_1, edge_weight_1) syn=self.relu(syn) syn=self.dropout(syn) syn =", "= self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores = self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2) sent_vec = torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim = 1).expand(batch,seq,1,layer),x) return sent_vec.squeeze(dim", "self.pos_emb.pe[:, :n_out] seq_mask=subsequent_mask(inputs) self_attn_mask = torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out, -1) + seq_mask), 0) inputs=inputs+pos_emb for", "= nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, d_hidden , bias=True) self.wi", "dim) position = torch.arange(0, max_len).unsqueeze(1) div_term = torch.exp((torch.arange(0, dim, 2, dtype=torch.float) * -(math.log(10000.0)", "self).__init__() self.linear1 = nn.Linear(hidden_size, 1) self.sigmoid = nn.Sigmoid() def forward(self, x, mask_cls): h", "= nn.Linear(d_hidden, 1, bias=True) self.LR = nn.LeakyReLU() self.softmax = nn.Softmax(dim=-1) def forward(self, top_vecs,", "torch.transpose(memory_bank, 1, 0) # sent_scores = self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores = self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2) sent_vec =", "hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo = nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout)", "d_ff, dropout): super(TransformerDecoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model,", "dropout): super(TransformerDecoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff,", "self.sigmoid(self.wo(memory_bank)) sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores class GCN(nn.Module): def __init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN,", "def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder, self).__init__() num_directions = 2 if", "edge_weight_1) syn = self.relu(syn) syn = self.dropout(syn) # x2 = self.gcn_x_21(x_1, edge_index_2, edge_weight_2)", "top_vecs.size(0), top_vecs.size(1) pos_emb = self.pos_emb.pe[:, :n_sents] x = top_vecs * mask[:, :, None].float()", "position = torch.arange(0, max_len).unsqueeze(1) div_term = torch.exp((torch.arange(0, dim, 2, dtype=torch.float) * -(math.log(10000.0) /", "emb = emb + self.pe[:, step][:, None, :] else: emb = emb +", "sent_scores = self.sigmoid(self.wo(x)) sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores class GRUEncoder_attn(nn.Module): def", "= nn.Softmax() print('this is dropout',dropout) def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" batch, layer,", "= emb * math.sqrt(self.dim) if (step): emb = emb + self.pe[:, step][:, None,", "edge_weight_2) # syn=self.gcn_x_12(mix, edge_index_1, edge_weight_1) # syn=self.relu(syn) # syn=self.dropout(syn) # x2 = self.relu(x2)", "self.sigmoid = nn.Sigmoid() def forward(self, x, mask_cls): h = self.linear1(x).squeeze(-1) sent_scores = self.sigmoid(h)", "sent_scores class GCN(nn.Module): def __init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN, self).__init__() self.in_channel=in_channel self.out_channel=out_channel self.hidden_dim=hidden_dim self.dropout = nn.Dropout(p=drop)", "input_norm, mask=mask) out = self.dropout(context) + inputs return self.feed_forward(out) class TransformerInterEncoder(nn.Module): def __init__(self,", "x1 memory_bank = torch.transpose(memory_bank, 1, 0) # sent_scores = self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores = self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1)", "context = self.self_attn(inputs, inputs, inputs, mask=self_attn_mask) dec_output = self.self_attn( ent_enc, ent_enc, context, mask=context_attn_mask)", "nn.Linear(d_model, d_hidden, bias=True) self.v = nn.Linear(d_hidden, 1, bias=True) self.LR = nn.LeakyReLU() self.softmax =", "dim, 2, dtype=torch.float) * -(math.log(10000.0) / dim))) pe[:, 0::2] = torch.sin(position.float() * div_term)", "sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores class GRUEncoder_attn(nn.Module): def __init__(self,bidirectional, num_layers, input_size,", "LayerNormLSTM class Classifier(nn.Module): def __init__(self, hidden_size): super(Classifier, self).__init__() self.linear1 = nn.Linear(hidden_size, 1) self.sigmoid", "step][:, None, :] else: emb = emb + self.pe[:, :emb.size(1)] emb = self.dropout(emb)", "\"\"\" See :obj:`EncoderBase.forward()`\"\"\" batch_size, n_sents = top_vecs.size(0), top_vecs.size(1) pos_emb = self.pos_emb.pe[:, :n_sents] x", "super(RNNEncoder, self).__init__() num_directions = 2 if bidirectional else 1 assert hidden_size % num_directions", "= self.gcn_x_21(x_1, edge_index_2, edge_weight_2) # x2 = self.relu(x2) # x2 = self.dropout(x2) #", "nn.Linear(hidden_size, 1) self.sigmoid = nn.Sigmoid() def forward(self, x, mask_cls): h = self.linear1(x).squeeze(-1) sent_scores", "edge_weight_2) # x2 = self.relu(x2) # x2 = self.dropout(x2) # mix = self.gcn_mix(torch.cat((syn,x2),-1),", "nn.Softmax(dim=-1) def forward(self, top_vecs, inputs, mask, label_mask=None): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" n_out = inputs.size(1)", "self.wo = nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.sigmoid = nn.Sigmoid()", "self.dropout = nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 # self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) # self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 # self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True) def", "= torch.exp((torch.arange(0, dim, 2, dtype=torch.float) * -(math.log(10000.0) / dim))) pe[:, 0::2] = torch.sin(position.float()", "if bidirectional else 1 assert hidden_size % num_directions == 0 hidden_size = hidden_size", "class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout): super(TransformerDecoderLayer, self).__init__() self.self_attn = MultiHeadedAttention(", "1, 0) memory_bank, _ = self.rnn(x) memory_bank = self.dropout(memory_bank) + x memory_bank =", "= nn.LayerNorm(d_model, eps=1e-6) self.dropout = nn.Dropout(dropout) def forward(self, iter, query, inputs, mask): if", "self.relu(syn) syn = self.dropout(syn) # x2 = self.gcn_x_21(x_1, edge_index_2, edge_weight_2) # x2 =", "ent_enc, ent_enc, context, mask=context_attn_mask) dec_output = self.feed_forward(dec_output) return dec_output class TransformerInterDecoder(nn.Module): def __init__(self,", "pe = pe.unsqueeze(0) super(PositionalEncoding, self).__init__() self.register_buffer('pe', pe) self.dropout = nn.Dropout(p=dropout) self.dim = dim", "hidden_size = hidden_size // num_directions self.relu = nn.ReLU() self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size,", "seq_mask=subsequent_mask(inputs) self_attn_mask = torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out, -1) + seq_mask), 0) inputs=inputs+pos_emb for i in", "bias=True) self.dropout = nn.Dropout(dropout) self.softmax = nn.Softmax() print('this is dropout',dropout) def forward(self, x,", "self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.dropout = nn.Dropout(dropout) def forward(self, iter, query, inputs, mask):", "syn=self.dropout(syn) syn = self.gcn_x_12(syn, edge_index_1, edge_weight_1) syn = self.relu(syn) syn = self.dropout(syn) #", "= nn.Sigmoid() def forward(self, x, mask_cls): h = self.linear1(x).squeeze(-1) sent_scores = self.sigmoid(h) *", "= 2) class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout): super(TransformerDecoderLayer, self).__init__() self.self_attn", "= self.gcn_x_12(syn, edge_index_1, edge_weight_1) syn = self.relu(syn) syn = self.dropout(syn) # x2 =", "= nn.Dropout(p=dropout) self.dim = dim def forward(self, emb, step=None): emb = emb *", "else: emb = emb + self.pe[:, :emb.size(1)] emb = self.dropout(emb) return emb def", "= sent_scores.squeeze(-1) * mask.float() return sent_scores class GRUEncoder_attn(nn.Module): def __init__(self,bidirectional, num_layers, input_size, hidden_size,dropout=0.0):", "forward(self, x, mask_cls): h = self.linear1(x).squeeze(-1) sent_scores = self.sigmoid(h) * mask_cls.float() return sent_scores", "def forward(self, x_1, edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1, edge_index_1, edge_weight_1) syn=self.relu(syn) syn=self.dropout(syn) syn = self.gcn_x_12(syn,", "= nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, 1, bias=True) self.sigmoid =", "nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.sigmoid = nn.Sigmoid() def forward(self,", "\"\"\"See :func:`EncoderBase.forward()`\"\"\" x = torch.transpose(x, 1, 0) memory_bank, _ = self.rnn(x) memory_bank =", "input_size, hidden_size, dropout=0.0): super(RNNEncoder_attn, self).__init__() num_directions = 2 if bidirectional else 1 assert", "= nn.LayerNorm(d_model, eps=1e-6) def forward(self, iter, ent_enc, inputs, self_attn_mask=None,context_attn_mask=None): context = self.self_attn(inputs, inputs,", "\"\"\" See :obj:`EncoderBase.forward()`\"\"\" n_out = inputs.size(1) pos_emb = self.pos_emb.pe[:, :n_out] seq_mask=subsequent_mask(inputs) self_attn_mask =", "= top_vecs * mask[:, :, None].float() x = x + pos_emb for i", "edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1, edge_index_1, edge_weight_1) syn=self.relu(syn) syn=self.dropout(syn) syn = self.gcn_x_12(syn, edge_index_1, edge_weight_1) syn", "edge_weight_1) # syn=self.relu(syn) # syn=self.dropout(syn) # x2 = self.relu(x2) # x2 = self.dropout(x2)", "torch.transpose(x1, 1, 0) memory_bank, _ = self.rnn(x1) memory_bank = self.dropout(memory_bank) + x1 memory_bank", "mask[:, :, None].float() x = x + pos_emb for i in range(self.num_inter_layers): x", "= self.sigmoid(h) * mask_cls.float() return sent_scores class PositionalEncoding(nn.Module): def __init__(self, dropout, dim, max_len=5000):", "num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder, self).__init__() num_directions = 2 if bidirectional else 1", "syn=self.gcn_x_11(x_1, edge_index_1, edge_weight_1) syn=self.relu(syn) syn=self.dropout(syn) syn = self.gcn_x_12(syn, edge_index_1, edge_weight_1) syn = self.relu(syn)", "_ = self.rnn(x) memory_bank = self.dropout(memory_bank) + x memory_bank = torch.transpose(memory_bank, 1, 0)", "self).__init__() self.in_channel=in_channel self.out_channel=out_channel self.hidden_dim=hidden_dim self.dropout = nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 # self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) # self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2", "= self.self_attn(inputs, inputs, inputs, mask=self_attn_mask) dec_output = self.self_attn( ent_enc, ent_enc, context, mask=context_attn_mask) dec_output", "top_vecs.size(1) pos_emb = self.pos_emb.pe[:, :n_sents] x = top_vecs * mask[:, :, None].float() x", "self.self_attn(inputs, inputs, inputs, mask=self_attn_mask) dec_output = self.self_attn( ent_enc, ent_enc, context, mask=context_attn_mask) dec_output =", "sent_scores.squeeze(-1) * mask.float() return sent_scores class GRUEncoder_attn(nn.Module): def __init__(self,bidirectional, num_layers, input_size, hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__()", "dec_output = self.feed_forward(dec_output) return dec_output class TransformerInterDecoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout,", "self.dropout(memory_bank) + x memory_bank = torch.transpose(memory_bank, 1, 0) sent_scores = self.sigmoid(self.wo(memory_bank)) sent_scores =", "self.d_model = d_model self.num_inter_layers = num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList(", "class PositionalEncoding(nn.Module): def __init__(self, dropout, dim, max_len=5000): pe = torch.zeros(max_len, dim) position =", "// num_directions self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo = nn.Linear(num_directions *", "torch import torch.nn as nn from models.neural import MultiHeadedAttention, PositionwiseFeedForward from models.rnn import", "= self.sigmoid(self.wo(memory_bank)) sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores class GCN(nn.Module): def __init__(self,in_channel,out_channel,hidden_dim,drop):", "n_sents = top_vecs.size(0), top_vecs.size(1) pos_emb = self.pos_emb.pe[:, :n_sents] x = top_vecs * mask[:,", "super(GRUEncoder_attn,self).__init__() class RNNEncoder_attn(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder_attn, self).__init__() num_directions", "heads, d_ff, dropout): super(TransformerDecoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward =", "self.dim = dim def forward(self, emb, step=None): emb = emb * math.sqrt(self.dim) if", ":emb.size(1)] class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout): super(TransformerEncoderLayer, self).__init__() self.self_attn =", "self.dropout(emb) return emb def get_emb(self, emb): return self.pe[:, :emb.size(1)] class TransformerEncoderLayer(nn.Module): def __init__(self,", "i in range(self.num_inter_layers): x = self.transformer_inter[i](i, x, x, ~mask) # all_sents * max_tokens", "bias=True) self.dropout = nn.Dropout(dropout) self.sigmoid = nn.Sigmoid() def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\"", "edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1, edge_index_1, edge_weight_1) syn=self.relu(syn) syn=self.dropout(syn) syn = self.gcn_x_12(syn, edge_index_1, edge_weight_1) syn =", "top_vecs.size(1), -1) + self.wi(top_vecs).unsqueeze( 1))).squeeze(-1) sent_scores = self.softmax(scores) return sent_scores class RNNEncoder(nn.Module): def", "self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores = self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2) sent_vec = torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim = 1).expand(batch,seq,1,layer),x) return sent_vec.squeeze(dim =", "def forward(self, x, mask_cls): h = self.linear1(x).squeeze(-1) sent_scores = self.sigmoid(h) * mask_cls.float() return", "emb * math.sqrt(self.dim) if (step): emb = emb + self.pe[:, step][:, None, :]", "nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, 1, bias=True) self.sigmoid = nn.Sigmoid()", "dim x = self.layer_norm(x) sent_scores = self.sigmoid(self.wo(x)) sent_scores = sent_scores.squeeze(-1) * mask.float() return", "self.transformer_inter[i](i, x, x, ~mask) # all_sents * max_tokens * dim x = self.layer_norm(x)", "* mask.float() return sent_scores class GCN(nn.Module): def __init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN, self).__init__() self.in_channel=in_channel self.out_channel=out_channel self.hidden_dim=hidden_dim", "mask = mask.unsqueeze(1) context = self.self_attn(input_norm, input_norm, input_norm, mask=mask) out = self.dropout(context) +", "sent_scores = self.softmax(scores) return sent_scores class RNNEncoder(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size,", "div_term) pe[:, 1::2] = torch.cos(position.float() * div_term) pe = pe.unsqueeze(0) super(PositionalEncoding, self).__init__() self.register_buffer('pe',", "= d_model self.num_inter_layers = num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerDecoderLayer(d_model,", "self.dropout = nn.Dropout(dropout) def forward(self, iter, query, inputs, mask): if (iter != 0):", "class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout): super(TransformerEncoderLayer, self).__init__() self.self_attn = MultiHeadedAttention(", "return sent_scores class GRUEncoder_attn(nn.Module): def __init__(self,bidirectional, num_layers, input_size, hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__() class RNNEncoder_attn(nn.Module): def", "# syn=self.gcn_x_12(mix, edge_index_1, edge_weight_1) # syn=self.relu(syn) # syn=self.dropout(syn) # x2 = self.relu(x2) #", "self.pe[:, :emb.size(1)] emb = self.dropout(emb) return emb def get_emb(self, emb): return self.pe[:, :emb.size(1)]", "context = self.self_attn(input_norm, input_norm, input_norm, mask=mask) out = self.dropout(context) + inputs return self.feed_forward(out)", "bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder_attn, self).__init__() num_directions = 2 if bidirectional else", "MultiHeadedAttention, PositionwiseFeedForward from models.rnn import LayerNormLSTM class Classifier(nn.Module): def __init__(self, hidden_size): super(Classifier, self).__init__()", "self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.dropout = nn.Dropout(dropout) def", "num_layers=num_layers, bidirectional=bidirectional) self.wo = nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.softmax", "return sent_scores class RNNEncoder(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder, self).__init__()", "self.self_attn(input_norm, input_norm, input_norm, mask=mask) out = self.dropout(context) + inputs return self.feed_forward(out) class TransformerInterEncoder(nn.Module):", "sent_scores = self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2) sent_vec = torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim = 1).expand(batch,seq,1,layer),x) return sent_vec.squeeze(dim = 2)", "1))).squeeze(-1) sent_scores = self.softmax(scores) return sent_scores class RNNEncoder(nn.Module): def __init__(self, bidirectional, num_layers, input_size,", "0) # sent_scores = self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores = self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2) sent_vec = torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim =", "self).__init__() self.register_buffer('pe', pe) self.dropout = nn.Dropout(p=dropout) self.dim = dim def forward(self, emb, step=None):", "hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.softmax = nn.Softmax() print('this is dropout',dropout) def", "1, 0) sent_scores = self.sigmoid(self.wo(memory_bank)) sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores class", "self.dropout = nn.Dropout(p=dropout) self.dim = dim def forward(self, emb, step=None): emb = emb", "__init__(self, dropout, dim, max_len=5000): pe = torch.zeros(max_len, dim) position = torch.arange(0, max_len).unsqueeze(1) div_term", "syn = self.relu(syn) syn = self.dropout(syn) # x2 = self.gcn_x_21(x_1, edge_index_2, edge_weight_2) #", "% num_directions == 0 hidden_size = hidden_size // num_directions self.rnn = LayerNormLSTM( input_size=input_size,", "bidirectional else 1 assert hidden_size % num_directions == 0 hidden_size = hidden_size //", "inputs return self.feed_forward(out) class TransformerInterEncoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout, num_inter_layers=0): super(TransformerInterEncoder,", "= self.rnn(x1) memory_bank = self.dropout(memory_bank) + x1 memory_bank = torch.transpose(memory_bank, 1, 0) #", "d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) def forward(self, iter, ent_enc, inputs, self_attn_mask=None,context_attn_mask=None): context", "= emb + self.pe[:, step][:, None, :] else: emb = emb + self.pe[:,", "ent_enc, context, mask=context_attn_mask) dec_output = self.feed_forward(dec_output) return dec_output class TransformerInterDecoder(nn.Module): def __init__(self, d_model,", "torch.arange(0, max_len).unsqueeze(1) div_term = torch.exp((torch.arange(0, dim, 2, dtype=torch.float) * -(math.log(10000.0) / dim))) pe[:,", "1, bias=True) self.sigmoid = nn.Sigmoid() def forward(self, top_vecs, mask): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" batch_size,", "forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" x = torch.transpose(x, 1, 0) memory_bank, _ =", "= self.self_attn(input_norm, input_norm, input_norm, mask=mask) out = self.dropout(context) + inputs return self.feed_forward(out) class", "hidden_size // num_directions self.relu = nn.ReLU() self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional)", "range(num_inter_layers)]) self.dropout = nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, d_hidden ,", "syn = self.gcn_x_12(syn, edge_index_1, edge_weight_1) syn = self.relu(syn) syn = self.dropout(syn) # x2", "= dim def forward(self, emb, step=None): emb = emb * math.sqrt(self.dim) if (step):", "num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder_attn, self).__init__() num_directions = 2 if bidirectional else 1", "d_ff, dropout): super(TransformerEncoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model,", "= torch.transpose(memory_bank, 1, 0) sent_scores = self.sigmoid(self.wo(memory_bank)) sent_scores = sent_scores.squeeze(-1) * mask.float() return", "-1) + seq_mask), 0) inputs=inputs+pos_emb for i in range(self.num_inter_layers): inputs = self.transformer_inter[i](i, top_vecs,", "* -(math.log(10000.0) / dim))) pe[:, 0::2] = torch.sin(position.float() * div_term) pe[:, 1::2] =", "# x2 = self.relu(x2) # x2 = self.dropout(x2) # mix = self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2,", "= self.relu(syn) syn = self.dropout(syn) # x2 = self.gcn_x_21(x_1, edge_index_2, edge_weight_2) # x2", "x, mask_cls): h = self.linear1(x).squeeze(-1) sent_scores = self.sigmoid(h) * mask_cls.float() return sent_scores class", "range(num_inter_layers)]) self.dropout = nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, 1, bias=True)", "self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter =", "x memory_bank = torch.transpose(memory_bank, 1, 0) sent_scores = self.sigmoid(self.wo(memory_bank)) sent_scores = sent_scores.squeeze(-1) *", "self.linear1(x).squeeze(-1) sent_scores = self.sigmoid(h) * mask_cls.float() return sent_scores class PositionalEncoding(nn.Module): def __init__(self, dropout,", "math.sqrt(self.dim) if (step): emb = emb + self.pe[:, step][:, None, :] else: emb", "assert hidden_size % num_directions == 0 hidden_size = hidden_size // num_directions self.relu =", "= nn.Sigmoid() def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" x = torch.transpose(x, 1, 0)", "hidden = x.size() x1=x.contiguous().view(batch * layer, -1, hidden) x1 = torch.transpose(x1, 1, 0)", "heads, dropout, d_hidden, num_inter_layers=0): super(TransformerInterDecoder, self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers self.pos_emb", "math import torch import torch.nn as nn from models.neural import MultiHeadedAttention, PositionwiseFeedForward from", "Classifier(nn.Module): def __init__(self, hidden_size): super(Classifier, self).__init__() self.linear1 = nn.Linear(hidden_size, 1) self.sigmoid = nn.Sigmoid()", "[TransformerEncoderLayer(d_model, heads, d_ff, dropout) for _ in range(num_inter_layers)]) self.dropout = nn.Dropout(dropout) self.layer_norm =", "heads, d_ff, dropout) for _ in range(num_inter_layers)]) self.dropout = nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model,", "bias=True) self.wi = nn.Linear(d_model, d_hidden, bias=True) self.v = nn.Linear(d_hidden, 1, bias=True) self.LR =", "= nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.sigmoid = nn.Sigmoid() def", "edge_index_2, edge_weight_2) # x2 = self.relu(x2) # x2 = self.dropout(x2) # mix =", "PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.dropout = nn.Dropout(dropout) def forward(self, iter,", "sent_scores = self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores = self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2) sent_vec = torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim = 1).expand(batch,seq,1,layer),x) return", "heads, d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.dropout", "dropout=0.0): super(RNNEncoder, self).__init__() num_directions = 2 if bidirectional else 1 assert hidden_size %", "d_ff, heads, dropout, num_inter_layers=0): super(TransformerInterEncoder, self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers self.pos_emb", "emb + self.pe[:, step][:, None, :] else: emb = emb + self.pe[:, :emb.size(1)]", "num_directions == 0 hidden_size = hidden_size // num_directions self.relu = nn.ReLU() self.rnn =", "def get_emb(self, emb): return self.pe[:, :emb.size(1)] class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff,", "self_attn_mask=None,context_attn_mask=None): context = self.self_attn(inputs, inputs, inputs, mask=self_attn_mask) dec_output = self.self_attn( ent_enc, ent_enc, context,", "dropout=0.0): super(RNNEncoder_attn, self).__init__() num_directions = 2 if bidirectional else 1 assert hidden_size %", "sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores class GCN(nn.Module): def __init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN, self).__init__()", "x2 = self.gcn_x_22(mix, edge_index_2, edge_weight_2) # syn=self.gcn_x_12(mix, edge_index_1, edge_weight_1) # syn=self.relu(syn) # syn=self.dropout(syn)", "= x + pos_emb for i in range(self.num_inter_layers): x = self.transformer_inter[i](i, x, x,", "mask=context_attn_mask) dec_output = self.feed_forward(dec_output) return dec_output class TransformerInterDecoder(nn.Module): def __init__(self, d_model, d_ff, heads,", "edge_weight_2) # x2 = self.gcn_x_22(mix, edge_index_2, edge_weight_2) # syn=self.gcn_x_12(mix, edge_index_1, edge_weight_1) # syn=self.relu(syn)", "mask_cls): h = self.linear1(x).squeeze(-1) sent_scores = self.sigmoid(h) * mask_cls.float() return sent_scores class PositionalEncoding(nn.Module):", "context, mask=context_attn_mask) dec_output = self.feed_forward(dec_output) return dec_output class TransformerInterDecoder(nn.Module): def __init__(self, d_model, d_ff,", "memory_bank = self.dropout(memory_bank) + x memory_bank = torch.transpose(memory_bank, 1, 0) sent_scores = self.sigmoid(self.wo(memory_bank))", "assert hidden_size % num_directions == 0 hidden_size = hidden_size // num_directions self.rnn =", "_ in range(num_inter_layers)]) self.dropout = nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model,", "forward(self, emb, step=None): emb = emb * math.sqrt(self.dim) if (step): emb = emb", "sent_scores.squeeze(-1) * mask.float() return sent_scores class GCN(nn.Module): def __init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN, self).__init__() self.in_channel=in_channel self.out_channel=out_channel", "class TransformerInterEncoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout, num_inter_layers=0): super(TransformerInterEncoder, self).__init__() self.d_model =", "self.wi(top_vecs).unsqueeze( 1))).squeeze(-1) sent_scores = self.softmax(scores) return sent_scores class RNNEncoder(nn.Module): def __init__(self, bidirectional, num_layers,", "(step): emb = emb + self.pe[:, step][:, None, :] else: emb = emb", "return self.feed_forward(out) class TransformerInterEncoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout, num_inter_layers=0): super(TransformerInterEncoder, self).__init__()", "nn.Sigmoid() def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" x = torch.transpose(x, 1, 0) memory_bank,", "# x2 = self.dropout(x2) # mix = self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2, edge_weight_2) # x2 =", "__init__(self, d_model, d_ff, heads, dropout, d_hidden, num_inter_layers=0): super(TransformerInterDecoder, self).__init__() self.d_model = d_model self.num_inter_layers", "[TransformerDecoderLayer(d_model, heads, d_ff, dropout) for _ in range(num_inter_layers)]) self.dropout = nn.Dropout(dropout) self.layer_norm =", "torch.nn as nn from models.neural import MultiHeadedAttention, PositionwiseFeedForward from models.rnn import LayerNormLSTM class", ":] else: emb = emb + self.pe[:, :emb.size(1)] emb = self.dropout(emb) return emb", "nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, d_hidden , bias=True) self.wi =", "n_out = inputs.size(1) pos_emb = self.pos_emb.pe[:, :n_out] seq_mask=subsequent_mask(inputs) self_attn_mask = torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out, -1)", "* mask_cls.float() return sent_scores class PositionalEncoding(nn.Module): def __init__(self, dropout, dim, max_len=5000): pe =", "def __init__(self, d_model, heads, d_ff, dropout): super(TransformerDecoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model,", "+ self.wi(top_vecs).unsqueeze( 1))).squeeze(-1) sent_scores = self.softmax(scores) return sent_scores class RNNEncoder(nn.Module): def __init__(self, bidirectional,", "inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1, n_out,-1)) scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1, -1, top_vecs.size(1), -1) + self.wi(top_vecs).unsqueeze( 1))).squeeze(-1) sent_scores =", "# self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 # self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True) def forward(self, x_1, edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1, edge_index_1, edge_weight_1)", "syn=self.relu(syn) syn=self.dropout(syn) syn = self.gcn_x_12(syn, edge_index_1, edge_weight_1) syn = self.relu(syn) syn = self.dropout(syn)", "mask=self_attn_mask) dec_output = self.self_attn( ent_enc, ent_enc, context, mask=context_attn_mask) dec_output = self.feed_forward(dec_output) return dec_output", "x, x, ~mask) # all_sents * max_tokens * dim x = self.layer_norm(x) sent_scores", "self.relu(x2) # x2 = self.dropout(x2) # mix = self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2, edge_weight_2) # x2", "nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 # self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) # self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 # self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True) def forward(self, x_1,", "out = self.dropout(context) + inputs return self.feed_forward(out) class TransformerInterEncoder(nn.Module): def __init__(self, d_model, d_ff,", "= nn.ReLU() self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo = nn.Linear(num_directions *", "mask): if (iter != 0): input_norm = self.layer_norm(inputs) else: input_norm = inputs mask", "# syn=self.relu(syn) # syn=self.dropout(syn) # x2 = self.relu(x2) # x2 = self.dropout(x2) return", "mask_cls.float() return sent_scores class PositionalEncoding(nn.Module): def __init__(self, dropout, dim, max_len=5000): pe = torch.zeros(max_len,", "PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) def forward(self, iter, ent_enc, inputs, self_attn_mask=None,context_attn_mask=None):", "= torch.transpose(memory_bank, 1, 0) # sent_scores = self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores = self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2) sent_vec", "x=x.transpose(1,2) sent_vec = torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim = 1).expand(batch,seq,1,layer),x) return sent_vec.squeeze(dim = 2) class TransformerDecoderLayer(nn.Module): def", "PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerEncoderLayer(d_model, heads, d_ff, dropout) for _ in range(num_inter_layers)])", "self.dropout(memory_bank) + x1 memory_bank = torch.transpose(memory_bank, 1, 0) # sent_scores = self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores", "self.num_inter_layers = num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerDecoderLayer(d_model, heads, d_ff,", "* div_term) pe[:, 1::2] = torch.cos(position.float() * div_term) pe = pe.unsqueeze(0) super(PositionalEncoding, self).__init__()", "1::2] = torch.cos(position.float() * div_term) pe = pe.unsqueeze(0) super(PositionalEncoding, self).__init__() self.register_buffer('pe', pe) self.dropout", ":func:`EncoderBase.forward()`\"\"\" x = torch.transpose(x, 1, 0) memory_bank, _ = self.rnn(x) memory_bank = self.dropout(memory_bank)", "= self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2, edge_weight_2) # x2 = self.gcn_x_22(mix, edge_index_2, edge_weight_2) # syn=self.gcn_x_12(mix, edge_index_1,", "d_model) self.transformer_inter = nn.ModuleList( [TransformerDecoderLayer(d_model, heads, d_ff, dropout) for _ in range(num_inter_layers)]) self.dropout", "get_emb(self, emb): return self.pe[:, :emb.size(1)] class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout):", "= torch.transpose(x, 1, 0) memory_bank, _ = self.rnn(x) memory_bank = self.dropout(memory_bank) + x", "nn.Dropout(dropout) def forward(self, iter, query, inputs, mask): if (iter != 0): input_norm =", "dropout): super(TransformerEncoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff,", "d_model self.num_inter_layers = num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerDecoderLayer(d_model, heads,", "nn.LayerNorm(d_model, eps=1e-6) def forward(self, iter, ent_enc, inputs, self_attn_mask=None,context_attn_mask=None): context = self.self_attn(inputs, inputs, inputs,", "MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6)", "from models.neural import MultiHeadedAttention, PositionwiseFeedForward from models.rnn import LayerNormLSTM class Classifier(nn.Module): def __init__(self,", "d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.dropout =", "= self.dropout(memory_bank) + x1 memory_bank = torch.transpose(memory_bank, 1, 0) # sent_scores = self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1)", "self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm =", "= self.transformer_inter[i](i, x, x, ~mask) # all_sents * max_tokens * dim x =", "0::2] = torch.sin(position.float() * div_term) pe[:, 1::2] = torch.cos(position.float() * div_term) pe =", "= PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerEncoderLayer(d_model, heads, d_ff, dropout) for _ in", "emb, step=None): emb = emb * math.sqrt(self.dim) if (step): emb = emb +", "0 hidden_size = hidden_size // num_directions self.relu = nn.ReLU() self.rnn = LayerNormLSTM( input_size=input_size,", "sent_scores class PositionalEncoding(nn.Module): def __init__(self, dropout, dim, max_len=5000): pe = torch.zeros(max_len, dim) position", "pe[:, 1::2] = torch.cos(position.float() * div_term) pe = pe.unsqueeze(0) super(PositionalEncoding, self).__init__() self.register_buffer('pe', pe)", "num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerDecoderLayer(d_model, heads, d_ff, dropout) for", "= nn.Linear(d_model, d_hidden , bias=True) self.wi = nn.Linear(d_model, d_hidden, bias=True) self.v = nn.Linear(d_hidden,", "self.feed_forward(dec_output) return dec_output class TransformerInterDecoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout, d_hidden, num_inter_layers=0):", "self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerEncoderLayer(d_model, heads, d_ff, dropout) for _", "torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim = 1).expand(batch,seq,1,layer),x) return sent_vec.squeeze(dim = 2) class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, heads,", "bias=True) self.sigmoid = nn.Sigmoid() def forward(self, top_vecs, mask): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" batch_size, n_sents", "inputs=inputs+pos_emb for i in range(self.num_inter_layers): inputs = self.transformer_inter[i](i, top_vecs, inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1, n_out,-1)) scores=self.v(self.LR(", "class RNNEncoder(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder, self).__init__() num_directions =", "# self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) # self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 # self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True) def forward(self, x_1, edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1,", "= self.linear1(x).squeeze(-1) sent_scores = self.sigmoid(h) * mask_cls.float() return sent_scores class PositionalEncoding(nn.Module): def __init__(self,", ", bias=True) self.wi = nn.Linear(d_model, d_hidden, bias=True) self.v = nn.Linear(d_hidden, 1, bias=True) self.LR", "self.wo = nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.softmax = nn.Softmax()", "x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" x = torch.transpose(x, 1, 0) memory_bank, _ = self.rnn(x)", "num_inter_layers=0): super(TransformerInterDecoder, self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model)", "memory_bank, _ = self.rnn(x) memory_bank = self.dropout(memory_bank) + x memory_bank = torch.transpose(memory_bank, 1,", "self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) def forward(self, iter, ent_enc, inputs, self_attn_mask=None,context_attn_mask=None): context = self.self_attn(inputs,", "num_layers=num_layers, bidirectional=bidirectional) self.wo = nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.sigmoid", "+ pos_emb for i in range(self.num_inter_layers): x = self.transformer_inter[i](i, x, x, ~mask) #", "def __init__(self, d_model, d_ff, heads, dropout, num_inter_layers=0): super(TransformerInterEncoder, self).__init__() self.d_model = d_model self.num_inter_layers", "def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder_attn, self).__init__() num_directions = 2 if", "step=None): emb = emb * math.sqrt(self.dim) if (step): emb = emb + self.pe[:,", "* dim x = self.layer_norm(x) sent_scores = self.sigmoid(self.wo(x)) sent_scores = sent_scores.squeeze(-1) * mask.float()", "nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.softmax = nn.Softmax() print('this is", "return emb def get_emb(self, emb): return self.pe[:, :emb.size(1)] class TransformerEncoderLayer(nn.Module): def __init__(self, d_model,", "x_1, edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1, edge_index_1, edge_weight_1) syn=self.relu(syn) syn=self.dropout(syn) syn = self.gcn_x_12(syn, edge_index_1, edge_weight_1)", "syn = self.dropout(syn) # x2 = self.gcn_x_21(x_1, edge_index_2, edge_weight_2) # x2 = self.relu(x2)", "RNNEncoder_attn(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder_attn, self).__init__() num_directions = 2", "x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" batch, layer, seq, hidden = x.size() x1=x.contiguous().view(batch * layer,", "top_vecs, inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1, n_out,-1)) scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1, -1, top_vecs.size(1), -1) + self.wi(top_vecs).unsqueeze( 1))).squeeze(-1) sent_scores", "mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" x = torch.transpose(x, 1, 0) memory_bank, _ = self.rnn(x) memory_bank", "edge_index_1, edge_weight_1) # syn=self.relu(syn) # syn=self.dropout(syn) # x2 = self.relu(x2) # x2 =", "__init__(self, hidden_size): super(Classifier, self).__init__() self.linear1 = nn.Linear(hidden_size, 1) self.sigmoid = nn.Sigmoid() def forward(self,", "forward(self, top_vecs, mask): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" batch_size, n_sents = top_vecs.size(0), top_vecs.size(1) pos_emb =", "= LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo = nn.Linear(num_directions * hidden_size, 1, bias=True)", "dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) def forward(self, iter, ent_enc, inputs, self_attn_mask=None,context_attn_mask=None): context =", "= nn.Dropout(dropout) def forward(self, iter, query, inputs, mask): if (iter != 0): input_norm", "mask.float() return sent_scores class GRUEncoder_attn(nn.Module): def __init__(self,bidirectional, num_layers, input_size, hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__() class RNNEncoder_attn(nn.Module):", "range(self.num_inter_layers): inputs = self.transformer_inter[i](i, top_vecs, inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1, n_out,-1)) scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1, -1, top_vecs.size(1), -1)", "num_inter_layers=0): super(TransformerInterEncoder, self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model)", "d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) def forward(self,", "in range(self.num_inter_layers): inputs = self.transformer_inter[i](i, top_vecs, inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1, n_out,-1)) scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1, -1, top_vecs.size(1),", "self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2, edge_weight_2) # x2 = self.gcn_x_22(mix, edge_index_2, edge_weight_2) # syn=self.gcn_x_12(mix, edge_index_1, edge_weight_1)", "= self.transformer_inter[i](i, top_vecs, inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1, n_out,-1)) scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1, -1, top_vecs.size(1), -1) + self.wi(top_vecs).unsqueeze(", "syn=self.gcn_x_12(mix, edge_index_1, edge_weight_1) # syn=self.relu(syn) # syn=self.dropout(syn) # x2 = self.relu(x2) # x2", "memory_bank = self.dropout(memory_bank) + x1 memory_bank = torch.transpose(memory_bank, 1, 0) # sent_scores =", "1, bias=True) self.LR = nn.LeakyReLU() self.softmax = nn.Softmax(dim=-1) def forward(self, top_vecs, inputs, mask,", "edge_index_2, edge_weight_2) # syn=self.gcn_x_12(mix, edge_index_1, edge_weight_1) # syn=self.relu(syn) # syn=self.dropout(syn) # x2 =", "batch, layer, seq, hidden = x.size() x1=x.contiguous().view(batch * layer, -1, hidden) x1 =", "+ seq_mask), 0) inputs=inputs+pos_emb for i in range(self.num_inter_layers): inputs = self.transformer_inter[i](i, top_vecs, inputs,self_attn_mask,~", "self.pe[:, :emb.size(1)] class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout): super(TransformerEncoderLayer, self).__init__() self.self_attn", "= nn.Softmax(dim=-1) def forward(self, top_vecs, inputs, mask, label_mask=None): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" n_out =", "max_len).unsqueeze(1) div_term = torch.exp((torch.arange(0, dim, 2, dtype=torch.float) * -(math.log(10000.0) / dim))) pe[:, 0::2]", "x = top_vecs * mask[:, :, None].float() x = x + pos_emb for", "-1, hidden) x1 = torch.transpose(x1, 1, 0) memory_bank, _ = self.rnn(x1) memory_bank =", "self.gcn_x_21(x_1, edge_index_2, edge_weight_2) # x2 = self.relu(x2) # x2 = self.dropout(x2) # mix", "None, :] else: emb = emb + self.pe[:, :emb.size(1)] emb = self.dropout(emb) return", "d_model self.num_inter_layers = num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerEncoderLayer(d_model, heads,", "-1, top_vecs.size(1), -1) + self.wi(top_vecs).unsqueeze( 1))).squeeze(-1) sent_scores = self.softmax(scores) return sent_scores class RNNEncoder(nn.Module):", "return sent_scores class GCN(nn.Module): def __init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN, self).__init__() self.in_channel=in_channel self.out_channel=out_channel self.hidden_dim=hidden_dim self.dropout =", "__init__(self,bidirectional, num_layers, input_size, hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__() class RNNEncoder_attn(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size,", "2) class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout): super(TransformerDecoderLayer, self).__init__() self.self_attn =", "max_tokens * dim x = self.layer_norm(x) sent_scores = self.sigmoid(self.wo(x)) sent_scores = sent_scores.squeeze(-1) *", "= mask.unsqueeze(1) context = self.self_attn(input_norm, input_norm, input_norm, mask=mask) out = self.dropout(context) + inputs", "syn=self.relu(syn) # syn=self.dropout(syn) # x2 = self.relu(x2) # x2 = self.dropout(x2) return syn", "= nn.Linear(d_model, 1, bias=True) self.sigmoid = nn.Sigmoid() def forward(self, top_vecs, mask): \"\"\" See", "edge_index_1, edge_weight_1) syn = self.relu(syn) syn = self.dropout(syn) # x2 = self.gcn_x_21(x_1, edge_index_2,", "GCN(nn.Module): def __init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN, self).__init__() self.in_channel=in_channel self.out_channel=out_channel self.hidden_dim=hidden_dim self.dropout = nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2", "* hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.softmax = nn.Softmax() print('this is dropout',dropout)", "nn.ModuleList( [TransformerDecoderLayer(d_model, heads, d_ff, dropout) for _ in range(num_inter_layers)]) self.dropout = nn.Dropout(dropout) self.layer_norm", "nn.Dropout(dropout) self.softmax = nn.Softmax() print('this is dropout',dropout) def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\"", "= x.size() x1=x.contiguous().view(batch * layer, -1, hidden) x1 = torch.transpose(x1, 1, 0) memory_bank,", "import math import torch import torch.nn as nn from models.neural import MultiHeadedAttention, PositionwiseFeedForward", "max_len=5000): pe = torch.zeros(max_len, dim) position = torch.arange(0, max_len).unsqueeze(1) div_term = torch.exp((torch.arange(0, dim,", "def forward(self, top_vecs, mask): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" batch_size, n_sents = top_vecs.size(0), top_vecs.size(1) pos_emb", "= self.dropout(memory_bank) + x memory_bank = torch.transpose(memory_bank, 1, 0) sent_scores = self.sigmoid(self.wo(memory_bank)) sent_scores", "sent_scores class GRUEncoder_attn(nn.Module): def __init__(self,bidirectional, num_layers, input_size, hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__() class RNNEncoder_attn(nn.Module): def __init__(self,", "pe[:, 0::2] = torch.sin(position.float() * div_term) pe[:, 1::2] = torch.cos(position.float() * div_term) pe", "= nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, d_hidden , bias=True) self.wi = nn.Linear(d_model, d_hidden,", "= sent_scores.squeeze(-1) * mask.float() return sent_scores class GCN(nn.Module): def __init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN, self).__init__() self.in_channel=in_channel", "sent_vec = torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim = 1).expand(batch,seq,1,layer),x) return sent_vec.squeeze(dim = 2) class TransformerDecoderLayer(nn.Module): def __init__(self,", "print('this is dropout',dropout) def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" batch, layer, seq, hidden", "= self.pos_emb.pe[:, :n_sents] x = top_vecs * mask[:, :, None].float() x = x", "* hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.sigmoid = nn.Sigmoid() def forward(self, x,", "self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, 1, bias=True) self.sigmoid = nn.Sigmoid() def", "= nn.Sigmoid() def forward(self, top_vecs, mask): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" batch_size, n_sents = top_vecs.size(0),", "forward(self, iter, ent_enc, inputs, self_attn_mask=None,context_attn_mask=None): context = self.self_attn(inputs, inputs, inputs, mask=self_attn_mask) dec_output =", "hidden) x1 = torch.transpose(x1, 1, 0) memory_bank, _ = self.rnn(x1) memory_bank = self.dropout(memory_bank)", "d_ff, heads, dropout, d_hidden, num_inter_layers=0): super(TransformerInterDecoder, self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers", "d_model, heads, d_ff, dropout): super(TransformerDecoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward", ":emb.size(1)] emb = self.dropout(emb) return emb def get_emb(self, emb): return self.pe[:, :emb.size(1)] class", "top_vecs * mask[:, :, None].float() x = x + pos_emb for i in", "self.softmax = nn.Softmax(dim=-1) def forward(self, top_vecs, inputs, mask, label_mask=None): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" n_out", "inputs, inputs, mask=self_attn_mask) dec_output = self.self_attn( ent_enc, ent_enc, context, mask=context_attn_mask) dec_output = self.feed_forward(dec_output)", "1, bias=True) self.dropout = nn.Dropout(dropout) self.softmax = nn.Softmax() print('this is dropout',dropout) def forward(self,", "for _ in range(num_inter_layers)]) self.dropout = nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo =", "nn.Softmax() print('this is dropout',dropout) def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" batch, layer, seq,", "num_directions == 0 hidden_size = hidden_size // num_directions self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size,", "self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True) def forward(self, x_1, edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1, edge_index_1, edge_weight_1) syn=self.relu(syn) syn=self.dropout(syn) syn", "dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.dropout = nn.Dropout(dropout) def forward(self, iter, query, inputs,", "__init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN, self).__init__() self.in_channel=in_channel self.out_channel=out_channel self.hidden_dim=hidden_dim self.dropout = nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 # self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim)", "self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo = nn.Linear(num_directions * hidden_size, 1,", "d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.dropout = nn.Dropout(dropout) def forward(self, iter, query,", "= self.dropout(x2) # mix = self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2, edge_weight_2) # x2 = self.gcn_x_22(mix, edge_index_2,", "= hidden_size // num_directions self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo =", "self.transformer_inter = nn.ModuleList( [TransformerDecoderLayer(d_model, heads, d_ff, dropout) for _ in range(num_inter_layers)]) self.dropout =", "self.register_buffer('pe', pe) self.dropout = nn.Dropout(p=dropout) self.dim = dim def forward(self, emb, step=None): emb", "bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder, self).__init__() num_directions = 2 if bidirectional else", "LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo = nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout", "def __init__(self, d_model, d_ff, heads, dropout, d_hidden, num_inter_layers=0): super(TransformerInterDecoder, self).__init__() self.d_model = d_model", "= self.rnn(x) memory_bank = self.dropout(memory_bank) + x memory_bank = torch.transpose(memory_bank, 1, 0) sent_scores", "layer, seq, hidden = x.size() x1=x.contiguous().view(batch * layer, -1, hidden) x1 = torch.transpose(x1,", "# self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True) def forward(self, x_1, edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1, edge_index_1, edge_weight_1) syn=self.relu(syn) syn=self.dropout(syn)", "in range(self.num_inter_layers): x = self.transformer_inter[i](i, x, x, ~mask) # all_sents * max_tokens *", "nn.Sigmoid() def forward(self, top_vecs, mask): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" batch_size, n_sents = top_vecs.size(0), top_vecs.size(1)", "= hidden_size // num_directions self.relu = nn.ReLU() self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers,", "See :obj:`EncoderBase.forward()`\"\"\" n_out = inputs.size(1) pos_emb = self.pos_emb.pe[:, :n_out] seq_mask=subsequent_mask(inputs) self_attn_mask = torch.gt((~label_mask.unsqueeze(1).expand(-1,", "n_out,-1)) scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1, -1, top_vecs.size(1), -1) + self.wi(top_vecs).unsqueeze( 1))).squeeze(-1) sent_scores = self.softmax(scores) return", "seq, hidden = x.size() x1=x.contiguous().view(batch * layer, -1, hidden) x1 = torch.transpose(x1, 1,", "nn.Dropout(p=dropout) self.dim = dim def forward(self, emb, step=None): emb = emb * math.sqrt(self.dim)", "num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerEncoderLayer(d_model, heads, d_ff, dropout) for", "self.sigmoid = nn.Sigmoid() def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" x = torch.transpose(x, 1,", "class RNNEncoder_attn(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder_attn, self).__init__() num_directions =", "+ x memory_bank = torch.transpose(memory_bank, 1, 0) sent_scores = self.sigmoid(self.wo(memory_bank)) sent_scores = sent_scores.squeeze(-1)", "import torch.nn as nn from models.neural import MultiHeadedAttention, PositionwiseFeedForward from models.rnn import LayerNormLSTM", "eps=1e-6) self.wo = nn.Linear(d_model, d_hidden , bias=True) self.wi = nn.Linear(d_model, d_hidden, bias=True) self.v", "num_directions self.relu = nn.ReLU() self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo =", "hidden_size % num_directions == 0 hidden_size = hidden_size // num_directions self.relu = nn.ReLU()", "memory_bank, _ = self.rnn(x1) memory_bank = self.dropout(memory_bank) + x1 memory_bank = torch.transpose(memory_bank, 1,", "nn.Dropout(dropout) self.sigmoid = nn.Sigmoid() def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" x = torch.transpose(x,", "layer, -1, hidden) x1 = torch.transpose(x1, 1, 0) memory_bank, _ = self.rnn(x1) memory_bank", "= self.relu(x2) # x2 = self.dropout(x2) # mix = self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2, edge_weight_2) #", "x = self.transformer_inter[i](i, x, x, ~mask) # all_sents * max_tokens * dim x", "return sent_scores class PositionalEncoding(nn.Module): def __init__(self, dropout, dim, max_len=5000): pe = torch.zeros(max_len, dim)", "self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 # self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) # self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 # self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True) def forward(self, x_1, edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None):", "self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerDecoderLayer(d_model, heads, d_ff, dropout) for _", "self.in_channel=in_channel self.out_channel=out_channel self.hidden_dim=hidden_dim self.dropout = nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 # self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) # self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 #", "self_attn_mask = torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out, -1) + seq_mask), 0) inputs=inputs+pos_emb for i in range(self.num_inter_layers):", "dim, max_len=5000): pe = torch.zeros(max_len, dim) position = torch.arange(0, max_len).unsqueeze(1) div_term = torch.exp((torch.arange(0,", "models.neural import MultiHeadedAttention, PositionwiseFeedForward from models.rnn import LayerNormLSTM class Classifier(nn.Module): def __init__(self, hidden_size):", "= nn.ModuleList( [TransformerEncoderLayer(d_model, heads, d_ff, dropout) for _ in range(num_inter_layers)]) self.dropout = nn.Dropout(dropout)", "hidden_size = hidden_size // num_directions self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo", "__init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder_attn, self).__init__() num_directions = 2 if bidirectional", "= nn.Linear(d_model, d_hidden, bias=True) self.v = nn.Linear(d_hidden, 1, bias=True) self.LR = nn.LeakyReLU() self.softmax", "dropout) for _ in range(num_inter_layers)]) self.dropout = nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo", "GRUEncoder_attn(nn.Module): def __init__(self,bidirectional, num_layers, input_size, hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__() class RNNEncoder_attn(nn.Module): def __init__(self, bidirectional, num_layers,", "% num_directions == 0 hidden_size = hidden_size // num_directions self.relu = nn.ReLU() self.rnn", "= num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerEncoderLayer(d_model, heads, d_ff, dropout)", "d_ff, dropout) for _ in range(num_inter_layers)]) self.dropout = nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6)", "See :obj:`EncoderBase.forward()`\"\"\" batch_size, n_sents = top_vecs.size(0), top_vecs.size(1) pos_emb = self.pos_emb.pe[:, :n_sents] x =", "hidden_size, dropout=0.0): super(RNNEncoder, self).__init__() num_directions = 2 if bidirectional else 1 assert hidden_size", "0): input_norm = self.layer_norm(inputs) else: input_norm = inputs mask = mask.unsqueeze(1) context =", "nn.Sigmoid() def forward(self, x, mask_cls): h = self.linear1(x).squeeze(-1) sent_scores = self.sigmoid(h) * mask_cls.float()", "self.softmax(scores) return sent_scores class RNNEncoder(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder,", "super(TransformerInterDecoder, self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter", "in range(num_inter_layers)]) self.dropout = nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, 1,", "n_out, -1) + seq_mask), 0) inputs=inputs+pos_emb for i in range(self.num_inter_layers): inputs = self.transformer_inter[i](i,", "edge_weight_1) syn=self.relu(syn) syn=self.dropout(syn) syn = self.gcn_x_12(syn, edge_index_1, edge_weight_1) syn = self.relu(syn) syn =", "iter, query, inputs, mask): if (iter != 0): input_norm = self.layer_norm(inputs) else: input_norm", "nn.ReLU() self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo = nn.Linear(num_directions * hidden_size,", "= self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2) sent_vec = torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim = 1).expand(batch,seq,1,layer),x) return sent_vec.squeeze(dim = 2) class", "dim def forward(self, emb, step=None): emb = emb * math.sqrt(self.dim) if (step): emb", "+ x1 memory_bank = torch.transpose(memory_bank, 1, 0) # sent_scores = self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores =", "input_norm, input_norm, mask=mask) out = self.dropout(context) + inputs return self.feed_forward(out) class TransformerInterEncoder(nn.Module): def", "x, ~mask) # all_sents * max_tokens * dim x = self.layer_norm(x) sent_scores =", "emb = emb + self.pe[:, :emb.size(1)] emb = self.dropout(emb) return emb def get_emb(self,", "super(TransformerEncoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout)", "self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) def forward(self, iter, ent_enc,", "self.dropout(context) + inputs return self.feed_forward(out) class TransformerInterEncoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout,", "* div_term) pe = pe.unsqueeze(0) super(PositionalEncoding, self).__init__() self.register_buffer('pe', pe) self.dropout = nn.Dropout(p=dropout) self.dim", "= 1).expand(batch,seq,1,layer),x) return sent_vec.squeeze(dim = 2) class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff,", "# x2 = self.gcn_x_22(mix, edge_index_2, edge_weight_2) # syn=self.gcn_x_12(mix, edge_index_1, edge_weight_1) # syn=self.relu(syn) #", "torch.sin(position.float() * div_term) pe[:, 1::2] = torch.cos(position.float() * div_term) pe = pe.unsqueeze(0) super(PositionalEncoding,", "dropout, dim, max_len=5000): pe = torch.zeros(max_len, dim) position = torch.arange(0, max_len).unsqueeze(1) div_term =", "* mask.float() return sent_scores class GRUEncoder_attn(nn.Module): def __init__(self,bidirectional, num_layers, input_size, hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__() class", "inputs, self_attn_mask=None,context_attn_mask=None): context = self.self_attn(inputs, inputs, inputs, mask=self_attn_mask) dec_output = self.self_attn( ent_enc, ent_enc,", "self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, d_hidden , bias=True) self.wi = nn.Linear(d_model,", "self.v = nn.Linear(d_hidden, 1, bias=True) self.LR = nn.LeakyReLU() self.softmax = nn.Softmax(dim=-1) def forward(self,", "__init__(self, d_model, heads, d_ff, dropout): super(TransformerEncoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout)", "eps=1e-6) self.dropout = nn.Dropout(dropout) def forward(self, iter, query, inputs, mask): if (iter !=", "def __init__(self,bidirectional, num_layers, input_size, hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__() class RNNEncoder_attn(nn.Module): def __init__(self, bidirectional, num_layers, input_size,", "d_model, d_ff, heads, dropout, num_inter_layers=0): super(TransformerInterEncoder, self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers", "dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) def forward(self, iter,", "hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.sigmoid = nn.Sigmoid() def forward(self, x, mask):", "* layer, -1, hidden) x1 = torch.transpose(x1, 1, 0) memory_bank, _ = self.rnn(x1)", "PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerDecoderLayer(d_model, heads, d_ff, dropout) for _ in range(num_inter_layers)])", "class GRUEncoder_attn(nn.Module): def __init__(self,bidirectional, num_layers, input_size, hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__() class RNNEncoder_attn(nn.Module): def __init__(self, bidirectional,", "def forward(self, iter, query, inputs, mask): if (iter != 0): input_norm = self.layer_norm(inputs)", "import MultiHeadedAttention, PositionwiseFeedForward from models.rnn import LayerNormLSTM class Classifier(nn.Module): def __init__(self, hidden_size): super(Classifier,", "heads, d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) def", "emb + self.pe[:, :emb.size(1)] emb = self.dropout(emb) return emb def get_emb(self, emb): return", "self.sigmoid(h) * mask_cls.float() return sent_scores class PositionalEncoding(nn.Module): def __init__(self, dropout, dim, max_len=5000): pe", "\"\"\"See :func:`EncoderBase.forward()`\"\"\" batch, layer, seq, hidden = x.size() x1=x.contiguous().view(batch * layer, -1, hidden)", "class GCN(nn.Module): def __init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN, self).__init__() self.in_channel=in_channel self.out_channel=out_channel self.hidden_dim=hidden_dim self.dropout = nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim)", "# all_sents * max_tokens * dim x = self.layer_norm(x) sent_scores = self.sigmoid(self.wo(x)) sent_scores", "d_model, heads, d_ff, dropout): super(TransformerEncoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward", "sent_vec.squeeze(dim = 2) class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout): super(TransformerDecoderLayer, self).__init__()", "self.transformer_inter[i](i, top_vecs, inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1, n_out,-1)) scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1, -1, top_vecs.size(1), -1) + self.wi(top_vecs).unsqueeze( 1))).squeeze(-1)", "def __init__(self, d_model, heads, d_ff, dropout): super(TransformerEncoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model,", "torch.cos(position.float() * div_term) pe = pe.unsqueeze(0) super(PositionalEncoding, self).__init__() self.register_buffer('pe', pe) self.dropout = nn.Dropout(p=dropout)", "memory_bank = torch.transpose(memory_bank, 1, 0) sent_scores = self.sigmoid(self.wo(memory_bank)) sent_scores = sent_scores.squeeze(-1) * mask.float()", "x2 = self.gcn_x_21(x_1, edge_index_2, edge_weight_2) # x2 = self.relu(x2) # x2 = self.dropout(x2)", "pos_emb for i in range(self.num_inter_layers): x = self.transformer_inter[i](i, x, x, ~mask) # all_sents", "x1=x.contiguous().view(batch * layer, -1, hidden) x1 = torch.transpose(x1, 1, 0) memory_bank, _ =", "= pe.unsqueeze(0) super(PositionalEncoding, self).__init__() self.register_buffer('pe', pe) self.dropout = nn.Dropout(p=dropout) self.dim = dim def", "class TransformerInterDecoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout, d_hidden, num_inter_layers=0): super(TransformerInterDecoder, self).__init__() self.d_model", "= nn.Dropout(dropout) self.sigmoid = nn.Sigmoid() def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" x =", "def forward(self, emb, step=None): emb = emb * math.sqrt(self.dim) if (step): emb =", "eps=1e-6) self.wo = nn.Linear(d_model, 1, bias=True) self.sigmoid = nn.Sigmoid() def forward(self, top_vecs, mask):", "nn.ModuleList( [TransformerEncoderLayer(d_model, heads, d_ff, dropout) for _ in range(num_inter_layers)]) self.dropout = nn.Dropout(dropout) self.layer_norm", "~mask) # all_sents * max_tokens * dim x = self.layer_norm(x) sent_scores = self.sigmoid(self.wo(x))", "div_term) pe = pe.unsqueeze(0) super(PositionalEncoding, self).__init__() self.register_buffer('pe', pe) self.dropout = nn.Dropout(p=dropout) self.dim =", "mask.unsqueeze(1) context = self.self_attn(input_norm, input_norm, input_norm, mask=mask) out = self.dropout(context) + inputs return", "self.dropout = nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, d_hidden , bias=True)", "self.rnn(x) memory_bank = self.dropout(memory_bank) + x memory_bank = torch.transpose(memory_bank, 1, 0) sent_scores =", "forward(self, iter, query, inputs, mask): if (iter != 0): input_norm = self.layer_norm(inputs) else:", "for i in range(self.num_inter_layers): inputs = self.transformer_inter[i](i, top_vecs, inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1, n_out,-1)) scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1,", "return self.pe[:, :emb.size(1)] class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout): super(TransformerEncoderLayer, self).__init__()", "self.pe[:, step][:, None, :] else: emb = emb + self.pe[:, :emb.size(1)] emb =", "1) self.sigmoid = nn.Sigmoid() def forward(self, x, mask_cls): h = self.linear1(x).squeeze(-1) sent_scores =", "query, inputs, mask): if (iter != 0): input_norm = self.layer_norm(inputs) else: input_norm =", "// num_directions self.relu = nn.ReLU() self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo", "= self.sigmoid(self.wo(x)) sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores class GRUEncoder_attn(nn.Module): def __init__(self,bidirectional,", "self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2) sent_vec = torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim = 1).expand(batch,seq,1,layer),x) return sent_vec.squeeze(dim = 2) class TransformerDecoderLayer(nn.Module):", "edge_index_2, edge_weight_2) # x2 = self.gcn_x_22(mix, edge_index_2, edge_weight_2) # syn=self.gcn_x_12(mix, edge_index_1, edge_weight_1) #", "_ = self.rnn(x1) memory_bank = self.dropout(memory_bank) + x1 memory_bank = torch.transpose(memory_bank, 1, 0)", "models.rnn import LayerNormLSTM class Classifier(nn.Module): def __init__(self, hidden_size): super(Classifier, self).__init__() self.linear1 = nn.Linear(hidden_size,", "num_layers, input_size, hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__() class RNNEncoder_attn(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0):", "self.wo = nn.Linear(d_model, 1, bias=True) self.sigmoid = nn.Sigmoid() def forward(self, top_vecs, mask): \"\"\"", "hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__() class RNNEncoder_attn(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder_attn, self).__init__()", "self.relu = nn.ReLU() self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo = nn.Linear(num_directions", "memory_bank = torch.transpose(memory_bank, 1, 0) # sent_scores = self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores = self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2)", ":obj:`EncoderBase.forward()`\"\"\" n_out = inputs.size(1) pos_emb = self.pos_emb.pe[:, :n_out] seq_mask=subsequent_mask(inputs) self_attn_mask = torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out,", ":obj:`EncoderBase.forward()`\"\"\" batch_size, n_sents = top_vecs.size(0), top_vecs.size(1) pos_emb = self.pos_emb.pe[:, :n_sents] x = top_vecs", "nn.Linear(d_model, 1, bias=True) self.sigmoid = nn.Sigmoid() def forward(self, top_vecs, mask): \"\"\" See :obj:`EncoderBase.forward()`\"\"\"", "dtype=torch.float) * -(math.log(10000.0) / dim))) pe[:, 0::2] = torch.sin(position.float() * div_term) pe[:, 1::2]", "self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm", "0 hidden_size = hidden_size // num_directions self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional)", "x1 = torch.transpose(x1, 1, 0) memory_bank, _ = self.rnn(x1) memory_bank = self.dropout(memory_bank) +", "self.transformer_inter = nn.ModuleList( [TransformerEncoderLayer(d_model, heads, d_ff, dropout) for _ in range(num_inter_layers)]) self.dropout =", "1, 0) memory_bank, _ = self.rnn(x1) memory_bank = self.dropout(memory_bank) + x1 memory_bank =", "d_model) self.transformer_inter = nn.ModuleList( [TransformerEncoderLayer(d_model, heads, d_ff, dropout) for _ in range(num_inter_layers)]) self.dropout", "= nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.softmax = nn.Softmax() print('this", "x = torch.transpose(x, 1, 0) memory_bank, _ = self.rnn(x) memory_bank = self.dropout(memory_bank) +", "heads, dropout, num_inter_layers=0): super(TransformerInterEncoder, self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers self.pos_emb =", "= torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim = 1).expand(batch,seq,1,layer),x) return sent_vec.squeeze(dim = 2) class TransformerDecoderLayer(nn.Module): def __init__(self, d_model,", "self.pos_emb.pe[:, :n_sents] x = top_vecs * mask[:, :, None].float() x = x +", "dec_output = self.self_attn( ent_enc, ent_enc, context, mask=context_attn_mask) dec_output = self.feed_forward(dec_output) return dec_output class", "hidden_size, dropout=0.0): super(RNNEncoder_attn, self).__init__() num_directions = 2 if bidirectional else 1 assert hidden_size", "2 if bidirectional else 1 assert hidden_size % num_directions == 0 hidden_size =", "d_hidden , bias=True) self.wi = nn.Linear(d_model, d_hidden, bias=True) self.v = nn.Linear(d_hidden, 1, bias=True)", "= torch.zeros(max_len, dim) position = torch.arange(0, max_len).unsqueeze(1) div_term = torch.exp((torch.arange(0, dim, 2, dtype=torch.float)", "heads, d_ff, dropout): super(TransformerEncoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward =", "= inputs mask = mask.unsqueeze(1) context = self.self_attn(input_norm, input_norm, input_norm, mask=mask) out =", "= torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out, -1) + seq_mask), 0) inputs=inputs+pos_emb for i in range(self.num_inter_layers): inputs", "None].float() x = x + pos_emb for i in range(self.num_inter_layers): x = self.transformer_inter[i](i,", "__init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder, self).__init__() num_directions = 2 if bidirectional", "mix = self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2, edge_weight_2) # x2 = self.gcn_x_22(mix, edge_index_2, edge_weight_2) # syn=self.gcn_x_12(mix,", "= nn.LeakyReLU() self.softmax = nn.Softmax(dim=-1) def forward(self, top_vecs, inputs, mask, label_mask=None): \"\"\" See", "nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, d_hidden , bias=True) self.wi = nn.Linear(d_model, d_hidden, bias=True)", "torch.transpose(x, 1, 0) memory_bank, _ = self.rnn(x) memory_bank = self.dropout(memory_bank) + x memory_bank", "self.gcn_x_12(syn, edge_index_1, edge_weight_1) syn = self.relu(syn) syn = self.dropout(syn) # x2 = self.gcn_x_21(x_1,", "input_size, hidden_size, dropout=0.0): super(RNNEncoder, self).__init__() num_directions = 2 if bidirectional else 1 assert", "= d_model self.num_inter_layers = num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerEncoderLayer(d_model,", "= num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerDecoderLayer(d_model, heads, d_ff, dropout)", "nn from models.neural import MultiHeadedAttention, PositionwiseFeedForward from models.rnn import LayerNormLSTM class Classifier(nn.Module): def", "!= 0): input_norm = self.layer_norm(inputs) else: input_norm = inputs mask = mask.unsqueeze(1) context", "self.LR = nn.LeakyReLU() self.softmax = nn.Softmax(dim=-1) def forward(self, top_vecs, inputs, mask, label_mask=None): \"\"\"", "1).expand(batch,seq,1,layer),x) return sent_vec.squeeze(dim = 2) class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout):", "= torch.transpose(x1, 1, 0) memory_bank, _ = self.rnn(x1) memory_bank = self.dropout(memory_bank) + x1", "= nn.Dropout(dropout) self.softmax = nn.Softmax() print('this is dropout',dropout) def forward(self, x, mask): \"\"\"See", "forward(self, top_vecs, inputs, mask, label_mask=None): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" n_out = inputs.size(1) pos_emb =", "nn.LeakyReLU() self.softmax = nn.Softmax(dim=-1) def forward(self, top_vecs, inputs, mask, label_mask=None): \"\"\" See :obj:`EncoderBase.forward()`\"\"\"", "self.sigmoid = nn.Sigmoid() def forward(self, top_vecs, mask): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" batch_size, n_sents =", "* math.sqrt(self.dim) if (step): emb = emb + self.pe[:, step][:, None, :] else:", "inputs, mask): if (iter != 0): input_norm = self.layer_norm(inputs) else: input_norm = inputs", "batch_size, n_sents = top_vecs.size(0), top_vecs.size(1) pos_emb = self.pos_emb.pe[:, :n_sents] x = top_vecs *", "= inputs.size(1) pos_emb = self.pos_emb.pe[:, :n_out] seq_mask=subsequent_mask(inputs) self_attn_mask = torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out, -1) +", "inputs, mask, label_mask=None): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" n_out = inputs.size(1) pos_emb = self.pos_emb.pe[:, :n_out]", "input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo = nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout =", "if (step): emb = emb + self.pe[:, step][:, None, :] else: emb =", "hidden_size): super(Classifier, self).__init__() self.linear1 = nn.Linear(hidden_size, 1) self.sigmoid = nn.Sigmoid() def forward(self, x,", "nn.Linear(d_hidden, 1, bias=True) self.LR = nn.LeakyReLU() self.softmax = nn.Softmax(dim=-1) def forward(self, top_vecs, inputs,", "0) sent_scores = self.sigmoid(self.wo(memory_bank)) sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores class GCN(nn.Module):", "= 2 if bidirectional else 1 assert hidden_size % num_directions == 0 hidden_size", "num_directions = 2 if bidirectional else 1 assert hidden_size % num_directions == 0", "bias=True) self.v = nn.Linear(d_hidden, 1, bias=True) self.LR = nn.LeakyReLU() self.softmax = nn.Softmax(dim=-1) def", "super(RNNEncoder_attn, self).__init__() num_directions = 2 if bidirectional else 1 assert hidden_size % num_directions", "hidden_size // num_directions self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo = nn.Linear(num_directions", "def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" x = torch.transpose(x, 1, 0) memory_bank, _", "self.gcn_x_22(mix, edge_index_2, edge_weight_2) # syn=self.gcn_x_12(mix, edge_index_1, edge_weight_1) # syn=self.relu(syn) # syn=self.dropout(syn) # x2", "= PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.dropout = nn.Dropout(dropout) def forward(self,", "= self.dropout(emb) return emb def get_emb(self, emb): return self.pe[:, :emb.size(1)] class TransformerEncoderLayer(nn.Module): def", "self.sigmoid(self.wo(x)) sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores class GRUEncoder_attn(nn.Module): def __init__(self,bidirectional, num_layers,", "iter, ent_enc, inputs, self_attn_mask=None,context_attn_mask=None): context = self.self_attn(inputs, inputs, inputs, mask=self_attn_mask) dec_output = self.self_attn(", "self.wo(inputs.unsqueeze(2)).expand(-1, -1, top_vecs.size(1), -1) + self.wi(top_vecs).unsqueeze( 1))).squeeze(-1) sent_scores = self.softmax(scores) return sent_scores class", "def __init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN, self).__init__() self.in_channel=in_channel self.out_channel=out_channel self.hidden_dim=hidden_dim self.dropout = nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 #", "= self.dropout(syn) # x2 = self.gcn_x_21(x_1, edge_index_2, edge_weight_2) # x2 = self.relu(x2) #", "= MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model,", "def forward(self, top_vecs, inputs, mask, label_mask=None): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" n_out = inputs.size(1) pos_emb", "bias=True) self.LR = nn.LeakyReLU() self.softmax = nn.Softmax(dim=-1) def forward(self, top_vecs, inputs, mask, label_mask=None):", "1 assert hidden_size % num_directions == 0 hidden_size = hidden_size // num_directions self.rnn", "TransformerInterDecoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout, d_hidden, num_inter_layers=0): super(TransformerInterDecoder, self).__init__() self.d_model =", "(iter != 0): input_norm = self.layer_norm(inputs) else: input_norm = inputs mask = mask.unsqueeze(1)", "nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, 1, bias=True) self.sigmoid = nn.Sigmoid() def forward(self, top_vecs,", "sent_scores class RNNEncoder(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder, self).__init__() num_directions", "# x2 = self.gcn_x_21(x_1, edge_index_2, edge_weight_2) # x2 = self.relu(x2) # x2 =", "x = self.layer_norm(x) sent_scores = self.sigmoid(self.wo(x)) sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores", "hidden_size % num_directions == 0 hidden_size = hidden_size // num_directions self.rnn = LayerNormLSTM(", "super(PositionalEncoding, self).__init__() self.register_buffer('pe', pe) self.dropout = nn.Dropout(p=dropout) self.dim = dim def forward(self, emb,", "mask.float() return sent_scores class GCN(nn.Module): def __init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN, self).__init__() self.in_channel=in_channel self.out_channel=out_channel self.hidden_dim=hidden_dim self.dropout", "x2 = self.dropout(x2) # mix = self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2, edge_weight_2) # x2 = self.gcn_x_22(mix,", "if (iter != 0): input_norm = self.layer_norm(inputs) else: input_norm = inputs mask =", "self.self_attn( ent_enc, ent_enc, context, mask=context_attn_mask) dec_output = self.feed_forward(dec_output) return dec_output class TransformerInterDecoder(nn.Module): def", "pe = torch.zeros(max_len, dim) position = torch.arange(0, max_len).unsqueeze(1) div_term = torch.exp((torch.arange(0, dim, 2,", "nn.Linear(d_model, d_hidden , bias=True) self.wi = nn.Linear(d_model, d_hidden, bias=True) self.v = nn.Linear(d_hidden, 1,", "/ dim))) pe[:, 0::2] = torch.sin(position.float() * div_term) pe[:, 1::2] = torch.cos(position.float() *", "self.layer_norm(x) sent_scores = self.sigmoid(self.wo(x)) sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores class GRUEncoder_attn(nn.Module):", "mask, label_mask=None): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" n_out = inputs.size(1) pos_emb = self.pos_emb.pe[:, :n_out] seq_mask=subsequent_mask(inputs)", "= torch.cos(position.float() * div_term) pe = pe.unsqueeze(0) super(PositionalEncoding, self).__init__() self.register_buffer('pe', pe) self.dropout =", "dropout, num_inter_layers=0): super(TransformerInterEncoder, self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers self.pos_emb = PositionalEncoding(dropout,", "def forward(self, iter, ent_enc, inputs, self_attn_mask=None,context_attn_mask=None): context = self.self_attn(inputs, inputs, inputs, mask=self_attn_mask) dec_output", "self).__init__() num_directions = 2 if bidirectional else 1 assert hidden_size % num_directions ==", "pe) self.dropout = nn.Dropout(p=dropout) self.dim = dim def forward(self, emb, step=None): emb =", "d_hidden, num_inter_layers=0): super(TransformerInterDecoder, self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers self.pos_emb = PositionalEncoding(dropout,", "0) memory_bank, _ = self.rnn(x) memory_bank = self.dropout(memory_bank) + x memory_bank = torch.transpose(memory_bank,", "TransformerInterEncoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout, num_inter_layers=0): super(TransformerInterEncoder, self).__init__() self.d_model = d_model", "self.layer_norm(inputs) else: input_norm = inputs mask = mask.unsqueeze(1) context = self.self_attn(input_norm, input_norm, input_norm,", "eps=1e-6) def forward(self, iter, ent_enc, inputs, self_attn_mask=None,context_attn_mask=None): context = self.self_attn(inputs, inputs, inputs, mask=self_attn_mask)", "dim))) pe[:, 0::2] = torch.sin(position.float() * div_term) pe[:, 1::2] = torch.cos(position.float() * div_term)", "# mix = self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2, edge_weight_2) # x2 = self.gcn_x_22(mix, edge_index_2, edge_weight_2) #", "inputs mask = mask.unsqueeze(1) context = self.self_attn(input_norm, input_norm, input_norm, mask=mask) out = self.dropout(context)", "inputs = self.transformer_inter[i](i, top_vecs, inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1, n_out,-1)) scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1, -1, top_vecs.size(1), -1) +", "= PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerDecoderLayer(d_model, heads, d_ff, dropout) for _ in", "+ self.pe[:, step][:, None, :] else: emb = emb + self.pe[:, :emb.size(1)] emb", "for i in range(self.num_inter_layers): x = self.transformer_inter[i](i, x, x, ~mask) # all_sents *", "sent_scores = self.sigmoid(self.wo(memory_bank)) sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores class GCN(nn.Module): def", "x.size() x1=x.contiguous().view(batch * layer, -1, hidden) x1 = torch.transpose(x1, 1, 0) memory_bank, _", "self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 # self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True) def forward(self, x_1, edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1, edge_index_1, edge_weight_1) syn=self.relu(syn)", "* mask[:, :, None].float() x = x + pos_emb for i in range(self.num_inter_layers):", "range(self.num_inter_layers): x = self.transformer_inter[i](i, x, x, ~mask) # all_sents * max_tokens * dim", "+ self.pe[:, :emb.size(1)] emb = self.dropout(emb) return emb def get_emb(self, emb): return self.pe[:,", "= nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, 1, bias=True) self.sigmoid = nn.Sigmoid() def forward(self,", "def __init__(self, dropout, dim, max_len=5000): pe = torch.zeros(max_len, dim) position = torch.arange(0, max_len).unsqueeze(1)", "= self.layer_norm(x) sent_scores = self.sigmoid(self.wo(x)) sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores class", "+ inputs return self.feed_forward(out) class TransformerInterEncoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout, num_inter_layers=0):", "forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" batch, layer, seq, hidden = x.size() x1=x.contiguous().view(batch *", "0) memory_bank, _ = self.rnn(x1) memory_bank = self.dropout(memory_bank) + x1 memory_bank = torch.transpose(memory_bank,", "div_term = torch.exp((torch.arange(0, dim, 2, dtype=torch.float) * -(math.log(10000.0) / dim))) pe[:, 0::2] =", "dropout',dropout) def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" batch, layer, seq, hidden = x.size()", "dropout, d_hidden, num_inter_layers=0): super(TransformerInterDecoder, self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers self.pos_emb =", "d_hidden, bias=True) self.v = nn.Linear(d_hidden, 1, bias=True) self.LR = nn.LeakyReLU() self.softmax = nn.Softmax(dim=-1)", "sent_scores = self.sigmoid(h) * mask_cls.float() return sent_scores class PositionalEncoding(nn.Module): def __init__(self, dropout, dim,", "RNNEncoder(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder, self).__init__() num_directions = 2", "self.hidden_dim=hidden_dim self.dropout = nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 # self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) # self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 # self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True)", ":, None].float() x = x + pos_emb for i in range(self.num_inter_layers): x =", "seq_mask), 0) inputs=inputs+pos_emb for i in range(self.num_inter_layers): inputs = self.transformer_inter[i](i, top_vecs, inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1,", ":n_sents] x = top_vecs * mask[:, :, None].float() x = x + pos_emb", "h = self.linear1(x).squeeze(-1) sent_scores = self.sigmoid(h) * mask_cls.float() return sent_scores class PositionalEncoding(nn.Module): def", "== 0 hidden_size = hidden_size // num_directions self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers,", "input_norm = self.layer_norm(inputs) else: input_norm = inputs mask = mask.unsqueeze(1) context = self.self_attn(input_norm,", "= nn.Linear(hidden_size, 1) self.sigmoid = nn.Sigmoid() def forward(self, x, mask_cls): h = self.linear1(x).squeeze(-1)", "self.dropout = nn.Dropout(dropout) self.softmax = nn.Softmax() print('this is dropout',dropout) def forward(self, x, mask):", "num_directions self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo = nn.Linear(num_directions * hidden_size,", "edge_index_1, edge_weight_1) syn=self.relu(syn) syn=self.dropout(syn) syn = self.gcn_x_12(syn, edge_index_1, edge_weight_1) syn = self.relu(syn) syn", "= self.pos_emb.pe[:, :n_out] seq_mask=subsequent_mask(inputs) self_attn_mask = torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out, -1) + seq_mask), 0) inputs=inputs+pos_emb", "super(TransformerDecoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout)", "1, bias=True) self.dropout = nn.Dropout(dropout) self.sigmoid = nn.Sigmoid() def forward(self, x, mask): \"\"\"See", "i in range(self.num_inter_layers): inputs = self.transformer_inter[i](i, top_vecs, inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1, n_out,-1)) scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1, -1,", "inputs.size(1) pos_emb = self.pos_emb.pe[:, :n_out] seq_mask=subsequent_mask(inputs) self_attn_mask = torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out, -1) + seq_mask),", "pos_emb = self.pos_emb.pe[:, :n_out] seq_mask=subsequent_mask(inputs) self_attn_mask = torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out, -1) + seq_mask), 0)", "d_model, d_ff, heads, dropout, d_hidden, num_inter_layers=0): super(TransformerInterDecoder, self).__init__() self.d_model = d_model self.num_inter_layers =", "= self.self_attn( ent_enc, ent_enc, context, mask=context_attn_mask) dec_output = self.feed_forward(dec_output) return dec_output class TransformerInterDecoder(nn.Module):", ":n_out] seq_mask=subsequent_mask(inputs) self_attn_mask = torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out, -1) + seq_mask), 0) inputs=inputs+pos_emb for i", "label_mask=None): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" n_out = inputs.size(1) pos_emb = self.pos_emb.pe[:, :n_out] seq_mask=subsequent_mask(inputs) self_attn_mask", "-1) + self.wi(top_vecs).unsqueeze( 1))).squeeze(-1) sent_scores = self.softmax(scores) return sent_scores class RNNEncoder(nn.Module): def __init__(self,", "= self.softmax(scores) return sent_scores class RNNEncoder(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0):", "nn.LayerNorm(d_model, eps=1e-6) self.dropout = nn.Dropout(dropout) def forward(self, iter, query, inputs, mask): if (iter", "input_norm = inputs mask = mask.unsqueeze(1) context = self.self_attn(input_norm, input_norm, input_norm, mask=mask) out", "= emb + self.pe[:, :emb.size(1)] emb = self.dropout(emb) return emb def get_emb(self, emb):", "in range(num_inter_layers)]) self.dropout = nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, d_hidden", "= self.layer_norm(inputs) else: input_norm = inputs mask = mask.unsqueeze(1) context = self.self_attn(input_norm, input_norm,", "super(TransformerInterEncoder, self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter", "* max_tokens * dim x = self.layer_norm(x) sent_scores = self.sigmoid(self.wo(x)) sent_scores = sent_scores.squeeze(-1)", "self.wi = nn.Linear(d_model, d_hidden, bias=True) self.v = nn.Linear(d_hidden, 1, bias=True) self.LR = nn.LeakyReLU()", "= self.dropout(context) + inputs return self.feed_forward(out) class TransformerInterEncoder(nn.Module): def __init__(self, d_model, d_ff, heads,", "pe.unsqueeze(0) super(PositionalEncoding, self).__init__() self.register_buffer('pe', pe) self.dropout = nn.Dropout(p=dropout) self.dim = dim def forward(self,", "== 0 hidden_size = hidden_size // num_directions self.relu = nn.ReLU() self.rnn = LayerNormLSTM(", "else: input_norm = inputs mask = mask.unsqueeze(1) context = self.self_attn(input_norm, input_norm, input_norm, mask=mask)", "as nn from models.neural import MultiHeadedAttention, PositionwiseFeedForward from models.rnn import LayerNormLSTM class Classifier(nn.Module):", "top_vecs, inputs, mask, label_mask=None): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" n_out = inputs.size(1) pos_emb = self.pos_emb.pe[:,", "2, dtype=torch.float) * -(math.log(10000.0) / dim))) pe[:, 0::2] = torch.sin(position.float() * div_term) pe[:,", ":func:`EncoderBase.forward()`\"\"\" batch, layer, seq, hidden = x.size() x1=x.contiguous().view(batch * layer, -1, hidden) x1", "-(math.log(10000.0) / dim))) pe[:, 0::2] = torch.sin(position.float() * div_term) pe[:, 1::2] = torch.cos(position.float()", "self.out_channel=out_channel self.hidden_dim=hidden_dim self.dropout = nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 # self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) # self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 # self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2", "torch.exp((torch.arange(0, dim, 2, dtype=torch.float) * -(math.log(10000.0) / dim))) pe[:, 0::2] = torch.sin(position.float() *", "super(Classifier, self).__init__() self.linear1 = nn.Linear(hidden_size, 1) self.sigmoid = nn.Sigmoid() def forward(self, x, mask_cls):", "self.rnn(x1) memory_bank = self.dropout(memory_bank) + x1 memory_bank = torch.transpose(memory_bank, 1, 0) # sent_scores", "= torch.sin(position.float() * div_term) pe[:, 1::2] = torch.cos(position.float() * div_term) pe = pe.unsqueeze(0)", "= torch.arange(0, max_len).unsqueeze(1) div_term = torch.exp((torch.arange(0, dim, 2, dtype=torch.float) * -(math.log(10000.0) / dim)))", "emb = emb * math.sqrt(self.dim) if (step): emb = emb + self.pe[:, step][:,", "__init__(self, d_model, d_ff, heads, dropout, num_inter_layers=0): super(TransformerInterEncoder, self).__init__() self.d_model = d_model self.num_inter_layers =", "= self.feed_forward(dec_output) return dec_output class TransformerInterDecoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout, d_hidden,", "else 1 assert hidden_size % num_directions == 0 hidden_size = hidden_size // num_directions", "PositionwiseFeedForward from models.rnn import LayerNormLSTM class Classifier(nn.Module): def __init__(self, hidden_size): super(Classifier, self).__init__() self.linear1", "return dec_output class TransformerInterDecoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout, d_hidden, num_inter_layers=0): super(TransformerInterDecoder,", "inputs, mask=self_attn_mask) dec_output = self.self_attn( ent_enc, ent_enc, context, mask=context_attn_mask) dec_output = self.feed_forward(dec_output) return", "PositionalEncoding(nn.Module): def __init__(self, dropout, dim, max_len=5000): pe = torch.zeros(max_len, dim) position = torch.arange(0,", "input_size, hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__() class RNNEncoder_attn(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder_attn,", "is dropout',dropout) def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" batch, layer, seq, hidden =", "mask): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" batch_size, n_sents = top_vecs.size(0), top_vecs.size(1) pos_emb = self.pos_emb.pe[:, :n_sents]", "= PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) def forward(self, iter, ent_enc, inputs,", "self.num_inter_layers = num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerEncoderLayer(d_model, heads, d_ff,", "= nn.ModuleList( [TransformerDecoderLayer(d_model, heads, d_ff, dropout) for _ in range(num_inter_layers)]) self.dropout = nn.Dropout(dropout)", "emb = self.dropout(emb) return emb def get_emb(self, emb): return self.pe[:, :emb.size(1)] class TransformerEncoderLayer(nn.Module):", "from models.rnn import LayerNormLSTM class Classifier(nn.Module): def __init__(self, hidden_size): super(Classifier, self).__init__() self.linear1 =", "= nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 # self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) # self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 # self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True) def forward(self,", "pos_emb = self.pos_emb.pe[:, :n_sents] x = top_vecs * mask[:, :, None].float() x =", "mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" batch, layer, seq, hidden = x.size() x1=x.contiguous().view(batch * layer, -1,", "x2 = self.relu(x2) # x2 = self.dropout(x2) # mix = self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2, edge_weight_2)", "self.dropout(x2) # mix = self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2, edge_weight_2) # x2 = self.gcn_x_22(mix, edge_index_2, edge_weight_2)", "self.wo = nn.Linear(d_model, d_hidden , bias=True) self.wi = nn.Linear(d_model, d_hidden, bias=True) self.v =", "mask.unsqueeze(1).expand(-1, n_out,-1)) scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1, -1, top_vecs.size(1), -1) + self.wi(top_vecs).unsqueeze( 1))).squeeze(-1) sent_scores = self.softmax(scores)", "0) inputs=inputs+pos_emb for i in range(self.num_inter_layers): inputs = self.transformer_inter[i](i, top_vecs, inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1, n_out,-1))", "self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 # self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) # self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 # self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True) def forward(self, x_1, edge_index_1,", "x + pos_emb for i in range(self.num_inter_layers): x = self.transformer_inter[i](i, x, x, ~mask)", "bidirectional=bidirectional) self.wo = nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.softmax =", "self.softmax = nn.Softmax() print('this is dropout',dropout) def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" batch,", "def __init__(self, hidden_size): super(Classifier, self).__init__() self.linear1 = nn.Linear(hidden_size, 1) self.sigmoid = nn.Sigmoid() def", "scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1, -1, top_vecs.size(1), -1) + self.wi(top_vecs).unsqueeze( 1))).squeeze(-1) sent_scores = self.softmax(scores) return sent_scores", "emb def get_emb(self, emb): return self.pe[:, :emb.size(1)] class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, heads,", "self.linear1 = nn.Linear(hidden_size, 1) self.sigmoid = nn.Sigmoid() def forward(self, x, mask_cls): h =", "x = x + pos_emb for i in range(self.num_inter_layers): x = self.transformer_inter[i](i, x,", "import torch import torch.nn as nn from models.neural import MultiHeadedAttention, PositionwiseFeedForward from models.rnn", "self.dropout = nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, 1, bias=True) self.sigmoid", "= top_vecs.size(0), top_vecs.size(1) pos_emb = self.pos_emb.pe[:, :n_sents] x = top_vecs * mask[:, :,", "return sent_vec.squeeze(dim = 2) class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout): super(TransformerDecoderLayer,", "1, 0) # sent_scores = self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores = self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2) sent_vec = torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim", "ent_enc, inputs, self_attn_mask=None,context_attn_mask=None): context = self.self_attn(inputs, inputs, inputs, mask=self_attn_mask) dec_output = self.self_attn( ent_enc,", "dec_output class TransformerInterDecoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout, d_hidden, num_inter_layers=0): super(TransformerInterDecoder, self).__init__()", "all_sents * max_tokens * dim x = self.layer_norm(x) sent_scores = self.sigmoid(self.wo(x)) sent_scores =", "# sent_scores = self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores = self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2) sent_vec = torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim = 1).expand(batch,seq,1,layer),x)", "top_vecs, mask): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" batch_size, n_sents = top_vecs.size(0), top_vecs.size(1) pos_emb = self.pos_emb.pe[:,", "forward(self, x_1, edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1, edge_index_1, edge_weight_1) syn=self.relu(syn) syn=self.dropout(syn) syn = self.gcn_x_12(syn, edge_index_1,", "self.dropout = nn.Dropout(dropout) self.sigmoid = nn.Sigmoid() def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" x", "self.feed_forward(out) class TransformerInterEncoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout, num_inter_layers=0): super(TransformerInterEncoder, self).__init__() self.d_model", "= self.gcn_x_22(mix, edge_index_2, edge_weight_2) # syn=self.gcn_x_12(mix, edge_index_1, edge_weight_1) # syn=self.relu(syn) # syn=self.dropout(syn) #" ]
[ "= \"https\" def complete_login(self, request, app, token, **kwargs): response = requests.post( self.profile_url, headers={\"Authorization\":", "= \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol = \"https\" def complete_login(self, request, app, token, **kwargs): response =", "token, **kwargs): response = requests.post( self.profile_url, headers={\"Authorization\": \"Bearer %s\" % (token.token,)}, ) response.raise_for_status()", "DropboxOAuth2Provider.id access_token_url = \"https://api.dropbox.com/oauth2/token\" authorize_url = \"https://www.dropbox.com/oauth2/authorize\" profile_url = \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol = \"https\"", "from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import DropboxOAuth2Provider class", "complete_login(self, request, app, token, **kwargs): response = requests.post( self.profile_url, headers={\"Authorization\": \"Bearer %s\" %", "DropboxOAuth2Adapter(OAuth2Adapter): provider_id = DropboxOAuth2Provider.id access_token_url = \"https://api.dropbox.com/oauth2/token\" authorize_url = \"https://www.dropbox.com/oauth2/authorize\" profile_url = \"https://api.dropbox.com/2/users/get_current_account\"", "OAuth2LoginView, ) from .provider import DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter): provider_id = DropboxOAuth2Provider.id access_token_url =", "%s\" % (token.token,)}, ) response.raise_for_status() return self.get_provider().sociallogin_from_response(request, response.json()) oauth_login = OAuth2LoginView.adapter_view(DropboxOAuth2Adapter) oauth_callback =", "requests.post( self.profile_url, headers={\"Authorization\": \"Bearer %s\" % (token.token,)}, ) response.raise_for_status() return self.get_provider().sociallogin_from_response(request, response.json()) oauth_login", "% (token.token,)}, ) response.raise_for_status() return self.get_provider().sociallogin_from_response(request, response.json()) oauth_login = OAuth2LoginView.adapter_view(DropboxOAuth2Adapter) oauth_callback = OAuth2CallbackView.adapter_view(DropboxOAuth2Adapter)", "\"https\" def complete_login(self, request, app, token, **kwargs): response = requests.post( self.profile_url, headers={\"Authorization\": \"Bearer", "DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter): provider_id = DropboxOAuth2Provider.id access_token_url = \"https://api.dropbox.com/oauth2/token\" authorize_url = \"https://www.dropbox.com/oauth2/authorize\" profile_url", "OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter): provider_id = DropboxOAuth2Provider.id", "self.profile_url, headers={\"Authorization\": \"Bearer %s\" % (token.token,)}, ) response.raise_for_status() return self.get_provider().sociallogin_from_response(request, response.json()) oauth_login =", "= requests.post( self.profile_url, headers={\"Authorization\": \"Bearer %s\" % (token.token,)}, ) response.raise_for_status() return self.get_provider().sociallogin_from_response(request, response.json())", "**kwargs): response = requests.post( self.profile_url, headers={\"Authorization\": \"Bearer %s\" % (token.token,)}, ) response.raise_for_status() return", "redirect_uri_protocol = \"https\" def complete_login(self, request, app, token, **kwargs): response = requests.post( self.profile_url,", "headers={\"Authorization\": \"Bearer %s\" % (token.token,)}, ) response.raise_for_status() return self.get_provider().sociallogin_from_response(request, response.json()) oauth_login = OAuth2LoginView.adapter_view(DropboxOAuth2Adapter)", "( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter): provider_id =", "request, app, token, **kwargs): response = requests.post( self.profile_url, headers={\"Authorization\": \"Bearer %s\" % (token.token,)},", "requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import DropboxOAuth2Provider", "import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter): provider_id", "provider_id = DropboxOAuth2Provider.id access_token_url = \"https://api.dropbox.com/oauth2/token\" authorize_url = \"https://www.dropbox.com/oauth2/authorize\" profile_url = \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol", ".provider import DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter): provider_id = DropboxOAuth2Provider.id access_token_url = \"https://api.dropbox.com/oauth2/token\" authorize_url =", "allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter):", "\"https://api.dropbox.com/oauth2/token\" authorize_url = \"https://www.dropbox.com/oauth2/authorize\" profile_url = \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol = \"https\" def complete_login(self, request,", "profile_url = \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol = \"https\" def complete_login(self, request, app, token, **kwargs): response", "app, token, **kwargs): response = requests.post( self.profile_url, headers={\"Authorization\": \"Bearer %s\" % (token.token,)}, )", "class DropboxOAuth2Adapter(OAuth2Adapter): provider_id = DropboxOAuth2Provider.id access_token_url = \"https://api.dropbox.com/oauth2/token\" authorize_url = \"https://www.dropbox.com/oauth2/authorize\" profile_url =", "= DropboxOAuth2Provider.id access_token_url = \"https://api.dropbox.com/oauth2/token\" authorize_url = \"https://www.dropbox.com/oauth2/authorize\" profile_url = \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol =", "response = requests.post( self.profile_url, headers={\"Authorization\": \"Bearer %s\" % (token.token,)}, ) response.raise_for_status() return self.get_provider().sociallogin_from_response(request,", "import DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter): provider_id = DropboxOAuth2Provider.id access_token_url = \"https://api.dropbox.com/oauth2/token\" authorize_url = \"https://www.dropbox.com/oauth2/authorize\"", "import requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import", "\"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol = \"https\" def complete_login(self, request, app, token, **kwargs): response = requests.post(", "access_token_url = \"https://api.dropbox.com/oauth2/token\" authorize_url = \"https://www.dropbox.com/oauth2/authorize\" profile_url = \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol = \"https\" def", "authorize_url = \"https://www.dropbox.com/oauth2/authorize\" profile_url = \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol = \"https\" def complete_login(self, request, app,", "\"https://www.dropbox.com/oauth2/authorize\" profile_url = \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol = \"https\" def complete_login(self, request, app, token, **kwargs):", "\"Bearer %s\" % (token.token,)}, ) response.raise_for_status() return self.get_provider().sociallogin_from_response(request, response.json()) oauth_login = OAuth2LoginView.adapter_view(DropboxOAuth2Adapter) oauth_callback", "= \"https://www.dropbox.com/oauth2/authorize\" profile_url = \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol = \"https\" def complete_login(self, request, app, token,", "OAuth2CallbackView, OAuth2LoginView, ) from .provider import DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter): provider_id = DropboxOAuth2Provider.id access_token_url", "from .provider import DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter): provider_id = DropboxOAuth2Provider.id access_token_url = \"https://api.dropbox.com/oauth2/token\" authorize_url", "= \"https://api.dropbox.com/oauth2/token\" authorize_url = \"https://www.dropbox.com/oauth2/authorize\" profile_url = \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol = \"https\" def complete_login(self,", "def complete_login(self, request, app, token, **kwargs): response = requests.post( self.profile_url, headers={\"Authorization\": \"Bearer %s\"", ") from .provider import DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter): provider_id = DropboxOAuth2Provider.id access_token_url = \"https://api.dropbox.com/oauth2/token\"" ]
[ "= '1.2.7' # The full version, including alpha/beta/rc tags release = f'v{version}' #", "tags release = f'v{version}' # endregion # region General configuration # Add any", "sys.path.insert(0, os.path.abspath('..')) # endregion # region Project information project = 'Upkeep' copyright =", "contain templates here, relative to this directory. templates_path = ['_templates'] # List of", "output # The theme to use for HTML and HTML Help pages. See", "for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns: Sequence[str]", "# so a file named \"default.css\" will overwrite the builtin \"default.css\". html_static_path =", "= [] master_doc = 'index' # endregion # region Options for HTML output", "exclude_patterns: Sequence[str] = [] master_doc = 'index' # endregion # region Options for", "['_templates'] # List of patterns, relative to source directory, that match files and", "directory. templates_path = ['_templates'] # List of patterns, relative to source directory, that", "'<NAME>' # The short X.Y version version = '1.2.7' # The full version,", "overwrite the builtin \"default.css\". html_static_path = ['_static'] # endregion # region Extension configuration", "author = '<NAME>' # The short X.Y version version = '1.2.7' # The", "templates here, relative to this directory. templates_path = ['_templates'] # List of patterns,", "so a file named \"default.css\" will overwrite the builtin \"default.css\". html_static_path = ['_static']", "region Path setup sys.path.insert(0, os.path.abspath('..')) # endregion # region Project information project =", "# The short X.Y version version = '1.2.7' # The full version, including", "file named \"default.css\" will overwrite the builtin \"default.css\". html_static_path = ['_static'] # endregion", "Add any paths that contain templates here, relative to this directory. templates_path =", "files and # directories to ignore when looking for source files. # This", "theme to use for HTML and HTML Help pages. See the documentation for", "patterns, relative to source directory, that match files and # directories to ignore", "directory. They are copied after the builtin static files, # so a file", "from typing import Sequence import os import sys # region Path setup sys.path.insert(0,", "version = '1.2.7' # The full version, including alpha/beta/rc tags release = f'v{version}'", "any paths that contain custom static files (such as style sheets) here, #", "['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] # Add any paths that contain templates here, relative to this", "endregion # region Project information project = 'Upkeep' copyright = '2020, <NAME>' author", "also affects html_static_path and html_extra_path. exclude_patterns: Sequence[str] = [] master_doc = 'index' #", "any paths that contain templates here, relative to this directory. templates_path = ['_templates']", "files (such as style sheets) here, # relative to this directory. They are", "= '<NAME>' # The short X.Y version version = '1.2.7' # The full", "be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones.", "typing import Sequence import os import sys # region Path setup sys.path.insert(0, os.path.abspath('..'))", "here, # relative to this directory. They are copied after the builtin static", "# List of patterns, relative to source directory, that match files and #", "relative to this directory. templates_path = ['_templates'] # List of patterns, relative to", "'alabaster' # Add any paths that contain custom static files (such as style", "# a list of builtin themes. html_theme = 'alabaster' # Add any paths", "static files (such as style sheets) here, # relative to this directory. They", "contain custom static files (such as style sheets) here, # relative to this", "after the builtin static files, # so a file named \"default.css\" will overwrite", "List of patterns, relative to source directory, that match files and # directories", "copyright = '2020, <NAME>' author = '<NAME>' # The short X.Y version version", "names here, as strings. They can be # extensions coming with Sphinx (named", "'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] # Add any", "\"\"\"See https://www.sphinx-doc.org/en/master/usage/configuration.html\"\"\" from typing import Sequence import os import sys # region Path", "https://www.sphinx-doc.org/en/master/usage/configuration.html\"\"\" from typing import Sequence import os import sys # region Path setup", "project = 'Upkeep' copyright = '2020, <NAME>' author = '<NAME>' # The short", "relative to this directory. They are copied after the builtin static files, #", "# region Options for HTML output # The theme to use for HTML", "Path setup sys.path.insert(0, os.path.abspath('..')) # endregion # region Project information project = 'Upkeep'", "[] master_doc = 'index' # endregion # region Options for HTML output #", "that contain templates here, relative to this directory. templates_path = ['_templates'] # List", "Sequence[str] = [] master_doc = 'index' # endregion # region Options for HTML", "a file named \"default.css\" will overwrite the builtin \"default.css\". html_static_path = ['_static'] #", "import Sequence import os import sys # region Path setup sys.path.insert(0, os.path.abspath('..')) #", "master_doc = 'index' # endregion # region Options for HTML output # The", "are copied after the builtin static files, # so a file named \"default.css\"", "# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions", "configuration # Add any Sphinx extension module names here, as strings. They can", "to this directory. They are copied after the builtin static files, # so", "General configuration # Add any Sphinx extension module names here, as strings. They", "match files and # directories to ignore when looking for source files. #", "style sheets) here, # relative to this directory. They are copied after the", "version, including alpha/beta/rc tags release = f'v{version}' # endregion # region General configuration", "endregion # region General configuration # Add any Sphinx extension module names here,", "any Sphinx extension module names here, as strings. They can be # extensions", "directories to ignore when looking for source files. # This pattern also affects", "# The theme to use for HTML and HTML Help pages. See the", "(named 'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] # Add", "# Add any Sphinx extension module names here, as strings. They can be", "# region Path setup sys.path.insert(0, os.path.abspath('..')) # endregion # region Project information project", "setup sys.path.insert(0, os.path.abspath('..')) # endregion # region Project information project = 'Upkeep' copyright", "directory, that match files and # directories to ignore when looking for source", "region Options for HTML output # The theme to use for HTML and", "HTML Help pages. See the documentation for # a list of builtin themes.", "Sphinx extension module names here, as strings. They can be # extensions coming", "or your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] # Add any paths", "version version = '1.2.7' # The full version, including alpha/beta/rc tags release =", "= 'alabaster' # Add any paths that contain custom static files (such as", "can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom #", "Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] #", "Sequence import os import sys # region Path setup sys.path.insert(0, os.path.abspath('..')) # endregion", "# pylint: disable=redefined-builtin,invalid-name \"\"\"See https://www.sphinx-doc.org/en/master/usage/configuration.html\"\"\" from typing import Sequence import os import sys", "# The full version, including alpha/beta/rc tags release = f'v{version}' # endregion #", "paths that contain templates here, relative to this directory. templates_path = ['_templates'] #", "They are copied after the builtin static files, # so a file named", "'Upkeep' copyright = '2020, <NAME>' author = '<NAME>' # The short X.Y version", "of patterns, relative to source directory, that match files and # directories to", "This pattern also affects html_static_path and html_extra_path. exclude_patterns: Sequence[str] = [] master_doc =", "as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or", "pages. See the documentation for # a list of builtin themes. html_theme =", "module names here, as strings. They can be # extensions coming with Sphinx", "to source directory, that match files and # directories to ignore when looking", "for HTML output # The theme to use for HTML and HTML Help", "html_theme = 'alabaster' # Add any paths that contain custom static files (such", "for # a list of builtin themes. html_theme = 'alabaster' # Add any", "alpha/beta/rc tags release = f'v{version}' # endregion # region General configuration # Add", "os.path.abspath('..')) # endregion # region Project information project = 'Upkeep' copyright = '2020,", "here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*')", "builtin \"default.css\". html_static_path = ['_static'] # endregion # region Extension configuration # endregion", "to ignore when looking for source files. # This pattern also affects html_static_path", "MIT # pylint: disable=redefined-builtin,invalid-name \"\"\"See https://www.sphinx-doc.org/en/master/usage/configuration.html\"\"\" from typing import Sequence import os import", "X.Y version version = '1.2.7' # The full version, including alpha/beta/rc tags release", "import os import sys # region Path setup sys.path.insert(0, os.path.abspath('..')) # endregion #", "that contain custom static files (such as style sheets) here, # relative to", "with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon']", "Help pages. See the documentation for # a list of builtin themes. html_theme", "# SPDX-License-Identifier: MIT # pylint: disable=redefined-builtin,invalid-name \"\"\"See https://www.sphinx-doc.org/en/master/usage/configuration.html\"\"\" from typing import Sequence import", "list of builtin themes. html_theme = 'alabaster' # Add any paths that contain", "HTML and HTML Help pages. See the documentation for # a list of", "(such as style sheets) here, # relative to this directory. They are copied", "will overwrite the builtin \"default.css\". html_static_path = ['_static'] # endregion # region Extension", "disable=redefined-builtin,invalid-name \"\"\"See https://www.sphinx-doc.org/en/master/usage/configuration.html\"\"\" from typing import Sequence import os import sys # region", "when looking for source files. # This pattern also affects html_static_path and html_extra_path.", "# Add any paths that contain templates here, relative to this directory. templates_path", "region General configuration # Add any Sphinx extension module names here, as strings.", "= 'index' # endregion # region Options for HTML output # The theme", "html_extra_path. exclude_patterns: Sequence[str] = [] master_doc = 'index' # endregion # region Options", "for HTML and HTML Help pages. See the documentation for # a list", "Add any paths that contain custom static files (such as style sheets) here,", "'1.2.7' # The full version, including alpha/beta/rc tags release = f'v{version}' # endregion", "extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] # Add any paths that contain templates here, relative", "custom static files (such as style sheets) here, # relative to this directory.", "builtin static files, # so a file named \"default.css\" will overwrite the builtin", "HTML output # The theme to use for HTML and HTML Help pages.", "= '2020, <NAME>' author = '<NAME>' # The short X.Y version version =", "your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] # Add any paths that", "# endregion # region Project information project = 'Upkeep' copyright = '2020, <NAME>'", "= ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] # Add any paths that contain templates here, relative to", "relative to source directory, that match files and # directories to ignore when", "pattern also affects html_static_path and html_extra_path. exclude_patterns: Sequence[str] = [] master_doc = 'index'", "static files, # so a file named \"default.css\" will overwrite the builtin \"default.css\".", "See the documentation for # a list of builtin themes. html_theme = 'alabaster'", "the builtin static files, # so a file named \"default.css\" will overwrite the", "short X.Y version version = '1.2.7' # The full version, including alpha/beta/rc tags", "Options for HTML output # The theme to use for HTML and HTML", "# endregion # region General configuration # Add any Sphinx extension module names", "'index' # endregion # region Options for HTML output # The theme to", "use for HTML and HTML Help pages. See the documentation for # a", "ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] # Add any paths that contain templates here,", "builtin themes. html_theme = 'alabaster' # Add any paths that contain custom static", "# ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] # Add any paths that contain templates", "the documentation for # a list of builtin themes. html_theme = 'alabaster' #", "release = f'v{version}' # endregion # region General configuration # Add any Sphinx", "of builtin themes. html_theme = 'alabaster' # Add any paths that contain custom", "'sphinx.ext.napoleon'] # Add any paths that contain templates here, relative to this directory.", "custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] # Add any paths that contain", "source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns: Sequence[str] =", "to this directory. templates_path = ['_templates'] # List of patterns, relative to source", "themes. html_theme = 'alabaster' # Add any paths that contain custom static files", "The short X.Y version version = '1.2.7' # The full version, including alpha/beta/rc", "The theme to use for HTML and HTML Help pages. See the documentation", "sheets) here, # relative to this directory. They are copied after the builtin", "and # directories to ignore when looking for source files. # This pattern", "that match files and # directories to ignore when looking for source files.", "and HTML Help pages. See the documentation for # a list of builtin", "'2020, <NAME>' author = '<NAME>' # The short X.Y version version = '1.2.7'", "# Add any paths that contain custom static files (such as style sheets)", "html_static_path and html_extra_path. exclude_patterns: Sequence[str] = [] master_doc = 'index' # endregion #", "templates_path = ['_templates'] # List of patterns, relative to source directory, that match", "endregion # region Options for HTML output # The theme to use for", "f'v{version}' # endregion # region General configuration # Add any Sphinx extension module", "strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your", "coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.autodoc',", "\"default.css\" will overwrite the builtin \"default.css\". html_static_path = ['_static'] # endregion # region", "copied after the builtin static files, # so a file named \"default.css\" will", "# relative to this directory. They are copied after the builtin static files,", "import sys # region Path setup sys.path.insert(0, os.path.abspath('..')) # endregion # region Project", "# directories to ignore when looking for source files. # This pattern also", "looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns:", "named \"default.css\" will overwrite the builtin \"default.css\". html_static_path = ['_static'] # endregion #", "SPDX-License-Identifier: MIT # pylint: disable=redefined-builtin,invalid-name \"\"\"See https://www.sphinx-doc.org/en/master/usage/configuration.html\"\"\" from typing import Sequence import os", "# endregion # region Options for HTML output # The theme to use", "# region Project information project = 'Upkeep' copyright = '2020, <NAME>' author =", "this directory. They are copied after the builtin static files, # so a", "# This pattern also affects html_static_path and html_extra_path. exclude_patterns: Sequence[str] = [] master_doc", "region Project information project = 'Upkeep' copyright = '2020, <NAME>' author = '<NAME>'", "extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions =", "They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom", "this directory. templates_path = ['_templates'] # List of patterns, relative to source directory,", "and html_extra_path. exclude_patterns: Sequence[str] = [] master_doc = 'index' # endregion # region", "full version, including alpha/beta/rc tags release = f'v{version}' # endregion # region General", "a list of builtin themes. html_theme = 'alabaster' # Add any paths that", "extension module names here, as strings. They can be # extensions coming with", "ignore when looking for source files. # This pattern also affects html_static_path and", "paths that contain custom static files (such as style sheets) here, # relative", "pylint: disable=redefined-builtin,invalid-name \"\"\"See https://www.sphinx-doc.org/en/master/usage/configuration.html\"\"\" from typing import Sequence import os import sys #", "<NAME>' author = '<NAME>' # The short X.Y version version = '1.2.7' #", "os import sys # region Path setup sys.path.insert(0, os.path.abspath('..')) # endregion # region", "= 'Upkeep' copyright = '2020, <NAME>' author = '<NAME>' # The short X.Y", "# region General configuration # Add any Sphinx extension module names here, as", "= ['_templates'] # List of patterns, relative to source directory, that match files", "here, relative to this directory. templates_path = ['_templates'] # List of patterns, relative", "as style sheets) here, # relative to this directory. They are copied after", "sys # region Path setup sys.path.insert(0, os.path.abspath('..')) # endregion # region Project information", "information project = 'Upkeep' copyright = '2020, <NAME>' author = '<NAME>' # The", "the builtin \"default.css\". html_static_path = ['_static'] # endregion # region Extension configuration #", "including alpha/beta/rc tags release = f'v{version}' # endregion # region General configuration #", "= f'v{version}' # endregion # region General configuration # Add any Sphinx extension", "files, # so a file named \"default.css\" will overwrite the builtin \"default.css\". html_static_path", "documentation for # a list of builtin themes. html_theme = 'alabaster' # Add", "The full version, including alpha/beta/rc tags release = f'v{version}' # endregion # region", "Project information project = 'Upkeep' copyright = '2020, <NAME>' author = '<NAME>' #", "source directory, that match files and # directories to ignore when looking for", "files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns: Sequence[str] = []", "to use for HTML and HTML Help pages. See the documentation for #", "Add any Sphinx extension module names here, as strings. They can be #", "affects html_static_path and html_extra_path. exclude_patterns: Sequence[str] = [] master_doc = 'index' # endregion" ]
[ "variables def get_enums(header): enums = [e for e in header.enums if e.get(\"name\")] #", "return enums def read_header(header_path, skip_macros=None): # I tried to do this in multiple", "main_classes[(module, header)] methods_defined_outside = get_methods_defined_outside(header_functions) class_definitions = generate_class_definitions(header_classes, module, header, path, methods_need_overloading.get(module), methods_defined_outside)", "#skip_modules = [\"visualization\"] skip_modules = [] all_headers = get_headers(skip_modules=skip_modules) not_every_point_type = \"--not-every-point-type\" in", "module, \"pcl::%s::\" % module)] functions = sorted(functions, key=lambda f: f[\"name\"]) filtered = filter_module_level_functions(functions)", "header_name, path in headers_to_generate: if (module, header_name) in HEADERS_TO_SKIP: continue headers_to_generate_temp.append(tuple([module, header_name, path]))", "module, header_name + \"pp\") files_to_write[output_path] = text # loaders loader_modules = defaultdict(list) for", "class_ in main_classes: methods = class_[\"methods\"][\"public\"] methods = filter_methods_for_parser_errors(methods) methods = filter_methods_to_skip(methods) private_and_protected", "base_class: base_class_methods = get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if", "== 1 boost_function = single_argument and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if not boost_function: continue filtered_methods.append(m) return", "return variables def get_enums(header): enums = [e for e in header.enums if e.get(\"name\")]", "method is not implemented all_implemented_inherited_methods = get_all_class_methods_not_pure_virtual(class_) namespace_class = make_namespace_class(class_[\"namespace\"], class_[\"name\"]) for base_name_nsp", "text.append a(common_includes) a(EXPLICIT_INCLUDES.get((module, header_name), \"\")) a(make_header_include_name(module, header_name, path)) a(\"\") namespaces = set([c[\"namespace\"] for", "in m2[\"parameters\"]: if m1[\"name\"] == m2[\"name\"] and same_parameters(p1, p2): break else: return False", "path in headers_to_generate: if (module, header_name) in HEADERS_TO_SKIP: continue headers_to_generate_temp.append(tuple([module, header_name, path])) return", "p in nested_class[\"properties\"][\"public\"] if \"union\" in nested_class[\"name\"]] class_properties += union_properties class_properties = filter_class_properties(module,", "if same_methods(m_private, m_outside): private_defined_outside.append(m_private) break return private_defined_outside def generate_class_definitions(main_classes, module, header_name, path, needs_overloading:", "{} for module, header_name, path in headers_to_generate[:]: header_full_path = join(PCL_BASE, path) if path", "class_.get(\"template\") and \"<\" in class_[\"name\"] if specialized_template: to_skip = any((\"<%s>\" % type_) in", "delete_others: os.remove(path) print(\"Deleted: \" + path) # write new files for path, text", "c in header.classes.values() if c[\"namespace\"] in (\"pcl\", \"pcl::\" + module)] filtered_main_classes = []", "filter_methods_for_parser_errors(methods) methods = filter_methods_to_skip(methods) private_and_protected = class_[\"methods\"][\"private\"] + class_[\"methods\"][\"protected\"] methods += private_methods_defined_outside(private_and_protected, methods_defined_outside)", "-> OrderedDict: \"\"\" :return: OrderedDict \"\"\" main_classes, module_functions, module_variables, module_enums = {}, {},", "in class_[\"methods\"][a] if not m[\"pure_virtual\"]]) def flag_instantiatable_class(dependency_tree, main_classes): \"\"\"determine if the class can", "continue relative_base = os.path.abspath(base).replace(PCL_BASE, \"\")[1:] for f in files: if f.endswith(\".h\"): found_modules.append([f, join(relative_base,", "if f.get(\"returns_const\"): keep = False for param in f[\"parameters\"]: for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP:", "CppHeaderParser is not thread safe... if skip_macros is None: skip_macros = [] header_file_str", "for e in header.enums if e.get(\"name\")] # skip nameless enums enums = sorted(enums,", "in CLASSES_TO_IGNORE: pass else: filtered_main_classes.append(class_) filtered_main_classes = sorted(filtered_main_classes, key=lambda c: c[\"name\"]) return filtered_main_classes", "in HEADERS_TO_SKIP: continue headers_to_generate_temp.append(tuple([module, header_name, path])) return headers_to_generate_temp def get_pure_virtual_methods(class_: CppHeaderParser.CppClass) -> Set[str]:", "ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE, METHODS_TO_SKIP, SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES, \\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from generators.definitions.function import generate_function_definitions, get_methods_defined_outside from", "ImageGrabber<PointT>::\" is the return type path = m1.get(\"path\", m2.get(\"path\")) path = path[path.rfind(\":\") +", "v in extra_point_types.items(): if k in classes_point_types: classes_point_types[k].append(v) else: classes_point_types[k] = v return", "set(module for module, _ in generated_headers.keys()) make_module_dirs(modules) # hpp files_to_write = {} for", "needs_overloading) if not class_[\"can_be_instantiated\"]: constructors = [] class_def = ClassDefinition(class_, constructors, variables, others,", "module_enums[(module, header_name)] = get_enums(header) classes = [c for module, header, path in headers_to_generate", "\"pcl::%s\" % module, \"pcl::%s::\" % module)] functions = sorted(functions, key=lambda f: f[\"name\"]) filtered", "CLASSES_TO_IGNORE, METHODS_TO_SKIP, SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES, \\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from generators.definitions.function import generate_function_definitions, get_methods_defined_outside from generators.definitions.method", "filtered_properties = [] for p in properties: if p[\"name\"] in to_ignore: continue filtered_properties.append(p)", "class_[\"methods\"][\"public\"] methods = filter_methods_for_parser_errors(methods) methods = filter_methods_to_skip(methods) private_and_protected = class_[\"methods\"][\"private\"] + class_[\"methods\"][\"protected\"] methods", "in files: path = join(base, f) if path in files_to_write: if is_file_different(path, files_to_write[path]):", "\"\"\" :return: OrderedDict \"\"\" main_classes, module_functions, module_variables, module_enums = {}, {}, {}, {}", "in %s\" print(message % (class_[\"name\"], header_name)) elif (module, header_name, class_[\"name\"]) in CLASSES_TO_IGNORE: pass", "\"\")) a(make_header_include_name(module, header_name, path)) a(\"\") namespaces = set([c[\"namespace\"] for c in main_classes]) for", "\"_%s_loader.cpp\" % module) files_to_write[path_loader] = generate_loader(module, headers) files_to_write[PATH_LOADER] = generate_main_loader(loader_modules) write_if_different(files_to_write, delete_others) if", "SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES, \\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from generators.definitions.function import generate_function_definitions, get_methods_defined_outside from generators.definitions.method import split_methods_by_type", "import ClassDefinition from generators.instantiations import Instantiations from generators.point_types_utils import unpack_yaml_point_types from generators.utils import", "\"void ImageGrabber<PointT>::\" is the return type path = m1.get(\"path\", m2.get(\"path\")) path = path[path.rfind(\":\")", "header_name, path) for module in modules for header_name, path in listmod(module)] base_headers =", "header_name + \"pp\") files_to_write[output_path] = text # loaders loader_modules = defaultdict(list) for (module,", "Dict, Set from CppHeaderParser import CppHeaderParser from CppHeaderParser.CppHeaderParser import CppMethod import generators.dependency_tree from", "something_instantiated or keep_if_no_instantiation: text = [class_definitions, function_definitions, instantiation_function] return \"\\n\".join(text) generated_headers = OrderedDict()", "not windows: skip_macros = [\"_MSC_VER\"] #skip_modules = [\"visualization\"] skip_modules = [] all_headers =", "is_file_different(path, files_to_write[path]): open(path, \"w\").write(files_to_write[path]) written.append(path) elif delete_others: os.remove(path) print(\"Deleted: \" + path) #", "list(dependency_tree.leaf_iterator()) def index_for_class(class_): return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"])) # sort classes inside modules based on", "= [] for module, header_name, path in headers_to_generate: if (module, header_name) in HEADERS_TO_SKIP:", "return filtered def get_variables(header): variables = [v for v in header.variables if v.get(\"defaultValue\")", "header_name in main_classes: for class_ in main_classes[(module, header_name)]: can_be_instantiated = True if class_[\"abstract\"]:", "generated_headers def main(): import time t = time.time() windows = platform.system() == \"Windows\"", "generate(headers_to_generate, skip_macros, not_every_point_type=False) -> OrderedDict: \"\"\" :return: OrderedDict \"\"\" main_classes, module_functions, module_variables, module_enums", "# check if any pure virtual method is not implemented all_implemented_inherited_methods = get_all_class_methods_not_pure_virtual(class_)", "class_[\"name\"])) # sort classes inside modules based on inheritance for module, header in", "= dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first = list(dependency_tree.leaf_iterator()) def index_for_class(class_): return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"])) # sort classes", "private_defined_outside = [] for m_private in private_methods: for m_outside in methods_declared_outside: if same_methods(m_private,", "= set([c[\"namespace\"] for c in main_classes]) for namespace in namespaces: if not namespace", "class_[\"abstract\"]: can_be_instantiated = False else: # check if any pure virtual method is", "class_def = ClassDefinition(class_, constructors, variables, others, module) a(class_def.to_class_function_definition()) a(\"\") return \"\\n\".join(text) def filter_class_properties(module,", "header.variables if v.get(\"defaultValue\") and 'using' != v.get('type')] variables = sorted(variables, key=lambda v: v[\"name\"])", "return filtered def filter_module_level_functions(functions: List[CppMethod]): filtered = [] for f in functions: keep", "+ module)] filtered_main_classes = [] for class_ in main_classes: specialized_template = class_.get(\"template\") and", "in header.functions if f[\"namespace\"] in (\"pcl\", \"pcl::\", \"pcl::%s\" % module, \"pcl::%s::\" % module)]", "a(\"\\n\") for class_ in main_classes: methods = class_[\"methods\"][\"public\"] methods = filter_methods_for_parser_errors(methods) methods =", "m[\"name\"]) in METHODS_TO_SKIP: continue if \"Callback\" in m[\"name\"]: single_argument = len(m[\"parameters\"]) == 1", "join(PCL_BASE, path) if path else join(PCL_BASE, module, header_name) header = read_header(header_full_path, skip_macros) main_classes[(module,", "header_name): # header = read_headers(base_path, header_name, module) main_classes = [c for c in", "\"Warning: Template class specialization not implemented for class %s in %s\" print(message %", "CppMethod, m2: CppMethod) -> bool: if m1[\"name\"] != m2[\"name\"]: return False # bug", "inside modules based on inheritance for module, header in main_classes: main_classes[(module, header)] =", "if m not in skip_modules] headers_to_generate = [(module, header_name, path) for module in", "Dict) -> bool: fields = [\"constant\", \"name\", \"raw_type\", \"reference\", \"static\"] return all(p1[f] ==", "return needs_overloading def get_headers(modules=None, skip_modules=None): def listmod(module): found_modules = [] for base, folders,", "for class_ in main_classes: methods = class_[\"methods\"][\"public\"] methods = filter_methods_for_parser_errors(methods) methods = filter_methods_to_skip(methods)", "m in class_[\"methods\"][a] if not m[\"pure_virtual\"]]) def flag_instantiatable_class(dependency_tree, main_classes): \"\"\"determine if the class", "OrderedDict from os.path import join from typing import List, Dict, Set from CppHeaderParser", "protected public\".split() return set([m[\"name\"] for a in access for m in class_[\"methods\"][a] if", "import shutil import sys from collections import Counter from collections import defaultdict, OrderedDict", "in main_classes[(module, header_name)]: can_be_instantiated = True if class_[\"abstract\"]: can_be_instantiated = False else: #", "skip_macros = [] skip_modules = [] if not windows: skip_macros = [\"_MSC_VER\"] #skip_modules", "not_every_point_type=not_every_point_type) instantiations = Instantiations(header_classes, module, header, classes_point_types, module_variables[(module, header)], module_enums[(module, header)], ) instantiation_function", "= any((\"<%s>\" % type_) in class_[\"name\"] for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if not to_skip:", "methods if not m[\"name\"] in (\"void\", \"bool\")] def filter_methods_to_skip(methods): filtered_methods = [] for", "[] a = text.append a(common_includes) a(EXPLICIT_INCLUDES.get((module, header_name), \"\")) a(make_header_include_name(module, header_name, path)) a(\"\") namespaces", "(module, header, class_name) # ignore properties without a name properties = [p for", "PATH_LOADER, PATH_MODULES, MODULES_TO_BUILD, \\ HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE, METHODS_TO_SKIP, SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES, \\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from", "\\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from generators.definitions.function import generate_function_definitions, get_methods_defined_outside from generators.definitions.method import split_methods_by_type from generators.definitions.submodule_loader", "return private_defined_outside def generate_class_definitions(main_classes, module, header_name, path, needs_overloading: List[str], methods_defined_outside: List[CppMethod]) -> str:", "= [p for nested_class in class_[\"nested_classes\"] for p in nested_class[\"properties\"][\"public\"] if \"union\" in", "folder = join(PATH_MODULES, f) if f not in modules and os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True)", "list(sorted(main_classes[(module, header)], key=index_for_class)) headers_to_generate = sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros) methods_need_overloading = check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree, main_classes) def", "argType=\"string\") return header def clean(): try: os.remove(PATH_LOADER) except FileNotFoundError: pass if os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES)", "== m2[\"name\"] and same_parameters(p1, p2): break else: return False return len(m1[\"parameters\"]) == len(m2[\"parameters\"])", "= v return classes_point_types def make_module_dirs(modules): for module in modules: module_dir = join(PATH_MODULES,", "if not os.path.exists(module_dir): os.makedirs(module_dir) def is_file_different(path, text): v = open(path).read() if v !=", "= generate(all_headers, skip_macros, not_every_point_type) write_stuff_if_needed(generated_headers, delete_others=True) print(\"generated in %.2f s\" % (time.time() -", "= get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class and", "parser = CppHeaderParser parser.debug = False header = parser.CppHeader(header_file_str, argType=\"string\") return header def", "m1[\"name\"] == m2[\"name\"] and same_parameters(p1, p2): break else: return False return len(m1[\"parameters\"]) ==", "t = time.time() windows = platform.system() == \"Windows\" skip_macros = [] skip_modules =", "import List, Dict, Set from CppHeaderParser import CppHeaderParser from CppHeaderParser.CppHeaderParser import CppMethod import", "= False header = parser.CppHeader(header_file_str, argType=\"string\") return header def clean(): try: os.remove(PATH_LOADER) except", "MODULES_TO_BUILD, \\ HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE, METHODS_TO_SKIP, SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES, \\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from generators.definitions.function import", "get_headers(modules=None, skip_modules=None): def listmod(module): found_modules = [] for base, folders, files in os.walk(join(PCL_BASE,", "write_if_different(files_to_write, delete_others): written = [] for base, folder, files in os.walk(PATH_MODULES): for f", "header)] = list(sorted(main_classes[(module, header)], key=index_for_class)) headers_to_generate = sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros) methods_need_overloading = check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree,", "for (module, _), class_ in main_classes.items(): classes_by_module[module] += class_ for module, classes in", "path, text in files_to_write.items(): if path not in written: open(path, \"w\").write(files_to_write[path]) def delete_other_dirs(modules):", "main_classes: for class_ in main_classes[(module, header_name)]: can_be_instantiated = True if class_[\"abstract\"]: can_be_instantiated =", "path, keep_if_no_instantiation) -> str: header_functions = module_functions[(module, header)] header_classes = main_classes[(module, header)] methods_defined_outside", "v.get(\"defaultValue\") and 'using' != v.get('type')] variables = sorted(variables, key=lambda v: v[\"name\"]) return variables", "filtered_methods def same_parameters(p1: Dict, p2: Dict) -> bool: fields = [\"constant\", \"name\", \"raw_type\",", "f.endswith(\".h\"): found_modules.append([f, join(relative_base, f)]) return found_modules if modules is None: modules = MODULES_TO_BUILD", "m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if not boost_function: continue filtered_methods.append(m) return filtered_methods def same_parameters(p1: Dict, p2: Dict)", "str: header_functions = module_functions[(module, header)] header_classes = main_classes[(module, header)] methods_defined_outside = get_methods_defined_outside(header_functions) class_definitions", "filter_methods_to_skip(methods): filtered_methods = [] for m in methods: if (m[\"parent\"][\"name\"], m[\"name\"]) in METHODS_TO_SKIP:", "instantiated\"\"\" main_classes_by_name_namespace = {make_namespace_class(c[\"namespace\"], c[\"name\"]): c for classes in main_classes.values() for c in", "a(EXPLICIT_INCLUDES.get((module, header_name), \"\")) a(make_header_include_name(module, header_name, path)) a(\"\") namespaces = set([c[\"namespace\"] for c in", "modules based on inheritance for module, header in main_classes: main_classes[(module, header)] = list(sorted(main_classes[(module,", "[f for f in header.functions if f[\"namespace\"] in (\"pcl\", \"pcl::\", \"pcl::%s\" % module,", "something_instantiated = len(instantiation_function.split(\"\\n\")) > 2 text = [] if something_instantiated or keep_if_no_instantiation: text", "path) if path else join(PCL_BASE, module, header_name) header = read_header(header_full_path, skip_macros) main_classes[(module, header_name)]", "in generated_headers.items(): if text: output_path = join(PATH_MODULES, module, header_name + \"pp\") files_to_write[output_path] =", "continue if \"Callback\" in m[\"name\"]: single_argument = len(m[\"parameters\"]) == 1 boost_function = single_argument", "= [\"_MSC_VER\"] #skip_modules = [\"visualization\"] skip_modules = [] all_headers = get_headers(skip_modules=skip_modules) not_every_point_type =", "files in os.walk(PATH_MODULES): for f in files: path = join(base, f) if path", "hpp files_to_write = {} for (module, header_name), text in generated_headers.items(): if text: output_path", "os.path.abspath(base).replace(PCL_BASE, \"\")[1:] for f in files: if f.endswith(\".h\"): found_modules.append([f, join(relative_base, f)]) return found_modules", "module_enums = {}, {}, {}, {} for module, header_name, path in headers_to_generate[:]: header_full_path", "= join(PATH_MODULES, module) if not os.path.exists(module_dir): os.makedirs(module_dir) def is_file_different(path, text): v = open(path).read()", "v != text: print(\"File is different: %s\" % os.path.split(path)[1]) return True # print(\"File", "in header.variables if v.get(\"defaultValue\") and 'using' != v.get('type')] variables = sorted(variables, key=lambda v:", "f) if path in files_to_write: if is_file_different(path, files_to_write[path]): open(path, \"w\").write(files_to_write[path]) written.append(path) elif delete_others:", "for type_ in [m1[\"rtnType\"], m2[\"rtnType\"]]): return False # same parameters for p1 in", "= [] for class_ in main_classes: specialized_template = class_.get(\"template\") and \"<\" in class_[\"name\"]", "skip_macros) parser = CppHeaderParser parser.debug = False header = parser.CppHeader(header_file_str, argType=\"string\") return header", "enums = [e for e in header.enums if e.get(\"name\")] # skip nameless enums", "c: c[\"name\"]) return filtered_main_classes def get_functions(header, module): functions = [f for f in", "import split_methods_by_type from generators.definitions.submodule_loader import generate_loader from generators.definitions.templated_class import ClassDefinition from generators.instantiations import", "modules: module_dir = join(PATH_MODULES, module) if not os.path.exists(module_dir): os.makedirs(module_dir) def is_file_different(path, text): v", "\"pcl::%s::\" % module)] functions = sorted(functions, key=lambda f: f[\"name\"]) filtered = filter_module_level_functions(functions) return", "!= text: print(\"File is different: %s\" % os.path.split(path)[1]) return True # print(\"File is", "True if class_[\"abstract\"]: can_be_instantiated = False else: # check if any pure virtual", "thread safe... if skip_macros is None: skip_macros = [] header_file_str = read_header_file(header_path, skip_macros)", "main_classes[(module, header_name)] = get_main_classes(header, module, header_name) module_functions[(module, header_name)] = get_functions(header, module) module_variables[(module, header_name)]", "files for path, text in files_to_write.items(): if path not in written: open(path, \"w\").write(files_to_write[path])", "None: skip_macros = [] header_file_str = read_header_file(header_path, skip_macros) parser = CppHeaderParser parser.debug =", "<filename>generators/generate_pybind11_bindings.py import os import platform import shutil import sys from collections import Counter", "for class_ in main_classes[(module, header_name)]: can_be_instantiated = True if class_[\"abstract\"]: can_be_instantiated = False", "and same_parameters(p1, p2): break else: return False return len(m1[\"parameters\"]) == len(m2[\"parameters\"]) def private_methods_defined_outside(private_methods:", "keep = False for param in f[\"parameters\"]: for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_", "for class_ in classes: count = Counter(m[\"name\"] for methods in class_[\"methods\"].values() for m", "= Counter(m[\"name\"] for methods in class_[\"methods\"].values() for m in methods) for name, count", "return header def clean(): try: os.remove(PATH_LOADER) except FileNotFoundError: pass if os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES) def", "in headers_to_generate[:]: header_full_path = join(PCL_BASE, path) if path else join(PCL_BASE, module, header_name) header", "f) for f in os.listdir(PCL_BASE) if f.endswith(\".h\")] headers_to_generate += base_headers headers_to_generate_temp = []", "read_headers(base_path, header_name, module) main_classes = [c for c in header.classes.values() if c[\"namespace\"] in", "if \"Callback\" in m[\"name\"]: single_argument = len(m[\"parameters\"]) == 1 boost_function = single_argument and", "same_methods(m1: CppMethod, m2: CppMethod) -> bool: if m1[\"name\"] != m2[\"name\"]: return False #", "for m in class_[\"methods\"][a] if not m[\"pure_virtual\"]]) def flag_instantiatable_class(dependency_tree, main_classes): \"\"\"determine if the", "import os import platform import shutil import sys from collections import Counter from", "virtual method is not implemented all_implemented_inherited_methods = get_all_class_methods_not_pure_virtual(class_) namespace_class = make_namespace_class(class_[\"namespace\"], class_[\"name\"]) for", "\"pcl\": a(\"using namespace %s;\" % namespace) a(\"\\n\") for class_ in main_classes: methods =", "not class_[\"can_be_instantiated\"]: constructors = [] class_def = ClassDefinition(class_, constructors, variables, others, module) a(class_def.to_class_function_definition())", "\"void ImageGrabber<PointT>::publish\", \"void ImageGrabber<PointT>::\" is the return type path = m1.get(\"path\", m2.get(\"path\")) path", "ATTRIBUTES_TO_SKIP: to_ignore = ATTRIBUTES_TO_SKIP[key] filtered_properties = [] for p in properties: if p[\"name\"]", "CppMethod) -> bool: if m1[\"name\"] != m2[\"name\"]: return False # bug in CppHeaderParser", "delete_others): written = [] for base, folder, files in os.walk(PATH_MODULES): for f in", "functions: keep = True if f.get(\"returns_const\"): keep = False for param in f[\"parameters\"]:", "%s\" % os.path.split(path)[1]) return False def write_if_different(files_to_write, delete_others): written = [] for base,", "namespaces = set([c[\"namespace\"] for c in main_classes]) for namespace in namespaces: if not", "any((\"<%s>\" % type_) in class_[\"name\"] for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if not to_skip: message", "generated_headers[(module, header)] = generate_header(module, header, path, keep_if_no_instantiation=False) return generated_headers def main(): import time", "in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if not to_skip: message = \"Warning: Template class specialization not implemented", "module, _ in generated_headers.keys()) make_module_dirs(modules) # hpp files_to_write = {} for (module, header_name),", "\"bool\")] def filter_methods_to_skip(methods): filtered_methods = [] for m in methods: if (m[\"parent\"][\"name\"], m[\"name\"])", "for m in modules if m not in skip_modules] headers_to_generate = [(module, header_name,", "# in \"void ImageGrabber<PointT>::publish\", \"void ImageGrabber<PointT>::\" is the return type path = m1.get(\"path\",", "to_skip = any((\"<%s>\" % type_) in class_[\"name\"] for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if not", "return generated_headers def main(): import time t = time.time() windows = platform.system() ==", "= [] class_def = ClassDefinition(class_, constructors, variables, others, module) a(class_def.to_class_function_definition()) a(\"\") return \"\\n\".join(text)", "files_to_write[path_loader] = generate_loader(module, headers) files_to_write[PATH_LOADER] = generate_main_loader(loader_modules) write_if_different(files_to_write, delete_others) if delete_others: delete_other_dirs(modules) def", "do this in multiple threads but it seems like CppHeaderParser is not thread", "p2 in m2[\"parameters\"]: if m1[\"name\"] == m2[\"name\"] and same_parameters(p1, p2): break else: return", "= make_namespace_class(class_[\"namespace\"], class_[\"name\"]) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class: base_class_methods", "classes_by_module.items(): needs = [] for class_ in classes: count = Counter(m[\"name\"] for methods", "+= private_methods_defined_outside(private_and_protected, methods_defined_outside) class_properties = [p for p in class_[\"properties\"][\"public\"] if not \"using\"", "is the same: %s\" % os.path.split(path)[1]) return False def write_if_different(files_to_write, delete_others): written =", "ClassDefinition from generators.instantiations import Instantiations from generators.point_types_utils import unpack_yaml_point_types from generators.utils import make_header_include_name,", "def clean(): try: os.remove(PATH_LOADER) except FileNotFoundError: pass if os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES) def check_if_needs_overloading(main_classes): needs_overloading", "if f.endswith(\".h\")] headers_to_generate += base_headers headers_to_generate_temp = [] for module, header_name, path in", "sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros) methods_need_overloading = check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree, main_classes) def generate_header(module, header, path, keep_if_no_instantiation) ->", "read_header_file(header_path, skip_macros) parser = CppHeaderParser parser.debug = False header = parser.CppHeader(header_file_str, argType=\"string\") return", "= join(base, f) if path in files_to_write: if is_file_different(path, files_to_write[path]): open(path, \"w\").write(files_to_write[path]) written.append(path)", "= get_variables(header) module_enums[(module, header_name)] = get_enums(header) classes = [c for module, header, path", "if path in files_to_write: if is_file_different(path, files_to_write[path]): open(path, \"w\").write(files_to_write[path]) written.append(path) elif delete_others: os.remove(path)", "is different: %s\" % os.path.split(path)[1]) return True # print(\"File is the same: %s\"", "if m1[\"name\"] == m2[\"name\"] and same_parameters(p1, p2): break else: return False return len(m1[\"parameters\"])", "split_methods_by_type from generators.definitions.submodule_loader import generate_loader from generators.definitions.templated_class import ClassDefinition from generators.instantiations import Instantiations", "import common_includes, PCL_BASE, PATH_LOADER, PATH_MODULES, MODULES_TO_BUILD, \\ HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE, METHODS_TO_SKIP, SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES,", "type_) in class_[\"name\"] for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if not to_skip: message = \"Warning:", "base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class: base_class_methods = get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods) for", "= generate_header(module, header, path, keep_if_no_instantiation=False) return generated_headers def main(): import time t =", "{} classes_by_module = defaultdict(list) for (module, _), class_ in main_classes.items(): classes_by_module[module] += class_", "instantiations = Instantiations(header_classes, module, header, classes_point_types, module_variables[(module, header)], module_enums[(module, header)], ) instantiation_function =", "main_classes.values() for c in classes} for module, header_name in main_classes: for class_ in", "set([m[\"name\"] for a in access for m in class_[\"methods\"][a] if m[\"pure_virtual\"]]) def get_all_class_methods_not_pure_virtual(class_:", "SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if not to_skip: message = \"Warning: Template class specialization not implemented for", "type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if not to_skip: message = \"Warning: Template class specialization not", "def filter_class_properties(module, header, class_name, properties): key = (module, header, class_name) # ignore properties", "loaded_point_types = load_yaml_point_types(not_every_point_type) classes_point_types: OrderedDict = dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first = list(dependency_tree.leaf_iterator()) def index_for_class(class_): return", "in loader_modules.items(): path_loader = join(PATH_MODULES, \"_%s_loader.cpp\" % module) files_to_write[path_loader] = generate_loader(module, headers) files_to_write[PATH_LOADER]", "FileNotFoundError: pass if os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES) def check_if_needs_overloading(main_classes): needs_overloading = {} classes_by_module = defaultdict(list)", "header, class_name) # ignore properties without a name properties = [p for p", "the class can be instantiated\"\"\" main_classes_by_name_namespace = {make_namespace_class(c[\"namespace\"], c[\"name\"]): c for classes in", "for header_name, path in listmod(module)] base_headers = [(\"\", f, f) for f in", "\"union\" in nested_class[\"name\"]] class_properties += union_properties class_properties = filter_class_properties(module, header_name, class_[\"name\"], class_properties) constructors,", "if specialized_template: to_skip = any((\"<%s>\" % type_) in class_[\"name\"] for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP)", "header_name, path in listmod(module)] base_headers = [(\"\", f, f) for f in os.listdir(PCL_BASE)", "header_functions = module_functions[(module, header)] header_classes = main_classes[(module, header)] methods_defined_outside = get_methods_defined_outside(header_functions) class_definitions =", "join from typing import List, Dict, Set from CppHeaderParser import CppHeaderParser from CppHeaderParser.CppHeaderParser", "elif delete_others: os.remove(path) print(\"Deleted: \" + path) # write new files for path,", "modules and os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True) def write_stuff_if_needed(generated_headers: OrderedDict, delete_others=True): modules = set(module for", "= [e for e in header.enums if e.get(\"name\")] # skip nameless enums enums", "m_private in private_methods: for m_outside in methods_declared_outside: if same_methods(m_private, m_outside): private_defined_outside.append(m_private) break return", "module_dir = join(PATH_MODULES, module) if not os.path.exists(module_dir): os.makedirs(module_dir) def is_file_different(path, text): v =", "import generators.dependency_tree from generators.config import common_includes, PCL_BASE, PATH_LOADER, PATH_MODULES, MODULES_TO_BUILD, \\ HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP,", "return filtered_methods def same_parameters(p1: Dict, p2: Dict) -> bool: fields = [\"constant\", \"name\",", "methods_need_overloading = check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree, main_classes) def generate_header(module, header, path, keep_if_no_instantiation) -> str: header_functions", "generators.point_types_utils import unpack_yaml_point_types from generators.utils import make_header_include_name, sort_headers_by_dependencies, \\ generate_main_loader, make_namespace_class, read_header_file def", "if not class_[\"can_be_instantiated\"]: constructors = [] class_def = ClassDefinition(class_, constructors, variables, others, module)", "classes = [c for module, header, path in headers_to_generate for c in main_classes[(module,", "= [p for p in class_[\"properties\"][\"public\"] if not \"using\" in p[\"type\"] and not", "= parser.CppHeader(header_file_str, argType=\"string\") return header def clean(): try: os.remove(PATH_LOADER) except FileNotFoundError: pass if", "for module, classes in classes_by_module.items(): needs = [] for class_ in classes: count", "key=index_for_class)) headers_to_generate = sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros) methods_need_overloading = check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree, main_classes) def generate_header(module, header,", "generated_headers.items(): if text: output_path = join(PATH_MODULES, module, header_name + \"pp\") files_to_write[output_path] = text", "folders, files in os.walk(join(PCL_BASE, module)): if any(base.endswith(m) for m in SUBMODULES_TO_SKIP): continue relative_base", "= False else: # check if any pure virtual method is not implemented", "methods = class_[\"methods\"][\"public\"] methods = filter_methods_for_parser_errors(methods) methods = filter_methods_to_skip(methods) private_and_protected = class_[\"methods\"][\"private\"] +", "m in methods if not m[\"name\"] in (\"void\", \"bool\")] def filter_methods_to_skip(methods): filtered_methods =", "= [] for f in functions: keep = True if f.get(\"returns_const\"): keep =", "base_headers = [(\"\", f, f) for f in os.listdir(PCL_BASE) if f.endswith(\".h\")] headers_to_generate +=", "{} for (module, header_name), text in generated_headers.items(): if text: output_path = join(PATH_MODULES, module,", "= [c for module, header, path in headers_to_generate for c in main_classes[(module, header)]]", "= [] for m_private in private_methods: for m_outside in methods_declared_outside: if same_methods(m_private, m_outside):", "in main_classes: methods = class_[\"methods\"][\"public\"] methods = filter_methods_for_parser_errors(methods) methods = filter_methods_to_skip(methods) private_and_protected =", "modules is None: modules = MODULES_TO_BUILD if skip_modules is not None: modules =", "= [(module, header_name, path) for module in modules for header_name, path in listmod(module)]", "needs_overloading[module] = needs return needs_overloading def get_headers(modules=None, skip_modules=None): def listmod(module): found_modules = []", "filter_module_level_functions(functions) return filtered def filter_module_level_functions(functions: List[CppMethod]): filtered = [] for f in functions:", "for module, header_name, path in headers_to_generate[:]: header_full_path = join(PCL_BASE, path) if path else", "module, header_name, path, needs_overloading: List[str], methods_defined_outside: List[CppMethod]) -> str: text = [] a", "if skip_macros is None: skip_macros = [] header_file_str = read_header_file(header_path, skip_macros) parser =", "False return len(m1[\"parameters\"]) == len(m2[\"parameters\"]) def private_methods_defined_outside(private_methods: List[CppMethod], methods_declared_outside: List[CppMethod]) -> List[CppMethod]: private_defined_outside", "k, v in extra_point_types.items(): if k in classes_point_types: classes_point_types[k].append(v) else: classes_point_types[k] = v", "in functions: keep = True if f.get(\"returns_const\"): keep = False for param in", "get_variables(header) module_enums[(module, header_name)] = get_enums(header) classes = [c for module, header, path in", "join(PATH_MODULES, \"_%s_loader.cpp\" % module) files_to_write[path_loader] = generate_loader(module, headers) files_to_write[PATH_LOADER] = generate_main_loader(loader_modules) write_if_different(files_to_write, delete_others)", "from generators.definitions.submodule_loader import generate_loader from generators.definitions.templated_class import ClassDefinition from generators.instantiations import Instantiations from", "header)] header_classes = main_classes[(module, header)] methods_defined_outside = get_methods_defined_outside(header_functions) class_definitions = generate_class_definitions(header_classes, module, header,", "common_includes, PCL_BASE, PATH_LOADER, PATH_MODULES, MODULES_TO_BUILD, \\ HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE, METHODS_TO_SKIP, SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES, \\", "class_[\"methods\"].values() for m in methods) for name, count in count.items(): if count >=", "{make_namespace_class(c[\"namespace\"], c[\"name\"]): c for classes in main_classes.values() for c in classes} for module,", "class_[\"name\"] if specialized_template: to_skip = any((\"<%s>\" % type_) in class_[\"name\"] for type_ in", "for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class and base_class[\"abstract\"]: base_pure_virtual_methods =", "sorted(enums, key=lambda v: v[\"name\"]) return enums def read_header(header_path, skip_macros=None): # I tried to", "the same: %s\" % os.path.split(path)[1]) return False def write_if_different(files_to_write, delete_others): written = []", "= join(PATH_MODULES, f) if f not in modules and os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True) def", "path, keep_if_no_instantiation=False) return generated_headers def main(): import time t = time.time() windows =", "but it seems like CppHeaderParser is not thread safe... if skip_macros is None:", "properties def get_main_classes(header, module, header_name): # header = read_headers(base_path, header_name, module) main_classes =", "return True # print(\"File is the same: %s\" % os.path.split(path)[1]) return False def", "nested_class in class_[\"nested_classes\"] for p in nested_class[\"properties\"][\"public\"] if \"union\" in nested_class[\"name\"]] class_properties +=", "generate_header(module, header, path, keep_if_no_instantiation=False) return generated_headers def main(): import time t = time.time()", "ignore properties without a name properties = [p for p in properties if", "header_name) in HEADERS_TO_SKIP: continue headers_to_generate_temp.append(tuple([module, header_name, path])) return headers_to_generate_temp def get_pure_virtual_methods(class_: CppHeaderParser.CppClass) ->", "in type_ for type_ in [m1[\"rtnType\"], m2[\"rtnType\"]]): return False # same parameters for", "PATH_MODULES, MODULES_TO_BUILD, \\ HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE, METHODS_TO_SKIP, SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES, \\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from generators.definitions.function", "= [] a = text.append a(common_includes) a(EXPLICIT_INCLUDES.get((module, header_name), \"\")) a(make_header_include_name(module, header_name, path)) a(\"\")", "function_definitions = generate_function_definitions(header_functions, module, header, not_every_point_type=not_every_point_type) instantiations = Instantiations(header_classes, module, header, classes_point_types, module_variables[(module,", "for class %s in %s\" print(message % (class_[\"name\"], header_name)) elif (module, header_name, class_[\"name\"])", "[m for m in methods if not m[\"name\"] in (\"void\", \"bool\")] def filter_methods_to_skip(methods):", "def generate_header(module, header, path, keep_if_no_instantiation) -> str: header_functions = module_functions[(module, header)] header_classes =", "for c in header.classes.values() if c[\"namespace\"] in (\"pcl\", \"pcl::\" + module)] filtered_main_classes =", "(\"void\", \"bool\")] def filter_methods_to_skip(methods): filtered_methods = [] for m in methods: if (m[\"parent\"][\"name\"],", "List[CppMethod]: private_defined_outside = [] for m_private in private_methods: for m_outside in methods_declared_outside: if", "= set(module for module, _ in generated_headers.keys()) make_module_dirs(modules) # hpp files_to_write = {}", "headers) files_to_write[PATH_LOADER] = generate_main_loader(loader_modules) write_if_different(files_to_write, delete_others) if delete_others: delete_other_dirs(modules) def generate(headers_to_generate, skip_macros, not_every_point_type=False)", "in methods if not m[\"name\"] in (\"void\", \"bool\")] def filter_methods_to_skip(methods): filtered_methods = []", "[\"constant\", \"name\", \"raw_type\", \"reference\", \"static\"] return all(p1[f] == p2[f] for f in fields)", "header_file_str = read_header_file(header_path, skip_macros) parser = CppHeaderParser parser.debug = False header = parser.CppHeader(header_file_str,", "= \"--not-every-point-type\" in sys.argv generated_headers = generate(all_headers, skip_macros, not_every_point_type) write_stuff_if_needed(generated_headers, delete_others=True) print(\"generated in", "collections import defaultdict, OrderedDict from os.path import join from typing import List, Dict,", "for module, header, path in headers_to_generate for c in main_classes[(module, header)]] dependency_tree =", "properties: if p[\"name\"] in to_ignore: continue filtered_properties.append(p) properties = filtered_properties return properties def", "if any pure virtual method is not implemented all_implemented_inherited_methods = get_all_class_methods_not_pure_virtual(class_) namespace_class =", "def same_methods(m1: CppMethod, m2: CppMethod) -> bool: if m1[\"name\"] != m2[\"name\"]: return False", "= len(instantiation_function.split(\"\\n\")) > 2 text = [] if something_instantiated or keep_if_no_instantiation: text =", "module) main_classes = [c for c in header.classes.values() if c[\"namespace\"] in (\"pcl\", \"pcl::\"", "in access for m in class_[\"methods\"][a] if m[\"pure_virtual\"]]) def get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass) -> Set[str]:", "not m[\"pure_virtual\"]]) def flag_instantiatable_class(dependency_tree, main_classes): \"\"\"determine if the class can be instantiated\"\"\" main_classes_by_name_namespace", "[] all_headers = get_headers(skip_modules=skip_modules) not_every_point_type = \"--not-every-point-type\" in sys.argv generated_headers = generate(all_headers, skip_macros,", "in param[\"type\"]: keep = False if keep: filtered.append(f) return filtered def get_variables(header): variables", "read_header(header_path, skip_macros=None): # I tried to do this in multiple threads but it", "get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private protected public\".split() return set([m[\"name\"] for a", "os.makedirs(module_dir) def is_file_different(path, text): v = open(path).read() if v != text: print(\"File is", "- all_implemented_inherited_methods: can_be_instantiated = False class_[\"can_be_instantiated\"] = can_be_instantiated def load_yaml_point_types(not_every_point_type): classes_point_types = unpack_yaml_point_types(\"point_types_generated.yml\",", "in extra_point_types.items(): if k in classes_point_types: classes_point_types[k].append(v) else: classes_point_types[k] = v return classes_point_types", "import platform import shutil import sys from collections import Counter from collections import", "methods_need_overloading.get(module), methods_defined_outside) function_definitions = generate_function_definitions(header_functions, module, header, not_every_point_type=not_every_point_type) instantiations = Instantiations(header_classes, module, header,", "make_namespace_class, read_header_file def filter_methods_for_parser_errors(methods): return [m for m in methods if not m[\"name\"]", "specialized_template: to_skip = any((\"<%s>\" % type_) in class_[\"name\"] for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if", "not_every_point_type=False) -> OrderedDict: \"\"\" :return: OrderedDict \"\"\" main_classes, module_functions, module_variables, module_enums = {},", "import unpack_yaml_point_types from generators.utils import make_header_include_name, sort_headers_by_dependencies, \\ generate_main_loader, make_namespace_class, read_header_file def filter_methods_for_parser_errors(methods):", "if (m[\"parent\"][\"name\"], m[\"name\"]) in METHODS_TO_SKIP: continue if \"Callback\" in m[\"name\"]: single_argument = len(m[\"parameters\"])", "= [v for v in header.variables if v.get(\"defaultValue\") and 'using' != v.get('type')] variables", "= generate_loader(module, headers) files_to_write[PATH_LOADER] = generate_main_loader(loader_modules) write_if_different(files_to_write, delete_others) if delete_others: delete_other_dirs(modules) def generate(headers_to_generate,", "is not implemented all_implemented_inherited_methods = get_all_class_methods_not_pure_virtual(class_) namespace_class = make_namespace_class(class_[\"namespace\"], class_[\"name\"]) for base_name_nsp in", "single_argument = len(m[\"parameters\"]) == 1 boost_function = single_argument and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if not boost_function:", "is None: skip_macros = [] header_file_str = read_header_file(header_path, skip_macros) parser = CppHeaderParser parser.debug", "m in modules if m not in skip_modules] headers_to_generate = [(module, header_name, path)", "c for classes in main_classes.values() for c in classes} for module, header_name in", "f in files: if f.endswith(\".h\"): found_modules.append([f, join(relative_base, f)]) return found_modules if modules is", "for p1 in m1[\"parameters\"]: for p2 in m2[\"parameters\"]: if m1[\"name\"] == m2[\"name\"] and", "= text.append a(common_includes) a(EXPLICIT_INCLUDES.get((module, header_name), \"\")) a(make_header_include_name(module, header_name, path)) a(\"\") namespaces = set([c[\"namespace\"]", "functions = [f for f in header.functions if f[\"namespace\"] in (\"pcl\", \"pcl::\", \"pcl::%s\"", "methods_declared_outside: if same_methods(m_private, m_outside): private_defined_outside.append(m_private) break return private_defined_outside def generate_class_definitions(main_classes, module, header_name, path,", "\"\\n\".join(text) generated_headers = OrderedDict() for module, header, path in headers_to_generate: generated_headers[(module, header)] =", "False def write_if_different(files_to_write, delete_others): written = [] for base, folder, files in os.walk(PATH_MODULES):", "header_name, path in headers_to_generate[:]: header_full_path = join(PCL_BASE, path) if path else join(PCL_BASE, module,", "class_ in main_classes: specialized_template = class_.get(\"template\") and \"<\" in class_[\"name\"] if specialized_template: to_skip", "generators.dependency_tree from generators.config import common_includes, PCL_BASE, PATH_LOADER, PATH_MODULES, MODULES_TO_BUILD, \\ HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE,", "\"Callback\" in m[\"name\"]: single_argument = len(m[\"parameters\"]) == 1 boost_function = single_argument and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\")", "in count.items(): if count >= 2: needs.append(name) needs_overloading[module] = needs return needs_overloading def", "written: open(path, \"w\").write(files_to_write[path]) def delete_other_dirs(modules): for f in os.listdir(PATH_MODULES): folder = join(PATH_MODULES, f)", "text in generated_headers.items(): if text: loader_modules[module or \"base\"].append(header_name) for module, headers in loader_modules.items():", "modules if m not in skip_modules] headers_to_generate = [(module, header_name, path) for module", "!= m2[\"name\"]: return False # bug in CppHeaderParser # in \"void ImageGrabber<PointT>::publish\", \"void", "module in modules: module_dir = join(PATH_MODULES, module) if not os.path.exists(module_dir): os.makedirs(module_dir) def is_file_different(path,", "None: modules = MODULES_TO_BUILD if skip_modules is not None: modules = [m for", "a = text.append a(common_includes) a(EXPLICIT_INCLUDES.get((module, header_name), \"\")) a(make_header_include_name(module, header_name, path)) a(\"\") namespaces =", "enums def read_header(header_path, skip_macros=None): # I tried to do this in multiple threads", "enums enums = sorted(enums, key=lambda v: v[\"name\"]) return enums def read_header(header_path, skip_macros=None): #", "header_name, path)) a(\"\") namespaces = set([c[\"namespace\"] for c in main_classes]) for namespace in", "continue headers_to_generate_temp.append(tuple([module, header_name, path])) return headers_to_generate_temp def get_pure_virtual_methods(class_: CppHeaderParser.CppClass) -> Set[str]: access =", "or \"base\"].append(header_name) for module, headers in loader_modules.items(): path_loader = join(PATH_MODULES, \"_%s_loader.cpp\" % module)", "= sorted(filtered_main_classes, key=lambda c: c[\"name\"]) return filtered_main_classes def get_functions(header, module): functions = [f", "filtered = filter_module_level_functions(functions) return filtered def filter_module_level_functions(functions: List[CppMethod]): filtered = [] for f", "classes_point_types: OrderedDict = dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first = list(dependency_tree.leaf_iterator()) def index_for_class(class_): return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"])) #", "header_name, path, needs_overloading: List[str], methods_defined_outside: List[CppMethod]) -> str: text = [] a =", "len(instantiation_function.split(\"\\n\")) > 2 text = [] if something_instantiated or keep_if_no_instantiation: text = [class_definitions,", "from generators.config import common_includes, PCL_BASE, PATH_LOADER, PATH_MODULES, MODULES_TO_BUILD, \\ HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE, METHODS_TO_SKIP,", "shutil.rmtree(PATH_MODULES) def check_if_needs_overloading(main_classes): needs_overloading = {} classes_by_module = defaultdict(list) for (module, _), class_", "OrderedDict: \"\"\" :return: OrderedDict \"\"\" main_classes, module_functions, module_variables, module_enums = {}, {}, {},", "def make_module_dirs(modules): for module in modules: module_dir = join(PATH_MODULES, module) if not os.path.exists(module_dir):", "try: os.remove(PATH_LOADER) except FileNotFoundError: pass if os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES) def check_if_needs_overloading(main_classes): needs_overloading = {}", "= [f for f in header.functions if f[\"namespace\"] in (\"pcl\", \"pcl::\", \"pcl::%s\" %", "if not namespace == \"pcl\": a(\"using namespace %s;\" % namespace) a(\"\\n\") for class_", "header def clean(): try: os.remove(PATH_LOADER) except FileNotFoundError: pass if os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES) def check_if_needs_overloading(main_classes):", "c in classes} for module, header_name in main_classes: for class_ in main_classes[(module, header_name)]:", "Template class specialization not implemented for class %s in %s\" print(message % (class_[\"name\"],", "[] for p in properties: if p[\"name\"] in to_ignore: continue filtered_properties.append(p) properties =", "header.functions if f[\"namespace\"] in (\"pcl\", \"pcl::\", \"pcl::%s\" % module, \"pcl::%s::\" % module)] functions", "for m in methods if not m[\"name\"] in (\"void\", \"bool\")] def filter_methods_to_skip(methods): filtered_methods", "module) module_variables[(module, header_name)] = get_variables(header) module_enums[(module, header_name)] = get_enums(header) classes = [c for", "classes in main_classes.values() for c in classes} for module, header_name in main_classes: for", "generators.dependency_tree.DependencyTree(classes) loaded_point_types = load_yaml_point_types(not_every_point_type) classes_point_types: OrderedDict = dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first = list(dependency_tree.leaf_iterator()) def index_for_class(class_):", "files: if f.endswith(\".h\"): found_modules.append([f, join(relative_base, f)]) return found_modules if modules is None: modules", "filtered_properties return properties def get_main_classes(header, module, header_name): # header = read_headers(base_path, header_name, module)", "p in properties if p[\"name\"]] if key in ATTRIBUTES_TO_SKIP: to_ignore = ATTRIBUTES_TO_SKIP[key] filtered_properties", "[] for m_private in private_methods: for m_outside in methods_declared_outside: if same_methods(m_private, m_outside): private_defined_outside.append(m_private)", "in p[\"type\"]] union_properties = [p for nested_class in class_[\"nested_classes\"] for p in nested_class[\"properties\"][\"public\"]", "f in header.functions if f[\"namespace\"] in (\"pcl\", \"pcl::\", \"pcl::%s\" % module, \"pcl::%s::\" %", "header_name), \"\")) a(make_header_include_name(module, header_name, path)) a(\"\") namespaces = set([c[\"namespace\"] for c in main_classes])", "return all(p1[f] == p2[f] for f in fields) def same_methods(m1: CppMethod, m2: CppMethod)", "get_methods_defined_outside from generators.definitions.method import split_methods_by_type from generators.definitions.submodule_loader import generate_loader from generators.definitions.templated_class import ClassDefinition", "read_header_file def filter_methods_for_parser_errors(methods): return [m for m in methods if not m[\"name\"] in", "text in generated_headers.items(): if text: output_path = join(PATH_MODULES, module, header_name + \"pp\") files_to_write[output_path]", "header, path, keep_if_no_instantiation) -> str: header_functions = module_functions[(module, header)] header_classes = main_classes[(module, header)]", "True # print(\"File is the same: %s\" % os.path.split(path)[1]) return False def write_if_different(files_to_write,", "class_[\"can_be_instantiated\"]: constructors = [] class_def = ClassDefinition(class_, constructors, variables, others, module) a(class_def.to_class_function_definition()) a(\"\")", "m[\"pure_virtual\"]]) def get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private protected public\".split() return set([m[\"name\"]", "new files for path, text in files_to_write.items(): if path not in written: open(path,", "in files_to_write: if is_file_different(path, files_to_write[path]): open(path, \"w\").write(files_to_write[path]) written.append(path) elif delete_others: os.remove(path) print(\"Deleted: \"", "if c[\"namespace\"] in (\"pcl\", \"pcl::\" + module)] filtered_main_classes = [] for class_ in", "m[\"name\"]: single_argument = len(m[\"parameters\"]) == 1 boost_function = single_argument and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if not", "if p[\"name\"]] if key in ATTRIBUTES_TO_SKIP: to_ignore = ATTRIBUTES_TO_SKIP[key] filtered_properties = [] for", "message = \"Warning: Template class specialization not implemented for class %s in %s\"", "= OrderedDict() for module, header, path in headers_to_generate: generated_headers[(module, header)] = generate_header(module, header,", "defaultdict(list) for (module, header_name), text in generated_headers.items(): if text: loader_modules[module or \"base\"].append(header_name) for", "HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE, METHODS_TO_SKIP, SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES, \\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from generators.definitions.function import generate_function_definitions, get_methods_defined_outside", "for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class: base_class_methods = get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods)", "os.path import join from typing import List, Dict, Set from CppHeaderParser import CppHeaderParser", "files_to_write.items(): if path not in written: open(path, \"w\").write(files_to_write[path]) def delete_other_dirs(modules): for f in", "Set[str]: access = \"private protected public\".split() return set([m[\"name\"] for a in access for", "for k, v in extra_point_types.items(): if k in classes_point_types: classes_point_types[k].append(v) else: classes_point_types[k] =", "not m[\"name\"] in (\"void\", \"bool\")] def filter_methods_to_skip(methods): filtered_methods = [] for m in", "% module) files_to_write[path_loader] = generate_loader(module, headers) files_to_write[PATH_LOADER] = generate_main_loader(loader_modules) write_if_different(files_to_write, delete_others) if delete_others:", "key = (module, header, class_name) # ignore properties without a name properties =", "classes_sorted_base_first = list(dependency_tree.leaf_iterator()) def index_for_class(class_): return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"])) # sort classes inside modules", "print(\"File is the same: %s\" % os.path.split(path)[1]) return False def write_if_different(files_to_write, delete_others): written", "from generators.definitions.templated_class import ClassDefinition from generators.instantiations import Instantiations from generators.point_types_utils import unpack_yaml_point_types from", "= CppHeaderParser parser.debug = False header = parser.CppHeader(header_file_str, argType=\"string\") return header def clean():", "path = path[path.rfind(\":\") + 1:] if not any(path in type_ for type_ in", "check if any pure virtual method is not implemented all_implemented_inherited_methods = get_all_class_methods_not_pure_virtual(class_) namespace_class", "if path not in written: open(path, \"w\").write(files_to_write[path]) def delete_other_dirs(modules): for f in os.listdir(PATH_MODULES):", "delete_other_dirs(modules): for f in os.listdir(PATH_MODULES): folder = join(PATH_MODULES, f) if f not in", "text: loader_modules[module or \"base\"].append(header_name) for module, headers in loader_modules.items(): path_loader = join(PATH_MODULES, \"_%s_loader.cpp\"", "\"w\").write(files_to_write[path]) def delete_other_dirs(modules): for f in os.listdir(PATH_MODULES): folder = join(PATH_MODULES, f) if f", "header)] methods_defined_outside = get_methods_defined_outside(header_functions) class_definitions = generate_class_definitions(header_classes, module, header, path, methods_need_overloading.get(module), methods_defined_outside) function_definitions", "base, folders, files in os.walk(join(PCL_BASE, module)): if any(base.endswith(m) for m in SUBMODULES_TO_SKIP): continue", "not implemented all_implemented_inherited_methods = get_all_class_methods_not_pure_virtual(class_) namespace_class = make_namespace_class(class_[\"namespace\"], class_[\"name\"]) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class):", "if something_instantiated or keep_if_no_instantiation: text = [class_definitions, function_definitions, instantiation_function] return \"\\n\".join(text) generated_headers =", "shutil.rmtree(folder, ignore_errors=True) def write_stuff_if_needed(generated_headers: OrderedDict, delete_others=True): modules = set(module for module, _ in", "2: needs.append(name) needs_overloading[module] = needs return needs_overloading def get_headers(modules=None, skip_modules=None): def listmod(module): found_modules", "= read_header_file(header_path, skip_macros) parser = CppHeaderParser parser.debug = False header = parser.CppHeader(header_file_str, argType=\"string\")", "type_ for type_ in [m1[\"rtnType\"], m2[\"rtnType\"]]): return False # same parameters for p1", "def index_for_class(class_): return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"])) # sort classes inside modules based on inheritance", "for module, header in main_classes: main_classes[(module, header)] = list(sorted(main_classes[(module, header)], key=index_for_class)) headers_to_generate =", "= defaultdict(list) for (module, _), class_ in main_classes.items(): classes_by_module[module] += class_ for module,", "text: output_path = join(PATH_MODULES, module, header_name + \"pp\") files_to_write[output_path] = text # loaders", "continue filtered_methods.append(m) return filtered_methods def same_parameters(p1: Dict, p2: Dict) -> bool: fields =", "= get_all_class_methods_not_pure_virtual(class_) namespace_class = make_namespace_class(class_[\"namespace\"], class_[\"name\"]) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp)", "can_be_instantiated = False class_[\"can_be_instantiated\"] = can_be_instantiated def load_yaml_point_types(not_every_point_type): classes_point_types = unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type) extra_point_types", "to do this in multiple threads but it seems like CppHeaderParser is not", "load_yaml_point_types(not_every_point_type): classes_point_types = unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type) extra_point_types = unpack_yaml_point_types(\"point_types_extra.yml\") for k, v in extra_point_types.items():", "written = [] for base, folder, files in os.walk(PATH_MODULES): for f in files:", "classes_point_types[k] = v return classes_point_types def make_module_dirs(modules): for module in modules: module_dir =", "p in properties: if p[\"name\"] in to_ignore: continue filtered_properties.append(p) properties = filtered_properties return", "filtered_main_classes = [] for class_ in main_classes: specialized_template = class_.get(\"template\") and \"<\" in", "class_[\"methods\"][\"protected\"] methods += private_methods_defined_outside(private_and_protected, methods_defined_outside) class_properties = [p for p in class_[\"properties\"][\"public\"] if", "for f in functions: keep = True if f.get(\"returns_const\"): keep = False for", "read_header(header_full_path, skip_macros) main_classes[(module, header_name)] = get_main_classes(header, module, header_name) module_functions[(module, header_name)] = get_functions(header, module)", "set([m[\"name\"] for a in access for m in class_[\"methods\"][a] if not m[\"pure_virtual\"]]) def", "keep = False if keep: filtered.append(f) return filtered def get_variables(header): variables = [v", "class_properties += union_properties class_properties = filter_class_properties(module, header_name, class_[\"name\"], class_properties) constructors, variables, others =", "\"<\" in class_[\"name\"] if specialized_template: to_skip = any((\"<%s>\" % type_) in class_[\"name\"] for", "not namespace == \"pcl\": a(\"using namespace %s;\" % namespace) a(\"\\n\") for class_ in", "safe... if skip_macros is None: skip_macros = [] header_file_str = read_header_file(header_path, skip_macros) parser", "else: # check if any pure virtual method is not implemented all_implemented_inherited_methods =", "generated_headers = OrderedDict() for module, header, path in headers_to_generate: generated_headers[(module, header)] = generate_header(module,", "(module, header_name), text in generated_headers.items(): if text: loader_modules[module or \"base\"].append(header_name) for module, headers", "in main_classes[(module, header)]] dependency_tree = generators.dependency_tree.DependencyTree(classes) loaded_point_types = load_yaml_point_types(not_every_point_type) classes_point_types: OrderedDict = dependency_tree.get_point_types_with_dependencies(loaded_point_types)", "in os.listdir(PCL_BASE) if f.endswith(\".h\")] headers_to_generate += base_headers headers_to_generate_temp = [] for module, header_name,", "found_modules = [] for base, folders, files in os.walk(join(PCL_BASE, module)): if any(base.endswith(m) for", "== \"pcl\": a(\"using namespace %s;\" % namespace) a(\"\\n\") for class_ in main_classes: methods", "print(\"File is different: %s\" % os.path.split(path)[1]) return True # print(\"File is the same:", "or keep_if_no_instantiation: text = [class_definitions, function_definitions, instantiation_function] return \"\\n\".join(text) generated_headers = OrderedDict() for", "classes in classes_by_module.items(): needs = [] for class_ in classes: count = Counter(m[\"name\"]", "f in os.listdir(PCL_BASE) if f.endswith(\".h\")] headers_to_generate += base_headers headers_to_generate_temp = [] for module,", "= False for param in f[\"parameters\"]: for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_ in", "== \"Windows\" skip_macros = [] skip_modules = [] if not windows: skip_macros =", "header, not_every_point_type=not_every_point_type) instantiations = Instantiations(header_classes, module, header, classes_point_types, module_variables[(module, header)], module_enums[(module, header)], )", "param[\"type\"]: keep = False if keep: filtered.append(f) return filtered def get_variables(header): variables =", "\"union\" in p[\"type\"]] union_properties = [p for nested_class in class_[\"nested_classes\"] for p in", "parser.CppHeader(header_file_str, argType=\"string\") return header def clean(): try: os.remove(PATH_LOADER) except FileNotFoundError: pass if os.path.exists(PATH_MODULES):", "\"base\"].append(header_name) for module, headers in loader_modules.items(): path_loader = join(PATH_MODULES, \"_%s_loader.cpp\" % module) files_to_write[path_loader]", "= [] for base, folder, files in os.walk(PATH_MODULES): for f in files: path", "base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class and base_class[\"abstract\"]: base_pure_virtual_methods = get_pure_virtual_methods(base_class)", "path in files_to_write: if is_file_different(path, files_to_write[path]): open(path, \"w\").write(files_to_write[path]) written.append(path) elif delete_others: os.remove(path) print(\"Deleted:", "for c in main_classes]) for namespace in namespaces: if not namespace == \"pcl\":", "class_[\"name\"]) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class: base_class_methods = get_all_class_methods_not_pure_virtual(base_class)", "return [m for m in methods if not m[\"name\"] in (\"void\", \"bool\")] def", "def write_stuff_if_needed(generated_headers: OrderedDict, delete_others=True): modules = set(module for module, _ in generated_headers.keys()) make_module_dirs(modules)", "delete_others=True) print(\"generated in %.2f s\" % (time.time() - t,)) if __name__ == '__main__':", "from collections import Counter from collections import defaultdict, OrderedDict from os.path import join", "[\"visualization\"] skip_modules = [] all_headers = get_headers(skip_modules=skip_modules) not_every_point_type = \"--not-every-point-type\" in sys.argv generated_headers", "delete_other_dirs(modules) def generate(headers_to_generate, skip_macros, not_every_point_type=False) -> OrderedDict: \"\"\" :return: OrderedDict \"\"\" main_classes, module_functions,", "Dict, p2: Dict) -> bool: fields = [\"constant\", \"name\", \"raw_type\", \"reference\", \"static\"] return", "v in header.variables if v.get(\"defaultValue\") and 'using' != v.get('type')] variables = sorted(variables, key=lambda", "get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class and base_class[\"abstract\"]:", "get_functions(header, module) module_variables[(module, header_name)] = get_variables(header) module_enums[(module, header_name)] = get_enums(header) classes = [c", "a(\"using namespace %s;\" % namespace) a(\"\\n\") for class_ in main_classes: methods = class_[\"methods\"][\"public\"]", "+ class_[\"methods\"][\"protected\"] methods += private_methods_defined_outside(private_and_protected, methods_defined_outside) class_properties = [p for p in class_[\"properties\"][\"public\"]", "filter_class_properties(module, header_name, class_[\"name\"], class_properties) constructors, variables, others = split_methods_by_type(methods, class_properties, needs_overloading) if not", "= list(sorted(main_classes[(module, header)], key=index_for_class)) headers_to_generate = sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros) methods_need_overloading = check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree, main_classes)", "[] for module, header_name, path in headers_to_generate: if (module, header_name) in HEADERS_TO_SKIP: continue", "def filter_methods_for_parser_errors(methods): return [m for m in methods if not m[\"name\"] in (\"void\",", "generated_headers = generate(all_headers, skip_macros, not_every_point_type) write_stuff_if_needed(generated_headers, delete_others=True) print(\"generated in %.2f s\" % (time.time()", "if skip_modules is not None: modules = [m for m in modules if", "unpack_yaml_point_types(\"point_types_extra.yml\") for k, v in extra_point_types.items(): if k in classes_point_types: classes_point_types[k].append(v) else: classes_point_types[k]", "class_[\"methods\"][a] if not m[\"pure_virtual\"]]) def flag_instantiatable_class(dependency_tree, main_classes): \"\"\"determine if the class can be", "get_enums(header): enums = [e for e in header.enums if e.get(\"name\")] # skip nameless", "header, class_name, properties): key = (module, header, class_name) # ignore properties without a", "headers_to_generate = sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros) methods_need_overloading = check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree, main_classes) def generate_header(module, header, path,", "header_classes = main_classes[(module, header)] methods_defined_outside = get_methods_defined_outside(header_functions) class_definitions = generate_class_definitions(header_classes, module, header, path,", "class_[\"methods\"][a] if m[\"pure_virtual\"]]) def get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private protected public\".split()", "len(m[\"parameters\"]) == 1 boost_function = single_argument and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if not boost_function: continue filtered_methods.append(m)", "f.endswith(\".h\")] headers_to_generate += base_headers headers_to_generate_temp = [] for module, header_name, path in headers_to_generate:", "parameters for p1 in m1[\"parameters\"]: for p2 in m2[\"parameters\"]: if m1[\"name\"] == m2[\"name\"]", "in [m1[\"rtnType\"], m2[\"rtnType\"]]): return False # same parameters for p1 in m1[\"parameters\"]: for", "\"pp\") files_to_write[output_path] = text # loaders loader_modules = defaultdict(list) for (module, header_name), text", "headers_to_generate += base_headers headers_to_generate_temp = [] for module, header_name, path in headers_to_generate: if", "path) # write new files for path, text in files_to_write.items(): if path not", "skip_modules = [] if not windows: skip_macros = [\"_MSC_VER\"] #skip_modules = [\"visualization\"] skip_modules", "= True if class_[\"abstract\"]: can_be_instantiated = False else: # check if any pure", "[\"_MSC_VER\"] #skip_modules = [\"visualization\"] skip_modules = [] all_headers = get_headers(skip_modules=skip_modules) not_every_point_type = \"--not-every-point-type\"", "get_pure_virtual_methods(base_class) if base_pure_virtual_methods - all_implemented_inherited_methods: can_be_instantiated = False class_[\"can_be_instantiated\"] = can_be_instantiated def load_yaml_point_types(not_every_point_type):", "def delete_other_dirs(modules): for f in os.listdir(PATH_MODULES): folder = join(PATH_MODULES, f) if f not", "for f in files: if f.endswith(\".h\"): found_modules.append([f, join(relative_base, f)]) return found_modules if modules", "= sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros) methods_need_overloading = check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree, main_classes) def generate_header(module, header, path, keep_if_no_instantiation)", "% os.path.split(path)[1]) return True # print(\"File is the same: %s\" % os.path.split(path)[1]) return", "def get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private protected public\".split() return set([m[\"name\"] for", "not in written: open(path, \"w\").write(files_to_write[path]) def delete_other_dirs(modules): for f in os.listdir(PATH_MODULES): folder =", "in methods_declared_outside: if same_methods(m_private, m_outside): private_defined_outside.append(m_private) break return private_defined_outside def generate_class_definitions(main_classes, module, header_name,", "pure virtual method is not implemented all_implemented_inherited_methods = get_all_class_methods_not_pure_virtual(class_) namespace_class = make_namespace_class(class_[\"namespace\"], class_[\"name\"])", "path) for module in modules for header_name, path in listmod(module)] base_headers = [(\"\",", "% module, \"pcl::%s::\" % module)] functions = sorted(functions, key=lambda f: f[\"name\"]) filtered =", "count in count.items(): if count >= 2: needs.append(name) needs_overloading[module] = needs return needs_overloading", "path, needs_overloading: List[str], methods_defined_outside: List[CppMethod]) -> str: text = [] a = text.append", "private_methods: for m_outside in methods_declared_outside: if same_methods(m_private, m_outside): private_defined_outside.append(m_private) break return private_defined_outside def", "import generate_loader from generators.definitions.templated_class import ClassDefinition from generators.instantiations import Instantiations from generators.point_types_utils import", "p1 in m1[\"parameters\"]: for p2 in m2[\"parameters\"]: if m1[\"name\"] == m2[\"name\"] and same_parameters(p1,", "text = [class_definitions, function_definitions, instantiation_function] return \"\\n\".join(text) generated_headers = OrderedDict() for module, header,", "namespace == \"pcl\": a(\"using namespace %s;\" % namespace) a(\"\\n\") for class_ in main_classes:", "namespace in namespaces: if not namespace == \"pcl\": a(\"using namespace %s;\" % namespace)", "write_if_different(files_to_write, delete_others) if delete_others: delete_other_dirs(modules) def generate(headers_to_generate, skip_macros, not_every_point_type=False) -> OrderedDict: \"\"\" :return:", "generate_header(module, header, path, keep_if_no_instantiation) -> str: header_functions = module_functions[(module, header)] header_classes = main_classes[(module,", "= [m for m in modules if m not in skip_modules] headers_to_generate =", "OrderedDict() for module, header, path in headers_to_generate: generated_headers[(module, header)] = generate_header(module, header, path,", "skip_modules=None): def listmod(module): found_modules = [] for base, folders, files in os.walk(join(PCL_BASE, module)):", "= filtered_properties return properties def get_main_classes(header, module, header_name): # header = read_headers(base_path, header_name,", "in methods: if (m[\"parent\"][\"name\"], m[\"name\"]) in METHODS_TO_SKIP: continue if \"Callback\" in m[\"name\"]: single_argument", "[c for module, header, path in headers_to_generate for c in main_classes[(module, header)]] dependency_tree", "if m1[\"name\"] != m2[\"name\"]: return False # bug in CppHeaderParser # in \"void", "sorted(filtered_main_classes, key=lambda c: c[\"name\"]) return filtered_main_classes def get_functions(header, module): functions = [f for", "generators.definitions.submodule_loader import generate_loader from generators.definitions.templated_class import ClassDefinition from generators.instantiations import Instantiations from generators.point_types_utils", "if not windows: skip_macros = [\"_MSC_VER\"] #skip_modules = [\"visualization\"] skip_modules = [] all_headers", "for m_private in private_methods: for m_outside in methods_declared_outside: if same_methods(m_private, m_outside): private_defined_outside.append(m_private) break", "= filter_methods_to_skip(methods) private_and_protected = class_[\"methods\"][\"private\"] + class_[\"methods\"][\"protected\"] methods += private_methods_defined_outside(private_and_protected, methods_defined_outside) class_properties =", "name properties = [p for p in properties if p[\"name\"]] if key in", "def get_variables(header): variables = [v for v in header.variables if v.get(\"defaultValue\") and 'using'", "class_[\"methods\"][\"private\"] + class_[\"methods\"][\"protected\"] methods += private_methods_defined_outside(private_and_protected, methods_defined_outside) class_properties = [p for p in", "if not boost_function: continue filtered_methods.append(m) return filtered_methods def same_parameters(p1: Dict, p2: Dict) ->", "not_every_point_type = \"--not-every-point-type\" in sys.argv generated_headers = generate(all_headers, skip_macros, not_every_point_type) write_stuff_if_needed(generated_headers, delete_others=True) print(\"generated", "def get_functions(header, module): functions = [f for f in header.functions if f[\"namespace\"] in", "in written: open(path, \"w\").write(files_to_write[path]) def delete_other_dirs(modules): for f in os.listdir(PATH_MODULES): folder = join(PATH_MODULES,", "def write_if_different(files_to_write, delete_others): written = [] for base, folder, files in os.walk(PATH_MODULES): for", "= ATTRIBUTES_TO_SKIP[key] filtered_properties = [] for p in properties: if p[\"name\"] in to_ignore:", "= platform.system() == \"Windows\" skip_macros = [] skip_modules = [] if not windows:", "function_definitions, instantiation_function] return \"\\n\".join(text) generated_headers = OrderedDict() for module, header, path in headers_to_generate:", "False else: # check if any pure virtual method is not implemented all_implemented_inherited_methods", "in nested_class[\"name\"]] class_properties += union_properties class_properties = filter_class_properties(module, header_name, class_[\"name\"], class_properties) constructors, variables,", "properties): key = (module, header, class_name) # ignore properties without a name properties", "import time t = time.time() windows = platform.system() == \"Windows\" skip_macros = []", "generate_main_loader, make_namespace_class, read_header_file def filter_methods_for_parser_errors(methods): return [m for m in methods if not", "m1[\"name\"] != m2[\"name\"]: return False # bug in CppHeaderParser # in \"void ImageGrabber<PointT>::publish\",", "elif (module, header_name, class_[\"name\"]) in CLASSES_TO_IGNORE: pass else: filtered_main_classes.append(class_) filtered_main_classes = sorted(filtered_main_classes, key=lambda", "= main_classes[(module, header)] methods_defined_outside = get_methods_defined_outside(header_functions) class_definitions = generate_class_definitions(header_classes, module, header, path, methods_need_overloading.get(module),", "in class_[\"nested_classes\"] for p in nested_class[\"properties\"][\"public\"] if \"union\" in nested_class[\"name\"]] class_properties += union_properties", "False header = parser.CppHeader(header_file_str, argType=\"string\") return header def clean(): try: os.remove(PATH_LOADER) except FileNotFoundError:", "listmod(module): found_modules = [] for base, folders, files in os.walk(join(PCL_BASE, module)): if any(base.endswith(m)", "CppHeaderParser import CppHeaderParser from CppHeaderParser.CppHeaderParser import CppMethod import generators.dependency_tree from generators.config import common_includes,", "generate_loader from generators.definitions.templated_class import ClassDefinition from generators.instantiations import Instantiations from generators.point_types_utils import unpack_yaml_point_types", "for v in header.variables if v.get(\"defaultValue\") and 'using' != v.get('type')] variables = sorted(variables,", "f in fields) def same_methods(m1: CppMethod, m2: CppMethod) -> bool: if m1[\"name\"] !=", "print(\"generated in %.2f s\" % (time.time() - t,)) if __name__ == '__main__': main()", "generators.definitions.method import split_methods_by_type from generators.definitions.submodule_loader import generate_loader from generators.definitions.templated_class import ClassDefinition from generators.instantiations", "= join(PATH_MODULES, module, header_name + \"pp\") files_to_write[output_path] = text # loaders loader_modules =", "m2[\"rtnType\"]]): return False # same parameters for p1 in m1[\"parameters\"]: for p2 in", "f: f[\"name\"]) filtered = filter_module_level_functions(functions) return filtered def filter_module_level_functions(functions: List[CppMethod]): filtered = []", "implemented for class %s in %s\" print(message % (class_[\"name\"], header_name)) elif (module, header_name,", "a name properties = [p for p in properties if p[\"name\"]] if key", "in modules and os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True) def write_stuff_if_needed(generated_headers: OrderedDict, delete_others=True): modules = set(module", "if modules is None: modules = MODULES_TO_BUILD if skip_modules is not None: modules", "for module in modules: module_dir = join(PATH_MODULES, module) if not os.path.exists(module_dir): os.makedirs(module_dir) def", "if (module, header_name) in HEADERS_TO_SKIP: continue headers_to_generate_temp.append(tuple([module, header_name, path])) return headers_to_generate_temp def get_pure_virtual_methods(class_:", "namespace) a(\"\\n\") for class_ in main_classes: methods = class_[\"methods\"][\"public\"] methods = filter_methods_for_parser_errors(methods) methods", "filter_module_level_functions(functions: List[CppMethod]): filtered = [] for f in functions: keep = True if", "def get_pure_virtual_methods(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private protected public\".split() return set([m[\"name\"] for", "class specialization not implemented for class %s in %s\" print(message % (class_[\"name\"], header_name))", "else: classes_point_types[k] = v return classes_point_types def make_module_dirs(modules): for module in modules: module_dir", "class can be instantiated\"\"\" main_classes_by_name_namespace = {make_namespace_class(c[\"namespace\"], c[\"name\"]): c for classes in main_classes.values()", "files_to_write[PATH_LOADER] = generate_main_loader(loader_modules) write_if_different(files_to_write, delete_others) if delete_others: delete_other_dirs(modules) def generate(headers_to_generate, skip_macros, not_every_point_type=False) ->", "skip_modules] headers_to_generate = [(module, header_name, path) for module in modules for header_name, path", "header)], ) instantiation_function = instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated = len(instantiation_function.split(\"\\n\")) > 2 text = []", "same: %s\" % os.path.split(path)[1]) return False def write_if_different(files_to_write, delete_others): written = [] for", "CppHeaderParser.CppClass) -> Set[str]: access = \"private protected public\".split() return set([m[\"name\"] for a in", "\"raw_type\", \"reference\", \"static\"] return all(p1[f] == p2[f] for f in fields) def same_methods(m1:", "[m for m in modules if m not in skip_modules] headers_to_generate = [(module,", "def read_header(header_path, skip_macros=None): # I tried to do this in multiple threads but", "in main_classes: main_classes[(module, header)] = list(sorted(main_classes[(module, header)], key=index_for_class)) headers_to_generate = sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros) methods_need_overloading", "get_enums(header) classes = [c for module, header, path in headers_to_generate for c in", "clean(): try: os.remove(PATH_LOADER) except FileNotFoundError: pass if os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES) def check_if_needs_overloading(main_classes): needs_overloading =", "text # loaders loader_modules = defaultdict(list) for (module, header_name), text in generated_headers.items(): if", "return headers_to_generate_temp def get_pure_virtual_methods(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private protected public\".split() return", "[v for v in header.variables if v.get(\"defaultValue\") and 'using' != v.get('type')] variables =", "(module, header_name), text in generated_headers.items(): if text: output_path = join(PATH_MODULES, module, header_name +", "output_path = join(PATH_MODULES, module, header_name + \"pp\") files_to_write[output_path] = text # loaders loader_modules", "filtered_methods.append(m) return filtered_methods def same_parameters(p1: Dict, p2: Dict) -> bool: fields = [\"constant\",", "skip_macros is None: skip_macros = [] header_file_str = read_header_file(header_path, skip_macros) parser = CppHeaderParser", "filter_methods_to_skip(methods) private_and_protected = class_[\"methods\"][\"private\"] + class_[\"methods\"][\"protected\"] methods += private_methods_defined_outside(private_and_protected, methods_defined_outside) class_properties = [p", "(\"pcl\", \"pcl::\", \"pcl::%s\" % module, \"pcl::%s::\" % module)] functions = sorted(functions, key=lambda f:", "and os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True) def write_stuff_if_needed(generated_headers: OrderedDict, delete_others=True): modules = set(module for module,", "header_name)] = get_main_classes(header, module, header_name) module_functions[(module, header_name)] = get_functions(header, module) module_variables[(module, header_name)] =", "k in classes_point_types: classes_point_types[k].append(v) else: classes_point_types[k] = v return classes_point_types def make_module_dirs(modules): for", "= get_functions(header, module) module_variables[(module, header_name)] = get_variables(header) module_enums[(module, header_name)] = get_enums(header) classes =", "List[CppMethod]) -> str: text = [] a = text.append a(common_includes) a(EXPLICIT_INCLUDES.get((module, header_name), \"\"))", "# I tried to do this in multiple threads but it seems like", "a(common_includes) a(EXPLICIT_INCLUDES.get((module, header_name), \"\")) a(make_header_include_name(module, header_name, path)) a(\"\") namespaces = set([c[\"namespace\"] for c", "count.items(): if count >= 2: needs.append(name) needs_overloading[module] = needs return needs_overloading def get_headers(modules=None,", "= path[path.rfind(\":\") + 1:] if not any(path in type_ for type_ in [m1[\"rtnType\"],", "os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES) def check_if_needs_overloading(main_classes): needs_overloading = {} classes_by_module = defaultdict(list) for (module, _),", "p[\"name\"] in to_ignore: continue filtered_properties.append(p) properties = filtered_properties return properties def get_main_classes(header, module,", "p[\"name\"]] if key in ATTRIBUTES_TO_SKIP: to_ignore = ATTRIBUTES_TO_SKIP[key] filtered_properties = [] for p", "not \"union\" in p[\"type\"]] union_properties = [p for nested_class in class_[\"nested_classes\"] for p", "= generators.dependency_tree.DependencyTree(classes) loaded_point_types = load_yaml_point_types(not_every_point_type) classes_point_types: OrderedDict = dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first = list(dependency_tree.leaf_iterator()) def", "= Instantiations(header_classes, module, header, classes_point_types, module_variables[(module, header)], module_enums[(module, header)], ) instantiation_function = instantiations.generate_instantiation_function(has_functions=bool(header_functions))", "if not m[\"name\"] in (\"void\", \"bool\")] def filter_methods_to_skip(methods): filtered_methods = [] for m", "m[\"pure_virtual\"]]) def flag_instantiatable_class(dependency_tree, main_classes): \"\"\"determine if the class can be instantiated\"\"\" main_classes_by_name_namespace =", "if base_class and base_class[\"abstract\"]: base_pure_virtual_methods = get_pure_virtual_methods(base_class) if base_pure_virtual_methods - all_implemented_inherited_methods: can_be_instantiated =", "header)], key=index_for_class)) headers_to_generate = sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros) methods_need_overloading = check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree, main_classes) def generate_header(module,", "all_implemented_inherited_methods.update(base_class_methods) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class and base_class[\"abstract\"]: base_pure_virtual_methods", "in main_classes: specialized_template = class_.get(\"template\") and \"<\" in class_[\"name\"] if specialized_template: to_skip =", "!= v.get('type')] variables = sorted(variables, key=lambda v: v[\"name\"]) return variables def get_enums(header): enums", "return set([m[\"name\"] for a in access for m in class_[\"methods\"][a] if m[\"pure_virtual\"]]) def", "skip_modules = [] all_headers = get_headers(skip_modules=skip_modules) not_every_point_type = \"--not-every-point-type\" in sys.argv generated_headers =", "to_skip: message = \"Warning: Template class specialization not implemented for class %s in", "module_functions, module_variables, module_enums = {}, {}, {}, {} for module, header_name, path in", "[(\"\", f, f) for f in os.listdir(PCL_BASE) if f.endswith(\".h\")] headers_to_generate += base_headers headers_to_generate_temp", "= [\"visualization\"] skip_modules = [] all_headers = get_headers(skip_modules=skip_modules) not_every_point_type = \"--not-every-point-type\" in sys.argv", "if class_[\"abstract\"]: can_be_instantiated = False else: # check if any pure virtual method", "if count >= 2: needs.append(name) needs_overloading[module] = needs return needs_overloading def get_headers(modules=None, skip_modules=None):", "= os.path.abspath(base).replace(PCL_BASE, \"\")[1:] for f in files: if f.endswith(\".h\"): found_modules.append([f, join(relative_base, f)]) return", "loader_modules[module or \"base\"].append(header_name) for module, headers in loader_modules.items(): path_loader = join(PATH_MODULES, \"_%s_loader.cpp\" %", "classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"])) # sort classes inside modules based on inheritance for module, header", "import CppMethod import generators.dependency_tree from generators.config import common_includes, PCL_BASE, PATH_LOADER, PATH_MODULES, MODULES_TO_BUILD, \\", "flag_instantiatable_class(dependency_tree, main_classes) def generate_header(module, header, path, keep_if_no_instantiation) -> str: header_functions = module_functions[(module, header)]", "-> str: text = [] a = text.append a(common_includes) a(EXPLICIT_INCLUDES.get((module, header_name), \"\")) a(make_header_include_name(module,", "header_name)] = get_variables(header) module_enums[(module, header_name)] = get_enums(header) classes = [c for module, header,", "variables, others = split_methods_by_type(methods, class_properties, needs_overloading) if not class_[\"can_be_instantiated\"]: constructors = [] class_def", "\"\\n\".join(text) def filter_class_properties(module, header, class_name, properties): key = (module, header, class_name) # ignore", "p[\"type\"]] union_properties = [p for nested_class in class_[\"nested_classes\"] for p in nested_class[\"properties\"][\"public\"] if", "instantiation_function = instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated = len(instantiation_function.split(\"\\n\")) > 2 text = [] if something_instantiated", "main_classes: methods = class_[\"methods\"][\"public\"] methods = filter_methods_for_parser_errors(methods) methods = filter_methods_to_skip(methods) private_and_protected = class_[\"methods\"][\"private\"]", "m2[\"name\"]: return False # bug in CppHeaderParser # in \"void ImageGrabber<PointT>::publish\", \"void ImageGrabber<PointT>::\"", "sorted(variables, key=lambda v: v[\"name\"]) return variables def get_enums(header): enums = [e for e", "modules = set(module for module, _ in generated_headers.keys()) make_module_dirs(modules) # hpp files_to_write =", "CLASSES_TO_IGNORE: pass else: filtered_main_classes.append(class_) filtered_main_classes = sorted(filtered_main_classes, key=lambda c: c[\"name\"]) return filtered_main_classes def", "= sorted(variables, key=lambda v: v[\"name\"]) return variables def get_enums(header): enums = [e for", "path])) return headers_to_generate_temp def get_pure_virtual_methods(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private protected public\".split()", "sys from collections import Counter from collections import defaultdict, OrderedDict from os.path import", "c[\"namespace\"] in (\"pcl\", \"pcl::\" + module)] filtered_main_classes = [] for class_ in main_classes:", "def get_enums(header): enums = [e for e in header.enums if e.get(\"name\")] # skip", "in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_ in param[\"type\"]: keep = False if keep: filtered.append(f) return", "e.get(\"name\")] # skip nameless enums enums = sorted(enums, key=lambda v: v[\"name\"]) return enums", "% namespace) a(\"\\n\") for class_ in main_classes: methods = class_[\"methods\"][\"public\"] methods = filter_methods_for_parser_errors(methods)", "path_loader = join(PATH_MODULES, \"_%s_loader.cpp\" % module) files_to_write[path_loader] = generate_loader(module, headers) files_to_write[PATH_LOADER] = generate_main_loader(loader_modules)", "c in main_classes[(module, header)]] dependency_tree = generators.dependency_tree.DependencyTree(classes) loaded_point_types = load_yaml_point_types(not_every_point_type) classes_point_types: OrderedDict =", "-> bool: fields = [\"constant\", \"name\", \"raw_type\", \"reference\", \"static\"] return all(p1[f] == p2[f]", "time t = time.time() windows = platform.system() == \"Windows\" skip_macros = [] skip_modules", "not to_skip: message = \"Warning: Template class specialization not implemented for class %s", "collections import Counter from collections import defaultdict, OrderedDict from os.path import join from", "= class_.get(\"template\") and \"<\" in class_[\"name\"] if specialized_template: to_skip = any((\"<%s>\" % type_)", "import make_header_include_name, sort_headers_by_dependencies, \\ generate_main_loader, make_namespace_class, read_header_file def filter_methods_for_parser_errors(methods): return [m for m", "classes_point_types = unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type) extra_point_types = unpack_yaml_point_types(\"point_types_extra.yml\") for k, v in extra_point_types.items(): if", "[] for class_ in main_classes: specialized_template = class_.get(\"template\") and \"<\" in class_[\"name\"] if", "break return private_defined_outside def generate_class_definitions(main_classes, module, header_name, path, needs_overloading: List[str], methods_defined_outside: List[CppMethod]) ->", "module_enums[(module, header)], ) instantiation_function = instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated = len(instantiation_function.split(\"\\n\")) > 2 text =", "loader_modules.items(): path_loader = join(PATH_MODULES, \"_%s_loader.cpp\" % module) files_to_write[path_loader] = generate_loader(module, headers) files_to_write[PATH_LOADER] =", "\"\"\" main_classes, module_functions, module_variables, module_enums = {}, {}, {}, {} for module, header_name,", "if base_pure_virtual_methods - all_implemented_inherited_methods: can_be_instantiated = False class_[\"can_be_instantiated\"] = can_be_instantiated def load_yaml_point_types(not_every_point_type): classes_point_types", "write_stuff_if_needed(generated_headers: OrderedDict, delete_others=True): modules = set(module for module, _ in generated_headers.keys()) make_module_dirs(modules) #", "%s\" % os.path.split(path)[1]) return True # print(\"File is the same: %s\" % os.path.split(path)[1])", "in classes} for module, header_name in main_classes: for class_ in main_classes[(module, header_name)]: can_be_instantiated", "= module_functions[(module, header)] header_classes = main_classes[(module, header)] methods_defined_outside = get_methods_defined_outside(header_functions) class_definitions = generate_class_definitions(header_classes,", "key=lambda v: v[\"name\"]) return variables def get_enums(header): enums = [e for e in", "make_namespace_class(class_[\"namespace\"], class_[\"name\"]) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class: base_class_methods =", "make_module_dirs(modules) # hpp files_to_write = {} for (module, header_name), text in generated_headers.items(): if", "found_modules.append([f, join(relative_base, f)]) return found_modules if modules is None: modules = MODULES_TO_BUILD if", "module, header, path in headers_to_generate for c in main_classes[(module, header)]] dependency_tree = generators.dependency_tree.DependencyTree(classes)", "METHODS_TO_SKIP: continue if \"Callback\" in m[\"name\"]: single_argument = len(m[\"parameters\"]) == 1 boost_function =", "generate_loader(module, headers) files_to_write[PATH_LOADER] = generate_main_loader(loader_modules) write_if_different(files_to_write, delete_others) if delete_others: delete_other_dirs(modules) def generate(headers_to_generate, skip_macros,", "header, path in headers_to_generate for c in main_classes[(module, header)]] dependency_tree = generators.dependency_tree.DependencyTree(classes) loaded_point_types", "needs.append(name) needs_overloading[module] = needs return needs_overloading def get_headers(modules=None, skip_modules=None): def listmod(module): found_modules =", "= main_classes_by_name_namespace.get(base_name_nsp) if base_class: base_class_methods = get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class", "modules for header_name, path in listmod(module)] base_headers = [(\"\", f, f) for f", "header)] = generate_header(module, header, path, keep_if_no_instantiation=False) return generated_headers def main(): import time t", "if \"union\" in nested_class[\"name\"]] class_properties += union_properties class_properties = filter_class_properties(module, header_name, class_[\"name\"], class_properties)", "v return classes_point_types def make_module_dirs(modules): for module in modules: module_dir = join(PATH_MODULES, module)", "\\ HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE, METHODS_TO_SKIP, SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES, \\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from generators.definitions.function import generate_function_definitions,", "bool: if m1[\"name\"] != m2[\"name\"]: return False # bug in CppHeaderParser # in", "return found_modules if modules is None: modules = MODULES_TO_BUILD if skip_modules is not", "= unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type) extra_point_types = unpack_yaml_point_types(\"point_types_extra.yml\") for k, v in extra_point_types.items(): if k", "name, count in count.items(): if count >= 2: needs.append(name) needs_overloading[module] = needs return", "c in main_classes]) for namespace in namespaces: if not namespace == \"pcl\": a(\"using", "variables, others, module) a(class_def.to_class_function_definition()) a(\"\") return \"\\n\".join(text) def filter_class_properties(module, header, class_name, properties): key", "main_classes_by_name_namespace.get(base_name_nsp) if base_class: base_class_methods = get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class =", "module, header_name) header = read_header(header_full_path, skip_macros) main_classes[(module, header_name)] = get_main_classes(header, module, header_name) module_functions[(module,", "if is_file_different(path, files_to_write[path]): open(path, \"w\").write(files_to_write[path]) written.append(path) elif delete_others: os.remove(path) print(\"Deleted: \" + path)", "methods = filter_methods_for_parser_errors(methods) methods = filter_methods_to_skip(methods) private_and_protected = class_[\"methods\"][\"private\"] + class_[\"methods\"][\"protected\"] methods +=", "p2): break else: return False return len(m1[\"parameters\"]) == len(m2[\"parameters\"]) def private_methods_defined_outside(private_methods: List[CppMethod], methods_declared_outside:", "return False def write_if_different(files_to_write, delete_others): written = [] for base, folder, files in", "[] if something_instantiated or keep_if_no_instantiation: text = [class_definitions, function_definitions, instantiation_function] return \"\\n\".join(text) generated_headers", "in header.classes.values() if c[\"namespace\"] in (\"pcl\", \"pcl::\" + module)] filtered_main_classes = [] for", "in (\"pcl\", \"pcl::\" + module)] filtered_main_classes = [] for class_ in main_classes: specialized_template", "from CppHeaderParser import CppHeaderParser from CppHeaderParser.CppHeaderParser import CppMethod import generators.dependency_tree from generators.config import", "in classes: count = Counter(m[\"name\"] for methods in class_[\"methods\"].values() for m in methods)", "f, f) for f in os.listdir(PCL_BASE) if f.endswith(\".h\")] headers_to_generate += base_headers headers_to_generate_temp =", "delete_others=True): modules = set(module for module, _ in generated_headers.keys()) make_module_dirs(modules) # hpp files_to_write", "and not \"union\" in p[\"type\"]] union_properties = [p for nested_class in class_[\"nested_classes\"] for", "header_name, class_[\"name\"]) in CLASSES_TO_IGNORE: pass else: filtered_main_classes.append(class_) filtered_main_classes = sorted(filtered_main_classes, key=lambda c: c[\"name\"])", "[(module, header_name, path) for module in modules for header_name, path in listmod(module)] base_headers", "files_to_write: if is_file_different(path, files_to_write[path]): open(path, \"w\").write(files_to_write[path]) written.append(path) elif delete_others: os.remove(path) print(\"Deleted: \" +", "properties if p[\"name\"]] if key in ATTRIBUTES_TO_SKIP: to_ignore = ATTRIBUTES_TO_SKIP[key] filtered_properties = []", "pass else: filtered_main_classes.append(class_) filtered_main_classes = sorted(filtered_main_classes, key=lambda c: c[\"name\"]) return filtered_main_classes def get_functions(header,", "classes_point_types: classes_point_types[k].append(v) else: classes_point_types[k] = v return classes_point_types def make_module_dirs(modules): for module in", "all_implemented_inherited_methods = get_all_class_methods_not_pure_virtual(class_) namespace_class = make_namespace_class(class_[\"namespace\"], class_[\"name\"]) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class =", "= text # loaders loader_modules = defaultdict(list) for (module, header_name), text in generated_headers.items():", "module in modules for header_name, path in listmod(module)] base_headers = [(\"\", f, f)", "can_be_instantiated = True if class_[\"abstract\"]: can_be_instantiated = False else: # check if any", "List[CppMethod]): filtered = [] for f in functions: keep = True if f.get(\"returns_const\"):", "from generators.point_types_utils import unpack_yaml_point_types from generators.utils import make_header_include_name, sort_headers_by_dependencies, \\ generate_main_loader, make_namespace_class, read_header_file", "for m in methods: if (m[\"parent\"][\"name\"], m[\"name\"]) in METHODS_TO_SKIP: continue if \"Callback\" in", "m1.get(\"path\", m2.get(\"path\")) path = path[path.rfind(\":\") + 1:] if not any(path in type_ for", "skip_modules is not None: modules = [m for m in modules if m", "get_main_classes(header, module, header_name) module_functions[(module, header_name)] = get_functions(header, module) module_variables[(module, header_name)] = get_variables(header) module_enums[(module,", "any pure virtual method is not implemented all_implemented_inherited_methods = get_all_class_methods_not_pure_virtual(class_) namespace_class = make_namespace_class(class_[\"namespace\"],", "for namespace in namespaces: if not namespace == \"pcl\": a(\"using namespace %s;\" %", "= (module, header, class_name) # ignore properties without a name properties = [p", "is None: modules = MODULES_TO_BUILD if skip_modules is not None: modules = [m", "classes_point_types def make_module_dirs(modules): for module in modules: module_dir = join(PATH_MODULES, module) if not", "f[\"name\"]) filtered = filter_module_level_functions(functions) return filtered def filter_module_level_functions(functions: List[CppMethod]): filtered = [] for", "extra_point_types.items(): if k in classes_point_types: classes_point_types[k].append(v) else: classes_point_types[k] = v return classes_point_types def", "return \"\\n\".join(text) def filter_class_properties(module, header, class_name, properties): key = (module, header, class_name) #", "\"\"\"determine if the class can be instantiated\"\"\" main_classes_by_name_namespace = {make_namespace_class(c[\"namespace\"], c[\"name\"]): c for", "in skip_modules] headers_to_generate = [(module, header_name, path) for module in modules for header_name,", "import sys from collections import Counter from collections import defaultdict, OrderedDict from os.path", "v: v[\"name\"]) return enums def read_header(header_path, skip_macros=None): # I tried to do this", "join(PCL_BASE, module, header_name) header = read_header(header_full_path, skip_macros) main_classes[(module, header_name)] = get_main_classes(header, module, header_name)", "a(\"\") return \"\\n\".join(text) def filter_class_properties(module, header, class_name, properties): key = (module, header, class_name)", "tried to do this in multiple threads but it seems like CppHeaderParser is", "if text: output_path = join(PATH_MODULES, module, header_name + \"pp\") files_to_write[output_path] = text #", "generate_class_definitions(header_classes, module, header, path, methods_need_overloading.get(module), methods_defined_outside) function_definitions = generate_function_definitions(header_functions, module, header, not_every_point_type=not_every_point_type) instantiations", "folder, files in os.walk(PATH_MODULES): for f in files: path = join(base, f) if", "if keep: filtered.append(f) return filtered def get_variables(header): variables = [v for v in", "main_classes[(module, header_name)]: can_be_instantiated = True if class_[\"abstract\"]: can_be_instantiated = False else: # check", "[] for f in functions: keep = True if f.get(\"returns_const\"): keep = False", "private_defined_outside def generate_class_definitions(main_classes, module, header_name, path, needs_overloading: List[str], methods_defined_outside: List[CppMethod]) -> str: text", "class_[\"name\"]) in CLASSES_TO_IGNORE: pass else: filtered_main_classes.append(class_) filtered_main_classes = sorted(filtered_main_classes, key=lambda c: c[\"name\"]) return", ">= 2: needs.append(name) needs_overloading[module] = needs return needs_overloading def get_headers(modules=None, skip_modules=None): def listmod(module):", "in namespaces: if not namespace == \"pcl\": a(\"using namespace %s;\" % namespace) a(\"\\n\")", "for f in files: path = join(base, f) if path in files_to_write: if", "if not to_skip: message = \"Warning: Template class specialization not implemented for class", "OrderedDict = dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first = list(dependency_tree.leaf_iterator()) def index_for_class(class_): return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"])) # sort", "class %s in %s\" print(message % (class_[\"name\"], header_name)) elif (module, header_name, class_[\"name\"]) in", "break else: return False return len(m1[\"parameters\"]) == len(m2[\"parameters\"]) def private_methods_defined_outside(private_methods: List[CppMethod], methods_declared_outside: List[CppMethod])", "and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if not boost_function: continue filtered_methods.append(m) return filtered_methods def same_parameters(p1: Dict, p2:", "= {} for (module, header_name), text in generated_headers.items(): if text: output_path = join(PATH_MODULES,", "(module, header_name) in HEADERS_TO_SKIP: continue headers_to_generate_temp.append(tuple([module, header_name, path])) return headers_to_generate_temp def get_pure_virtual_methods(class_: CppHeaderParser.CppClass)", "# hpp files_to_write = {} for (module, header_name), text in generated_headers.items(): if text:", "import Counter from collections import defaultdict, OrderedDict from os.path import join from typing", "if not \"using\" in p[\"type\"] and not \"union\" in p[\"type\"]] union_properties = [p", "SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from generators.definitions.function import generate_function_definitions, get_methods_defined_outside from generators.definitions.method import split_methods_by_type from generators.definitions.submodule_loader import", "m2: CppMethod) -> bool: if m1[\"name\"] != m2[\"name\"]: return False # bug in", "def private_methods_defined_outside(private_methods: List[CppMethod], methods_declared_outside: List[CppMethod]) -> List[CppMethod]: private_defined_outside = [] for m_private in", "class_[\"name\"], class_properties) constructors, variables, others = split_methods_by_type(methods, class_properties, needs_overloading) if not class_[\"can_be_instantiated\"]: constructors", "path)) a(\"\") namespaces = set([c[\"namespace\"] for c in main_classes]) for namespace in namespaces:", "header, path in headers_to_generate: generated_headers[(module, header)] = generate_header(module, header, path, keep_if_no_instantiation=False) return generated_headers", "flag_instantiatable_class(dependency_tree, main_classes): \"\"\"determine if the class can be instantiated\"\"\" main_classes_by_name_namespace = {make_namespace_class(c[\"namespace\"], c[\"name\"]):", "methods_defined_outside) class_properties = [p for p in class_[\"properties\"][\"public\"] if not \"using\" in p[\"type\"]", "in modules for header_name, path in listmod(module)] base_headers = [(\"\", f, f) for", "private_defined_outside.append(m_private) break return private_defined_outside def generate_class_definitions(main_classes, module, header_name, path, needs_overloading: List[str], methods_defined_outside: List[CppMethod])", "headers_to_generate: generated_headers[(module, header)] = generate_header(module, header, path, keep_if_no_instantiation=False) return generated_headers def main(): import", "class_ for module, classes in classes_by_module.items(): needs = [] for class_ in classes:", "%s;\" % namespace) a(\"\\n\") for class_ in main_classes: methods = class_[\"methods\"][\"public\"] methods =", "False if keep: filtered.append(f) return filtered def get_variables(header): variables = [v for v", "module_functions[(module, header)] header_classes = main_classes[(module, header)] methods_defined_outside = get_methods_defined_outside(header_functions) class_definitions = generate_class_definitions(header_classes, module,", "generators.definitions.function import generate_function_definitions, get_methods_defined_outside from generators.definitions.method import split_methods_by_type from generators.definitions.submodule_loader import generate_loader from", "module, header, path, methods_need_overloading.get(module), methods_defined_outside) function_definitions = generate_function_definitions(header_functions, module, header, not_every_point_type=not_every_point_type) instantiations =", "Instantiations(header_classes, module, header, classes_point_types, module_variables[(module, header)], module_enums[(module, header)], ) instantiation_function = instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated", "= False if keep: filtered.append(f) return filtered def get_variables(header): variables = [v for", "= MODULES_TO_BUILD if skip_modules is not None: modules = [m for m in", "v = open(path).read() if v != text: print(\"File is different: %s\" % os.path.split(path)[1])", "f[\"parameters\"]: for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_ in param[\"type\"]: keep = False if", "main_classes.items(): classes_by_module[module] += class_ for module, classes in classes_by_module.items(): needs = [] for", "module, header_name, path in headers_to_generate[:]: header_full_path = join(PCL_BASE, path) if path else join(PCL_BASE,", "modules = MODULES_TO_BUILD if skip_modules is not None: modules = [m for m", "def main(): import time t = time.time() windows = platform.system() == \"Windows\" skip_macros", "= get_main_classes(header, module, header_name) module_functions[(module, header_name)] = get_functions(header, module) module_variables[(module, header_name)] = get_variables(header)", "import join from typing import List, Dict, Set from CppHeaderParser import CppHeaderParser from", "False # bug in CppHeaderParser # in \"void ImageGrabber<PointT>::publish\", \"void ImageGrabber<PointT>::\" is the", "os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True) def write_stuff_if_needed(generated_headers: OrderedDict, delete_others=True): modules = set(module for module, _", "def filter_methods_to_skip(methods): filtered_methods = [] for m in methods: if (m[\"parent\"][\"name\"], m[\"name\"]) in", "module) if not os.path.exists(module_dir): os.makedirs(module_dir) def is_file_different(path, text): v = open(path).read() if v", "= get_enums(header) classes = [c for module, header, path in headers_to_generate for c", "for base, folders, files in os.walk(join(PCL_BASE, module)): if any(base.endswith(m) for m in SUBMODULES_TO_SKIP):", "platform import shutil import sys from collections import Counter from collections import defaultdict,", "Set from CppHeaderParser import CppHeaderParser from CppHeaderParser.CppHeaderParser import CppMethod import generators.dependency_tree from generators.config", "ImageGrabber<PointT>::publish\", \"void ImageGrabber<PointT>::\" is the return type path = m1.get(\"path\", m2.get(\"path\")) path =", "os.path.split(path)[1]) return False def write_if_different(files_to_write, delete_others): written = [] for base, folder, files", "for a in access for m in class_[\"methods\"][a] if m[\"pure_virtual\"]]) def get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass)", "variables = [v for v in header.variables if v.get(\"defaultValue\") and 'using' != v.get('type')]", "written.append(path) elif delete_others: os.remove(path) print(\"Deleted: \" + path) # write new files for", "= sorted(functions, key=lambda f: f[\"name\"]) filtered = filter_module_level_functions(functions) return filtered def filter_module_level_functions(functions: List[CppMethod]):", "a in access for m in class_[\"methods\"][a] if m[\"pure_virtual\"]]) def get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass) ->", "in p[\"type\"] and not \"union\" in p[\"type\"]] union_properties = [p for nested_class in", "text): v = open(path).read() if v != text: print(\"File is different: %s\" %", "[p for nested_class in class_[\"nested_classes\"] for p in nested_class[\"properties\"][\"public\"] if \"union\" in nested_class[\"name\"]]", "make_header_include_name, sort_headers_by_dependencies, \\ generate_main_loader, make_namespace_class, read_header_file def filter_methods_for_parser_errors(methods): return [m for m in", "def get_headers(modules=None, skip_modules=None): def listmod(module): found_modules = [] for base, folders, files in", "check_if_needs_overloading(main_classes): needs_overloading = {} classes_by_module = defaultdict(list) for (module, _), class_ in main_classes.items():", "# write new files for path, text in files_to_write.items(): if path not in", "module, header_name, path in headers_to_generate: if (module, header_name) in HEADERS_TO_SKIP: continue headers_to_generate_temp.append(tuple([module, header_name,", "{}, {}, {}, {} for module, header_name, path in headers_to_generate[:]: header_full_path = join(PCL_BASE,", "-> str: header_functions = module_functions[(module, header)] header_classes = main_classes[(module, header)] methods_defined_outside = get_methods_defined_outside(header_functions)", "p2[f] for f in fields) def same_methods(m1: CppMethod, m2: CppMethod) -> bool: if", "skip_macros) main_classes[(module, header_name)] = get_main_classes(header, module, header_name) module_functions[(module, header_name)] = get_functions(header, module) module_variables[(module,", "enums = sorted(enums, key=lambda v: v[\"name\"]) return enums def read_header(header_path, skip_macros=None): # I", "text in files_to_write.items(): if path not in written: open(path, \"w\").write(files_to_write[path]) def delete_other_dirs(modules): for", "index_for_class(class_): return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"])) # sort classes inside modules based on inheritance for", "class_[\"can_be_instantiated\"] = can_be_instantiated def load_yaml_point_types(not_every_point_type): classes_point_types = unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type) extra_point_types = unpack_yaml_point_types(\"point_types_extra.yml\") for", "if key in ATTRIBUTES_TO_SKIP: to_ignore = ATTRIBUTES_TO_SKIP[key] filtered_properties = [] for p in", "in METHODS_TO_SKIP: continue if \"Callback\" in m[\"name\"]: single_argument = len(m[\"parameters\"]) == 1 boost_function", "for path, text in files_to_write.items(): if path not in written: open(path, \"w\").write(files_to_write[path]) def", "type_ in [m1[\"rtnType\"], m2[\"rtnType\"]]): return False # same parameters for p1 in m1[\"parameters\"]:", "header_name, module) main_classes = [c for c in header.classes.values() if c[\"namespace\"] in (\"pcl\",", "module, classes in classes_by_module.items(): needs = [] for class_ in classes: count =", "for m in class_[\"methods\"][a] if m[\"pure_virtual\"]]) def get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass) -> Set[str]: access =", "= [p for p in properties if p[\"name\"]] if key in ATTRIBUTES_TO_SKIP: to_ignore", "in headers_to_generate: generated_headers[(module, header)] = generate_header(module, header, path, keep_if_no_instantiation=False) return generated_headers def main():", "= True if f.get(\"returns_const\"): keep = False for param in f[\"parameters\"]: for type_", "Counter from collections import defaultdict, OrderedDict from os.path import join from typing import", "class_name, properties): key = (module, header, class_name) # ignore properties without a name", "methods_defined_outside) function_definitions = generate_function_definitions(header_functions, module, header, not_every_point_type=not_every_point_type) instantiations = Instantiations(header_classes, module, header, classes_point_types,", "extra_point_types = unpack_yaml_point_types(\"point_types_extra.yml\") for k, v in extra_point_types.items(): if k in classes_point_types: classes_point_types[k].append(v)", "in generated_headers.keys()) make_module_dirs(modules) # hpp files_to_write = {} for (module, header_name), text in", "methods_defined_outside: List[CppMethod]) -> str: text = [] a = text.append a(common_includes) a(EXPLICIT_INCLUDES.get((module, header_name),", "loaders loader_modules = defaultdict(list) for (module, header_name), text in generated_headers.items(): if text: loader_modules[module", "== len(m2[\"parameters\"]) def private_methods_defined_outside(private_methods: List[CppMethod], methods_declared_outside: List[CppMethod]) -> List[CppMethod]: private_defined_outside = [] for", "base_class and base_class[\"abstract\"]: base_pure_virtual_methods = get_pure_virtual_methods(base_class) if base_pure_virtual_methods - all_implemented_inherited_methods: can_be_instantiated = False", "= get_headers(skip_modules=skip_modules) not_every_point_type = \"--not-every-point-type\" in sys.argv generated_headers = generate(all_headers, skip_macros, not_every_point_type) write_stuff_if_needed(generated_headers,", "get_pure_virtual_methods(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private protected public\".split() return set([m[\"name\"] for a", "in properties: if p[\"name\"] in to_ignore: continue filtered_properties.append(p) properties = filtered_properties return properties", "not \"using\" in p[\"type\"] and not \"union\" in p[\"type\"]] union_properties = [p for", "ATTRIBUTES_TO_SKIP[key] filtered_properties = [] for p in properties: if p[\"name\"] in to_ignore: continue", "class_[\"properties\"][\"public\"] if not \"using\" in p[\"type\"] and not \"union\" in p[\"type\"]] union_properties =", "is not None: modules = [m for m in modules if m not", "for module, _ in generated_headers.keys()) make_module_dirs(modules) # hpp files_to_write = {} for (module,", "# skip nameless enums enums = sorted(enums, key=lambda v: v[\"name\"]) return enums def", "= m1.get(\"path\", m2.get(\"path\")) path = path[path.rfind(\":\") + 1:] if not any(path in type_", "if f.endswith(\".h\"): found_modules.append([f, join(relative_base, f)]) return found_modules if modules is None: modules =", "def get_main_classes(header, module, header_name): # header = read_headers(base_path, header_name, module) main_classes = [c", "main_classes, module_functions, module_variables, module_enums = {}, {}, {}, {} for module, header_name, path", "for methods in class_[\"methods\"].values() for m in methods) for name, count in count.items():", "if v != text: print(\"File is different: %s\" % os.path.split(path)[1]) return True #", "not implemented for class %s in %s\" print(message % (class_[\"name\"], header_name)) elif (module,", "CppHeaderParser from CppHeaderParser.CppHeaderParser import CppMethod import generators.dependency_tree from generators.config import common_includes, PCL_BASE, PATH_LOADER,", "if e.get(\"name\")] # skip nameless enums enums = sorted(enums, key=lambda v: v[\"name\"]) return", "= [] for class_ in classes: count = Counter(m[\"name\"] for methods in class_[\"methods\"].values()", "= get_methods_defined_outside(header_functions) class_definitions = generate_class_definitions(header_classes, module, header, path, methods_need_overloading.get(module), methods_defined_outside) function_definitions = generate_function_definitions(header_functions,", "= filter_methods_for_parser_errors(methods) methods = filter_methods_to_skip(methods) private_and_protected = class_[\"methods\"][\"private\"] + class_[\"methods\"][\"protected\"] methods += private_methods_defined_outside(private_and_protected,", "List, Dict, Set from CppHeaderParser import CppHeaderParser from CppHeaderParser.CppHeaderParser import CppMethod import generators.dependency_tree", "return set([m[\"name\"] for a in access for m in class_[\"methods\"][a] if not m[\"pure_virtual\"]])", "single_argument and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if not boost_function: continue filtered_methods.append(m) return filtered_methods def same_parameters(p1: Dict,", "public\".split() return set([m[\"name\"] for a in access for m in class_[\"methods\"][a] if not", "in properties if p[\"name\"]] if key in ATTRIBUTES_TO_SKIP: to_ignore = ATTRIBUTES_TO_SKIP[key] filtered_properties =", "[e for e in header.enums if e.get(\"name\")] # skip nameless enums enums =", "key=lambda c: c[\"name\"]) return filtered_main_classes def get_functions(header, module): functions = [f for f", "get_main_classes(header, module, header_name): # header = read_headers(base_path, header_name, module) main_classes = [c for", "from generators.instantiations import Instantiations from generators.point_types_utils import unpack_yaml_point_types from generators.utils import make_header_include_name, sort_headers_by_dependencies,", "m in class_[\"methods\"][a] if m[\"pure_virtual\"]]) def get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private", "= filter_module_level_functions(functions) return filtered def filter_module_level_functions(functions: List[CppMethod]): filtered = [] for f in", "any(base.endswith(m) for m in SUBMODULES_TO_SKIP): continue relative_base = os.path.abspath(base).replace(PCL_BASE, \"\")[1:] for f in", "CppHeaderParser.CppHeaderParser import CppMethod import generators.dependency_tree from generators.config import common_includes, PCL_BASE, PATH_LOADER, PATH_MODULES, MODULES_TO_BUILD,", "specialized_template = class_.get(\"template\") and \"<\" in class_[\"name\"] if specialized_template: to_skip = any((\"<%s>\" %", "else: return False return len(m1[\"parameters\"]) == len(m2[\"parameters\"]) def private_methods_defined_outside(private_methods: List[CppMethod], methods_declared_outside: List[CppMethod]) ->", "a(class_def.to_class_function_definition()) a(\"\") return \"\\n\".join(text) def filter_class_properties(module, header, class_name, properties): key = (module, header,", "(\"pcl\", \"pcl::\" + module)] filtered_main_classes = [] for class_ in main_classes: specialized_template =", "can_be_instantiated def load_yaml_point_types(not_every_point_type): classes_point_types = unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type) extra_point_types = unpack_yaml_point_types(\"point_types_extra.yml\") for k, v", "{}, {}, {} for module, header_name, path in headers_to_generate[:]: header_full_path = join(PCL_BASE, path)", "class_properties = filter_class_properties(module, header_name, class_[\"name\"], class_properties) constructors, variables, others = split_methods_by_type(methods, class_properties, needs_overloading)", "count = Counter(m[\"name\"] for methods in class_[\"methods\"].values() for m in methods) for name,", "from os.path import join from typing import List, Dict, Set from CppHeaderParser import", "return classes_point_types def make_module_dirs(modules): for module in modules: module_dir = join(PATH_MODULES, module) if", "methods_defined_outside = get_methods_defined_outside(header_functions) class_definitions = generate_class_definitions(header_classes, module, header, path, methods_need_overloading.get(module), methods_defined_outside) function_definitions =", "m2[\"name\"] and same_parameters(p1, p2): break else: return False return len(m1[\"parameters\"]) == len(m2[\"parameters\"]) def", "threads but it seems like CppHeaderParser is not thread safe... if skip_macros is", "base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class and base_class[\"abstract\"]: base_pure_virtual_methods = get_pure_virtual_methods(base_class) if base_pure_virtual_methods -", "from generators.utils import make_header_include_name, sort_headers_by_dependencies, \\ generate_main_loader, make_namespace_class, read_header_file def filter_methods_for_parser_errors(methods): return [m", "f.get(\"returns_const\"): keep = False for param in f[\"parameters\"]: for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if", "def check_if_needs_overloading(main_classes): needs_overloading = {} classes_by_module = defaultdict(list) for (module, _), class_ in", "headers_to_generate_temp = [] for module, header_name, path in headers_to_generate: if (module, header_name) in", "[p for p in class_[\"properties\"][\"public\"] if not \"using\" in p[\"type\"] and not \"union\"", "header_name), text in generated_headers.items(): if text: output_path = join(PATH_MODULES, module, header_name + \"pp\")", "in headers_to_generate for c in main_classes[(module, header)]] dependency_tree = generators.dependency_tree.DependencyTree(classes) loaded_point_types = load_yaml_point_types(not_every_point_type)", "# header = read_headers(base_path, header_name, module) main_classes = [c for c in header.classes.values()", "private_and_protected = class_[\"methods\"][\"private\"] + class_[\"methods\"][\"protected\"] methods += private_methods_defined_outside(private_and_protected, methods_defined_outside) class_properties = [p for", "for p in class_[\"properties\"][\"public\"] if not \"using\" in p[\"type\"] and not \"union\" in", "not in modules and os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True) def write_stuff_if_needed(generated_headers: OrderedDict, delete_others=True): modules =", "+= union_properties class_properties = filter_class_properties(module, header_name, class_[\"name\"], class_properties) constructors, variables, others = split_methods_by_type(methods,", "boost_function: continue filtered_methods.append(m) return filtered_methods def same_parameters(p1: Dict, p2: Dict) -> bool: fields", "header_name), text in generated_headers.items(): if text: loader_modules[module or \"base\"].append(header_name) for module, headers in", "(m[\"parent\"][\"name\"], m[\"name\"]) in METHODS_TO_SKIP: continue if \"Callback\" in m[\"name\"]: single_argument = len(m[\"parameters\"]) ==", "% type_) in class_[\"name\"] for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if not to_skip: message =", "from typing import List, Dict, Set from CppHeaderParser import CppHeaderParser from CppHeaderParser.CppHeaderParser import", "filter_methods_for_parser_errors(methods): return [m for m in methods if not m[\"name\"] in (\"void\", \"bool\")]", "[p for p in properties if p[\"name\"]] if key in ATTRIBUTES_TO_SKIP: to_ignore =", "m2.get(\"path\")) path = path[path.rfind(\":\") + 1:] if not any(path in type_ for type_", "import CppHeaderParser from CppHeaderParser.CppHeaderParser import CppMethod import generators.dependency_tree from generators.config import common_includes, PCL_BASE,", "v: v[\"name\"]) return variables def get_enums(header): enums = [e for e in header.enums", "in os.walk(PATH_MODULES): for f in files: path = join(base, f) if path in", "= read_headers(base_path, header_name, module) main_classes = [c for c in header.classes.values() if c[\"namespace\"]", "module, header, not_every_point_type=not_every_point_type) instantiations = Instantiations(header_classes, module, header, classes_point_types, module_variables[(module, header)], module_enums[(module, header)],", "header_full_path = join(PCL_BASE, path) if path else join(PCL_BASE, module, header_name) header = read_header(header_full_path,", "(module, header_name, class_[\"name\"]) in CLASSES_TO_IGNORE: pass else: filtered_main_classes.append(class_) filtered_main_classes = sorted(filtered_main_classes, key=lambda c:", "others = split_methods_by_type(methods, class_properties, needs_overloading) if not class_[\"can_be_instantiated\"]: constructors = [] class_def =", "in sys.argv generated_headers = generate(all_headers, skip_macros, not_every_point_type) write_stuff_if_needed(generated_headers, delete_others=True) print(\"generated in %.2f s\"", "is_file_different(path, text): v = open(path).read() if v != text: print(\"File is different: %s\"", "seems like CppHeaderParser is not thread safe... if skip_macros is None: skip_macros =", "all_headers = get_headers(skip_modules=skip_modules) not_every_point_type = \"--not-every-point-type\" in sys.argv generated_headers = generate(all_headers, skip_macros, not_every_point_type)", "write_stuff_if_needed(generated_headers, delete_others=True) print(\"generated in %.2f s\" % (time.time() - t,)) if __name__ ==", "join(PATH_MODULES, module, header_name + \"pp\") files_to_write[output_path] = text # loaders loader_modules = defaultdict(list)", "= instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated = len(instantiation_function.split(\"\\n\")) > 2 text = [] if something_instantiated or", "private_methods_defined_outside(private_and_protected, methods_defined_outside) class_properties = [p for p in class_[\"properties\"][\"public\"] if not \"using\" in", "class_name) # ignore properties without a name properties = [p for p in", "in classes_by_module.items(): needs = [] for class_ in classes: count = Counter(m[\"name\"] for", "loader_modules = defaultdict(list) for (module, header_name), text in generated_headers.items(): if text: loader_modules[module or", "not boost_function: continue filtered_methods.append(m) return filtered_methods def same_parameters(p1: Dict, p2: Dict) -> bool:", "dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first = list(dependency_tree.leaf_iterator()) def index_for_class(class_): return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"])) # sort classes inside", "\" + path) # write new files for path, text in files_to_write.items(): if", "(module, _), class_ in main_classes.items(): classes_by_module[module] += class_ for module, classes in classes_by_module.items():", "= [\"constant\", \"name\", \"raw_type\", \"reference\", \"static\"] return all(p1[f] == p2[f] for f in", "for p2 in m2[\"parameters\"]: if m1[\"name\"] == m2[\"name\"] and same_parameters(p1, p2): break else:", "header)]] dependency_tree = generators.dependency_tree.DependencyTree(classes) loaded_point_types = load_yaml_point_types(not_every_point_type) classes_point_types: OrderedDict = dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first =", "for (module, header_name), text in generated_headers.items(): if text: loader_modules[module or \"base\"].append(header_name) for module,", "needs return needs_overloading def get_headers(modules=None, skip_modules=None): def listmod(module): found_modules = [] for base,", "main(): import time t = time.time() windows = platform.system() == \"Windows\" skip_macros =", "len(m2[\"parameters\"]) def private_methods_defined_outside(private_methods: List[CppMethod], methods_declared_outside: List[CppMethod]) -> List[CppMethod]: private_defined_outside = [] for m_private", "= [class_definitions, function_definitions, instantiation_function] return \"\\n\".join(text) generated_headers = OrderedDict() for module, header, path", "for module, header_name, path in headers_to_generate: if (module, header_name) in HEADERS_TO_SKIP: continue headers_to_generate_temp.append(tuple([module,", "access for m in class_[\"methods\"][a] if m[\"pure_virtual\"]]) def get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass) -> Set[str]: access", "2 text = [] if something_instantiated or keep_if_no_instantiation: text = [class_definitions, function_definitions, instantiation_function]", "in main_classes.values() for c in classes} for module, header_name in main_classes: for class_", "keep_if_no_instantiation=False) return generated_headers def main(): import time t = time.time() windows = platform.system()", "type path = m1.get(\"path\", m2.get(\"path\")) path = path[path.rfind(\":\") + 1:] if not any(path", "if text: loader_modules[module or \"base\"].append(header_name) for module, headers in loader_modules.items(): path_loader = join(PATH_MODULES,", "nameless enums enums = sorted(enums, key=lambda v: v[\"name\"]) return enums def read_header(header_path, skip_macros=None):", "= check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree, main_classes) def generate_header(module, header, path, keep_if_no_instantiation) -> str: header_functions =", "= [] skip_modules = [] if not windows: skip_macros = [\"_MSC_VER\"] #skip_modules =", "parser.debug = False header = parser.CppHeader(header_file_str, argType=\"string\") return header def clean(): try: os.remove(PATH_LOADER)", "module_variables, module_enums = {}, {}, {}, {} for module, header_name, path in headers_to_generate[:]:", "module, header_name): # header = read_headers(base_path, header_name, module) main_classes = [c for c", "count >= 2: needs.append(name) needs_overloading[module] = needs return needs_overloading def get_headers(modules=None, skip_modules=None): def", "main_classes]) for namespace in namespaces: if not namespace == \"pcl\": a(\"using namespace %s;\"", "implemented all_implemented_inherited_methods = get_all_class_methods_not_pure_virtual(class_) namespace_class = make_namespace_class(class_[\"namespace\"], class_[\"name\"]) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class", "if not any(path in type_ for type_ in [m1[\"rtnType\"], m2[\"rtnType\"]]): return False #", "in class_[\"name\"] for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if not to_skip: message = \"Warning: Template", "filtered.append(f) return filtered def get_variables(header): variables = [v for v in header.variables if", "f) if f not in modules and os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True) def write_stuff_if_needed(generated_headers: OrderedDict,", "classes_point_types, module_variables[(module, header)], module_enums[(module, header)], ) instantiation_function = instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated = len(instantiation_function.split(\"\\n\")) >", "import Instantiations from generators.point_types_utils import unpack_yaml_point_types from generators.utils import make_header_include_name, sort_headers_by_dependencies, \\ generate_main_loader,", "multiple threads but it seems like CppHeaderParser is not thread safe... if skip_macros", "keep_if_no_instantiation) -> str: header_functions = module_functions[(module, header)] header_classes = main_classes[(module, header)] methods_defined_outside =", "union_properties class_properties = filter_class_properties(module, header_name, class_[\"name\"], class_properties) constructors, variables, others = split_methods_by_type(methods, class_properties,", "properties without a name properties = [p for p in properties if p[\"name\"]]", "[class_definitions, function_definitions, instantiation_function] return \"\\n\".join(text) generated_headers = OrderedDict() for module, header, path in", "not any(path in type_ for type_ in [m1[\"rtnType\"], m2[\"rtnType\"]]): return False # same", "def same_parameters(p1: Dict, p2: Dict) -> bool: fields = [\"constant\", \"name\", \"raw_type\", \"reference\",", "for c in main_classes[(module, header)]] dependency_tree = generators.dependency_tree.DependencyTree(classes) loaded_point_types = load_yaml_point_types(not_every_point_type) classes_point_types: OrderedDict", "main_classes[(module, header)]] dependency_tree = generators.dependency_tree.DependencyTree(classes) loaded_point_types = load_yaml_point_types(not_every_point_type) classes_point_types: OrderedDict = dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first", "Counter(m[\"name\"] for methods in class_[\"methods\"].values() for m in methods) for name, count in", "this in multiple threads but it seems like CppHeaderParser is not thread safe...", "header_name)) elif (module, header_name, class_[\"name\"]) in CLASSES_TO_IGNORE: pass else: filtered_main_classes.append(class_) filtered_main_classes = sorted(filtered_main_classes,", "generate_function_definitions(header_functions, module, header, not_every_point_type=not_every_point_type) instantiations = Instantiations(header_classes, module, header, classes_point_types, module_variables[(module, header)], module_enums[(module,", "c[\"name\"]) return filtered_main_classes def get_functions(header, module): functions = [f for f in header.functions", "write new files for path, text in files_to_write.items(): if path not in written:", "base_headers headers_to_generate_temp = [] for module, header_name, path in headers_to_generate: if (module, header_name)", "type_ in param[\"type\"]: keep = False if keep: filtered.append(f) return filtered def get_variables(header):", "base_class_methods = get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class", "else join(PCL_BASE, module, header_name) header = read_header(header_full_path, skip_macros) main_classes[(module, header_name)] = get_main_classes(header, module,", "if path else join(PCL_BASE, module, header_name) header = read_header(header_full_path, skip_macros) main_classes[(module, header_name)] =", "methods = filter_methods_to_skip(methods) private_and_protected = class_[\"methods\"][\"private\"] + class_[\"methods\"][\"protected\"] methods += private_methods_defined_outside(private_and_protected, methods_defined_outside) class_properties", "MODULES_TO_BUILD if skip_modules is not None: modules = [m for m in modules", "path, methods_need_overloading.get(module), methods_defined_outside) function_definitions = generate_function_definitions(header_functions, module, header, not_every_point_type=not_every_point_type) instantiations = Instantiations(header_classes, module,", "modules = [m for m in modules if m not in skip_modules] headers_to_generate", "False for param in f[\"parameters\"]: for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_ in param[\"type\"]:", "others, module) a(class_def.to_class_function_definition()) a(\"\") return \"\\n\".join(text) def filter_class_properties(module, header, class_name, properties): key =", "methods) for name, count in count.items(): if count >= 2: needs.append(name) needs_overloading[module] =", "def generate_class_definitions(main_classes, module, header_name, path, needs_overloading: List[str], methods_defined_outside: List[CppMethod]) -> str: text =", "module_variables[(module, header)], module_enums[(module, header)], ) instantiation_function = instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated = len(instantiation_function.split(\"\\n\")) > 2", "\"w\").write(files_to_write[path]) written.append(path) elif delete_others: os.remove(path) print(\"Deleted: \" + path) # write new files", "\"pcl::\" + module)] filtered_main_classes = [] for class_ in main_classes: specialized_template = class_.get(\"template\")", "print(\"Deleted: \" + path) # write new files for path, text in files_to_write.items():", "EXPLICIT_INCLUDES, \\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from generators.definitions.function import generate_function_definitions, get_methods_defined_outside from generators.definitions.method import split_methods_by_type from", "header_name, class_[\"name\"], class_properties) constructors, variables, others = split_methods_by_type(methods, class_properties, needs_overloading) if not class_[\"can_be_instantiated\"]:", "f in functions: keep = True if f.get(\"returns_const\"): keep = False for param", "in os.listdir(PATH_MODULES): folder = join(PATH_MODULES, f) if f not in modules and os.path.isdir(folder):", "for f in header.functions if f[\"namespace\"] in (\"pcl\", \"pcl::\", \"pcl::%s\" % module, \"pcl::%s::\"", "text = [] if something_instantiated or keep_if_no_instantiation: text = [class_definitions, function_definitions, instantiation_function] return", "in class_[\"name\"] if specialized_template: to_skip = any((\"<%s>\" % type_) in class_[\"name\"] for type_", "like CppHeaderParser is not thread safe... if skip_macros is None: skip_macros = []", "if base_class: base_class_methods = get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp)", "generated_headers.items(): if text: loader_modules[module or \"base\"].append(header_name) for module, headers in loader_modules.items(): path_loader =", "return type path = m1.get(\"path\", m2.get(\"path\")) path = path[path.rfind(\":\") + 1:] if not", "get_all_class_methods_not_pure_virtual(class_) namespace_class = make_namespace_class(class_[\"namespace\"], class_[\"name\"]) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if", "if delete_others: delete_other_dirs(modules) def generate(headers_to_generate, skip_macros, not_every_point_type=False) -> OrderedDict: \"\"\" :return: OrderedDict \"\"\"", "m_outside): private_defined_outside.append(m_private) break return private_defined_outside def generate_class_definitions(main_classes, module, header_name, path, needs_overloading: List[str], methods_defined_outside:", "[] for base, folder, files in os.walk(PATH_MODULES): for f in files: path =", "# sort classes inside modules based on inheritance for module, header in main_classes:", "in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class and base_class[\"abstract\"]: base_pure_virtual_methods = get_pure_virtual_methods(base_class) if", "all(p1[f] == p2[f] for f in fields) def same_methods(m1: CppMethod, m2: CppMethod) ->", "in access for m in class_[\"methods\"][a] if not m[\"pure_virtual\"]]) def flag_instantiatable_class(dependency_tree, main_classes): \"\"\"determine", "not thread safe... if skip_macros is None: skip_macros = [] header_file_str = read_header_file(header_path,", "main_classes[(module, header)] = list(sorted(main_classes[(module, header)], key=index_for_class)) headers_to_generate = sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros) methods_need_overloading = check_if_needs_overloading(main_classes)", "= generate_main_loader(loader_modules) write_if_different(files_to_write, delete_others) if delete_others: delete_other_dirs(modules) def generate(headers_to_generate, skip_macros, not_every_point_type=False) -> OrderedDict:", "split_methods_by_type(methods, class_properties, needs_overloading) if not class_[\"can_be_instantiated\"]: constructors = [] class_def = ClassDefinition(class_, constructors,", "files_to_write = {} for (module, header_name), text in generated_headers.items(): if text: output_path =", "= read_header(header_full_path, skip_macros) main_classes[(module, header_name)] = get_main_classes(header, module, header_name) module_functions[(module, header_name)] = get_functions(header,", "path in headers_to_generate: generated_headers[(module, header)] = generate_header(module, header, path, keep_if_no_instantiation=False) return generated_headers def", "len(m1[\"parameters\"]) == len(m2[\"parameters\"]) def private_methods_defined_outside(private_methods: List[CppMethod], methods_declared_outside: List[CppMethod]) -> List[CppMethod]: private_defined_outside = []", "return len(m1[\"parameters\"]) == len(m2[\"parameters\"]) def private_methods_defined_outside(private_methods: List[CppMethod], methods_declared_outside: List[CppMethod]) -> List[CppMethod]: private_defined_outside =", "os.walk(PATH_MODULES): for f in files: path = join(base, f) if path in files_to_write:", "if p[\"name\"] in to_ignore: continue filtered_properties.append(p) properties = filtered_properties return properties def get_main_classes(header,", "_), class_ in main_classes.items(): classes_by_module[module] += class_ for module, classes in classes_by_module.items(): needs", "windows = platform.system() == \"Windows\" skip_macros = [] skip_modules = [] if not", "in to_ignore: continue filtered_properties.append(p) properties = filtered_properties return properties def get_main_classes(header, module, header_name):", "= single_argument and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if not boost_function: continue filtered_methods.append(m) return filtered_methods def same_parameters(p1:", "open(path, \"w\").write(files_to_write[path]) written.append(path) elif delete_others: os.remove(path) print(\"Deleted: \" + path) # write new", "+= base_headers headers_to_generate_temp = [] for module, header_name, path in headers_to_generate: if (module,", "in private_methods: for m_outside in methods_declared_outside: if same_methods(m_private, m_outside): private_defined_outside.append(m_private) break return private_defined_outside", "== p2[f] for f in fields) def same_methods(m1: CppMethod, m2: CppMethod) -> bool:", "in listmod(module)] base_headers = [(\"\", f, f) for f in os.listdir(PCL_BASE) if f.endswith(\".h\")]", "[] skip_modules = [] if not windows: skip_macros = [\"_MSC_VER\"] #skip_modules = [\"visualization\"]", "path in listmod(module)] base_headers = [(\"\", f, f) for f in os.listdir(PCL_BASE) if", "for module, headers in loader_modules.items(): path_loader = join(PATH_MODULES, \"_%s_loader.cpp\" % module) files_to_write[path_loader] =", "header.enums if e.get(\"name\")] # skip nameless enums enums = sorted(enums, key=lambda v: v[\"name\"])", "except FileNotFoundError: pass if os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES) def check_if_needs_overloading(main_classes): needs_overloading = {} classes_by_module =", "module, header_name) module_functions[(module, header_name)] = get_functions(header, module) module_variables[(module, header_name)] = get_variables(header) module_enums[(module, header_name)]", "filter_class_properties(module, header, class_name, properties): key = (module, header, class_name) # ignore properties without", "skip_macros, not_every_point_type=False) -> OrderedDict: \"\"\" :return: OrderedDict \"\"\" main_classes, module_functions, module_variables, module_enums =", "based on inheritance for module, header in main_classes: main_classes[(module, header)] = list(sorted(main_classes[(module, header)],", "% os.path.split(path)[1]) return False def write_if_different(files_to_write, delete_others): written = [] for base, folder,", "filtered_methods = [] for m in methods: if (m[\"parent\"][\"name\"], m[\"name\"]) in METHODS_TO_SKIP: continue", "if k in classes_point_types: classes_point_types[k].append(v) else: classes_point_types[k] = v return classes_point_types def make_module_dirs(modules):", "\"Windows\" skip_macros = [] skip_modules = [] if not windows: skip_macros = [\"_MSC_VER\"]", "f[\"namespace\"] in (\"pcl\", \"pcl::\", \"pcl::%s\" % module, \"pcl::%s::\" % module)] functions = sorted(functions,", "for nested_class in class_[\"nested_classes\"] for p in nested_class[\"properties\"][\"public\"] if \"union\" in nested_class[\"name\"]] class_properties", "a in access for m in class_[\"methods\"][a] if not m[\"pure_virtual\"]]) def flag_instantiatable_class(dependency_tree, main_classes):", "in \"void ImageGrabber<PointT>::publish\", \"void ImageGrabber<PointT>::\" is the return type path = m1.get(\"path\", m2.get(\"path\"))", "is the return type path = m1.get(\"path\", m2.get(\"path\")) path = path[path.rfind(\":\") + 1:]", "main_classes_by_name_namespace = {make_namespace_class(c[\"namespace\"], c[\"name\"]): c for classes in main_classes.values() for c in classes}", "methods += private_methods_defined_outside(private_and_protected, methods_defined_outside) class_properties = [p for p in class_[\"properties\"][\"public\"] if not", "else: filtered_main_classes.append(class_) filtered_main_classes = sorted(filtered_main_classes, key=lambda c: c[\"name\"]) return filtered_main_classes def get_functions(header, module):", "different: %s\" % os.path.split(path)[1]) return True # print(\"File is the same: %s\" %", "# bug in CppHeaderParser # in \"void ImageGrabber<PointT>::publish\", \"void ImageGrabber<PointT>::\" is the return", "CppMethod import generators.dependency_tree from generators.config import common_includes, PCL_BASE, PATH_LOADER, PATH_MODULES, MODULES_TO_BUILD, \\ HEADERS_TO_SKIP,", "files_to_write[path]): open(path, \"w\").write(files_to_write[path]) written.append(path) elif delete_others: os.remove(path) print(\"Deleted: \" + path) # write", "namespace %s;\" % namespace) a(\"\\n\") for class_ in main_classes: methods = class_[\"methods\"][\"public\"] methods", "filtered_main_classes.append(class_) filtered_main_classes = sorted(filtered_main_classes, key=lambda c: c[\"name\"]) return filtered_main_classes def get_functions(header, module): functions", "for class_ in main_classes: specialized_template = class_.get(\"template\") and \"<\" in class_[\"name\"] if specialized_template:", "SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_ in param[\"type\"]: keep = False if keep: filtered.append(f) return filtered", "os.listdir(PATH_MODULES): folder = join(PATH_MODULES, f) if f not in modules and os.path.isdir(folder): shutil.rmtree(folder,", "in class_[\"methods\"][a] if m[\"pure_virtual\"]]) def get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private protected", "1:] if not any(path in type_ for type_ in [m1[\"rtnType\"], m2[\"rtnType\"]]): return False", "needs_overloading: List[str], methods_defined_outside: List[CppMethod]) -> str: text = [] a = text.append a(common_includes)", "= [] for base, folders, files in os.walk(join(PCL_BASE, module)): if any(base.endswith(m) for m", "for m in SUBMODULES_TO_SKIP): continue relative_base = os.path.abspath(base).replace(PCL_BASE, \"\")[1:] for f in files:", "in files: if f.endswith(\".h\"): found_modules.append([f, join(relative_base, f)]) return found_modules if modules is None:", "load_yaml_point_types(not_every_point_type) classes_point_types: OrderedDict = dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first = list(dependency_tree.leaf_iterator()) def index_for_class(class_): return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"]))", "= filter_class_properties(module, header_name, class_[\"name\"], class_properties) constructors, variables, others = split_methods_by_type(methods, class_properties, needs_overloading) if", "in (\"void\", \"bool\")] def filter_methods_to_skip(methods): filtered_methods = [] for m in methods: if", "path[path.rfind(\":\") + 1:] if not any(path in type_ for type_ in [m1[\"rtnType\"], m2[\"rtnType\"]]):", "module)] functions = sorted(functions, key=lambda f: f[\"name\"]) filtered = filter_module_level_functions(functions) return filtered def", "os import platform import shutil import sys from collections import Counter from collections", "-> List[CppMethod]: private_defined_outside = [] for m_private in private_methods: for m_outside in methods_declared_outside:", "main_classes) def generate_header(module, header, path, keep_if_no_instantiation) -> str: header_functions = module_functions[(module, header)] header_classes", "generators.utils import make_header_include_name, sort_headers_by_dependencies, \\ generate_main_loader, make_namespace_class, read_header_file def filter_methods_for_parser_errors(methods): return [m for", "= [] for p in properties: if p[\"name\"] in to_ignore: continue filtered_properties.append(p) properties", "join(PATH_MODULES, module) if not os.path.exists(module_dir): os.makedirs(module_dir) def is_file_different(path, text): v = open(path).read() if", "f)]) return found_modules if modules is None: modules = MODULES_TO_BUILD if skip_modules is", "sys.argv generated_headers = generate(all_headers, skip_macros, not_every_point_type) write_stuff_if_needed(generated_headers, delete_others=True) print(\"generated in %.2f s\" %", "[] for class_ in classes: count = Counter(m[\"name\"] for methods in class_[\"methods\"].values() for", "headers_to_generate_temp def get_pure_virtual_methods(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private protected public\".split() return set([m[\"name\"]", "namespaces: if not namespace == \"pcl\": a(\"using namespace %s;\" % namespace) a(\"\\n\") for", "return \"\\n\".join(text) generated_headers = OrderedDict() for module, header, path in headers_to_generate: generated_headers[(module, header)]", "CppHeaderParser # in \"void ImageGrabber<PointT>::publish\", \"void ImageGrabber<PointT>::\" is the return type path =", "p[\"type\"] and not \"union\" in p[\"type\"]] union_properties = [p for nested_class in class_[\"nested_classes\"]", "not_every_point_type) extra_point_types = unpack_yaml_point_types(\"point_types_extra.yml\") for k, v in extra_point_types.items(): if k in classes_point_types:", "in m[\"name\"]: single_argument = len(m[\"parameters\"]) == 1 boost_function = single_argument and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if", "class_properties = [p for p in class_[\"properties\"][\"public\"] if not \"using\" in p[\"type\"] and", "same_methods(m_private, m_outside): private_defined_outside.append(m_private) break return private_defined_outside def generate_class_definitions(main_classes, module, header_name, path, needs_overloading: List[str],", "instantiation_function] return \"\\n\".join(text) generated_headers = OrderedDict() for module, header, path in headers_to_generate: generated_headers[(module,", "module)] filtered_main_classes = [] for class_ in main_classes: specialized_template = class_.get(\"template\") and \"<\"", "get_functions(header, module): functions = [f for f in header.functions if f[\"namespace\"] in (\"pcl\",", "dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class and base_class[\"abstract\"]: base_pure_virtual_methods = get_pure_virtual_methods(base_class) if base_pure_virtual_methods", "join(relative_base, f)]) return found_modules if modules is None: modules = MODULES_TO_BUILD if skip_modules", "for p in properties if p[\"name\"]] if key in ATTRIBUTES_TO_SKIP: to_ignore = ATTRIBUTES_TO_SKIP[key]", "nested_class[\"name\"]] class_properties += union_properties class_properties = filter_class_properties(module, header_name, class_[\"name\"], class_properties) constructors, variables, others", "for a in access for m in class_[\"methods\"][a] if not m[\"pure_virtual\"]]) def flag_instantiatable_class(dependency_tree,", "without a name properties = [p for p in properties if p[\"name\"]] if", "base, folder, files in os.walk(PATH_MODULES): for f in files: path = join(base, f)", "= generate_function_definitions(header_functions, module, header, not_every_point_type=not_every_point_type) instantiations = Instantiations(header_classes, module, header, classes_point_types, module_variables[(module, header)],", "needs = [] for class_ in classes: count = Counter(m[\"name\"] for methods in", "in main_classes.items(): classes_by_module[module] += class_ for module, classes in classes_by_module.items(): needs = []", "= sorted(enums, key=lambda v: v[\"name\"]) return enums def read_header(header_path, skip_macros=None): # I tried", "%s\" print(message % (class_[\"name\"], header_name)) elif (module, header_name, class_[\"name\"]) in CLASSES_TO_IGNORE: pass else:", "instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated = len(instantiation_function.split(\"\\n\")) > 2 text = [] if something_instantiated or keep_if_no_instantiation:", "for f in fields) def same_methods(m1: CppMethod, m2: CppMethod) -> bool: if m1[\"name\"]", "= {make_namespace_class(c[\"namespace\"], c[\"name\"]): c for classes in main_classes.values() for c in classes} for", "# print(\"File is the same: %s\" % os.path.split(path)[1]) return False def write_if_different(files_to_write, delete_others):", "= list(dependency_tree.leaf_iterator()) def index_for_class(class_): return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"])) # sort classes inside modules based", "= class_[\"methods\"][\"public\"] methods = filter_methods_for_parser_errors(methods) methods = filter_methods_to_skip(methods) private_and_protected = class_[\"methods\"][\"private\"] + class_[\"methods\"][\"protected\"]", "class_properties, needs_overloading) if not class_[\"can_be_instantiated\"]: constructors = [] class_def = ClassDefinition(class_, constructors, variables,", "os.path.split(path)[1]) return True # print(\"File is the same: %s\" % os.path.split(path)[1]) return False", "fields = [\"constant\", \"name\", \"raw_type\", \"reference\", \"static\"] return all(p1[f] == p2[f] for f", "# same parameters for p1 in m1[\"parameters\"]: for p2 in m2[\"parameters\"]: if m1[\"name\"]", "classes_by_module = defaultdict(list) for (module, _), class_ in main_classes.items(): classes_by_module[module] += class_ for", "found_modules if modules is None: modules = MODULES_TO_BUILD if skip_modules is not None:", "for module, header, path in headers_to_generate: generated_headers[(module, header)] = generate_header(module, header, path, keep_if_no_instantiation=False)", "module, header_name in main_classes: for class_ in main_classes[(module, header_name)]: can_be_instantiated = True if", "header.classes.values() if c[\"namespace\"] in (\"pcl\", \"pcl::\" + module)] filtered_main_classes = [] for class_", "a(\"\") namespaces = set([c[\"namespace\"] for c in main_classes]) for namespace in namespaces: if", "filtered_main_classes def get_functions(header, module): functions = [f for f in header.functions if f[\"namespace\"]", "properties = filtered_properties return properties def get_main_classes(header, module, header_name): # header = read_headers(base_path,", "class_definitions = generate_class_definitions(header_classes, module, header, path, methods_need_overloading.get(module), methods_defined_outside) function_definitions = generate_function_definitions(header_functions, module, header,", "= class_[\"methods\"][\"private\"] + class_[\"methods\"][\"protected\"] methods += private_methods_defined_outside(private_and_protected, methods_defined_outside) class_properties = [p for p", "[] if not windows: skip_macros = [\"_MSC_VER\"] #skip_modules = [\"visualization\"] skip_modules = []", "inheritance for module, header in main_classes: main_classes[(module, header)] = list(sorted(main_classes[(module, header)], key=index_for_class)) headers_to_generate", "module): functions = [f for f in header.functions if f[\"namespace\"] in (\"pcl\", \"pcl::\",", "same_parameters(p1: Dict, p2: Dict) -> bool: fields = [\"constant\", \"name\", \"raw_type\", \"reference\", \"static\"]", "def is_file_different(path, text): v = open(path).read() if v != text: print(\"File is different:", "and 'using' != v.get('type')] variables = sorted(variables, key=lambda v: v[\"name\"]) return variables def", "skip_macros=skip_macros) methods_need_overloading = check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree, main_classes) def generate_header(module, header, path, keep_if_no_instantiation) -> str:", "[] for m in methods: if (m[\"parent\"][\"name\"], m[\"name\"]) in METHODS_TO_SKIP: continue if \"Callback\"", "needs_overloading = {} classes_by_module = defaultdict(list) for (module, _), class_ in main_classes.items(): classes_by_module[module]", "in modules: module_dir = join(PATH_MODULES, module) if not os.path.exists(module_dir): os.makedirs(module_dir) def is_file_different(path, text):", "p2: Dict) -> bool: fields = [\"constant\", \"name\", \"raw_type\", \"reference\", \"static\"] return all(p1[f]", "headers_to_generate = [(module, header_name, path) for module in modules for header_name, path in", ") instantiation_function = instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated = len(instantiation_function.split(\"\\n\")) > 2 text = [] if", "can be instantiated\"\"\" main_classes_by_name_namespace = {make_namespace_class(c[\"namespace\"], c[\"name\"]): c for classes in main_classes.values() for", "functions = sorted(functions, key=lambda f: f[\"name\"]) filtered = filter_module_level_functions(functions) return filtered def filter_module_level_functions(functions:", "typing import List, Dict, Set from CppHeaderParser import CppHeaderParser from CppHeaderParser.CppHeaderParser import CppMethod", "= ClassDefinition(class_, constructors, variables, others, module) a(class_def.to_class_function_definition()) a(\"\") return \"\\n\".join(text) def filter_class_properties(module, header,", "for classes in main_classes.values() for c in classes} for module, header_name in main_classes:", "on inheritance for module, header in main_classes: main_classes[(module, header)] = list(sorted(main_classes[(module, header)], key=index_for_class))", "ignore_errors=True) def write_stuff_if_needed(generated_headers: OrderedDict, delete_others=True): modules = set(module for module, _ in generated_headers.keys())", "defaultdict(list) for (module, _), class_ in main_classes.items(): classes_by_module[module] += class_ for module, classes", "return filtered_main_classes def get_functions(header, module): functions = [f for f in header.functions if", "METHODS_TO_SKIP, SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES, \\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from generators.definitions.function import generate_function_definitions, get_methods_defined_outside from generators.definitions.method import", "methods: if (m[\"parent\"][\"name\"], m[\"name\"]) in METHODS_TO_SKIP: continue if \"Callback\" in m[\"name\"]: single_argument =", "for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if not to_skip: message = \"Warning: Template class specialization", "generated_headers.keys()) make_module_dirs(modules) # hpp files_to_write = {} for (module, header_name), text in generated_headers.items():", "keep_if_no_instantiation: text = [class_definitions, function_definitions, instantiation_function] return \"\\n\".join(text) generated_headers = OrderedDict() for module,", "for (module, header_name), text in generated_headers.items(): if text: output_path = join(PATH_MODULES, module, header_name", "keep: filtered.append(f) return filtered def get_variables(header): variables = [v for v in header.variables", "def filter_module_level_functions(functions: List[CppMethod]): filtered = [] for f in functions: keep = True", "module) files_to_write[path_loader] = generate_loader(module, headers) files_to_write[PATH_LOADER] = generate_main_loader(loader_modules) write_if_different(files_to_write, delete_others) if delete_others: delete_other_dirs(modules)", "access = \"private protected public\".split() return set([m[\"name\"] for a in access for m", "def listmod(module): found_modules = [] for base, folders, files in os.walk(join(PCL_BASE, module)): if", "constructors, variables, others, module) a(class_def.to_class_function_definition()) a(\"\") return \"\\n\".join(text) def filter_class_properties(module, header, class_name, properties):", "if f[\"namespace\"] in (\"pcl\", \"pcl::\", \"pcl::%s\" % module, \"pcl::%s::\" % module)] functions =", "and \"<\" in class_[\"name\"] if specialized_template: to_skip = any((\"<%s>\" % type_) in class_[\"name\"]", "os.walk(join(PCL_BASE, module)): if any(base.endswith(m) for m in SUBMODULES_TO_SKIP): continue relative_base = os.path.abspath(base).replace(PCL_BASE, \"\")[1:]", "in fields) def same_methods(m1: CppMethod, m2: CppMethod) -> bool: if m1[\"name\"] != m2[\"name\"]:", "'using' != v.get('type')] variables = sorted(variables, key=lambda v: v[\"name\"]) return variables def get_enums(header):", "for c in classes} for module, header_name in main_classes: for class_ in main_classes[(module,", "main_classes: specialized_template = class_.get(\"template\") and \"<\" in class_[\"name\"] if specialized_template: to_skip = any((\"<%s>\"", "module, header, classes_point_types, module_variables[(module, header)], module_enums[(module, header)], ) instantiation_function = instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated =", "in main_classes: for class_ in main_classes[(module, header_name)]: can_be_instantiated = True if class_[\"abstract\"]: can_be_instantiated", "header_name)] = get_functions(header, module) module_variables[(module, header_name)] = get_variables(header) module_enums[(module, header_name)] = get_enums(header) classes", "class_ in classes: count = Counter(m[\"name\"] for methods in class_[\"methods\"].values() for m in", "OrderedDict, delete_others=True): modules = set(module for module, _ in generated_headers.keys()) make_module_dirs(modules) # hpp", "dependency_tree = generators.dependency_tree.DependencyTree(classes) loaded_point_types = load_yaml_point_types(not_every_point_type) classes_point_types: OrderedDict = dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first = list(dependency_tree.leaf_iterator())", "type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_ in param[\"type\"]: keep = False if keep: filtered.append(f)", "is not thread safe... if skip_macros is None: skip_macros = [] header_file_str =", "= defaultdict(list) for (module, header_name), text in generated_headers.items(): if text: loader_modules[module or \"base\"].append(header_name)", "path else join(PCL_BASE, module, header_name) header = read_header(header_full_path, skip_macros) main_classes[(module, header_name)] = get_main_classes(header,", "in generated_headers.items(): if text: loader_modules[module or \"base\"].append(header_name) for module, headers in loader_modules.items(): path_loader", "return False # bug in CppHeaderParser # in \"void ImageGrabber<PointT>::publish\", \"void ImageGrabber<PointT>::\" is", "for base, folder, files in os.walk(PATH_MODULES): for f in files: path = join(base,", "join(base, f) if path in files_to_write: if is_file_different(path, files_to_write[path]): open(path, \"w\").write(files_to_write[path]) written.append(path) elif", "not os.path.exists(module_dir): os.makedirs(module_dir) def is_file_different(path, text): v = open(path).read() if v != text:", "base_pure_virtual_methods - all_implemented_inherited_methods: can_be_instantiated = False class_[\"can_be_instantiated\"] = can_be_instantiated def load_yaml_point_types(not_every_point_type): classes_point_types =", "%s in %s\" print(message % (class_[\"name\"], header_name)) elif (module, header_name, class_[\"name\"]) in CLASSES_TO_IGNORE:", "_ in generated_headers.keys()) make_module_dirs(modules) # hpp files_to_write = {} for (module, header_name), text", "if m[\"pure_virtual\"]]) def get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private protected public\".split() return", "base_class[\"abstract\"]: base_pure_virtual_methods = get_pure_virtual_methods(base_class) if base_pure_virtual_methods - all_implemented_inherited_methods: can_be_instantiated = False class_[\"can_be_instantiated\"] =", "header, path, keep_if_no_instantiation=False) return generated_headers def main(): import time t = time.time() windows", "False class_[\"can_be_instantiated\"] = can_be_instantiated def load_yaml_point_types(not_every_point_type): classes_point_types = unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type) extra_point_types = unpack_yaml_point_types(\"point_types_extra.yml\")", "headers_to_generate[:]: header_full_path = join(PCL_BASE, path) if path else join(PCL_BASE, module, header_name) header =", "not_every_point_type) write_stuff_if_needed(generated_headers, delete_others=True) print(\"generated in %.2f s\" % (time.time() - t,)) if __name__", "# loaders loader_modules = defaultdict(list) for (module, header_name), text in generated_headers.items(): if text:", "in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class: base_class_methods = get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods) for base_name_nsp", "boost_function = single_argument and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if not boost_function: continue filtered_methods.append(m) return filtered_methods def", "bool: fields = [\"constant\", \"name\", \"raw_type\", \"reference\", \"static\"] return all(p1[f] == p2[f] for", "List[str], methods_defined_outside: List[CppMethod]) -> str: text = [] a = text.append a(common_includes) a(EXPLICIT_INCLUDES.get((module,", "filtered def filter_module_level_functions(functions: List[CppMethod]): filtered = [] for f in functions: keep =", "fields) def same_methods(m1: CppMethod, m2: CppMethod) -> bool: if m1[\"name\"] != m2[\"name\"]: return", "path = join(base, f) if path in files_to_write: if is_file_different(path, files_to_write[path]): open(path, \"w\").write(files_to_write[path])", "return properties def get_main_classes(header, module, header_name): # header = read_headers(base_path, header_name, module) main_classes", "= needs return needs_overloading def get_headers(modules=None, skip_modules=None): def listmod(module): found_modules = [] for", "f in os.listdir(PATH_MODULES): folder = join(PATH_MODULES, f) if f not in modules and", "key in ATTRIBUTES_TO_SKIP: to_ignore = ATTRIBUTES_TO_SKIP[key] filtered_properties = [] for p in properties:", "List[CppMethod]) -> List[CppMethod]: private_defined_outside = [] for m_private in private_methods: for m_outside in", "False # same parameters for p1 in m1[\"parameters\"]: for p2 in m2[\"parameters\"]: if", "print(message % (class_[\"name\"], header_name)) elif (module, header_name, class_[\"name\"]) in CLASSES_TO_IGNORE: pass else: filtered_main_classes.append(class_)", "{}, {} for module, header_name, path in headers_to_generate[:]: header_full_path = join(PCL_BASE, path) if", "+ \"pp\") files_to_write[output_path] = text # loaders loader_modules = defaultdict(list) for (module, header_name),", "= False class_[\"can_be_instantiated\"] = can_be_instantiated def load_yaml_point_types(not_every_point_type): classes_point_types = unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type) extra_point_types =", "class_[\"nested_classes\"] for p in nested_class[\"properties\"][\"public\"] if \"union\" in nested_class[\"name\"]] class_properties += union_properties class_properties", "header, classes_point_types, module_variables[(module, header)], module_enums[(module, header)], ) instantiation_function = instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated = len(instantiation_function.split(\"\\n\"))", "= time.time() windows = platform.system() == \"Windows\" skip_macros = [] skip_modules = []", "v[\"name\"]) return enums def read_header(header_path, skip_macros=None): # I tried to do this in", "sort classes inside modules based on inheritance for module, header in main_classes: main_classes[(module,", "module, header in main_classes: main_classes[(module, header)] = list(sorted(main_classes[(module, header)], key=index_for_class)) headers_to_generate = sort_headers_by_dependencies(headers_to_generate,", "= can_be_instantiated def load_yaml_point_types(not_every_point_type): classes_point_types = unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type) extra_point_types = unpack_yaml_point_types(\"point_types_extra.yml\") for k,", "continue filtered_properties.append(p) properties = filtered_properties return properties def get_main_classes(header, module, header_name): # header", "= [] if not windows: skip_macros = [\"_MSC_VER\"] #skip_modules = [\"visualization\"] skip_modules =", "public\".split() return set([m[\"name\"] for a in access for m in class_[\"methods\"][a] if m[\"pure_virtual\"]])", "skip_macros = [\"_MSC_VER\"] #skip_modules = [\"visualization\"] skip_modules = [] all_headers = get_headers(skip_modules=skip_modules) not_every_point_type", "\"static\"] return all(p1[f] == p2[f] for f in fields) def same_methods(m1: CppMethod, m2:", "for name, count in count.items(): if count >= 2: needs.append(name) needs_overloading[module] = needs", "if type_ in param[\"type\"]: keep = False if keep: filtered.append(f) return filtered def", "constructors, variables, others = split_methods_by_type(methods, class_properties, needs_overloading) if not class_[\"can_be_instantiated\"]: constructors = []", "m in SUBMODULES_TO_SKIP): continue relative_base = os.path.abspath(base).replace(PCL_BASE, \"\")[1:] for f in files: if", "generate_main_loader(loader_modules) write_if_different(files_to_write, delete_others) if delete_others: delete_other_dirs(modules) def generate(headers_to_generate, skip_macros, not_every_point_type=False) -> OrderedDict: \"\"\"", "in class_[\"methods\"].values() for m in methods) for name, count in count.items(): if count", "same parameters for p1 in m1[\"parameters\"]: for p2 in m2[\"parameters\"]: if m1[\"name\"] ==", "path not in written: open(path, \"w\").write(files_to_write[path]) def delete_other_dirs(modules): for f in os.listdir(PATH_MODULES): folder", "\\ generate_main_loader, make_namespace_class, read_header_file def filter_methods_for_parser_errors(methods): return [m for m in methods if", "return False return len(m1[\"parameters\"]) == len(m2[\"parameters\"]) def private_methods_defined_outside(private_methods: List[CppMethod], methods_declared_outside: List[CppMethod]) -> List[CppMethod]:", "str: text = [] a = text.append a(common_includes) a(EXPLICIT_INCLUDES.get((module, header_name), \"\")) a(make_header_include_name(module, header_name,", "generators.config import common_includes, PCL_BASE, PATH_LOADER, PATH_MODULES, MODULES_TO_BUILD, \\ HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE, METHODS_TO_SKIP, SUBMODULES_TO_SKIP,", "nested_class[\"properties\"][\"public\"] if \"union\" in nested_class[\"name\"]] class_properties += union_properties class_properties = filter_class_properties(module, header_name, class_[\"name\"],", "for m_outside in methods_declared_outside: if same_methods(m_private, m_outside): private_defined_outside.append(m_private) break return private_defined_outside def generate_class_definitions(main_classes,", "Instantiations from generators.point_types_utils import unpack_yaml_point_types from generators.utils import make_header_include_name, sort_headers_by_dependencies, \\ generate_main_loader, make_namespace_class,", "SUBMODULES_TO_SKIP): continue relative_base = os.path.abspath(base).replace(PCL_BASE, \"\")[1:] for f in files: if f.endswith(\".h\"): found_modules.append([f,", "CppHeaderParser parser.debug = False header = parser.CppHeader(header_file_str, argType=\"string\") return header def clean(): try:", "can_be_instantiated = False else: # check if any pure virtual method is not", "[c for c in header.classes.values() if c[\"namespace\"] in (\"pcl\", \"pcl::\" + module)] filtered_main_classes", "header_name) header = read_header(header_full_path, skip_macros) main_classes[(module, header_name)] = get_main_classes(header, module, header_name) module_functions[(module, header_name)]", "m in methods) for name, count in count.items(): if count >= 2: needs.append(name)", "not None: modules = [m for m in modules if m not in", "ClassDefinition(class_, constructors, variables, others, module) a(class_def.to_class_function_definition()) a(\"\") return \"\\n\".join(text) def filter_class_properties(module, header, class_name,", "classes_by_module[module] += class_ for module, classes in classes_by_module.items(): needs = [] for class_", "path = m1.get(\"path\", m2.get(\"path\")) path = path[path.rfind(\":\") + 1:] if not any(path in", "in main_classes]) for namespace in namespaces: if not namespace == \"pcl\": a(\"using namespace", "if f not in modules and os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True) def write_stuff_if_needed(generated_headers: OrderedDict, delete_others=True):", "os.listdir(PCL_BASE) if f.endswith(\".h\")] headers_to_generate += base_headers headers_to_generate_temp = [] for module, header_name, path", "= {}, {}, {}, {} for module, header_name, path in headers_to_generate[:]: header_full_path =", "sorted(functions, key=lambda f: f[\"name\"]) filtered = filter_module_level_functions(functions) return filtered def filter_module_level_functions(functions: List[CppMethod]): filtered", "variables = sorted(variables, key=lambda v: v[\"name\"]) return variables def get_enums(header): enums = [e", "% (class_[\"name\"], header_name)) elif (module, header_name, class_[\"name\"]) in CLASSES_TO_IGNORE: pass else: filtered_main_classes.append(class_) filtered_main_classes", "a(make_header_include_name(module, header_name, path)) a(\"\") namespaces = set([c[\"namespace\"] for c in main_classes]) for namespace", "class_ in main_classes[(module, header_name)]: can_be_instantiated = True if class_[\"abstract\"]: can_be_instantiated = False else:", "\"reference\", \"static\"] return all(p1[f] == p2[f] for f in fields) def same_methods(m1: CppMethod,", "HEADERS_TO_SKIP: continue headers_to_generate_temp.append(tuple([module, header_name, path])) return headers_to_generate_temp def get_pure_virtual_methods(class_: CppHeaderParser.CppClass) -> Set[str]: access", "% module)] functions = sorted(functions, key=lambda f: f[\"name\"]) filtered = filter_module_level_functions(functions) return filtered", "m1[\"parameters\"]: for p2 in m2[\"parameters\"]: if m1[\"name\"] == m2[\"name\"] and same_parameters(p1, p2): break", "headers_to_generate: if (module, header_name) in HEADERS_TO_SKIP: continue headers_to_generate_temp.append(tuple([module, header_name, path])) return headers_to_generate_temp def", "access for m in class_[\"methods\"][a] if not m[\"pure_virtual\"]]) def flag_instantiatable_class(dependency_tree, main_classes): \"\"\"determine if", "windows: skip_macros = [\"_MSC_VER\"] #skip_modules = [\"visualization\"] skip_modules = [] all_headers = get_headers(skip_modules=skip_modules)", "the return type path = m1.get(\"path\", m2.get(\"path\")) path = path[path.rfind(\":\") + 1:] if", "in CppHeaderParser # in \"void ImageGrabber<PointT>::publish\", \"void ImageGrabber<PointT>::\" is the return type path", "OrderedDict \"\"\" main_classes, module_functions, module_variables, module_enums = {}, {}, {}, {} for module,", "v[\"name\"]) return variables def get_enums(header): enums = [e for e in header.enums if", "path in headers_to_generate[:]: header_full_path = join(PCL_BASE, path) if path else join(PCL_BASE, module, header_name)", "os.remove(PATH_LOADER) except FileNotFoundError: pass if os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES) def check_if_needs_overloading(main_classes): needs_overloading = {} classes_by_module", "join(PATH_MODULES, f) if f not in modules and os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True) def write_stuff_if_needed(generated_headers:", "in files_to_write.items(): if path not in written: open(path, \"w\").write(files_to_write[path]) def delete_other_dirs(modules): for f", "generate(all_headers, skip_macros, not_every_point_type) write_stuff_if_needed(generated_headers, delete_others=True) print(\"generated in %.2f s\" % (time.time() - t,))", "module_functions[(module, header_name)] = get_functions(header, module) module_variables[(module, header_name)] = get_variables(header) module_enums[(module, header_name)] = get_enums(header)", "1 boost_function = single_argument and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if not boost_function: continue filtered_methods.append(m) return filtered_methods", "delete_others: delete_other_dirs(modules) def generate(headers_to_generate, skip_macros, not_every_point_type=False) -> OrderedDict: \"\"\" :return: OrderedDict \"\"\" main_classes,", "\"using\" in p[\"type\"] and not \"union\" in p[\"type\"]] union_properties = [p for nested_class", "key=lambda f: f[\"name\"]) filtered = filter_module_level_functions(functions) return filtered def filter_module_level_functions(functions: List[CppMethod]): filtered =", "methods_declared_outside: List[CppMethod]) -> List[CppMethod]: private_defined_outside = [] for m_private in private_methods: for m_outside", "m2[\"parameters\"]: if m1[\"name\"] == m2[\"name\"] and same_parameters(p1, p2): break else: return False return", "in class_[\"properties\"][\"public\"] if not \"using\" in p[\"type\"] and not \"union\" in p[\"type\"]] union_properties", "for f in os.listdir(PCL_BASE) if f.endswith(\".h\")] headers_to_generate += base_headers headers_to_generate_temp = [] for", "= {} classes_by_module = defaultdict(list) for (module, _), class_ in main_classes.items(): classes_by_module[module] +=", "module)): if any(base.endswith(m) for m in SUBMODULES_TO_SKIP): continue relative_base = os.path.abspath(base).replace(PCL_BASE, \"\")[1:] for", "main_classes_by_name_namespace.get(base_name_nsp) if base_class and base_class[\"abstract\"]: base_pure_virtual_methods = get_pure_virtual_methods(base_class) if base_pure_virtual_methods - all_implemented_inherited_methods: can_be_instantiated", "if the class can be instantiated\"\"\" main_classes_by_name_namespace = {make_namespace_class(c[\"namespace\"], c[\"name\"]): c for classes", "m_outside in methods_declared_outside: if same_methods(m_private, m_outside): private_defined_outside.append(m_private) break return private_defined_outside def generate_class_definitions(main_classes, module,", "methods in class_[\"methods\"].values() for m in methods) for name, count in count.items(): if", "List[CppMethod], methods_declared_outside: List[CppMethod]) -> List[CppMethod]: private_defined_outside = [] for m_private in private_methods: for", "generate_class_definitions(main_classes, module, header_name, path, needs_overloading: List[str], methods_defined_outside: List[CppMethod]) -> str: text = []", "\"private protected public\".split() return set([m[\"name\"] for a in access for m in class_[\"methods\"][a]", "-> Set[str]: access = \"private protected public\".split() return set([m[\"name\"] for a in access", "class_ in main_classes.items(): classes_by_module[module] += class_ for module, classes in classes_by_module.items(): needs =", "skip_macros = [] header_file_str = read_header_file(header_path, skip_macros) parser = CppHeaderParser parser.debug = False", "in headers_to_generate: if (module, header_name) in HEADERS_TO_SKIP: continue headers_to_generate_temp.append(tuple([module, header_name, path])) return headers_to_generate_temp", "generators.instantiations import Instantiations from generators.point_types_utils import unpack_yaml_point_types from generators.utils import make_header_include_name, sort_headers_by_dependencies, \\", "= join(PATH_MODULES, \"_%s_loader.cpp\" % module) files_to_write[path_loader] = generate_loader(module, headers) files_to_write[PATH_LOADER] = generate_main_loader(loader_modules) write_if_different(files_to_write,", "= split_methods_by_type(methods, class_properties, needs_overloading) if not class_[\"can_be_instantiated\"]: constructors = [] class_def = ClassDefinition(class_,", "in header.enums if e.get(\"name\")] # skip nameless enums enums = sorted(enums, key=lambda v:", "main_classes = [c for c in header.classes.values() if c[\"namespace\"] in (\"pcl\", \"pcl::\" +", "from CppHeaderParser.CppHeaderParser import CppMethod import generators.dependency_tree from generators.config import common_includes, PCL_BASE, PATH_LOADER, PATH_MODULES,", "\"--not-every-point-type\" in sys.argv generated_headers = generate(all_headers, skip_macros, not_every_point_type) write_stuff_if_needed(generated_headers, delete_others=True) print(\"generated in %.2f", "for module, header_name in main_classes: for class_ in main_classes[(module, header_name)]: can_be_instantiated = True", "header in main_classes: main_classes[(module, header)] = list(sorted(main_classes[(module, header)], key=index_for_class)) headers_to_generate = sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros)", "to_ignore = ATTRIBUTES_TO_SKIP[key] filtered_properties = [] for p in properties: if p[\"name\"] in", "constructors = [] class_def = ClassDefinition(class_, constructors, variables, others, module) a(class_def.to_class_function_definition()) a(\"\") return", "needs_overloading def get_headers(modules=None, skip_modules=None): def listmod(module): found_modules = [] for base, folders, files", "filtered = [] for f in functions: keep = True if f.get(\"returns_const\"): keep", "not in skip_modules] headers_to_generate = [(module, header_name, path) for module in modules for", "[] class_def = ClassDefinition(class_, constructors, variables, others, module) a(class_def.to_class_function_definition()) a(\"\") return \"\\n\".join(text) def", "in (\"pcl\", \"pcl::\", \"pcl::%s\" % module, \"pcl::%s::\" % module)] functions = sorted(functions, key=lambda", "= [] if something_instantiated or keep_if_no_instantiation: text = [class_definitions, function_definitions, instantiation_function] return \"\\n\".join(text)", "for m in methods) for name, count in count.items(): if count >= 2:", "in SUBMODULES_TO_SKIP): continue relative_base = os.path.abspath(base).replace(PCL_BASE, \"\")[1:] for f in files: if f.endswith(\".h\"):", "classes_point_types[k].append(v) else: classes_point_types[k] = v return classes_point_types def make_module_dirs(modules): for module in modules:", "it seems like CppHeaderParser is not thread safe... if skip_macros is None: skip_macros", "unpack_yaml_point_types from generators.utils import make_header_include_name, sort_headers_by_dependencies, \\ generate_main_loader, make_namespace_class, read_header_file def filter_methods_for_parser_errors(methods): return", "path in headers_to_generate for c in main_classes[(module, header)]] dependency_tree = generators.dependency_tree.DependencyTree(classes) loaded_point_types =", "listmod(module)] base_headers = [(\"\", f, f) for f in os.listdir(PCL_BASE) if f.endswith(\".h\")] headers_to_generate", "open(path, \"w\").write(files_to_write[path]) def delete_other_dirs(modules): for f in os.listdir(PATH_MODULES): folder = join(PATH_MODULES, f) if", "sort_headers_by_dependencies, \\ generate_main_loader, make_namespace_class, read_header_file def filter_methods_for_parser_errors(methods): return [m for m in methods", "\"\")[1:] for f in files: if f.endswith(\".h\"): found_modules.append([f, join(relative_base, f)]) return found_modules if", "from collections import defaultdict, OrderedDict from os.path import join from typing import List,", "return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"])) # sort classes inside modules based on inheritance for module,", "header_name)] = get_enums(header) classes = [c for module, header, path in headers_to_generate for", "open(path).read() if v != text: print(\"File is different: %s\" % os.path.split(path)[1]) return True", "unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type) extra_point_types = unpack_yaml_point_types(\"point_types_extra.yml\") for k, v in extra_point_types.items(): if k in", "bug in CppHeaderParser # in \"void ImageGrabber<PointT>::publish\", \"void ImageGrabber<PointT>::\" is the return type", "= open(path).read() if v != text: print(\"File is different: %s\" % os.path.split(path)[1]) return", "= get_pure_virtual_methods(base_class) if base_pure_virtual_methods - all_implemented_inherited_methods: can_be_instantiated = False class_[\"can_be_instantiated\"] = can_be_instantiated def", "for param in f[\"parameters\"]: for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_ in param[\"type\"]: keep", "= [] header_file_str = read_header_file(header_path, skip_macros) parser = CppHeaderParser parser.debug = False header", "filtered_main_classes = sorted(filtered_main_classes, key=lambda c: c[\"name\"]) return filtered_main_classes def get_functions(header, module): functions =", "def generate(headers_to_generate, skip_macros, not_every_point_type=False) -> OrderedDict: \"\"\" :return: OrderedDict \"\"\" main_classes, module_functions, module_variables,", "files: path = join(base, f) if path in files_to_write: if is_file_different(path, files_to_write[path]): open(path,", "get_variables(header): variables = [v for v in header.variables if v.get(\"defaultValue\") and 'using' !=", "return False # same parameters for p1 in m1[\"parameters\"]: for p2 in m2[\"parameters\"]:", "c[\"name\"]): c for classes in main_classes.values() for c in classes} for module, header_name", "module, header, path in headers_to_generate: generated_headers[(module, header)] = generate_header(module, header, path, keep_if_no_instantiation=False) return", "from generators.definitions.method import split_methods_by_type from generators.definitions.submodule_loader import generate_loader from generators.definitions.templated_class import ClassDefinition from", "= \"Warning: Template class specialization not implemented for class %s in %s\" print(message", "relative_base = os.path.abspath(base).replace(PCL_BASE, \"\")[1:] for f in files: if f.endswith(\".h\"): found_modules.append([f, join(relative_base, f)])", "get_headers(skip_modules=skip_modules) not_every_point_type = \"--not-every-point-type\" in sys.argv generated_headers = generate(all_headers, skip_macros, not_every_point_type) write_stuff_if_needed(generated_headers, delete_others=True)", "dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class: base_class_methods = get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods) for base_name_nsp in", "skip_macros=None): # I tried to do this in multiple threads but it seems", "module, headers in loader_modules.items(): path_loader = join(PATH_MODULES, \"_%s_loader.cpp\" % module) files_to_write[path_loader] = generate_loader(module,", "check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree, main_classes) def generate_header(module, header, path, keep_if_no_instantiation) -> str: header_functions = module_functions[(module,", "\"pcl::\", \"pcl::%s\" % module, \"pcl::%s::\" % module)] functions = sorted(functions, key=lambda f: f[\"name\"])", "pass if os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES) def check_if_needs_overloading(main_classes): needs_overloading = {} classes_by_module = defaultdict(list) for", "private_methods_defined_outside(private_methods: List[CppMethod], methods_declared_outside: List[CppMethod]) -> List[CppMethod]: private_defined_outside = [] for m_private in private_methods:", "-> bool: if m1[\"name\"] != m2[\"name\"]: return False # bug in CppHeaderParser #", "headers_to_generate for c in main_classes[(module, header)]] dependency_tree = generators.dependency_tree.DependencyTree(classes) loaded_point_types = load_yaml_point_types(not_every_point_type) classes_point_types:", "delete_others) if delete_others: delete_other_dirs(modules) def generate(headers_to_generate, skip_macros, not_every_point_type=False) -> OrderedDict: \"\"\" :return: OrderedDict", "if os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES) def check_if_needs_overloading(main_classes): needs_overloading = {} classes_by_module = defaultdict(list) for (module,", "f not in modules and os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True) def write_stuff_if_needed(generated_headers: OrderedDict, delete_others=True): modules", "platform.system() == \"Windows\" skip_macros = [] skip_modules = [] if not windows: skip_macros", "header_name) module_functions[(module, header_name)] = get_functions(header, module) module_variables[(module, header_name)] = get_variables(header) module_enums[(module, header_name)] =", "main_classes): \"\"\"determine if the class can be instantiated\"\"\" main_classes_by_name_namespace = {make_namespace_class(c[\"namespace\"], c[\"name\"]): c", "import generate_function_definitions, get_methods_defined_outside from generators.definitions.method import split_methods_by_type from generators.definitions.submodule_loader import generate_loader from generators.definitions.templated_class", "in f[\"parameters\"]: for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_ in param[\"type\"]: keep = False", "classes inside modules based on inheritance for module, header in main_classes: main_classes[(module, header)]", "in methods) for name, count in count.items(): if count >= 2: needs.append(name) needs_overloading[module]", "= [] for m in methods: if (m[\"parent\"][\"name\"], m[\"name\"]) in METHODS_TO_SKIP: continue if", "[] for base, folders, files in os.walk(join(PCL_BASE, module)): if any(base.endswith(m) for m in", "headers in loader_modules.items(): path_loader = join(PATH_MODULES, \"_%s_loader.cpp\" % module) files_to_write[path_loader] = generate_loader(module, headers)", "defaultdict, OrderedDict from os.path import join from typing import List, Dict, Set from", "= [(\"\", f, f) for f in os.listdir(PCL_BASE) if f.endswith(\".h\")] headers_to_generate += base_headers", "class_properties) constructors, variables, others = split_methods_by_type(methods, class_properties, needs_overloading) if not class_[\"can_be_instantiated\"]: constructors =", "header_name)]: can_be_instantiated = True if class_[\"abstract\"]: can_be_instantiated = False else: # check if", "= join(PCL_BASE, path) if path else join(PCL_BASE, module, header_name) header = read_header(header_full_path, skip_macros)", "for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_ in param[\"type\"]: keep = False if keep:", "= unpack_yaml_point_types(\"point_types_extra.yml\") for k, v in extra_point_types.items(): if k in classes_point_types: classes_point_types[k].append(v) else:", "set([c[\"namespace\"] for c in main_classes]) for namespace in namespaces: if not namespace ==", "= [c for c in header.classes.values() if c[\"namespace\"] in (\"pcl\", \"pcl::\" + module)]", "same_parameters(p1, p2): break else: return False return len(m1[\"parameters\"]) == len(m2[\"parameters\"]) def private_methods_defined_outside(private_methods: List[CppMethod],", "import defaultdict, OrderedDict from os.path import join from typing import List, Dict, Set", "# ignore properties without a name properties = [p for p in properties", "key=lambda v: v[\"name\"]) return enums def read_header(header_path, skip_macros=None): # I tried to do", "for module in modules for header_name, path in listmod(module)] base_headers = [(\"\", f,", "to_ignore: continue filtered_properties.append(p) properties = filtered_properties return properties def get_main_classes(header, module, header_name): #", "shutil import sys from collections import Counter from collections import defaultdict, OrderedDict from", "PCL_BASE, PATH_LOADER, PATH_MODULES, MODULES_TO_BUILD, \\ HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE, METHODS_TO_SKIP, SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES, \\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP", "m not in skip_modules] headers_to_generate = [(module, header_name, path) for module in modules", "for p in properties: if p[\"name\"] in to_ignore: continue filtered_properties.append(p) properties = filtered_properties", "+ path) # write new files for path, text in files_to_write.items(): if path", "header = read_header(header_full_path, skip_macros) main_classes[(module, header_name)] = get_main_classes(header, module, header_name) module_functions[(module, header_name)] =", "specialization not implemented for class %s in %s\" print(message % (class_[\"name\"], header_name)) elif", "classes: count = Counter(m[\"name\"] for methods in class_[\"methods\"].values() for m in methods) for", "= generate_class_definitions(header_classes, module, header, path, methods_need_overloading.get(module), methods_defined_outside) function_definitions = generate_function_definitions(header_functions, module, header, not_every_point_type=not_every_point_type)", "I tried to do this in multiple threads but it seems like CppHeaderParser", "from generators.definitions.function import generate_function_definitions, get_methods_defined_outside from generators.definitions.method import split_methods_by_type from generators.definitions.submodule_loader import generate_loader", "skip_macros, not_every_point_type) write_stuff_if_needed(generated_headers, delete_others=True) print(\"generated in %.2f s\" % (time.time() - t,)) if", "True if f.get(\"returns_const\"): keep = False for param in f[\"parameters\"]: for type_ in", "generate_function_definitions, get_methods_defined_outside from generators.definitions.method import split_methods_by_type from generators.definitions.submodule_loader import generate_loader from generators.definitions.templated_class import", "param in f[\"parameters\"]: for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_ in param[\"type\"]: keep =", "e in header.enums if e.get(\"name\")] # skip nameless enums enums = sorted(enums, key=lambda", "class_[\"name\"] for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if not to_skip: message = \"Warning: Template class", "+ 1:] if not any(path in type_ for type_ in [m1[\"rtnType\"], m2[\"rtnType\"]]): return", "= main_classes_by_name_namespace.get(base_name_nsp) if base_class and base_class[\"abstract\"]: base_pure_virtual_methods = get_pure_virtual_methods(base_class) if base_pure_virtual_methods - all_implemented_inherited_methods:", "in modules if m not in skip_modules] headers_to_generate = [(module, header_name, path) for", "m in methods: if (m[\"parent\"][\"name\"], m[\"name\"]) in METHODS_TO_SKIP: continue if \"Callback\" in m[\"name\"]:", "for p in nested_class[\"properties\"][\"public\"] if \"union\" in nested_class[\"name\"]] class_properties += union_properties class_properties =", "> 2 text = [] if something_instantiated or keep_if_no_instantiation: text = [class_definitions, function_definitions,", "skip nameless enums enums = sorted(enums, key=lambda v: v[\"name\"]) return enums def read_header(header_path,", "text = [] a = text.append a(common_includes) a(EXPLICIT_INCLUDES.get((module, header_name), \"\")) a(make_header_include_name(module, header_name, path))", "if any(base.endswith(m) for m in SUBMODULES_TO_SKIP): continue relative_base = os.path.abspath(base).replace(PCL_BASE, \"\")[1:] for f", "header, path, methods_need_overloading.get(module), methods_defined_outside) function_definitions = generate_function_definitions(header_functions, module, header, not_every_point_type=not_every_point_type) instantiations = Instantiations(header_classes,", "base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class: base_class_methods = get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class):", "text: print(\"File is different: %s\" % os.path.split(path)[1]) return True # print(\"File is the", "(class_[\"name\"], header_name)) elif (module, header_name, class_[\"name\"]) in CLASSES_TO_IGNORE: pass else: filtered_main_classes.append(class_) filtered_main_classes =", "None: modules = [m for m in modules if m not in skip_modules]", "files_to_write[output_path] = text # loaders loader_modules = defaultdict(list) for (module, header_name), text in", "and base_class[\"abstract\"]: base_pure_virtual_methods = get_pure_virtual_methods(base_class) if base_pure_virtual_methods - all_implemented_inherited_methods: can_be_instantiated = False class_[\"can_be_instantiated\"]", ":return: OrderedDict \"\"\" main_classes, module_functions, module_variables, module_enums = {}, {}, {}, {} for", "base_pure_virtual_methods = get_pure_virtual_methods(base_class) if base_pure_virtual_methods - all_implemented_inherited_methods: can_be_instantiated = False class_[\"can_be_instantiated\"] = can_be_instantiated", "header_name, path])) return headers_to_generate_temp def get_pure_virtual_methods(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private protected", "in ATTRIBUTES_TO_SKIP: to_ignore = ATTRIBUTES_TO_SKIP[key] filtered_properties = [] for p in properties: if", "header = read_headers(base_path, header_name, module) main_classes = [c for c in header.classes.values() if", "if not m[\"pure_virtual\"]]) def flag_instantiatable_class(dependency_tree, main_classes): \"\"\"determine if the class can be instantiated\"\"\"", "= load_yaml_point_types(not_every_point_type) classes_point_types: OrderedDict = dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first = list(dependency_tree.leaf_iterator()) def index_for_class(class_): return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"],", "in nested_class[\"properties\"][\"public\"] if \"union\" in nested_class[\"name\"]] class_properties += union_properties class_properties = filter_class_properties(module, header_name,", "[] header_file_str = read_header_file(header_path, skip_macros) parser = CppHeaderParser parser.debug = False header =", "in m1[\"parameters\"]: for p2 in m2[\"parameters\"]: if m1[\"name\"] == m2[\"name\"] and same_parameters(p1, p2):", "keep = True if f.get(\"returns_const\"): keep = False for param in f[\"parameters\"]: for", "filtered def get_variables(header): variables = [v for v in header.variables if v.get(\"defaultValue\") and", "in multiple threads but it seems like CppHeaderParser is not thread safe... if", "time.time() windows = platform.system() == \"Windows\" skip_macros = [] skip_modules = [] if", "module) a(class_def.to_class_function_definition()) a(\"\") return \"\\n\".join(text) def filter_class_properties(module, header, class_name, properties): key = (module,", "classes} for module, header_name in main_classes: for class_ in main_classes[(module, header_name)]: can_be_instantiated =", "main_classes: main_classes[(module, header)] = list(sorted(main_classes[(module, header)], key=index_for_class)) headers_to_generate = sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros) methods_need_overloading =", "m[\"name\"] in (\"void\", \"bool\")] def filter_methods_to_skip(methods): filtered_methods = [] for m in methods:", "be instantiated\"\"\" main_classes_by_name_namespace = {make_namespace_class(c[\"namespace\"], c[\"name\"]): c for classes in main_classes.values() for c", "\"name\", \"raw_type\", \"reference\", \"static\"] return all(p1[f] == p2[f] for f in fields) def", "header)], module_enums[(module, header)], ) instantiation_function = instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated = len(instantiation_function.split(\"\\n\")) > 2 text", "filtered_properties.append(p) properties = filtered_properties return properties def get_main_classes(header, module, header_name): # header =", "+= class_ for module, classes in classes_by_module.items(): needs = [] for class_ in", "files in os.walk(join(PCL_BASE, module)): if any(base.endswith(m) for m in SUBMODULES_TO_SKIP): continue relative_base =", "properties = [p for p in properties if p[\"name\"]] if key in ATTRIBUTES_TO_SKIP:", "[m1[\"rtnType\"], m2[\"rtnType\"]]): return False # same parameters for p1 in m1[\"parameters\"]: for p2", "union_properties = [p for nested_class in class_[\"nested_classes\"] for p in nested_class[\"properties\"][\"public\"] if \"union\"", "in os.walk(join(PCL_BASE, module)): if any(base.endswith(m) for m in SUBMODULES_TO_SKIP): continue relative_base = os.path.abspath(base).replace(PCL_BASE,", "for f in os.listdir(PATH_MODULES): folder = join(PATH_MODULES, f) if f not in modules", "generators.definitions.templated_class import ClassDefinition from generators.instantiations import Instantiations from generators.point_types_utils import unpack_yaml_point_types from generators.utils", "header = parser.CppHeader(header_file_str, argType=\"string\") return header def clean(): try: os.remove(PATH_LOADER) except FileNotFoundError: pass", "p in class_[\"properties\"][\"public\"] if not \"using\" in p[\"type\"] and not \"union\" in p[\"type\"]]", "= \"private protected public\".split() return set([m[\"name\"] for a in access for m in", "any(path in type_ for type_ in [m1[\"rtnType\"], m2[\"rtnType\"]]): return False # same parameters", "f in files: path = join(base, f) if path in files_to_write: if is_file_different(path,", "os.path.exists(module_dir): os.makedirs(module_dir) def is_file_different(path, text): v = open(path).read() if v != text: print(\"File", "= len(m[\"parameters\"]) == 1 boost_function = single_argument and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if not boost_function: continue", "headers_to_generate_temp.append(tuple([module, header_name, path])) return headers_to_generate_temp def get_pure_virtual_methods(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private", "def load_yaml_point_types(not_every_point_type): classes_point_types = unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type) extra_point_types = unpack_yaml_point_types(\"point_types_extra.yml\") for k, v in", "get_methods_defined_outside(header_functions) class_definitions = generate_class_definitions(header_classes, module, header, path, methods_need_overloading.get(module), methods_defined_outside) function_definitions = generate_function_definitions(header_functions, module,", "namespace_class = make_namespace_class(class_[\"namespace\"], class_[\"name\"]) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class:", "make_module_dirs(modules): for module in modules: module_dir = join(PATH_MODULES, module) if not os.path.exists(module_dir): os.makedirs(module_dir)", "v.get('type')] variables = sorted(variables, key=lambda v: v[\"name\"]) return variables def get_enums(header): enums =", "in classes_point_types: classes_point_types[k].append(v) else: classes_point_types[k] = v return classes_point_types def make_module_dirs(modules): for module", "all_implemented_inherited_methods: can_be_instantiated = False class_[\"can_be_instantiated\"] = can_be_instantiated def load_yaml_point_types(not_every_point_type): classes_point_types = unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type)", "def flag_instantiatable_class(dependency_tree, main_classes): \"\"\"determine if the class can be instantiated\"\"\" main_classes_by_name_namespace = {make_namespace_class(c[\"namespace\"],", "module_variables[(module, header_name)] = get_variables(header) module_enums[(module, header_name)] = get_enums(header) classes = [c for module,", "os.remove(path) print(\"Deleted: \" + path) # write new files for path, text in", "= [] all_headers = get_headers(skip_modules=skip_modules) not_every_point_type = \"--not-every-point-type\" in sys.argv generated_headers = generate(all_headers,", "if v.get(\"defaultValue\") and 'using' != v.get('type')] variables = sorted(variables, key=lambda v: v[\"name\"]) return" ]
[ "= codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command = f.read() command = command.replace(\"$uid\", uid) # Call", "and replace params winrm_wrapper.writeLog(\"loading script\") f = codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command = f.read()", "stored in environment and you can get them by os.environ[\"paramName\"] import sys, os", "encoding='utf-8', mode='r') command = f.read() command = command.replace(\"$uid\", uid) # Call wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"],", "coding: utf-8 -*- # All params from IdM is stored in environment and", "import sys, os # this is needed for importing file winrm_wrapper from parent", "replace params winrm_wrapper.writeLog(\"loading script\") f = codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command = f.read() command", "python3 # -*- coding: utf-8 -*- # All params from IdM is stored", "os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete start for \" + uid) # Load PS script from file", "os.environ[\"password\"], os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"], command, uid) winrm_wrapper.writeLog(\"Delete end for \" + uid) print(\"__UID__=\" +", "command.replace(\"$uid\", uid) # Call wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"], os.environ[\"user\"], os.environ[\"password\"], os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"], command, uid)", "for \" + uid) # Load PS script from file and replace params", "\" + uid) # Load PS script from file and replace params winrm_wrapper.writeLog(\"loading", "import winrm_wrapper import codecs uid = os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete start for \" + uid)", "is needed for importing file winrm_wrapper from parent dir sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import winrm_wrapper", "<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # All params from IdM", "is stored in environment and you can get them by os.environ[\"paramName\"] import sys,", "#!/usr/bin/env python3 # -*- coding: utf-8 -*- # All params from IdM is", "codecs uid = os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete start for \" + uid) # Load PS", "# All params from IdM is stored in environment and you can get", "dir sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import winrm_wrapper import codecs uid = os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete start for", "# this is needed for importing file winrm_wrapper from parent dir sys.path.append(os.path.join(os.path.dirname(__file__), '..'))", "f = codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command = f.read() command = command.replace(\"$uid\", uid) #", "os.environ[\"user\"], os.environ[\"password\"], os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"], command, uid) winrm_wrapper.writeLog(\"Delete end for \" + uid) print(\"__UID__=\"", "os.environ[\"ignoreCaValidation\"], command, uid) winrm_wrapper.writeLog(\"Delete end for \" + uid) print(\"__UID__=\" + uid) sys.exit()", "environment and you can get them by os.environ[\"paramName\"] import sys, os # this", "this is needed for importing file winrm_wrapper from parent dir sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import", "file winrm_wrapper from parent dir sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import winrm_wrapper import codecs uid =", "from IdM is stored in environment and you can get them by os.environ[\"paramName\"]", "winrm_wrapper.writeLog(\"loading script\") f = codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command = f.read() command = command.replace(\"$uid\",", "PS script from file and replace params winrm_wrapper.writeLog(\"loading script\") f = codecs.open(os.environ[\"script\"], encoding='utf-8',", "start for \" + uid) # Load PS script from file and replace", "+ uid) # Load PS script from file and replace params winrm_wrapper.writeLog(\"loading script\")", "Call wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"], os.environ[\"user\"], os.environ[\"password\"], os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"], command, uid) winrm_wrapper.writeLog(\"Delete end for", "mode='r') command = f.read() command = command.replace(\"$uid\", uid) # Call wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"],", "them by os.environ[\"paramName\"] import sys, os # this is needed for importing file", "in environment and you can get them by os.environ[\"paramName\"] import sys, os #", "-*- # All params from IdM is stored in environment and you can", "uid = os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete start for \" + uid) # Load PS script", "# -*- coding: utf-8 -*- # All params from IdM is stored in", "All params from IdM is stored in environment and you can get them", "import codecs uid = os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete start for \" + uid) # Load", "file and replace params winrm_wrapper.writeLog(\"loading script\") f = codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command =", "get them by os.environ[\"paramName\"] import sys, os # this is needed for importing", "script from file and replace params winrm_wrapper.writeLog(\"loading script\") f = codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r')", "command = command.replace(\"$uid\", uid) # Call wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"], os.environ[\"user\"], os.environ[\"password\"], os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"],", "for importing file winrm_wrapper from parent dir sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import winrm_wrapper import codecs", "# Load PS script from file and replace params winrm_wrapper.writeLog(\"loading script\") f =", "params from IdM is stored in environment and you can get them by", "'..')) import winrm_wrapper import codecs uid = os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete start for \" +", "parent dir sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import winrm_wrapper import codecs uid = os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete start", "os.environ[\"paramName\"] import sys, os # this is needed for importing file winrm_wrapper from", "os.environ[\"authentication\"], os.environ[\"user\"], os.environ[\"password\"], os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"], command, uid) winrm_wrapper.writeLog(\"Delete end for \" + uid)", "importing file winrm_wrapper from parent dir sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import winrm_wrapper import codecs uid", "# Call wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"], os.environ[\"user\"], os.environ[\"password\"], os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"], command, uid) winrm_wrapper.writeLog(\"Delete end", "= os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete start for \" + uid) # Load PS script from", "sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import winrm_wrapper import codecs uid = os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete start for \"", "codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command = f.read() command = command.replace(\"$uid\", uid) # Call wrapper", "-*- coding: utf-8 -*- # All params from IdM is stored in environment", "Load PS script from file and replace params winrm_wrapper.writeLog(\"loading script\") f = codecs.open(os.environ[\"script\"],", "needed for importing file winrm_wrapper from parent dir sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import winrm_wrapper import", "= f.read() command = command.replace(\"$uid\", uid) # Call wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"], os.environ[\"user\"], os.environ[\"password\"],", "IdM is stored in environment and you can get them by os.environ[\"paramName\"] import", "and you can get them by os.environ[\"paramName\"] import sys, os # this is", "can get them by os.environ[\"paramName\"] import sys, os # this is needed for", "by os.environ[\"paramName\"] import sys, os # this is needed for importing file winrm_wrapper", "uid) # Load PS script from file and replace params winrm_wrapper.writeLog(\"loading script\") f", "os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"], command, uid) winrm_wrapper.writeLog(\"Delete end for \" + uid) print(\"__UID__=\" + uid)", "utf-8 -*- # All params from IdM is stored in environment and you", "script\") f = codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command = f.read() command = command.replace(\"$uid\", uid)", "params winrm_wrapper.writeLog(\"loading script\") f = codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command = f.read() command =", "winrm_wrapper.writeLog(\"Delete start for \" + uid) # Load PS script from file and", "winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"], os.environ[\"user\"], os.environ[\"password\"], os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"], command, uid) winrm_wrapper.writeLog(\"Delete end for \" +", "wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"], os.environ[\"user\"], os.environ[\"password\"], os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"], command, uid) winrm_wrapper.writeLog(\"Delete end for \"", "winrm_wrapper import codecs uid = os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete start for \" + uid) #", "you can get them by os.environ[\"paramName\"] import sys, os # this is needed", "uid) # Call wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"], os.environ[\"user\"], os.environ[\"password\"], os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"], command, uid) winrm_wrapper.writeLog(\"Delete", "from parent dir sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import winrm_wrapper import codecs uid = os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete", "= command.replace(\"$uid\", uid) # Call wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"], os.environ[\"user\"], os.environ[\"password\"], os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"], command,", "os # this is needed for importing file winrm_wrapper from parent dir sys.path.append(os.path.join(os.path.dirname(__file__),", "f.read() command = command.replace(\"$uid\", uid) # Call wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"], os.environ[\"user\"], os.environ[\"password\"], os.environ[\"caTrustPath\"],", "command = f.read() command = command.replace(\"$uid\", uid) # Call wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"], os.environ[\"user\"],", "from file and replace params winrm_wrapper.writeLog(\"loading script\") f = codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command", "winrm_wrapper from parent dir sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import winrm_wrapper import codecs uid = os.environ[\"__UID__\"]", "sys, os # this is needed for importing file winrm_wrapper from parent dir" ]
[ "@registry.extensible_enum class ExtensibleEnumeration(Enum): a = auto() b = auto() class RegistryTests(unittest.TestCase): def test_class_registry(self):", "@registry.autoregister class Extension4(object): pass def test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c in ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value, 3) def", "ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister(self): @registry.autoregister class Extension2(ExtensibleClass): pass self.assertTrue(Extension2", "ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister_args(self): @registry.autoregister_params(a=False, b=0) class Extension3(ExtensibleClass): pass self.assertTrue(Extension3", "rights reserved. import unittest from aenum import Enum, auto from dace import registry", "the DaCe authors. All rights reserved. import unittest from aenum import Enum, auto", "in ExtensibleClass.extensions()) def test_autoregister_args(self): @registry.autoregister_params(a=False, b=0) class Extension3(ExtensibleClass): pass self.assertTrue(Extension3 in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3],", "import Enum, auto from dace import registry @registry.make_registry class ExtensibleClass(object): pass class Extension(ExtensibleClass):", "ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False, b=0)) def test_autoregister_fail(self): with self.assertRaises(TypeError): @registry.autoregister class Extension4(object): pass def", "ExtensibleClass.extensions()) def test_autoregister_args(self): @registry.autoregister_params(a=False, b=0) class Extension3(ExtensibleClass): pass self.assertTrue(Extension3 in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False,", "def test_enum_registry_fail(self): with self.assertRaises(TypeError): @registry.extensible_enum class NotAnEnum(object): pass if __name__ == '__main__': unittest.main()", "self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False, b=0)) def test_autoregister_fail(self): with self.assertRaises(TypeError): @registry.autoregister class Extension4(object): pass def test_enum_registry(self):", "in ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister(self): @registry.autoregister class Extension2(ExtensibleClass): pass", "ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value, 3) def test_enum_registry_fail(self): with self.assertRaises(TypeError): @registry.extensible_enum class NotAnEnum(object): pass if __name__", "dict(a=True, b=1, c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister_args(self): @registry.autoregister_params(a=False, b=0) class", "b = auto() class RegistryTests(unittest.TestCase): def test_class_registry(self): ExtensibleClass.register(Extension) self.assertTrue(Extension in ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension) self.assertTrue(Extension", "pass self.assertTrue(Extension2 in ExtensibleClass.extensions()) def test_class_registry_args(self): ExtensibleClass.register(Extension, a=True, b=1, c=2) self.assertTrue(Extension in ExtensibleClass.extensions())", "with self.assertRaises(TypeError): @registry.autoregister class Extension4(object): pass def test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c in ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value,", "@registry.autoregister_params(a=False, b=0) class Extension3(ExtensibleClass): pass self.assertTrue(Extension3 in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False, b=0)) def test_autoregister_fail(self):", "import registry @registry.make_registry class ExtensibleClass(object): pass class Extension(ExtensibleClass): pass @registry.extensible_enum class ExtensibleEnumeration(Enum): a", "in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1, c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister_args(self):", "pass def test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c in ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value, 3) def test_enum_registry_fail(self): with self.assertRaises(TypeError):", "test_autoregister(self): @registry.autoregister class Extension2(ExtensibleClass): pass self.assertTrue(Extension2 in ExtensibleClass.extensions()) def test_class_registry_args(self): ExtensibleClass.register(Extension, a=True, b=1,", "test_autoregister_fail(self): with self.assertRaises(TypeError): @registry.autoregister class Extension4(object): pass def test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c in ExtensibleEnumeration)", "reserved. import unittest from aenum import Enum, auto from dace import registry @registry.make_registry", "self.assertTrue(Extension3 in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False, b=0)) def test_autoregister_fail(self): with self.assertRaises(TypeError): @registry.autoregister class Extension4(object):", "from dace import registry @registry.make_registry class ExtensibleClass(object): pass class Extension(ExtensibleClass): pass @registry.extensible_enum class", "Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved. import unittest", "ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1, c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister_args(self): @registry.autoregister_params(a=False,", "self.assertRaises(TypeError): @registry.autoregister class Extension4(object): pass def test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c in ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value, 3)", "class RegistryTests(unittest.TestCase): def test_class_registry(self): ExtensibleClass.register(Extension) self.assertTrue(Extension in ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions())", "self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister(self): @registry.autoregister class Extension2(ExtensibleClass): pass self.assertTrue(Extension2 in ExtensibleClass.extensions())", "b=1, c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister_args(self): @registry.autoregister_params(a=False, b=0) class Extension3(ExtensibleClass):", "@registry.make_registry class ExtensibleClass(object): pass class Extension(ExtensibleClass): pass @registry.extensible_enum class ExtensibleEnumeration(Enum): a = auto()", "in ExtensibleClass.extensions()) def test_class_registry_args(self): ExtensibleClass.register(Extension, a=True, b=1, c=2) self.assertTrue(Extension in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True,", "not in ExtensibleClass.extensions()) def test_autoregister(self): @registry.autoregister class Extension2(ExtensibleClass): pass self.assertTrue(Extension2 in ExtensibleClass.extensions()) def", "ExtensibleClass.register(Extension, a=True, b=1, c=2) self.assertTrue(Extension in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1, c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension", "ExtensibleClass(object): pass class Extension(ExtensibleClass): pass @registry.extensible_enum class ExtensibleEnumeration(Enum): a = auto() b =", "self.assertTrue(ExtensibleEnumeration.c in ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value, 3) def test_enum_registry_fail(self): with self.assertRaises(TypeError): @registry.extensible_enum class NotAnEnum(object): pass", "def test_class_registry(self): ExtensibleClass.register(Extension) self.assertTrue(Extension in ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister(self):", "self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister_args(self): @registry.autoregister_params(a=False, b=0) class Extension3(ExtensibleClass): pass self.assertTrue(Extension3 in", "not in ExtensibleClass.extensions()) def test_autoregister_args(self): @registry.autoregister_params(a=False, b=0) class Extension3(ExtensibleClass): pass self.assertTrue(Extension3 in ExtensibleClass.extensions())", "def test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c in ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value, 3) def test_enum_registry_fail(self): with self.assertRaises(TypeError): @registry.extensible_enum", "ExtensibleClass.extensions()) def test_class_registry_args(self): ExtensibleClass.register(Extension, a=True, b=1, c=2) self.assertTrue(Extension in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1,", "self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1, c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister_args(self): @registry.autoregister_params(a=False, b=0)", "Extension3(ExtensibleClass): pass self.assertTrue(Extension3 in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False, b=0)) def test_autoregister_fail(self): with self.assertRaises(TypeError): @registry.autoregister", "def test_autoregister_fail(self): with self.assertRaises(TypeError): @registry.autoregister class Extension4(object): pass def test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c in", "unittest from aenum import Enum, auto from dace import registry @registry.make_registry class ExtensibleClass(object):", "def test_autoregister(self): @registry.autoregister class Extension2(ExtensibleClass): pass self.assertTrue(Extension2 in ExtensibleClass.extensions()) def test_class_registry_args(self): ExtensibleClass.register(Extension, a=True,", "b=0) class Extension3(ExtensibleClass): pass self.assertTrue(Extension3 in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False, b=0)) def test_autoregister_fail(self): with", "pass self.assertTrue(Extension3 in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False, b=0)) def test_autoregister_fail(self): with self.assertRaises(TypeError): @registry.autoregister class", "self.assertTrue(Extension in ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister(self): @registry.autoregister class Extension2(ExtensibleClass):", "Extension2(ExtensibleClass): pass self.assertTrue(Extension2 in ExtensibleClass.extensions()) def test_class_registry_args(self): ExtensibleClass.register(Extension, a=True, b=1, c=2) self.assertTrue(Extension in", "# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved. import", "pass class Extension(ExtensibleClass): pass @registry.extensible_enum class ExtensibleEnumeration(Enum): a = auto() b = auto()", "class Extension3(ExtensibleClass): pass self.assertTrue(Extension3 in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False, b=0)) def test_autoregister_fail(self): with self.assertRaises(TypeError):", "auto() class RegistryTests(unittest.TestCase): def test_class_registry(self): ExtensibleClass.register(Extension) self.assertTrue(Extension in ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in", "in ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value, 3) def test_enum_registry_fail(self): with self.assertRaises(TypeError): @registry.extensible_enum class NotAnEnum(object): pass if", "ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister(self): @registry.autoregister class Extension2(ExtensibleClass): pass self.assertTrue(Extension2 in", "ExtensibleEnumeration(Enum): a = auto() b = auto() class RegistryTests(unittest.TestCase): def test_class_registry(self): ExtensibleClass.register(Extension) self.assertTrue(Extension", "RegistryTests(unittest.TestCase): def test_class_registry(self): ExtensibleClass.register(Extension) self.assertTrue(Extension in ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def", "b=0)) def test_autoregister_fail(self): with self.assertRaises(TypeError): @registry.autoregister class Extension4(object): pass def test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c", "class Extension(ExtensibleClass): pass @registry.extensible_enum class ExtensibleEnumeration(Enum): a = auto() b = auto() class", "in ExtensibleClass.extensions()) def test_autoregister(self): @registry.autoregister class Extension2(ExtensibleClass): pass self.assertTrue(Extension2 in ExtensibleClass.extensions()) def test_class_registry_args(self):", "ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c in ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value, 3) def test_enum_registry_fail(self): with self.assertRaises(TypeError): @registry.extensible_enum class NotAnEnum(object):", "b=1, c=2) self.assertTrue(Extension in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1, c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in", "from aenum import Enum, auto from dace import registry @registry.make_registry class ExtensibleClass(object): pass", "in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False, b=0)) def test_autoregister_fail(self): with self.assertRaises(TypeError): @registry.autoregister class Extension4(object): pass", "3) def test_enum_registry_fail(self): with self.assertRaises(TypeError): @registry.extensible_enum class NotAnEnum(object): pass if __name__ == '__main__':", "def test_autoregister_args(self): @registry.autoregister_params(a=False, b=0) class Extension3(ExtensibleClass): pass self.assertTrue(Extension3 in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False, b=0))", "2019-2021 ETH Zurich and the DaCe authors. All rights reserved. import unittest from", "= auto() class RegistryTests(unittest.TestCase): def test_class_registry(self): ExtensibleClass.register(Extension) self.assertTrue(Extension in ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not", "auto() b = auto() class RegistryTests(unittest.TestCase): def test_class_registry(self): ExtensibleClass.register(Extension) self.assertTrue(Extension in ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension)", "a=True, b=1, c=2) self.assertTrue(Extension in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1, c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not", "test_class_registry_args(self): ExtensibleClass.register(Extension, a=True, b=1, c=2) self.assertTrue(Extension in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1, c=2)) ExtensibleClass.unregister(Extension)", "test_class_registry(self): ExtensibleClass.register(Extension) self.assertTrue(Extension in ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister(self): @registry.autoregister", "pass @registry.extensible_enum class ExtensibleEnumeration(Enum): a = auto() b = auto() class RegistryTests(unittest.TestCase): def", "class ExtensibleClass(object): pass class Extension(ExtensibleClass): pass @registry.extensible_enum class ExtensibleEnumeration(Enum): a = auto() b", "ExtensibleClass.register(Extension) self.assertTrue(Extension in ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister(self): @registry.autoregister class", "= auto() b = auto() class RegistryTests(unittest.TestCase): def test_class_registry(self): ExtensibleClass.register(Extension) self.assertTrue(Extension in ExtensibleClass.extensions())", "Zurich and the DaCe authors. All rights reserved. import unittest from aenum import", "class ExtensibleEnumeration(Enum): a = auto() b = auto() class RegistryTests(unittest.TestCase): def test_class_registry(self): ExtensibleClass.register(Extension)", "a = auto() b = auto() class RegistryTests(unittest.TestCase): def test_class_registry(self): ExtensibleClass.register(Extension) self.assertTrue(Extension in", "ExtensibleClass.extensions()) def test_autoregister(self): @registry.autoregister class Extension2(ExtensibleClass): pass self.assertTrue(Extension2 in ExtensibleClass.extensions()) def test_class_registry_args(self): ExtensibleClass.register(Extension,", "All rights reserved. import unittest from aenum import Enum, auto from dace import", "dict(a=False, b=0)) def test_autoregister_fail(self): with self.assertRaises(TypeError): @registry.autoregister class Extension4(object): pass def test_enum_registry(self): ExtensibleEnumeration.register('c')", "class Extension2(ExtensibleClass): pass self.assertTrue(Extension2 in ExtensibleClass.extensions()) def test_class_registry_args(self): ExtensibleClass.register(Extension, a=True, b=1, c=2) self.assertTrue(Extension", "@registry.autoregister class Extension2(ExtensibleClass): pass self.assertTrue(Extension2 in ExtensibleClass.extensions()) def test_class_registry_args(self): ExtensibleClass.register(Extension, a=True, b=1, c=2)", "c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister_args(self): @registry.autoregister_params(a=False, b=0) class Extension3(ExtensibleClass): pass", "dace import registry @registry.make_registry class ExtensibleClass(object): pass class Extension(ExtensibleClass): pass @registry.extensible_enum class ExtensibleEnumeration(Enum):", "DaCe authors. All rights reserved. import unittest from aenum import Enum, auto from", "self.assertTrue(Extension in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1, c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def", "aenum import Enum, auto from dace import registry @registry.make_registry class ExtensibleClass(object): pass class", "def test_class_registry_args(self): ExtensibleClass.register(Extension, a=True, b=1, c=2) self.assertTrue(Extension in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1, c=2))", "and the DaCe authors. All rights reserved. import unittest from aenum import Enum,", "test_autoregister_args(self): @registry.autoregister_params(a=False, b=0) class Extension3(ExtensibleClass): pass self.assertTrue(Extension3 in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False, b=0)) def", "auto from dace import registry @registry.make_registry class ExtensibleClass(object): pass class Extension(ExtensibleClass): pass @registry.extensible_enum", "registry @registry.make_registry class ExtensibleClass(object): pass class Extension(ExtensibleClass): pass @registry.extensible_enum class ExtensibleEnumeration(Enum): a =", "self.assertTrue(Extension2 in ExtensibleClass.extensions()) def test_class_registry_args(self): ExtensibleClass.register(Extension, a=True, b=1, c=2) self.assertTrue(Extension in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension],", "self.assertEqual(ExtensibleEnumeration.c.value, 3) def test_enum_registry_fail(self): with self.assertRaises(TypeError): @registry.extensible_enum class NotAnEnum(object): pass if __name__ ==", "ETH Zurich and the DaCe authors. All rights reserved. import unittest from aenum", "import unittest from aenum import Enum, auto from dace import registry @registry.make_registry class", "authors. All rights reserved. import unittest from aenum import Enum, auto from dace", "class Extension4(object): pass def test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c in ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value, 3) def test_enum_registry_fail(self):", "test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c in ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value, 3) def test_enum_registry_fail(self): with self.assertRaises(TypeError): @registry.extensible_enum class", "Enum, auto from dace import registry @registry.make_registry class ExtensibleClass(object): pass class Extension(ExtensibleClass): pass", "Extension4(object): pass def test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c in ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value, 3) def test_enum_registry_fail(self): with", "c=2) self.assertTrue(Extension in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1, c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions())", "Extension(ExtensibleClass): pass @registry.extensible_enum class ExtensibleEnumeration(Enum): a = auto() b = auto() class RegistryTests(unittest.TestCase):" ]
[ "handler.wait_closed() await finalize() @pytest.fixture async def setup_logger(make_tcp_handler): async def go(*args, **kwargs): handler, server", "[loads(i) for i in s.split(\"\\n\") if i] async def close(self): if self.server is", "yield go async def finalize(): for server in servers: await server.close() await finalize()", "@property def jsons(self): s = self.data.decode(\"utf8\") return [loads(i) for i in s.split(\"\\n\") if", "fut = asyncio.get_event_loop().create_future() self.futs.add(fut) await fut self.futs.remove(fut) @pytest.fixture async def make_tcp_server(): servers =", "async def start(self): self.server = await asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property def port(self): return self.server.sockets[0].getsockname()[1]", "def finalize(): for server in servers: await server.close() await finalize() @pytest.fixture async def", "handler, server yield go async def finalize(): for handler in handlers: handler.close() await", "servers: await server.close() await finalize() @pytest.fixture async def make_tcp_handler(make_tcp_server): handlers = [] async", "def go(*args, level=logging.DEBUG, **kwargs): server = await make_tcp_server() handler = await create_tcp_handler(\"127.0.0.1\", server.port,", "await server.close() await finalize() @pytest.fixture async def make_tcp_handler(make_tcp_server): handlers = [] async def", "await fut self.futs.remove(fut) @pytest.fixture async def make_tcp_server(): servers = [] async def go():", "self.server.wait_closed() self.server = None async def on_connect(self, reader, writer): while True: data =", "server = await make_tcp_handler(*args, **kwargs) logger = logging.getLogger(\"aiologstash_test\") logger.addHandler(handler) return logger, handler, server", "return handler, server yield go async def finalize(): for handler in handlers: handler.close()", "fut.set_result(None) async def wait(self): fut = asyncio.get_event_loop().create_future() self.futs.add(fut) await fut self.futs.remove(fut) @pytest.fixture async", "def go(*args, **kwargs): handler, server = await make_tcp_handler(*args, **kwargs) logger = logging.getLogger(\"aiologstash_test\") logger.addHandler(handler)", "host=\"127.0.0.1\") @property def port(self): return self.server.sockets[0].getsockname()[1] @property def jsons(self): s = self.data.decode(\"utf8\") return", "import pytest from aiologstash2 import create_tcp_handler logging.getLogger().setLevel(logging.DEBUG) class FakeTcpServer: def __init__(self): self.data =", "return [loads(i) for i in s.split(\"\\n\") if i] async def close(self): if self.server", "def make_tcp_handler(make_tcp_server): handlers = [] async def go(*args, level=logging.DEBUG, **kwargs): server = await", "in handlers: handler.close() await handler.wait_closed() await finalize() @pytest.fixture async def setup_logger(make_tcp_handler): async def", "s = self.data.decode(\"utf8\") return [loads(i) for i in s.split(\"\\n\") if i] async def", "writer): while True: data = await reader.read(1024) if not data: break self.data.extend(data) for", "await create_tcp_handler(\"127.0.0.1\", server.port, **kwargs) handlers.append(handler) return handler, server yield go async def finalize():", "import asyncio import logging from json import loads import pytest from aiologstash2 import", "None: return self.server.close() await self.server.wait_closed() self.server = None async def on_connect(self, reader, writer):", "if self.server is None: return self.server.close() await self.server.wait_closed() self.server = None async def", "while True: data = await reader.read(1024) if not data: break self.data.extend(data) for fut", "yield go async def finalize(): for handler in handlers: handler.close() await handler.wait_closed() await", "async def finalize(): for server in servers: await server.close() await finalize() @pytest.fixture async", "async def make_tcp_server(): servers = [] async def go(): server = FakeTcpServer() await", "def wait(self): fut = asyncio.get_event_loop().create_future() self.futs.add(fut) await fut self.futs.remove(fut) @pytest.fixture async def make_tcp_server():", "@pytest.fixture async def setup_logger(make_tcp_handler): async def go(*args, **kwargs): handler, server = await make_tcp_handler(*args,", "= asyncio.get_event_loop().create_future() self.futs.add(fut) await fut self.futs.remove(fut) @pytest.fixture async def make_tcp_server(): servers = []", "async def go(*args, level=logging.DEBUG, **kwargs): server = await make_tcp_server() handler = await create_tcp_handler(\"127.0.0.1\",", "make_tcp_handler(make_tcp_server): handlers = [] async def go(*args, level=logging.DEBUG, **kwargs): server = await make_tcp_server()", "on_connect(self, reader, writer): while True: data = await reader.read(1024) if not data: break", "go async def finalize(): for server in servers: await server.close() await finalize() @pytest.fixture", "s.split(\"\\n\") if i] async def close(self): if self.server is None: return self.server.close() await", "in servers: await server.close() await finalize() @pytest.fixture async def make_tcp_handler(make_tcp_server): handlers = []", "self.data = bytearray() self.server = None self.futs = set() async def start(self): self.server", "await reader.read(1024) if not data: break self.data.extend(data) for fut in self.futs: if not", "server.close() await finalize() @pytest.fixture async def make_tcp_handler(make_tcp_server): handlers = [] async def go(*args,", "self.futs.remove(fut) @pytest.fixture async def make_tcp_server(): servers = [] async def go(): server =", "= None self.futs = set() async def start(self): self.server = await asyncio.start_server(self.on_connect, host=\"127.0.0.1\")", "def jsons(self): s = self.data.decode(\"utf8\") return [loads(i) for i in s.split(\"\\n\") if i]", "None self.futs = set() async def start(self): self.server = await asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property", "await server.start() servers.append(server) return server yield go async def finalize(): for server in", "def close(self): if self.server is None: return self.server.close() await self.server.wait_closed() self.server = None", "= [] async def go(*args, level=logging.DEBUG, **kwargs): server = await make_tcp_server() handler =", "server = FakeTcpServer() await server.start() servers.append(server) return server yield go async def finalize():", "for handler in handlers: handler.close() await handler.wait_closed() await finalize() @pytest.fixture async def setup_logger(make_tcp_handler):", "handler = await create_tcp_handler(\"127.0.0.1\", server.port, **kwargs) handlers.append(handler) return handler, server yield go async", "return self.server.close() await self.server.wait_closed() self.server = None async def on_connect(self, reader, writer): while", "= self.data.decode(\"utf8\") return [loads(i) for i in s.split(\"\\n\") if i] async def close(self):", "class FakeTcpServer: def __init__(self): self.data = bytearray() self.server = None self.futs = set()", "server yield go async def finalize(): for server in servers: await server.close() await", "import logging from json import loads import pytest from aiologstash2 import create_tcp_handler logging.getLogger().setLevel(logging.DEBUG)", "wait(self): fut = asyncio.get_event_loop().create_future() self.futs.add(fut) await fut self.futs.remove(fut) @pytest.fixture async def make_tcp_server(): servers", "port(self): return self.server.sockets[0].getsockname()[1] @property def jsons(self): s = self.data.decode(\"utf8\") return [loads(i) for i", "logging from json import loads import pytest from aiologstash2 import create_tcp_handler logging.getLogger().setLevel(logging.DEBUG) class", "= await reader.read(1024) if not data: break self.data.extend(data) for fut in self.futs: if", "self.server.close() await self.server.wait_closed() self.server = None async def on_connect(self, reader, writer): while True:", "create_tcp_handler logging.getLogger().setLevel(logging.DEBUG) class FakeTcpServer: def __init__(self): self.data = bytearray() self.server = None self.futs", "fut self.futs.remove(fut) @pytest.fixture async def make_tcp_server(): servers = [] async def go(): server", "await finalize() @pytest.fixture async def make_tcp_handler(make_tcp_server): handlers = [] async def go(*args, level=logging.DEBUG,", "handlers.append(handler) return handler, server yield go async def finalize(): for handler in handlers:", "self.data.extend(data) for fut in self.futs: if not fut.done(): fut.set_result(None) async def wait(self): fut", "not fut.done(): fut.set_result(None) async def wait(self): fut = asyncio.get_event_loop().create_future() self.futs.add(fut) await fut self.futs.remove(fut)", "self.futs = set() async def start(self): self.server = await asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property def", "asyncio import logging from json import loads import pytest from aiologstash2 import create_tcp_handler", "servers = [] async def go(): server = FakeTcpServer() await server.start() servers.append(server) return", "data: break self.data.extend(data) for fut in self.futs: if not fut.done(): fut.set_result(None) async def", "asyncio.get_event_loop().create_future() self.futs.add(fut) await fut self.futs.remove(fut) @pytest.fixture async def make_tcp_server(): servers = [] async", "setup_logger(make_tcp_handler): async def go(*args, **kwargs): handler, server = await make_tcp_handler(*args, **kwargs) logger =", "self.server.sockets[0].getsockname()[1] @property def jsons(self): s = self.data.decode(\"utf8\") return [loads(i) for i in s.split(\"\\n\")", "await handler.wait_closed() await finalize() @pytest.fixture async def setup_logger(make_tcp_handler): async def go(*args, **kwargs): handler,", "for fut in self.futs: if not fut.done(): fut.set_result(None) async def wait(self): fut =", "i] async def close(self): if self.server is None: return self.server.close() await self.server.wait_closed() self.server", "handler.close() await handler.wait_closed() await finalize() @pytest.fixture async def setup_logger(make_tcp_handler): async def go(*args, **kwargs):", "await finalize() @pytest.fixture async def setup_logger(make_tcp_handler): async def go(*args, **kwargs): handler, server =", "handler, server = await make_tcp_handler(*args, **kwargs) logger = logging.getLogger(\"aiologstash_test\") logger.addHandler(handler) return logger, handler,", "loads import pytest from aiologstash2 import create_tcp_handler logging.getLogger().setLevel(logging.DEBUG) class FakeTcpServer: def __init__(self): self.data", "pytest from aiologstash2 import create_tcp_handler logging.getLogger().setLevel(logging.DEBUG) class FakeTcpServer: def __init__(self): self.data = bytearray()", "self.server = None self.futs = set() async def start(self): self.server = await asyncio.start_server(self.on_connect,", "async def wait(self): fut = asyncio.get_event_loop().create_future() self.futs.add(fut) await fut self.futs.remove(fut) @pytest.fixture async def", "= set() async def start(self): self.server = await asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property def port(self):", "def on_connect(self, reader, writer): while True: data = await reader.read(1024) if not data:", "close(self): if self.server is None: return self.server.close() await self.server.wait_closed() self.server = None async", "@pytest.fixture async def make_tcp_handler(make_tcp_server): handlers = [] async def go(*args, level=logging.DEBUG, **kwargs): server", "async def go(*args, **kwargs): handler, server = await make_tcp_handler(*args, **kwargs) logger = logging.getLogger(\"aiologstash_test\")", "fut in self.futs: if not fut.done(): fut.set_result(None) async def wait(self): fut = asyncio.get_event_loop().create_future()", "= await make_tcp_server() handler = await create_tcp_handler(\"127.0.0.1\", server.port, **kwargs) handlers.append(handler) return handler, server", "i in s.split(\"\\n\") if i] async def close(self): if self.server is None: return", "break self.data.extend(data) for fut in self.futs: if not fut.done(): fut.set_result(None) async def wait(self):", "async def close(self): if self.server is None: return self.server.close() await self.server.wait_closed() self.server =", "@pytest.fixture async def make_tcp_server(): servers = [] async def go(): server = FakeTcpServer()", "await self.server.wait_closed() self.server = None async def on_connect(self, reader, writer): while True: data", "await asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property def port(self): return self.server.sockets[0].getsockname()[1] @property def jsons(self): s =", "def __init__(self): self.data = bytearray() self.server = None self.futs = set() async def", "go(*args, level=logging.DEBUG, **kwargs): server = await make_tcp_server() handler = await create_tcp_handler(\"127.0.0.1\", server.port, **kwargs)", "server.port, **kwargs) handlers.append(handler) return handler, server yield go async def finalize(): for handler", "**kwargs) handlers.append(handler) return handler, server yield go async def finalize(): for handler in", "True: data = await reader.read(1024) if not data: break self.data.extend(data) for fut in", "= FakeTcpServer() await server.start() servers.append(server) return server yield go async def finalize(): for", "= None async def on_connect(self, reader, writer): while True: data = await reader.read(1024)", "aiologstash2 import create_tcp_handler logging.getLogger().setLevel(logging.DEBUG) class FakeTcpServer: def __init__(self): self.data = bytearray() self.server =", "bytearray() self.server = None self.futs = set() async def start(self): self.server = await", "**kwargs): server = await make_tcp_server() handler = await create_tcp_handler(\"127.0.0.1\", server.port, **kwargs) handlers.append(handler) return", "finalize(): for handler in handlers: handler.close() await handler.wait_closed() await finalize() @pytest.fixture async def", "await make_tcp_server() handler = await create_tcp_handler(\"127.0.0.1\", server.port, **kwargs) handlers.append(handler) return handler, server yield", "= bytearray() self.server = None self.futs = set() async def start(self): self.server =", "[] async def go(*args, level=logging.DEBUG, **kwargs): server = await make_tcp_server() handler = await", "from json import loads import pytest from aiologstash2 import create_tcp_handler logging.getLogger().setLevel(logging.DEBUG) class FakeTcpServer:", "level=logging.DEBUG, **kwargs): server = await make_tcp_server() handler = await create_tcp_handler(\"127.0.0.1\", server.port, **kwargs) handlers.append(handler)", "make_tcp_server() handler = await create_tcp_handler(\"127.0.0.1\", server.port, **kwargs) handlers.append(handler) return handler, server yield go", "server.start() servers.append(server) return server yield go async def finalize(): for server in servers:", "self.futs: if not fut.done(): fut.set_result(None) async def wait(self): fut = asyncio.get_event_loop().create_future() self.futs.add(fut) await", "async def go(): server = FakeTcpServer() await server.start() servers.append(server) return server yield go", "reader, writer): while True: data = await reader.read(1024) if not data: break self.data.extend(data)", "[] async def go(): server = FakeTcpServer() await server.start() servers.append(server) return server yield", "async def on_connect(self, reader, writer): while True: data = await reader.read(1024) if not", "in s.split(\"\\n\") if i] async def close(self): if self.server is None: return self.server.close()", "= await create_tcp_handler(\"127.0.0.1\", server.port, **kwargs) handlers.append(handler) return handler, server yield go async def", "handlers: handler.close() await handler.wait_closed() await finalize() @pytest.fixture async def setup_logger(make_tcp_handler): async def go(*args,", "logging.getLogger().setLevel(logging.DEBUG) class FakeTcpServer: def __init__(self): self.data = bytearray() self.server = None self.futs =", "not data: break self.data.extend(data) for fut in self.futs: if not fut.done(): fut.set_result(None) async", "None async def on_connect(self, reader, writer): while True: data = await reader.read(1024) if", "@property def port(self): return self.server.sockets[0].getsockname()[1] @property def jsons(self): s = self.data.decode(\"utf8\") return [loads(i)", "reader.read(1024) if not data: break self.data.extend(data) for fut in self.futs: if not fut.done():", "= [] async def go(): server = FakeTcpServer() await server.start() servers.append(server) return server", "go async def finalize(): for handler in handlers: handler.close() await handler.wait_closed() await finalize()", "self.server is None: return self.server.close() await self.server.wait_closed() self.server = None async def on_connect(self,", "await make_tcp_handler(*args, **kwargs) logger = logging.getLogger(\"aiologstash_test\") logger.addHandler(handler) return logger, handler, server yield go", "self.data.decode(\"utf8\") return [loads(i) for i in s.split(\"\\n\") if i] async def close(self): if", "self.futs.add(fut) await fut self.futs.remove(fut) @pytest.fixture async def make_tcp_server(): servers = [] async def", "handler in handlers: handler.close() await handler.wait_closed() await finalize() @pytest.fixture async def setup_logger(make_tcp_handler): async", "finalize() @pytest.fixture async def make_tcp_handler(make_tcp_server): handlers = [] async def go(*args, level=logging.DEBUG, **kwargs):", "= await make_tcp_handler(*args, **kwargs) logger = logging.getLogger(\"aiologstash_test\") logger.addHandler(handler) return logger, handler, server yield", "def port(self): return self.server.sockets[0].getsockname()[1] @property def jsons(self): s = self.data.decode(\"utf8\") return [loads(i) for", "finalize() @pytest.fixture async def setup_logger(make_tcp_handler): async def go(*args, **kwargs): handler, server = await", "servers.append(server) return server yield go async def finalize(): for server in servers: await", "server in servers: await server.close() await finalize() @pytest.fixture async def make_tcp_handler(make_tcp_server): handlers =", "async def make_tcp_handler(make_tcp_server): handlers = [] async def go(*args, level=logging.DEBUG, **kwargs): server =", "def go(): server = FakeTcpServer() await server.start() servers.append(server) return server yield go async", "if not data: break self.data.extend(data) for fut in self.futs: if not fut.done(): fut.set_result(None)", "= await asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property def port(self): return self.server.sockets[0].getsockname()[1] @property def jsons(self): s", "self.server = None async def on_connect(self, reader, writer): while True: data = await", "FakeTcpServer() await server.start() servers.append(server) return server yield go async def finalize(): for server", "def finalize(): for handler in handlers: handler.close() await handler.wait_closed() await finalize() @pytest.fixture async", "**kwargs): handler, server = await make_tcp_handler(*args, **kwargs) logger = logging.getLogger(\"aiologstash_test\") logger.addHandler(handler) return logger,", "finalize(): for server in servers: await server.close() await finalize() @pytest.fixture async def make_tcp_handler(make_tcp_server):", "if i] async def close(self): if self.server is None: return self.server.close() await self.server.wait_closed()", "if not fut.done(): fut.set_result(None) async def wait(self): fut = asyncio.get_event_loop().create_future() self.futs.add(fut) await fut", "asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property def port(self): return self.server.sockets[0].getsockname()[1] @property def jsons(self): s = self.data.decode(\"utf8\")", "async def finalize(): for handler in handlers: handler.close() await handler.wait_closed() await finalize() @pytest.fixture", "for server in servers: await server.close() await finalize() @pytest.fixture async def make_tcp_handler(make_tcp_server): handlers", "import loads import pytest from aiologstash2 import create_tcp_handler logging.getLogger().setLevel(logging.DEBUG) class FakeTcpServer: def __init__(self):", "fut.done(): fut.set_result(None) async def wait(self): fut = asyncio.get_event_loop().create_future() self.futs.add(fut) await fut self.futs.remove(fut) @pytest.fixture", "from aiologstash2 import create_tcp_handler logging.getLogger().setLevel(logging.DEBUG) class FakeTcpServer: def __init__(self): self.data = bytearray() self.server", "make_tcp_server(): servers = [] async def go(): server = FakeTcpServer() await server.start() servers.append(server)", "return self.server.sockets[0].getsockname()[1] @property def jsons(self): s = self.data.decode(\"utf8\") return [loads(i) for i in", "json import loads import pytest from aiologstash2 import create_tcp_handler logging.getLogger().setLevel(logging.DEBUG) class FakeTcpServer: def", "jsons(self): s = self.data.decode(\"utf8\") return [loads(i) for i in s.split(\"\\n\") if i] async", "go(): server = FakeTcpServer() await server.start() servers.append(server) return server yield go async def", "go(*args, **kwargs): handler, server = await make_tcp_handler(*args, **kwargs) logger = logging.getLogger(\"aiologstash_test\") logger.addHandler(handler) return", "def make_tcp_server(): servers = [] async def go(): server = FakeTcpServer() await server.start()", "FakeTcpServer: def __init__(self): self.data = bytearray() self.server = None self.futs = set() async", "set() async def start(self): self.server = await asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property def port(self): return", "def setup_logger(make_tcp_handler): async def go(*args, **kwargs): handler, server = await make_tcp_handler(*args, **kwargs) logger", "for i in s.split(\"\\n\") if i] async def close(self): if self.server is None:", "import create_tcp_handler logging.getLogger().setLevel(logging.DEBUG) class FakeTcpServer: def __init__(self): self.data = bytearray() self.server = None", "is None: return self.server.close() await self.server.wait_closed() self.server = None async def on_connect(self, reader,", "create_tcp_handler(\"127.0.0.1\", server.port, **kwargs) handlers.append(handler) return handler, server yield go async def finalize(): for", "data = await reader.read(1024) if not data: break self.data.extend(data) for fut in self.futs:", "start(self): self.server = await asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property def port(self): return self.server.sockets[0].getsockname()[1] @property def", "def start(self): self.server = await asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property def port(self): return self.server.sockets[0].getsockname()[1] @property", "in self.futs: if not fut.done(): fut.set_result(None) async def wait(self): fut = asyncio.get_event_loop().create_future() self.futs.add(fut)", "server = await make_tcp_server() handler = await create_tcp_handler(\"127.0.0.1\", server.port, **kwargs) handlers.append(handler) return handler,", "handlers = [] async def go(*args, level=logging.DEBUG, **kwargs): server = await make_tcp_server() handler", "return server yield go async def finalize(): for server in servers: await server.close()", "server yield go async def finalize(): for handler in handlers: handler.close() await handler.wait_closed()", "async def setup_logger(make_tcp_handler): async def go(*args, **kwargs): handler, server = await make_tcp_handler(*args, **kwargs)", "self.server = await asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property def port(self): return self.server.sockets[0].getsockname()[1] @property def jsons(self):", "__init__(self): self.data = bytearray() self.server = None self.futs = set() async def start(self):" ]
[ "(not isinstance(value, dict) or not self._is_tc_entity(value)): raise RuntimeError('Invalid data provided for TcEntity.') #", "proper structure for Key Value.\"\"\" if data is None: return False return all(x", "self._output_variables_by_name = {} self._output_variables_by_type = {} for ov in self._output_variables: # parse the", "# spread the value so that we know it's a list (as opposed", "= json.dumps(value) except ValueError as e: # pragma: no cover raise RuntimeError(f'Failed to", "only be embedded one level deep. This method will automatically covert variables embedded", "from DB \"\"\" # TODO: need to verify if core still sends improper", "elif variable_type == 'KeyValue': # embedded variable can be unquoted, which breaks JSON.", "'Binary': value = self._load_value(value) if b64decode: value = base64.b64decode(value) if decode: value =", "loading JSON data ({value}). Error: ({e})') elif variable_type == 'StringArray': if embedded: value", "'TCEnhancedEntityArray']: value = self._load_value(value) # self.log.trace(f'pb create - context: {self._context}, key: {key}, value:", "..important:: Raw data can only be a byte, str or int. Other data", "(str): The Redis context (hash). output_variables (list): The requested output variables. \"\"\" def", "not self._is_tc_entity_array(value): raise RuntimeError('Invalid data provided for TcEntityArray.') # self.log.trace(f'pb create - context:", "for Key Value Array.\"\"\" for d in data: if not self._is_key_value(d): return False", "module\"\"\" # standard library import base64 import json import re from collections import", "The data to write to the DB. Returns: (str): Result of DB write.", "re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def _coerce_string_value(self, value): \"\"\"Return a string value from an bool or int.\"\"\"", "variable_pattern += r':([A-Za-z0-9_\\.\\-\\[\\]]+)' # variable name (:variable_name) variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' # variable type", "return value def _create(self, key, value, validate=True): \"\"\"Create the value in Redis if", "None: # pragma: no cover return value for variable in (v.group(0) for v", "value = self._coerce_string_value(value) if validate and not isinstance(value, str): raise RuntimeError('Invalid data provided", "standard playbook array variable types.\"\"\" return [ 'BinaryArray', 'KeyValueArray', 'StringArray', 'TCEntityArray', 'TCEnhancedEntityArray', ]", "value is not None: try: data = self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as", "self._load_value(value) elif variable_type == 'String': if embedded: value = self._read_embedded(value) # coerce string", "The ``read()`` method will automatically determine if the input is a variable or", "= json.loads(value, object_pairs_hook=OrderedDict) values = [] for v in value: if v is", "the DB. Returns: (str): Results retrieved from DB \"\"\" if value is None:", "Raises: RuntimeError: Raise error when data can't be loaded as JSON data. Returns:", "for variable in (v.group(0) for v in re.finditer(self._variable_parse, str(value))): v = self.read(variable) self.log.trace(f'embedded", "the resulting data is loadable JSON value = re.sub(f'\"{variable}\"', v, value) if v", "to say if value is just the variable reference, # sub None value,", "value = json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: # pragma: no cover raise", "create_raw(self, key, value): \"\"\"Create method of CRUD operation for raw data. ..important:: Raw", "have embedded variables. * Only String and KeyValueArray variables can have embedded variables.", "KeyValueArray with nested dict/list type replace the # quoted value to ensure the", "RuntimeError('Invalid data provided for Binary.') value = base64.b64encode(value).decode('utf-8') elif variable_type == 'KeyValue': if", "as e: # pragma: no cover raise RuntimeError(f'Failed loading JSON data ({value}). Error:", "key/value store. \"\"\" try: return json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: # pragma:", "types.\"\"\" return [ 'BinaryArray', 'KeyValueArray', 'StringArray', 'TCEntityArray', 'TCEnhancedEntityArray', ] @property def _variable_single_types(self): \"\"\"Return", "child method.\"\"\" raise NotImplementedError('Implemented in child class') def read(self, key, array=False, embedded=True): #", "not self._is_key_value(d): return False return True @staticmethod def _is_tc_entity(data): \"\"\"Return True if provided", "values elif variable_type == 'KeyValueArray': # embedded variable can be unquoted, which breaks", "3: Input: [{ \"key\": \"embedded string\", \"value\": \"This input has a embedded #App:7979:variable_name!String\"", "by name (e.g. \"status_code\") self._output_variables_by_name[variable_name] = {'variable': ov} # store the variables in", "try: return self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e) return None def", "base64 import json import re from collections import OrderedDict from collections.abc import Iterable", "to write to the DB. value (bytes|int|string): The data to write to the", "RuntimeError: Raise error when data can't be loaded as JSON data. Returns: any:", "variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for custom variable_pattern += r'[A-Za-z0-9_-]+))' # variable", "'TCEntity': if validate and (not isinstance(value, dict) or not self._is_tc_entity(value)): raise RuntimeError('Invalid data", "v = base64.b64decode(v) if decode: v = self._decode_binary(v) values.append(v) value = values elif", "re.sub(f'\"{variable}\"', v, value) if v is not None: # only replace variable if", "* Only user input can have embedded variables. * Only String and KeyValueArray", "self.variable_type(key) # Enhanced entity array is the wild-wild west, don't validate it if", "data has proper structure for TC Entity Array.\"\"\" for d in data: if", "def _read_array(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value in Redis if applicable.\"\"\"", "over set to handle duplicates # pull (#App:1441:embedded_string!String) from (\": #App:1441:embedded_string!String) variable_string =", "data for x in ['key', 'value']) def _is_key_value_array(self, data): \"\"\"Return True if provided", "return [ 'Binary', 'KeyValue', 'String', 'TCEntity', 'TCEnhancedEntity', ] @property def _variable_types(self): \"\"\"Return list", "# version of this method that gets the entire list/dict instead of just", "2: Input: [\"one\", #App:7979:two!String, \"three\"] Examples 3: Input: [{ \"key\": \"embedded string\", \"value\":", "'String': if embedded: value = self._read_embedded(value) # coerce string values value = self._coerce_string_value(self._load_value(value))", "value = self._read_embedded(value) # coerce string values value = self._coerce_string_value(self._load_value(value)) elif variable_type ==", "provided for Binary.') value = base64.b64encode(value).decode('utf-8') elif variable_type == 'KeyValue': if validate and", "= self.parse_variable(ov) variable_name = parsed_variable.get('name') variable_type = parsed_variable.get('type') # store the variables in", "from DB \"\"\" if value is None: # pragma: no cover return value", "= base64.b64encode(v).decode('utf-8') value_encoded.append(v) value = value_encoded elif variable_type == 'KeyValueArray': if validate and", "# properties self._output_variables_by_name = None self._output_variables_by_type = None self.log = tcex.log # match", "keyvalue embedded variable in double quotes. Args: data (str): The data with embedded", "provided for KeyValue.') elif variable_type == 'String': # coerce string values value =", "breaks JSON. value = self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) try: value =", "if v is not None and b64decode: v = base64.b64decode(v) if decode: v", "variables. Returns: (str): Results retrieved from DB \"\"\" # TODO: need to verify", "reference, # sub None value, else insert '' in string. That would require", "variable_type = parsed_variable.get('type') # store the variables in dict by name (e.g. \"status_code\")", "variable if a non-null value is returned from kv store # APP-1030 need", "be returned. Examples:: DB Values #App:7979:variable_name!String: \"embedded \\\\\"variable\\\\\"\" #App:7979:two!String: \"two\" #App:7979:variable_name!StringArray: [\"one\", \"two\",", "proper structure for TC Entity Array.\"\"\" for d in data: if not self._is_tc_entity(d):", "self.log.warning(f'Coercing float/int value ({value}) to a string (\"{str(value)}\").') value = str(value) return value", "custom variable_pattern += r'[A-Za-z0-9_-]+))' # variable type (custom) return variable_pattern @property def _variable_array_types(self):", "'type']) def _is_tc_entity_array(self, data): \"\"\"Return True if provided data has proper structure for", "\"embedded \\\\\"variable\\\\\"\" #App:7979:two!String: \"two\" #App:7979:variable_name!StringArray: [\"one\", \"two\", \"three\"] Examples 1: Input: \"This input", "= json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: # pragma: no cover raise RuntimeError(f'Failed", "properties self._output_variables_by_name = None self._output_variables_by_type = None self.log = tcex.log # match full", "data can't be loaded as JSON data. Returns: any: The de-serialized value from", "'KeyValueArray': # embedded variable can be unquoted, which breaks JSON. value = self._wrap_embedded_keyvalue(value)", "self._output_variables: # parse the variable to get individual parts parsed_variable = self.parse_variable(ov) variable_name", "to get individual parts parsed_variable = self.parse_variable(ov) variable_name = parsed_variable.get('name') variable_type = parsed_variable.get('type')", "DB. value (bytes|int|string): The data to write to the DB. Returns: (str): Result", "return self._variable_single_types + self._variable_array_types def _wrap_embedded_keyvalue(self, data): \"\"\"Wrap keyvalue embedded variable in double", "(v.group(0) for v in re.finditer(self._variable_parse, str(value))): v = self.read(variable) self.log.trace(f'embedded variable: {variable}, value:", "= str(value) return value def _create(self, key, value, validate=True): \"\"\"Create the value in", "list of standard playbook single variable types.\"\"\" return [ 'Binary', 'KeyValue', 'String', 'TCEntity',", "to replace the correct instance only, handling the case where a variable #", "= None if key is not None: value = self.tcex.key_value_store.read(self._context, key.strip()) else: self.log.warning('The", "= data.decode('latin-1') return data @staticmethod def _is_key_value(data): \"\"\"Return True if provided data has", "has a embedded #App:7979:variable_name!String\" }, { \"key\": \"string array\", \"value\": #App:7979:variable_name!StringArray }, {", "key is None or value is None: self.log.warning('The key or value field is", "The variable to read from the DB. Returns: (str): Results retrieved from DB.", "string. value = re.sub(variable, v, value) return value @property def _variable_pattern(self): \"\"\"Regex pattern", "value = self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) try: value = json.loads(value, object_pairs_hook=OrderedDict)", "in child class') def variable_type(self, variable): # pragma: no cover \"\"\"Set placeholder for", "\"\"\" if value is None: # pragma: no cover return value for variable", "dict by name-type (e.g. \"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}'] = {'variable': ov} def _read(self, key, embedded=True,", "= self._read_embedded(value) # convert int to str value_coerced = [] for v in", "embedded in a string with value retrieved from DB. If there are no", "None if key is not None: value = self.tcex.key_value_store.read(self._context, key.strip()) else: self.log.warning('The key", "_coerce_string_value(self, value): \"\"\"Return a string value from an bool or int.\"\"\" # coerce", "@staticmethod def _decode_binary(data): \"\"\"Return decoded bytes data handling data written by java apps.\"\"\"", "object_pairs_hook=OrderedDict) except ValueError as e: # pragma: no cover raise RuntimeError(f'Failed loading JSON", "return value def parse_variable(self, variable): # pragma: no cover \"\"\"Set placeholder for child", "object_pairs_hook=OrderedDict) except ValueError as e: # pragma: no cover raise RuntimeError(f'Failed to JSON", "determine if the input is a variable or needs to be searched for", "r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array) variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type variable_pattern +=", "double quotes. Args: data (str): The data with embedded variables. Returns: (str): Results", "= re.compile(self._variable_pattern) # match embedded variables without quotes (#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded = re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def", "for d in data: if not self._is_tc_entity(d): return False return True @staticmethod def", "for StringArray.') value_coerced.append(v) value = value_coerced elif variable_type == 'TCEntityArray': if validate and", "variable): # pragma: no cover \"\"\"Set placeholder for child method.\"\"\" raise NotImplementedError('Implemented in", "_variable_single_types(self): \"\"\"Return list of standard playbook single variable types.\"\"\" return [ 'Binary', 'KeyValue',", "the raw string will be returned. Examples:: DB Values #App:7979:variable_name!String: \"embedded \\\\\"variable\\\\\"\" #App:7979:two!String:", "and (not isinstance(value, dict) or not self._is_tc_entity(value)): raise RuntimeError('Invalid data provided for TcEntity.')", "data provided for Binary.') # if not isinstance(v, bytes): # v = v.encode('utf-8')", "None. Would like to be able to say if value is just the", "r':([\\d]+)' # app id (:7979) variable_pattern += r':([A-Za-z0-9_\\.\\-\\[\\]]+)' # variable name (:variable_name) variable_pattern", "if provided data has proper structure for Key Value.\"\"\" if data is None:", "written by java apps.\"\"\" try: data = data.decode('utf-8') except UnicodeDecodeError: # pragma: no", "(array) variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching", "data @staticmethod def _is_key_value(data): \"\"\"Return True if provided data has proper structure for", "@property def _variable_types(self): \"\"\"Return list of standard playbook variable typesd.\"\"\" return self._variable_single_types +", "be embedded one level deep. This method will automatically covert variables embedded in", "Redis context (hash). output_variables (list): The requested output variables. \"\"\" def __init__(self, tcex,", "provided data has proper structure for Key Value.\"\"\" if data is None: return", "elif variable_type == 'KeyValueArray': # embedded variable can be unquoted, which breaks JSON.", "OrderedDict from collections.abc import Iterable class PlaybooksBase: \"\"\"TcEx Playbook Module Base Class Args:", "def _variable_single_types(self): \"\"\"Return list of standard playbook single variable types.\"\"\" return [ 'Binary',", "from key/value store. Raises: RuntimeError: Raise error when data can't be loaded as", "from collections.abc import Iterable class PlaybooksBase: \"\"\"TcEx Playbook Module Base Class Args: tcex", "else insert '' in string. That would require a kv-specific # version of", "type (array) variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array) variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' #", "variable_pattern += r':([\\d]+)' # app id (:7979) variable_pattern += r':([A-Za-z0-9_\\.\\-\\[\\]]+)' # variable name", "_is_tc_entity_array(self, data): \"\"\"Return True if provided data has proper structure for TC Entity", "list of standard playbook variable typesd.\"\"\" return self._variable_single_types + self._variable_array_types def _wrap_embedded_keyvalue(self, data):", "replace the # quoted value to ensure the resulting data is loadable JSON", "self.log = tcex.log # match full variable self._variable_match = re.compile(fr'^{self._variable_pattern}$') # capture variable", "self._read_embedded(value) value = self._load_value(value) elif variable_type == 'String': if embedded: value = self._read_embedded(value)", "is an int if isinstance(value, bool): # coerce bool to str type self.log.warning(f'Coercing", "in kv/kvarrays that # are None. Would like to be able to say", "if value is None: return value if variable_type == 'BinaryArray': value = json.loads(value,", "self.variable_type(key) if variable_type == 'Binary': # if not isinstance(value, bytes): # value =", "in data for x in ['id', 'value', 'type']) def _is_tc_entity_array(self, data): \"\"\"Return True", "one level deep. This method will automatically covert variables embedded in a string", "in data: if not self._is_tc_entity(d): return False return True @staticmethod def _load_value(value): \"\"\"Return", "key, value, validate=True): \"\"\"Create the value in Redis if applicable.\"\"\" if key is", "json import re from collections import OrderedDict from collections.abc import Iterable class PlaybooksBase:", "r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array) variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array) variable_pattern", "not None: value = self.tcex.key_value_store.read(self._context, key.strip()) else: self.log.warning('The key field was None.') return", "variable_type = self.variable_type(key) if variable_type == 'Binary': # if not isinstance(value, bytes): #", "== 'Binary': # if not isinstance(value, bytes): # value = value.encode('utf-8') if validate", "this to handle variable references in kv/kvarrays that # are None. Would like", "validate and not self._is_tc_entity_array(value): raise RuntimeError('Invalid data provided for TcEntityArray.') # self.log.trace(f'pb create", "return data def create_raw(self, key, value): \"\"\"Create method of CRUD operation for raw", "data.decode('utf-8') except UnicodeDecodeError: # pragma: no cover # for data written an upstream", "validate=True): \"\"\"Create the value in Redis if applicable.\"\"\" if key is None or", "StringArray.') value_coerced.append(v) value = value_coerced elif variable_type == 'TCEntityArray': if validate and not", "kv/kvarrays that # are None. Would like to be able to say if", "value.encode('utf-8') if validate and not isinstance(value, bytes): raise RuntimeError('Invalid data provided for Binary.')", "None: # pragma: no cover variables = [] for v in re.finditer(self._vars_keyvalue_embedded, data):", "+= r':([A-Za-z0-9_\\.\\-\\[\\]]+)' # variable name (:variable_name) variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array)", "type (array) variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non", "key.strip(), value) except RuntimeError as e: self.log.error(e) return None @staticmethod def _decode_binary(data): \"\"\"Return", "+= r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for custom variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching", "Returns: any: The de-serialized value from the key/value store. \"\"\" try: return json.loads(value,", "if value is None: # pragma: no cover return value for variable in", "# for data written an upstream java App data = data.decode('latin-1') return data", "\"value\": #App:7979:variable_name!StringArray }, { \"key\": \"string\", \"value\": #App:7979:variable_name!String }] Args: value (str): The", "= re.search(self._variable_parse, var).group(0) # reformat to replace the correct instance only, handling the", "int to str value_coerced = [] for v in self._load_value(value): # coerce string", "tcex (TcEx): Instance of TcEx class. context (str): The Redis context (hash). output_variables", "provided for Binary.') # if not isinstance(v, bytes): # v = v.encode('utf-8') v", "= {'variable': ov} # store the variables in dict by name-type (e.g. \"status_code-String\")", "Only String and KeyValueArray variables can have embedded variables. * Variables can only", "dict by name (e.g. \"status_code\") self._output_variables_by_name[variable_name] = {'variable': ov} # store the variables", "key is None: # pragma: no cover self.log.warning('The null value for key was", "raise RuntimeError('Invalid data provided for TcEntity.') # self.log.trace(f'pb create - context: {self._context}, key:", "The data from key/value store. Raises: RuntimeError: Raise error when data can't be", "= [] for v in self._load_value(value): # coerce string values value_coerced.append(self._coerce_string_value(v)) value =", "String and KeyValueArray variables can have embedded variables. * Variables can only be", "{} for ov in self._output_variables: # parse the variable to get individual parts", "def _read_embedded(self, value): \"\"\"Read method for \"embedded\" variables. .. Note:: The ``read()`` method", "= [] for v in value: if v is not None and b64decode:", "v.encode('utf-8') v = base64.b64encode(v).decode('utf-8') value_encoded.append(v) value = value_encoded elif variable_type == 'KeyValueArray': if", "False return True @staticmethod def _is_tc_entity(data): \"\"\"Return True if provided data has proper", "not self._is_tc_entity(d): return False return True @staticmethod def _load_value(value): \"\"\"Return the loaded JSON", "in re.finditer(self._variable_parse, str(value))): v = self.read(variable) self.log.trace(f'embedded variable: {variable}, value: {v}') if isinstance(v,", "Input: [\"one\", #App:7979:two!String, \"three\"] Examples 3: Input: [{ \"key\": \"embedded string\", \"value\": \"This", "duplicates # pull (#App:1441:embedded_string!String) from (\": #App:1441:embedded_string!String) variable_string = re.search(self._variable_parse, var).group(0) # reformat", "matching for custom variable_pattern += r'[A-Za-z0-9_-]+))' # variable type (custom) return variable_pattern @property", "variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array) variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type", "data has proper structure for Key Value Array.\"\"\" for d in data: if", "parsed_variable.get('name') variable_type = parsed_variable.get('type') # store the variables in dict by name (e.g.", "return value if variable_type == 'BinaryArray': value = json.loads(value, object_pairs_hook=OrderedDict) values = []", "playbook single variable types.\"\"\" return [ 'Binary', 'KeyValue', 'String', 'TCEntity', 'TCEnhancedEntity', ] @property", "dict))): raise RuntimeError(f'Invalid data provided for {variable_type}.') value = [ *value ] #", "Args: key (str): The variable to read from the DB. Returns: (str): Results", "parse_variable(self, variable): # pragma: no cover \"\"\"Set placeholder for child method.\"\"\" raise NotImplementedError('Implemented", "self.log.error(e) return None if value is None: return value if variable_type == 'BinaryArray':", "== 'StringArray': if embedded: value = self._read_embedded(value) # convert int to str value_coerced", "deep. This method will automatically covert variables embedded in a string with value", "be loaded as JSON data. Returns: any: The de-serialized value from the key/value", "validate and (not isinstance(value, Iterable) or isinstance(value, (str, dict))): raise RuntimeError(f'Invalid data provided", "raise RuntimeError('Invalid data provided for String.') elif variable_type == 'TCEntity': if validate and", "is not None: if validate and not isinstance(v, bytes): raise RuntimeError('Invalid data provided", "embedded variable can be unquoted, which breaks JSON. value = self._wrap_embedded_keyvalue(value) if embedded:", "value = base64.b64encode(value).decode('utf-8') elif variable_type == 'KeyValue': if validate and (not isinstance(value, dict)", "self._is_key_value(d): return False return True @staticmethod def _is_tc_entity(data): \"\"\"Return True if provided data", "covert variables embedded in a string with value retrieved from DB. If there", "[{ \"key\": \"embedded string\", \"value\": \"This input has a embedded #App:7979:variable_name!String\" }, {", "from collections import OrderedDict from collections.abc import Iterable class PlaybooksBase: \"\"\"TcEx Playbook Module", "== 'TCEntity': if validate and (not isinstance(value, dict) or not self._is_tc_entity(value)): raise RuntimeError('Invalid", "decode: v = self._decode_binary(v) values.append(v) value = values elif variable_type == 'KeyValueArray': #", "DB Values #App:7979:variable_name!String: \"embedded \\\\\"variable\\\\\"\" #App:7979:two!String: \"two\" #App:7979:variable_name!StringArray: [\"one\", \"two\", \"three\"] Examples 1:", "value_coerced = [] for v in value: # coerce string values v =", "self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) value = self._load_value(value) elif variable_type == 'String':", "variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for", "isinstance(v, bytes): raise RuntimeError('Invalid data provided for Binary.') # if not isinstance(v, bytes):", "+= r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array) variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array)", "r':([A-Za-z0-9_\\.\\-\\[\\]]+)' # variable name (:variable_name) variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array) variable_pattern", "# Enhanced entity array is the wild-wild west, don't validate it if variable_type", "to a string (\"{str(value).lower()}\").') value = str(value).lower() # coerce int to str type", "_variable_types(self): \"\"\"Return list of standard playbook variable typesd.\"\"\" return self._variable_single_types + self._variable_array_types def", "The variable to write to the DB. value (bytes|int|string): The data to write", "self._is_key_value(value)): raise RuntimeError('Invalid data provided for KeyValue.') elif variable_type == 'String': # coerce", "+= r'[A-Za-z0-9_-]+))' # variable type (custom) return variable_pattern @property def _variable_array_types(self): \"\"\"Return list", "str(value).lower() # coerce int to str type if isinstance(value, (float, int)): self.log.warning(f'Coercing float/int", "\"\"\" try: return json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: # pragma: no cover", "Class properties.\"\"\" self.tcex = tcex self._context = context self._output_variables = output_variables or []", "variable in (v.group(0) for v in re.finditer(self._variable_parse, str(value))): v = self.read(variable) self.log.trace(f'embedded variable:", "variable typesd.\"\"\" return self._variable_single_types + self._variable_array_types def _wrap_embedded_keyvalue(self, data): \"\"\"Wrap keyvalue embedded variable", "this method that gets the entire list/dict instead of just the string. value", "str)): raise RuntimeError('Invalid data provided for StringArray.') value_coerced.append(v) value = value_coerced elif variable_type", "and not isinstance(v, bytes): raise RuntimeError('Invalid data provided for Binary.') # if not", "a embedded #App:7979:variable_name!String\" }, { \"key\": \"string array\", \"value\": #App:7979:variable_name!StringArray }, { \"key\":", "to be searched for embedded variables. Embedded variable rules: * Only user input", "of standard playbook variable typesd.\"\"\" return self._variable_single_types + self._variable_array_types def _wrap_embedded_keyvalue(self, data): \"\"\"Wrap", "pragma: no cover # for data written an upstream java App data =", "in data: if not self._is_key_value(d): return False return True @staticmethod def _is_tc_entity(data): \"\"\"Return", "variable_pattern += r'[A-Za-z0-9_-]+))' # variable type (custom) return variable_pattern @property def _variable_array_types(self): \"\"\"Return", "of standard playbook single variable types.\"\"\" return [ 'Binary', 'KeyValue', 'String', 'TCEntity', 'TCEnhancedEntity',", "revisit this to handle variable references in kv/kvarrays that # are None. Would", "_read_embedded(self, value): \"\"\"Read method for \"embedded\" variables. .. Note:: The ``read()`` method will", "value is None: # pragma: no cover return value for variable in (v.group(0)", "with embedded variables. Returns: (str): Results retrieved from DB \"\"\" # TODO: need", "(float, int)): self.log.warning(f'Coercing float/int value ({value}) to a string (\"{str(value)}\").') value = str(value)", "keys/variables the raw string will be returned. Examples:: DB Values #App:7979:variable_name!String: \"embedded \\\\\"variable\\\\\"\"", "return data def read_raw(self, key): \"\"\"Read method of CRUD operation for raw data.", "+= r':([\\d]+)' # app id (:7979) variable_pattern += r':([A-Za-z0-9_\\.\\-\\[\\]]+)' # variable name (:variable_name)", "None and b64decode: v = base64.b64decode(v) if decode: v = self._decode_binary(v) values.append(v) value", "can't be loaded as JSON data. Returns: any: The de-serialized value from the", "the DB. value (bytes|int|string): The data to write to the DB. Returns: (str):", "key is None: self.log.warning('The key is None.') return None # get variable type", "import OrderedDict from collections.abc import Iterable class PlaybooksBase: \"\"\"TcEx Playbook Module Base Class", "for key was provided.') return None # get variable type from variable value", "context (str): The Redis context (hash). output_variables (list): The requested output variables. \"\"\"", "json.loads(value, object_pairs_hook=OrderedDict) values = [] for v in value: if v is not", "except RuntimeError as e: self.log.error(e) else: self.log.warning('The key or value field was None.')", "\"status_code\") self._output_variables_by_name[variable_name] = {'variable': ov} # store the variables in dict by name-type", "bytes): # value = value.encode('utf-8') if validate and not isinstance(value, bytes): raise RuntimeError('Invalid", "variables provided to Playbook Class. **Example Variable Format**:: ['#App:1234:status!String', '#App:1234:status_code!String'] \"\"\" self._output_variables_by_name =", "elif variable_type == 'StringArray': value_coerced = [] for v in value: # coerce", "validate and not isinstance(v, (type(None), str)): raise RuntimeError('Invalid data provided for StringArray.') value_coerced.append(v)", "..important:: Bytes input will be returned a as string as there is no", "value: if v is not None and b64decode: v = base64.b64decode(v) if decode:", "not isinstance(value, bytes): # value = value.encode('utf-8') if validate and not isinstance(value, bytes):", "if provided data has proper structure for TC Entity Array.\"\"\" for d in", "be able to say if value is just the variable reference, # sub", "self._coerce_string_value(v) if validate and not isinstance(v, (type(None), str)): raise RuntimeError('Invalid data provided for", "value: {value}') return value def _read_embedded(self, value): \"\"\"Read method for \"embedded\" variables. ..", "iterable) if variable_type == 'BinaryArray': value_encoded = [] for v in value: if", "as e: self.log.error(e) return None @staticmethod def _decode_binary(data): \"\"\"Return decoded bytes data handling", "value: {value}') try: value = json.dumps(value) except ValueError as e: # pragma: no", "elif variable_type == 'TCEntity': value = self._load_value(value) return value def _read_array(self, key, embedded=True,", "{value}') return value def _read_embedded(self, value): \"\"\"Read method for \"embedded\" variables. .. Note::", "(\"{str(value)}\").') value = str(value) return value def _create(self, key, value, validate=True): \"\"\"Create the", "for custom variable_pattern += r'[A-Za-z0-9_-]+))' # variable type (custom) return variable_pattern @property def", "serialized. Args: key (str): The variable to write to the DB. value (bytes|int|string):", "raw data. ..important:: Raw data can only be a byte, str or int.", "variables. Embedded variable rules: * Only user input can have embedded variables. *", "the loaded JSON value or raise an error. Args: value (str): The data", "\"embedded string\", \"value\": \"This input has a embedded #App:7979:variable_name!String\" }, { \"key\": \"string", "RuntimeError(f'Failed to serialize value ({e}).') try: return self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as", "matching for custom variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for custom variable_pattern +=", "#App:7979:variable_name!StringArray: [\"one\", \"two\", \"three\"] Examples 1: Input: \"This input has a embedded #App:7979:variable_name!String\"", "from the DB. Returns: (str): Results retrieved from DB \"\"\" if value is", "if core still sends improper JSON for KeyValueArrays if data is not None:", "#App:7979:variable_name!StringArray }, { \"key\": \"string\", \"value\": #App:7979:variable_name!String }] Args: value (str): The value", "context self._output_variables = output_variables or [] # properties self._output_variables_by_name = None self._output_variables_by_type =", "== 'StringArray': value_coerced = [] for v in value: # coerce string values", "unquoted, which breaks JSON. value = self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) try:", "pragma: no cover raise RuntimeError(f'Failed to serialize value ({e}).') try: return self.tcex.key_value_store.create(self._context, key.strip(),", "#App:7979:two!String: \"two\" #App:7979:variable_name!StringArray: [\"one\", \"two\", \"three\"] Examples 1: Input: \"This input has a", "for v in re.finditer(self._variable_parse, str(value))): v = self.read(variable) self.log.trace(f'embedded variable: {variable}, value: {v}')", "references in kv/kvarrays that # are None. Would like to be able to", "return None # get variable type from variable value variable_type = self.variable_type(key) if", "- context: {self._context}, key: {key}, value: {value}') try: value = json.dumps(value) except ValueError", "for KeyValueArray.') elif variable_type == 'StringArray': value_coerced = [] for v in value:", "in ['TCEntityArray', 'TCEnhancedEntity', 'TCEnhancedEntityArray']: value = self._load_value(value) # self.log.trace(f'pb create - context: {self._context},", "= [ *value ] # spread the value so that we know it's", "type variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for custom variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' #", "variable # is embedded multiple times in the same key value array. data", "# if not isinstance(v, bytes): # v = v.encode('utf-8') v = base64.b64encode(v).decode('utf-8') value_encoded.append(v)", "value_coerced.append(self._coerce_string_value(v)) value = value_coerced elif variable_type in ['TCEntityArray', 'TCEnhancedEntity', 'TCEnhancedEntityArray']: value = self._load_value(value)", "\"embedded\" variables. .. Note:: The ``read()`` method will automatically determine if the input", "for child method.\"\"\" raise NotImplementedError('Implemented in child class') def variable_type(self, variable): # pragma:", "app id (:7979) variable_pattern += r':([A-Za-z0-9_\\.\\-\\[\\]]+)' # variable name (:variable_name) variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray'", "for raw data. ..important:: Raw data can only be a byte, str or", "reformat to replace the correct instance only, handling the case where a variable", "key or value field was None.') return data def read_raw(self, key): \"\"\"Read method", "= {'variable': ov} def _read(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value in", "of DB write. \"\"\" data = None if key is not None and", "value): \"\"\"Read method for \"embedded\" variables. .. Note:: The ``read()`` method will automatically", "provided.') return None # get variable type from variable value variable_type = self.variable_type(key)", "handle variable references in kv/kvarrays that # are None. Would like to be", "ValueError as e: # pragma: no cover raise RuntimeError(f'Failed to serialize value ({e}).')", "data written by java apps.\"\"\" try: data = data.decode('utf-8') except UnicodeDecodeError: # pragma:", "not None and value is not None: try: data = self.tcex.key_value_store.create(self._context, key.strip(), value)", "self._read_embedded(value) # convert int to str value_coerced = [] for v in self._load_value(value):", "there is no way to determine data from redis originated as bytes or", "data = None if key is not None and value is not None:", "quoted value to ensure the resulting data is loadable JSON value = re.sub(f'\"{variable}\"',", "value: {v}') if isinstance(v, (dict, list)): v = json.dumps(v) # for KeyValueArray with", "'TCEnhancedEntity', ] @property def _variable_types(self): \"\"\"Return list of standard playbook variable typesd.\"\"\" return", "``read()`` method will automatically determine if the input is a variable or needs", "tcex self._context = context self._output_variables = output_variables or [] # properties self._output_variables_by_name =", "embedded one level deep. This method will automatically covert variables embedded in a", "is the wild-wild west, don't validate it if variable_type != 'TCEnhancedEntityArray': if validate", "we know it's a list (as opposed to an iterable) if variable_type ==", "\"\"\"Initialize the Class properties.\"\"\" self.tcex = tcex self._context = context self._output_variables = output_variables", "+= r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array) variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type variable_pattern", "value = self._load_value(value) if b64decode: value = base64.b64decode(value) if decode: value = self._decode_binary(value)", "None self.log = tcex.log # match full variable self._variable_match = re.compile(fr'^{self._variable_pattern}$') # capture", "write to the DB. value (bytes|int|string): The data to write to the DB.", "method.\"\"\" raise NotImplementedError('Implemented in child class') def variable_type(self, variable): # pragma: no cover", "String variable_pattern += r':([\\d]+)' # app id (:7979) variable_pattern += r':([A-Za-z0-9_\\.\\-\\[\\]]+)' # variable", "if v is not None: # only replace variable if a non-null value", "if key is not None and value is not None: try: data =", "{'variable': ov} def _read(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value in Redis", "will automatically determine if the input is a variable or needs to be", "True @staticmethod def _load_value(value): \"\"\"Return the loaded JSON value or raise an error.", "variables in dict by name-type (e.g. \"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}'] = {'variable': ov} def _read(self,", "ValueError as e: # pragma: no cover raise RuntimeError(f'Failed loading JSON data ({value}).", "key.strip(), value) except RuntimeError as e: self.log.error(e) return None def _create_array(self, key, value,", "from redis originated as bytes or string. Args: key (str): The variable to", "v is not None and b64decode: v = base64.b64decode(v) if decode: v =", "quotes (#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded = re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def _coerce_string_value(self, value): \"\"\"Return a string value from", "# pragma: no cover raise RuntimeError(f'Failed to JSON load data \"{value}\" ({e}).') def", "from variable value variable_type = self.variable_type(key) try: value = self.tcex.key_value_store.read(self._context, key.strip()) except RuntimeError", "as there is no way to determine data from redis originated as bytes", "get variable type from variable value variable_type = self.variable_type(key) try: value = self.tcex.key_value_store.read(self._context,", "= r'#([A-Za-z]+)' # match literal (#App,#Trigger) at beginning of String variable_pattern += r':([\\d]+)'", "json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: # pragma: no cover raise RuntimeError(f'Failed loading", "data (str): The data with embedded variables. Returns: (str): Results retrieved from DB", "b64decode: value = base64.b64decode(value) if decode: value = self._decode_binary(value) elif variable_type == 'KeyValue':", "has proper structure for Key Value.\"\"\" if data is None: return False return", "(str): The data with embedded variables. Returns: (str): Results retrieved from DB \"\"\"", "be returned a as string as there is no way to determine data", "# store the variables in dict by name (e.g. \"status_code\") self._output_variables_by_name[variable_name] = {'variable':", "= value_coerced elif variable_type == 'TCEntityArray': if validate and not self._is_tc_entity_array(value): raise RuntimeError('Invalid", "= json.dumps(v) # for KeyValueArray with nested dict/list type replace the # quoted", "ov in self._output_variables: # parse the variable to get individual parts parsed_variable =", "can be unquoted, which breaks JSON. value = self._wrap_embedded_keyvalue(value) if embedded: value =", "'BinaryArray', 'KeyValueArray', 'StringArray', 'TCEntityArray', 'TCEnhancedEntityArray', ] @property def _variable_single_types(self): \"\"\"Return list of standard", "the same key value array. data = data.replace(var, f'\": \"{variable_string}\"') return data def", "= self._read_embedded(value) try: value = json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: # pragma:", "data has proper structure for Key Value.\"\"\" if data is None: return False", "= data.replace(var, f'\": \"{variable_string}\"') return data def create_raw(self, key, value): \"\"\"Create method of", "None: self.log.warning('The key or value field is None.') return None # get variable", "Examples 1: Input: \"This input has a embedded #App:7979:variable_name!String\" Examples 2: Input: [\"one\",", "method for \"embedded\" variables. .. Note:: The ``read()`` method will automatically determine if", "variable parts (exactly a variable) self._variable_parse = re.compile(self._variable_pattern) # match embedded variables without", "That would require a kv-specific # version of this method that gets the", "instance only, handling the case where a variable # is embedded multiple times", "data with embedded variables. Returns: (str): Results retrieved from DB \"\"\" # TODO:", "values value_coerced.append(self._coerce_string_value(v)) value = value_coerced elif variable_type in ['TCEntityArray', 'TCEnhancedEntity', 'TCEnhancedEntityArray']: value =", "error. Args: value (str): The data from key/value store. Raises: RuntimeError: Raise error", "JSON data. Returns: any: The de-serialized value from the key/value store. \"\"\" try:", "var in set(variables): # recursion over set to handle duplicates # pull (#App:1441:embedded_string!String)", "type (custom) return variable_pattern @property def _variable_array_types(self): \"\"\"Return list of standard playbook array", "structures (dict, list, etc) must be serialized. Args: key (str): The variable to", "Returns: (str): Result of DB write. \"\"\" data = None if key is", "{key}, value: {value}') try: value = json.dumps(value) except ValueError as e: # pragma:", "sub None value, else insert '' in string. That would require a kv-specific", "value = value.encode('utf-8') if validate and not isinstance(value, bytes): raise RuntimeError('Invalid data provided", "or not self._is_tc_entity(value)): raise RuntimeError('Invalid data provided for TcEntity.') # self.log.trace(f'pb create -", "data): \"\"\"Return True if provided data has proper structure for Key Value Array.\"\"\"", "from DB. \"\"\" value = None if key is not None: value =", "{variable_type}.') value = [ *value ] # spread the value so that we", "elif variable_type == 'StringArray': if embedded: value = self._read_embedded(value) # convert int to", "The value to parsed and updated from the DB. Returns: (str): Results retrieved", "None # get variable type from variable value variable_type = self.variable_type(key) if variable_type", "validate and (not isinstance(value, dict) or not self._is_tc_entity(value)): raise RuntimeError('Invalid data provided for", "or string. Args: key (str): The variable to read from the DB. Returns:", "value = str(value).lower() # coerce int to str type if isinstance(value, (float, int)):", "value ({value}) to a string (\"{str(value)}\").') value = str(value) return value def _create(self,", "variable_string = re.search(self._variable_parse, var).group(0) # reformat to replace the correct instance only, handling", "raise RuntimeError('Invalid data provided for TcEntityArray.') # self.log.trace(f'pb create - context: {self._context}, key:", "for Binary.') # if not isinstance(v, bytes): # v = v.encode('utf-8') v =", "get variable type from variable value variable_type = self.variable_type(key) # Enhanced entity array", "= v.encode('utf-8') v = base64.b64encode(v).decode('utf-8') value_encoded.append(v) value = value_encoded elif variable_type == 'KeyValueArray':", "= context self._output_variables = output_variables or [] # properties self._output_variables_by_name = None self._output_variables_by_type", "no cover raise RuntimeError(f'Failed to JSON load data \"{value}\" ({e}).') def _parse_output_variables(self): \"\"\"Parse", "is None: return value if variable_type == 'BinaryArray': value = json.loads(value, object_pairs_hook=OrderedDict) values", "isinstance(value, (float, int)): self.log.warning(f'Coercing float/int value ({value}) to a string (\"{str(value)}\").') value =", "\"\"\" # TODO: need to verify if core still sends improper JSON for", "coerce bool before int as python says a bool is an int if", "[ *value ] # spread the value so that we know it's a", "None value, else insert '' in string. That would require a kv-specific #", "for ov in self._output_variables: # parse the variable to get individual parts parsed_variable", "is not None and value is not None: try: data = self.tcex.key_value_store.create(self._context, key.strip(),", "__init__(self, tcex, context, output_variables): \"\"\"Initialize the Class properties.\"\"\" self.tcex = tcex self._context =", "as e: # pragma: no cover raise RuntimeError(f'Failed to serialize value ({e}).') try:", "= self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e) else: self.log.warning('The key or", "# coerce bool to str type self.log.warning(f'Coercing bool value ({value}) to a string", "variable to write to the DB. value (bytes|int|string): The data to write to", "that # are None. Would like to be able to say if value", "key: {key}, value: {value}') try: value = json.dumps(value) except ValueError as e: #", "= re.sub(variable, v, value) return value @property def _variable_pattern(self): \"\"\"Regex pattern to match", "[] for v in self._load_value(value): # coerce string values value_coerced.append(self._coerce_string_value(v)) value = value_coerced", "\"\"\"Wrap keyvalue embedded variable in double quotes. Args: data (str): The data with", "(not isinstance(value, dict) or not self._is_key_value(value)): raise RuntimeError('Invalid data provided for KeyValue.') elif", "self._output_variables_by_name[variable_name] = {'variable': ov} # store the variables in dict by name-type (e.g.", "a byte, str or int. Other data structures (dict, list, etc) must be", "was None.') return data def read_raw(self, key): \"\"\"Read method of CRUD operation for", "self.log.warning('The key is None.') return None # get variable type from variable value", "v = json.dumps(v) # for KeyValueArray with nested dict/list type replace the #", "self.log.error(e) else: self.log.warning('The key or value field was None.') return data def read_raw(self,", "from an bool or int.\"\"\" # coerce bool before int as python says", "no cover raise RuntimeError(f'Failed loading JSON data ({value}). Error: ({e})') elif variable_type ==", "input is a variable or needs to be searched for embedded variables. Embedded", "'TCEntityArray', 'TCEnhancedEntityArray', ] @property def _variable_single_types(self): \"\"\"Return list of standard playbook single variable", "data provided for {variable_type}.') value = [ *value ] # spread the value", "data from redis originated as bytes or string. Args: key (str): The variable", "self._load_value(value) if b64decode: value = base64.b64decode(value) if decode: value = self._decode_binary(value) elif variable_type", "value_encoded elif variable_type == 'KeyValueArray': if validate and not self._is_key_value_array(value): raise RuntimeError('Invalid data", "json.dumps(v) # for KeyValueArray with nested dict/list type replace the # quoted value", "The Redis context (hash). output_variables (list): The requested output variables. \"\"\" def __init__(self,", "data handling data written by java apps.\"\"\" try: data = data.decode('utf-8') except UnicodeDecodeError:", "Args: key (str): The variable to write to the DB. value (bytes|int|string): The", "a as string as there is no way to determine data from redis", "value is None: return value if variable_type == 'Binary': value = self._load_value(value) if", "the case where a variable # is embedded multiple times in the same", "key field was None.') return value def parse_variable(self, variable): # pragma: no cover", "value_coerced.append(v) value = value_coerced elif variable_type == 'TCEntityArray': if validate and not self._is_tc_entity_array(value):", "str(value))): v = self.read(variable) self.log.trace(f'embedded variable: {variable}, value: {v}') if isinstance(v, (dict, list)):", "'#App:1234:status_code!String'] \"\"\" self._output_variables_by_name = {} self._output_variables_by_type = {} for ov in self._output_variables: #", "must be serialized. Args: key (str): The variable to write to the DB.", "\"three\"] Examples 3: Input: [{ \"key\": \"embedded string\", \"value\": \"This input has a", "need to revisit this to handle variable references in kv/kvarrays that # are", "self.variable_type(key) try: value = self.tcex.key_value_store.read(self._context, key.strip()) except RuntimeError as e: self.log.error(e) return None", "{key}, value: {value}') return value def _read_embedded(self, value): \"\"\"Read method for \"embedded\" variables.", "value_coerced elif variable_type == 'TCEntityArray': if validate and not self._is_tc_entity_array(value): raise RuntimeError('Invalid data", "= value_coerced elif variable_type in ['TCEntityArray', 'TCEnhancedEntity', 'TCEnhancedEntityArray']: value = self._load_value(value) # self.log.trace(f'pb", "retrieved from DB. If there are no keys/variables the raw string will be", "== 'BinaryArray': value = json.loads(value, object_pairs_hook=OrderedDict) values = [] for v in value:", "in Redis if applicable.\"\"\" if key is None or value is None: self.log.warning('The", "\\\\\"variable\\\\\"\" #App:7979:two!String: \"two\" #App:7979:variable_name!StringArray: [\"one\", \"two\", \"three\"] Examples 1: Input: \"This input has", "== 'KeyValue': # embedded variable can be unquoted, which breaks JSON. value =", "except UnicodeDecodeError: # pragma: no cover # for data written an upstream java", "variables. * Variables can only be embedded one level deep. This method will", "True if provided data has proper structure for Key Value Array.\"\"\" for d", "= self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) value = self._load_value(value) elif variable_type ==", "child class') def variable_type(self, variable): # pragma: no cover \"\"\"Set placeholder for child", "= output_variables or [] # properties self._output_variables_by_name = None self._output_variables_by_type = None self.log", "not isinstance(v, (type(None), str)): raise RuntimeError('Invalid data provided for StringArray.') value_coerced.append(v) value =", "variable_type in ['TCEntityArray', 'TCEnhancedEntity', 'TCEnhancedEntityArray']: value = self._load_value(value) # self.log.trace(f'pb create - context:", "data ({value}). Error: ({e})') elif variable_type == 'StringArray': if embedded: value = self._read_embedded(value)", "able to say if value is just the variable reference, # sub None", "for v in re.finditer(self._vars_keyvalue_embedded, data): variables.append(v.group(0)) for var in set(variables): # recursion over", "sends improper JSON for KeyValueArrays if data is not None: # pragma: no", "self.log.warning('The key or value field is None.') return None # get variable type", "the DB. Returns: (str): Result of DB write. \"\"\" data = None if", "for String.') elif variable_type == 'TCEntity': if validate and (not isinstance(value, dict) or", "wild-wild west, don't validate it if variable_type != 'TCEnhancedEntityArray': if validate and (not", "self._is_key_value_array(value): raise RuntimeError('Invalid data provided for KeyValueArray.') elif variable_type == 'StringArray': value_coerced =", "RuntimeError('Invalid data provided for TcEntityArray.') # self.log.trace(f'pb create - context: {self._context}, key: {key},", "for KeyValueArray with nested dict/list type replace the # quoted value to ensure", "if data is not None: # pragma: no cover variables = [] for", "decode=False): \"\"\"Create the value in Redis if applicable.\"\"\" if key is None: #", "types.\"\"\" return [ 'Binary', 'KeyValue', 'String', 'TCEntity', 'TCEnhancedEntity', ] @property def _variable_types(self): \"\"\"Return", "match and parse a playbook variable.\"\"\" variable_pattern = r'#([A-Za-z]+)' # match literal (#App,#Trigger)", "string values value = self._coerce_string_value(self._load_value(value)) elif variable_type == 'TCEntity': value = self._load_value(value) return", "json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: # pragma: no cover raise RuntimeError(f'Failed to", "Iterable class PlaybooksBase: \"\"\"TcEx Playbook Module Base Class Args: tcex (TcEx): Instance of", "if applicable.\"\"\" if key is None: # pragma: no cover self.log.warning('The null value", "input will be returned a as string as there is no way to", "Value.\"\"\" if data is None: return False return all(x in data for x", "Key Value Array.\"\"\" for d in data: if not self._is_key_value(d): return False return", "#App:1441:embedded_string!String) variable_string = re.search(self._variable_parse, var).group(0) # reformat to replace the correct instance only,", "variable_type == 'Binary': # if not isinstance(value, bytes): # value = value.encode('utf-8') if", "#App:7979:variable_name!String }] Args: value (str): The value to parsed and updated from the", "True if provided data has proper structure for TC Entity Array.\"\"\" for d", "{ \"key\": \"string\", \"value\": #App:7979:variable_name!String }] Args: value (str): The value to parsed", "data to write to the DB. Returns: (str): Result of DB write. \"\"\"", "key, array=False, embedded=True): # pragma: no cover \"\"\"Set placeholder for child method.\"\"\" raise", "for KeyValue.') elif variable_type == 'String': # coerce string values value = self._coerce_string_value(value)", "\"\"\"Parse the output variables provided to Playbook Class. **Example Variable Format**:: ['#App:1234:status!String', '#App:1234:status_code!String']", "- context: {self._context}, key: {key}, value: {value}') return value def _read_embedded(self, value): \"\"\"Read", "def __init__(self, tcex, context, output_variables): \"\"\"Initialize the Class properties.\"\"\" self.tcex = tcex self._context", "\"\"\"Set placeholder for child method.\"\"\" raise NotImplementedError('Implemented in child class') def variable_type(self, variable):", "non-null value is returned from kv store # APP-1030 need to revisit this", "if key is not None: value = self.tcex.key_value_store.read(self._context, key.strip()) else: self.log.warning('The key field", "# app id (:7979) variable_pattern += r':([A-Za-z0-9_\\.\\-\\[\\]]+)' # variable name (:variable_name) variable_pattern +=", "value = self._read_embedded(value) # convert int to str value_coerced = [] for v", "_create_array(self, key, value, validate=True): \"\"\"Create the value in Redis if applicable.\"\"\" if key", "is a variable or needs to be searched for embedded variables. Embedded variable", "bool or int.\"\"\" # coerce bool before int as python says a bool", "if isinstance(v, (dict, list)): v = json.dumps(v) # for KeyValueArray with nested dict/list", "to determine data from redis originated as bytes or string. Args: key (str):", "Variable Format**:: ['#App:1234:status!String', '#App:1234:status_code!String'] \"\"\" self._output_variables_by_name = {} self._output_variables_by_type = {} for ov", "return data @staticmethod def _is_key_value(data): \"\"\"Return True if provided data has proper structure", "validate and (not isinstance(value, dict) or not self._is_key_value(value)): raise RuntimeError('Invalid data provided for", "None.') return value def parse_variable(self, variable): # pragma: no cover \"\"\"Set placeholder for", "#App:7979:variable_name!String\" }, { \"key\": \"string array\", \"value\": #App:7979:variable_name!StringArray }, { \"key\": \"string\", \"value\":", "without quotes (#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded = re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def _coerce_string_value(self, value): \"\"\"Return a string value", "no cover variables = [] for v in re.finditer(self._vars_keyvalue_embedded, data): variables.append(v.group(0)) for var", "TC Entity Array.\"\"\" for d in data: if not self._is_tc_entity(d): return False return", "value @property def _variable_pattern(self): \"\"\"Regex pattern to match and parse a playbook variable.\"\"\"", "data for x in ['id', 'value', 'type']) def _is_tc_entity_array(self, data): \"\"\"Return True if", "self._is_tc_entity(value)): raise RuntimeError('Invalid data provided for TcEntity.') # self.log.trace(f'pb create - context: {self._context},", "set to handle duplicates # pull (#App:1441:embedded_string!String) from (\": #App:1441:embedded_string!String) variable_string = re.search(self._variable_parse,", "if decode: v = self._decode_binary(v) values.append(v) value = values elif variable_type == 'KeyValueArray':", "self.log.warning(f'Coercing bool value ({value}) to a string (\"{str(value).lower()}\").') value = str(value).lower() # coerce", "JSON. value = self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) try: value = json.loads(value,", "\"\"\"TcEx Framework Playbook module\"\"\" # standard library import base64 import json import re", "create - context: {self._context}, key: {key}, value: {value}') try: value = json.dumps(value) except", "if key is None: self.log.warning('The key is None.') return None # get variable", "re.compile(fr'^{self._variable_pattern}$') # capture variable parts (exactly a variable) self._variable_parse = re.compile(self._variable_pattern) # match", "value = str(value) return value def _create(self, key, value, validate=True): \"\"\"Create the value", "= [] for v in re.finditer(self._vars_keyvalue_embedded, data): variables.append(v.group(0)) for var in set(variables): #", "not self._is_tc_entity(value)): raise RuntimeError('Invalid data provided for TcEntity.') # self.log.trace(f'pb create - context:", "# value = value.encode('utf-8') if validate and not isinstance(value, bytes): raise RuntimeError('Invalid data", "to revisit this to handle variable references in kv/kvarrays that # are None.", "in value: if v is not None: if validate and not isinstance(v, bytes):", "as e: self.log.error(e) else: self.log.warning('The key or value field was None.') return data", "playbook variable typesd.\"\"\" return self._variable_single_types + self._variable_array_types def _wrap_embedded_keyvalue(self, data): \"\"\"Wrap keyvalue embedded", "str type self.log.warning(f'Coercing bool value ({value}) to a string (\"{str(value).lower()}\").') value = str(value).lower()", "None: # only replace variable if a non-null value is returned from kv", "instead of just the string. value = re.sub(variable, v, value) return value @property", "no way to determine data from redis originated as bytes or string. Args:", "def _coerce_string_value(self, value): \"\"\"Return a string value from an bool or int.\"\"\" #", "variable.\"\"\" variable_pattern = r'#([A-Za-z]+)' # match literal (#App,#Trigger) at beginning of String variable_pattern", "JSON value or raise an error. Args: value (str): The data from key/value", "# coerce string values v = self._coerce_string_value(v) if validate and not isinstance(v, (type(None),", "= self._load_value(value) return value def _read_array(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value", "variable_type == 'TCEntity': value = self._load_value(value) return value def _read_array(self, key, embedded=True, b64decode=True,", "to an iterable) if variable_type == 'BinaryArray': value_encoded = [] for v in", "return all(x in data for x in ['key', 'value']) def _is_key_value_array(self, data): \"\"\"Return", "an error. Args: value (str): The data from key/value store. Raises: RuntimeError: Raise", "data can only be a byte, str or int. Other data structures (dict,", "array\", \"value\": #App:7979:variable_name!StringArray }, { \"key\": \"string\", \"value\": #App:7979:variable_name!String }] Args: value (str):", "a string (\"{str(value)}\").') value = str(value) return value def _create(self, key, value, validate=True):", "data provided for TcEntity.') # self.log.trace(f'pb create - context: {self._context}, key: {key}, value:", "# match full variable self._variable_match = re.compile(fr'^{self._variable_pattern}$') # capture variable parts (exactly a", "in value: if v is not None and b64decode: v = base64.b64decode(v) if", "embedded variables. Embedded variable rules: * Only user input can have embedded variables.", "\"\"\" self._output_variables_by_name = {} self._output_variables_by_type = {} for ov in self._output_variables: # parse", "a playbook variable.\"\"\" variable_pattern = r'#([A-Za-z]+)' # match literal (#App,#Trigger) at beginning of", "# standard library import base64 import json import re from collections import OrderedDict", "== 'String': # coerce string values value = self._coerce_string_value(value) if validate and not", "a variable or needs to be searched for embedded variables. Embedded variable rules:", "value) except RuntimeError as e: self.log.error(e) return None @staticmethod def _decode_binary(data): \"\"\"Return decoded", "says a bool is an int if isinstance(value, bool): # coerce bool to", "\"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}'] = {'variable': ov} def _read(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the", "an int if isinstance(value, bool): # coerce bool to str type self.log.warning(f'Coercing bool", "value = self._load_value(value) return value def _read_array(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the", "the DB. Returns: (str): Results retrieved from DB. \"\"\" value = None if", "if validate and not self._is_tc_entity_array(value): raise RuntimeError('Invalid data provided for TcEntityArray.') # self.log.trace(f'pb", "if provided data has proper structure for TC Entity.\"\"\" if data is None:", "if validate and (not isinstance(value, Iterable) or isinstance(value, (str, dict))): raise RuntimeError(f'Invalid data", "self.tcex = tcex self._context = context self._output_variables = output_variables or [] # properties", "value is None: self.log.warning('The key or value field is None.') return None #", "pragma: no cover raise RuntimeError(f'Failed loading JSON data ({value}). Error: ({e})') elif variable_type", "data \"{value}\" ({e}).') def _parse_output_variables(self): \"\"\"Parse the output variables provided to Playbook Class.", "the variables in dict by name (e.g. \"status_code\") self._output_variables_by_name[variable_name] = {'variable': ov} #", "only replace variable if a non-null value is returned from kv store #", "return all(x in data for x in ['id', 'value', 'type']) def _is_tc_entity_array(self, data):", "input has a embedded #App:7979:variable_name!String\" }, { \"key\": \"string array\", \"value\": #App:7979:variable_name!StringArray },", "list (as opposed to an iterable) if variable_type == 'BinaryArray': value_encoded = []", "\"two\" #App:7979:variable_name!StringArray: [\"one\", \"two\", \"three\"] Examples 1: Input: \"This input has a embedded", "'TCEntity', 'TCEnhancedEntity', ] @property def _variable_types(self): \"\"\"Return list of standard playbook variable typesd.\"\"\"", "@staticmethod def _is_tc_entity(data): \"\"\"Return True if provided data has proper structure for TC", "e: self.log.error(e) return None def _create_array(self, key, value, validate=True): \"\"\"Create the value in", "= base64.b64decode(value) if decode: value = self._decode_binary(value) elif variable_type == 'KeyValue': # embedded", "v = self._coerce_string_value(v) if validate and not isinstance(v, (type(None), str)): raise RuntimeError('Invalid data", "self._read_embedded(value) # coerce string values value = self._coerce_string_value(self._load_value(value)) elif variable_type == 'TCEntity': value", "etc) must be serialized. Args: key (str): The variable to write to the", "ValueError as e: # pragma: no cover raise RuntimeError(f'Failed to JSON load data", "output variables. \"\"\" def __init__(self, tcex, context, output_variables): \"\"\"Initialize the Class properties.\"\"\" self.tcex", "value def _read_embedded(self, value): \"\"\"Read method for \"embedded\" variables. .. Note:: The ``read()``", "String.') elif variable_type == 'TCEntity': if validate and (not isinstance(value, dict) or not", "Binary.') # if not isinstance(v, bytes): # v = v.encode('utf-8') v = base64.b64encode(v).decode('utf-8')", "method that gets the entire list/dict instead of just the string. value =", "validate and not isinstance(value, str): raise RuntimeError('Invalid data provided for String.') elif variable_type", "is not None: # pragma: no cover variables = [] for v in", "unquoted, which breaks JSON. value = self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) value", "[] for v in value: if v is not None and b64decode: v", "key.strip(), value) except RuntimeError as e: self.log.error(e) else: self.log.warning('The key or value field", "value = re.sub(variable, v, value) return value @property def _variable_pattern(self): \"\"\"Regex pattern to", "or value field was None.') return data def read_raw(self, key): \"\"\"Read method of", "match literal (#App,#Trigger) at beginning of String variable_pattern += r':([\\d]+)' # app id", "({e}).') def _parse_output_variables(self): \"\"\"Parse the output variables provided to Playbook Class. **Example Variable", "@staticmethod def _is_key_value(data): \"\"\"Return True if provided data has proper structure for Key", "value_coerced elif variable_type in ['TCEntityArray', 'TCEnhancedEntity', 'TCEnhancedEntityArray']: value = self._load_value(value) # self.log.trace(f'pb create", "value field is None.') return None # get variable type from variable value", "variable value variable_type = self.variable_type(key) try: value = self.tcex.key_value_store.read(self._context, key.strip()) except RuntimeError as", "variable type from variable value variable_type = self.variable_type(key) if variable_type == 'Binary': #", "a non-null value is returned from kv store # APP-1030 need to revisit", "embedded: value = self._read_embedded(value) # convert int to str value_coerced = [] for", "require a kv-specific # version of this method that gets the entire list/dict", "\"\"\"Create the value in Redis if applicable.\"\"\" if key is None: self.log.warning('The key", "value_coerced = [] for v in self._load_value(value): # coerce string values value_coerced.append(self._coerce_string_value(v)) value", "JSON for KeyValueArrays if data is not None: # pragma: no cover variables", "there are no keys/variables the raw string will be returned. Examples:: DB Values", "as e: self.log.error(e) return None def _create_array(self, key, value, validate=True): \"\"\"Create the value", "elif variable_type == 'KeyValue': if validate and (not isinstance(value, dict) or not self._is_key_value(value)):", "child method.\"\"\" raise NotImplementedError('Implemented in child class') def variable_type(self, variable): # pragma: no", "with value retrieved from DB. If there are no keys/variables the raw string", "x in ['id', 'value', 'type']) def _is_tc_entity_array(self, data): \"\"\"Return True if provided data", "in data for x in ['key', 'value']) def _is_key_value_array(self, data): \"\"\"Return True if", "pragma: no cover \"\"\"Set placeholder for child method.\"\"\" raise NotImplementedError('Implemented in child class')", "of just the string. value = re.sub(variable, v, value) return value @property def", "was provided.') return None # get variable type from variable value variable_type =", "string (\"{str(value)}\").') value = str(value) return value def _create(self, key, value, validate=True): \"\"\"Create", "is None: return value if variable_type == 'Binary': value = self._load_value(value) if b64decode:", "\"three\"] Examples 1: Input: \"This input has a embedded #App:7979:variable_name!String\" Examples 2: Input:", "value variable_type = self.variable_type(key) try: value = self.tcex.key_value_store.read(self._context, key.strip()) except RuntimeError as e:", "loaded JSON value or raise an error. Args: value (str): The data from", "DB. Returns: (str): Results retrieved from DB \"\"\" if value is None: #", "error when data can't be loaded as JSON data. Returns: any: The de-serialized", "key is not None: value = self.tcex.key_value_store.read(self._context, key.strip()) else: self.log.warning('The key field was", "\"\"\"Return decoded bytes data handling data written by java apps.\"\"\" try: data =", "cover # for data written an upstream java App data = data.decode('latin-1') return", "embedded=True, b64decode=True, decode=False): \"\"\"Create the value in Redis if applicable.\"\"\" if key is", "dict) or not self._is_key_value(value)): raise RuntimeError('Invalid data provided for KeyValue.') elif variable_type ==", "# variable name (:variable_name) variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array) variable_pattern +=", "of TcEx class. context (str): The Redis context (hash). output_variables (list): The requested", "if validate and not isinstance(v, bytes): raise RuntimeError('Invalid data provided for Binary.') #", "def _wrap_embedded_keyvalue(self, data): \"\"\"Wrap keyvalue embedded variable in double quotes. Args: data (str):", "variable type variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for custom variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)'", "except ValueError as e: # pragma: no cover raise RuntimeError(f'Failed to JSON load", "output_variables or [] # properties self._output_variables_by_name = None self._output_variables_by_type = None self.log =", "= value.encode('utf-8') if validate and not isinstance(value, bytes): raise RuntimeError('Invalid data provided for", "retrieved from DB \"\"\" if value is None: # pragma: no cover return", "and not self._is_key_value_array(value): raise RuntimeError('Invalid data provided for KeyValueArray.') elif variable_type == 'StringArray':", "= self.variable_type(key) try: value = self.tcex.key_value_store.read(self._context, key.strip()) except RuntimeError as e: self.log.error(e) return", "searched for embedded variables. Embedded variable rules: * Only user input can have", "1: Input: \"This input has a embedded #App:7979:variable_name!String\" Examples 2: Input: [\"one\", #App:7979:two!String,", "create - context: {self._context}, key: {key}, value: {value}') return value def _read_embedded(self, value):", "load data \"{value}\" ({e}).') def _parse_output_variables(self): \"\"\"Parse the output variables provided to Playbook", "not None: # pragma: no cover variables = [] for v in re.finditer(self._vars_keyvalue_embedded,", "data. Returns: any: The de-serialized value from the key/value store. \"\"\" try: return", "value: # coerce string values v = self._coerce_string_value(v) if validate and not isinstance(v,", "(#App:1441:embedded_string!String) from (\": #App:1441:embedded_string!String) variable_string = re.search(self._variable_parse, var).group(0) # reformat to replace the", "None: self.log.warning('The key is None.') return None # get variable type from variable", "for data written an upstream java App data = data.decode('latin-1') return data @staticmethod", "DB. Returns: (str): Result of DB write. \"\"\" data = None if key", "no cover self.log.warning('The null value for key was provided.') return None # get", "originated as bytes or string. Args: key (str): The variable to read from", "de-serialized value from the key/value store. \"\"\" try: return json.loads(value, object_pairs_hook=OrderedDict) except ValueError", "variables. \"\"\" def __init__(self, tcex, context, output_variables): \"\"\"Initialize the Class properties.\"\"\" self.tcex =", "if variable_type == 'BinaryArray': value = json.loads(value, object_pairs_hook=OrderedDict) values = [] for v", "or needs to be searched for embedded variables. Embedded variable rules: * Only", "(list): The requested output variables. \"\"\" def __init__(self, tcex, context, output_variables): \"\"\"Initialize the", "= values elif variable_type == 'KeyValueArray': # embedded variable can be unquoted, which", "value so that we know it's a list (as opposed to an iterable)", "variable type from variable value variable_type = self.variable_type(key) try: value = self.tcex.key_value_store.read(self._context, key.strip())", "The requested output variables. \"\"\" def __init__(self, tcex, context, output_variables): \"\"\"Initialize the Class", "(e.g. \"status_code\") self._output_variables_by_name[variable_name] = {'variable': ov} # store the variables in dict by", "has a embedded #App:7979:variable_name!String\" Examples 2: Input: [\"one\", #App:7979:two!String, \"three\"] Examples 3: Input:", "for x in ['id', 'value', 'type']) def _is_tc_entity_array(self, data): \"\"\"Return True if provided", "individual parts parsed_variable = self.parse_variable(ov) variable_name = parsed_variable.get('name') variable_type = parsed_variable.get('type') # store", "bool before int as python says a bool is an int if isinstance(value,", "self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) try: value = json.loads(value, object_pairs_hook=OrderedDict) except ValueError", "JSON. value = self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) value = self._load_value(value) elif", "variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array) variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' # variable type", "is None: # pragma: no cover return value for variable in (v.group(0) for", "and not self._is_tc_entity_array(value): raise RuntimeError('Invalid data provided for TcEntityArray.') # self.log.trace(f'pb create -", "isinstance(value, Iterable) or isinstance(value, (str, dict))): raise RuntimeError(f'Invalid data provided for {variable_type}.') value", "in a string with value retrieved from DB. If there are no keys/variables", "variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for custom variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' # non", "data = data.decode('utf-8') except UnicodeDecodeError: # pragma: no cover # for data written", "to serialize value ({e}).') try: return self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e:", "self._output_variables_by_name = None self._output_variables_by_type = None self.log = tcex.log # match full variable", "variable can be unquoted, which breaks JSON. value = self._wrap_embedded_keyvalue(value) if embedded: value", "like to be able to say if value is just the variable reference,", "bool to str type self.log.warning(f'Coercing bool value ({value}) to a string (\"{str(value).lower()}\").') value", "a string (\"{str(value).lower()}\").') value = str(value).lower() # coerce int to str type if", "str or int. Other data structures (dict, list, etc) must be serialized. Args:", "Playbook module\"\"\" # standard library import base64 import json import re from collections", "output_variables (list): The requested output variables. \"\"\" def __init__(self, tcex, context, output_variables): \"\"\"Initialize", "self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e) return None @staticmethod def _decode_binary(data):", "context, output_variables): \"\"\"Initialize the Class properties.\"\"\" self.tcex = tcex self._context = context self._output_variables", "data): \"\"\"Return True if provided data has proper structure for TC Entity Array.\"\"\"", "embedded #App:7979:variable_name!String\" Examples 2: Input: [\"one\", #App:7979:two!String, \"three\"] Examples 3: Input: [{ \"key\":", "variable_type == 'BinaryArray': value = json.loads(value, object_pairs_hook=OrderedDict) values = [] for v in", "int to str type if isinstance(value, (float, int)): self.log.warning(f'Coercing float/int value ({value}) to", "parse a playbook variable.\"\"\" variable_pattern = r'#([A-Za-z]+)' # match literal (#App,#Trigger) at beginning", "parsed_variable.get('type') # store the variables in dict by name (e.g. \"status_code\") self._output_variables_by_name[variable_name] =", "string as there is no way to determine data from redis originated as", "key, value): \"\"\"Create method of CRUD operation for raw data. ..important:: Raw data", "handling the case where a variable # is embedded multiple times in the", "= re.sub(f'\"{variable}\"', v, value) if v is not None: # only replace variable", "TcEx class. context (str): The Redis context (hash). output_variables (list): The requested output", "\"\"\"TcEx Playbook Module Base Class Args: tcex (TcEx): Instance of TcEx class. context", "# pull (#App:1441:embedded_string!String) from (\": #App:1441:embedded_string!String) variable_string = re.search(self._variable_parse, var).group(0) # reformat to", "match embedded variables without quotes (#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded = re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def _coerce_string_value(self, value): \"\"\"Return", "Bytes input will be returned a as string as there is no way", "it's a list (as opposed to an iterable) if variable_type == 'BinaryArray': value_encoded", "\"{variable_string}\"') return data def create_raw(self, key, value): \"\"\"Create method of CRUD operation for", "for TcEntity.') # self.log.trace(f'pb create - context: {self._context}, key: {key}, value: {value}') try:", "an bool or int.\"\"\" # coerce bool before int as python says a", "name-type (e.g. \"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}'] = {'variable': ov} def _read(self, key, embedded=True, b64decode=True, decode=False):", "from kv store # APP-1030 need to revisit this to handle variable references", "None: # pragma: no cover self.log.warning('The null value for key was provided.') return", "requested output variables. \"\"\" def __init__(self, tcex, context, output_variables): \"\"\"Initialize the Class properties.\"\"\"", "Format**:: ['#App:1234:status!String', '#App:1234:status_code!String'] \"\"\" self._output_variables_by_name = {} self._output_variables_by_type = {} for ov in", "for raw data. ..important:: Bytes input will be returned a as string as", "entire list/dict instead of just the string. value = re.sub(variable, v, value) return", "to handle duplicates # pull (#App:1441:embedded_string!String) from (\": #App:1441:embedded_string!String) variable_string = re.search(self._variable_parse, var).group(0)", "\"\"\"Create the value in Redis if applicable.\"\"\" if key is None or value", "v in self._load_value(value): # coerce string values value_coerced.append(self._coerce_string_value(v)) value = value_coerced elif variable_type", "value = self._read_embedded(value) try: value = json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: #", "# pragma: no cover variables = [] for v in re.finditer(self._vars_keyvalue_embedded, data): variables.append(v.group(0))", "self.log.trace(f'pb create - context: {self._context}, key: {key}, value: {value}') try: value = json.dumps(value)", "TcEntityArray.') # self.log.trace(f'pb create - context: {self._context}, key: {key}, value: {value}') try: value", "serialize value ({e}).') try: return self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e)", "not None and b64decode: v = base64.b64decode(v) if decode: v = self._decode_binary(v) values.append(v)", "set(variables): # recursion over set to handle duplicates # pull (#App:1441:embedded_string!String) from (\":", "variable_pattern = r'#([A-Za-z]+)' # match literal (#App,#Trigger) at beginning of String variable_pattern +=", "the variables in dict by name-type (e.g. \"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}'] = {'variable': ov} def", "f'\": \"{variable_string}\"') return data def create_raw(self, key, value): \"\"\"Create method of CRUD operation", "(\"{str(value).lower()}\").') value = str(value).lower() # coerce int to str type if isinstance(value, (float,", "of String variable_pattern += r':([\\d]+)' # app id (:7979) variable_pattern += r':([A-Za-z0-9_\\.\\-\\[\\]]+)' #", "as python says a bool is an int if isinstance(value, bool): # coerce", "_is_tc_entity(data): \"\"\"Return True if provided data has proper structure for TC Entity.\"\"\" if", "'KeyValue', 'String', 'TCEntity', 'TCEnhancedEntity', ] @property def _variable_types(self): \"\"\"Return list of standard playbook", "isinstance(value, str): raise RuntimeError('Invalid data provided for String.') elif variable_type == 'TCEntity': if", "variable reference, # sub None value, else insert '' in string. That would", "KeyValueArray.') elif variable_type == 'StringArray': value_coerced = [] for v in value: #", "not isinstance(value, bytes): raise RuntimeError('Invalid data provided for Binary.') value = base64.b64encode(value).decode('utf-8') elif", "from the DB. Returns: (str): Results retrieved from DB. \"\"\" value = None", "the value in Redis if applicable.\"\"\" if key is None or value is", "dict) or not self._is_tc_entity(value)): raise RuntimeError('Invalid data provided for TcEntity.') # self.log.trace(f'pb create", "# is embedded multiple times in the same key value array. data =", "self._variable_single_types + self._variable_array_types def _wrap_embedded_keyvalue(self, data): \"\"\"Wrap keyvalue embedded variable in double quotes.", "False return True @staticmethod def _load_value(value): \"\"\"Return the loaded JSON value or raise", "RuntimeError('Invalid data provided for Binary.') # if not isinstance(v, bytes): # v =", "self.log.error(e) return None def _create_array(self, key, value, validate=True): \"\"\"Create the value in Redis", "string. Args: key (str): The variable to read from the DB. Returns: (str):", "for x in ['key', 'value']) def _is_key_value_array(self, data): \"\"\"Return True if provided data", "if data is None: return False return all(x in data for x in", "applicable.\"\"\" if key is None: # pragma: no cover self.log.warning('The null value for", "self.log.warning('The key or value field was None.') return data def read_raw(self, key): \"\"\"Read", "gets the entire list/dict instead of just the string. value = re.sub(variable, v,", "int if isinstance(value, bool): # coerce bool to str type self.log.warning(f'Coercing bool value", "\"\"\"Regex pattern to match and parse a playbook variable.\"\"\" variable_pattern = r'#([A-Za-z]+)' #", "TODO: need to verify if core still sends improper JSON for KeyValueArrays if", "the variable to get individual parts parsed_variable = self.parse_variable(ov) variable_name = parsed_variable.get('name') variable_type", "= self.variable_type(key) # Enhanced entity array is the wild-wild west, don't validate it", "def create_raw(self, key, value): \"\"\"Create method of CRUD operation for raw data. ..important::", "array. data = data.replace(var, f'\": \"{variable_string}\"') return data def create_raw(self, key, value): \"\"\"Create", "elif variable_type == 'TCEntityArray': if validate and not self._is_tc_entity_array(value): raise RuntimeError('Invalid data provided", "e: self.log.error(e) return None if value is None: return value if variable_type ==", "self._decode_binary(v) values.append(v) value = values elif variable_type == 'KeyValueArray': # embedded variable can", "coerce string values value = self._coerce_string_value(self._load_value(value)) elif variable_type == 'TCEntity': value = self._load_value(value)", "'TCEntityArray': if validate and not self._is_tc_entity_array(value): raise RuntimeError('Invalid data provided for TcEntityArray.') #", "the variable reference, # sub None value, else insert '' in string. That", "# sub None value, else insert '' in string. That would require a", "KeyValue.') elif variable_type == 'String': # coerce string values value = self._coerce_string_value(value) if", "return None @staticmethod def _decode_binary(data): \"\"\"Return decoded bytes data handling data written by", "is not None: try: data = self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e:", "d in data: if not self._is_key_value(d): return False return True @staticmethod def _is_tc_entity(data):", "is just the variable reference, # sub None value, else insert '' in", "or int.\"\"\" # coerce bool before int as python says a bool is", "bool): # coerce bool to str type self.log.warning(f'Coercing bool value ({value}) to a", "key (str): The variable to write to the DB. value (bytes|int|string): The data", "class') def read(self, key, array=False, embedded=True): # pragma: no cover \"\"\"Set placeholder for", "value = base64.b64decode(value) if decode: value = self._decode_binary(value) elif variable_type == 'KeyValue': #", "value def _read_array(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value in Redis if", "the # quoted value to ensure the resulting data is loadable JSON value", "\"\"\"Return list of standard playbook single variable types.\"\"\" return [ 'Binary', 'KeyValue', 'String',", "] @property def _variable_single_types(self): \"\"\"Return list of standard playbook single variable types.\"\"\" return", "\"\"\"Return list of standard playbook variable typesd.\"\"\" return self._variable_single_types + self._variable_array_types def _wrap_embedded_keyvalue(self,", "the correct instance only, handling the case where a variable # is embedded", "(str): Results retrieved from DB \"\"\" if value is None: # pragma: no", "(str): Result of DB write. \"\"\" data = None if key is not", "data is None: return False return all(x in data for x in ['id',", "value = value_encoded elif variable_type == 'KeyValueArray': if validate and not self._is_key_value_array(value): raise", "_parse_output_variables(self): \"\"\"Parse the output variables provided to Playbook Class. **Example Variable Format**:: ['#App:1234:status!String',", "context: {self._context}, key: {key}, value: {value}') try: value = json.dumps(value) except ValueError as", "entity array is the wild-wild west, don't validate it if variable_type != 'TCEnhancedEntityArray':", "data provided for KeyValueArray.') elif variable_type == 'StringArray': value_coerced = [] for v", "will automatically covert variables embedded in a string with value retrieved from DB.", "(TcEx): Instance of TcEx class. context (str): The Redis context (hash). output_variables (list):", "value = self._read_embedded(value) value = self._load_value(value) elif variable_type == 'String': if embedded: value", "except RuntimeError as e: self.log.error(e) return None if value is None: return value", "JSON load data \"{value}\" ({e}).') def _parse_output_variables(self): \"\"\"Parse the output variables provided to", "embedded: value = self._read_embedded(value) value = self._load_value(value) elif variable_type == 'String': if embedded:", "loaded as JSON data. Returns: any: The de-serialized value from the key/value store.", "spread the value so that we know it's a list (as opposed to", "_decode_binary(data): \"\"\"Return decoded bytes data handling data written by java apps.\"\"\" try: data", "replace variable if a non-null value is returned from kv store # APP-1030", "= {} self._output_variables_by_type = {} for ov in self._output_variables: # parse the variable", "embedded variables without quotes (#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded = re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def _coerce_string_value(self, value): \"\"\"Return a", "string values value = self._coerce_string_value(value) if validate and not isinstance(value, str): raise RuntimeError('Invalid", "custom variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for custom variable_pattern += r'[A-Za-z0-9_-]+))' #", "value is returned from kv store # APP-1030 need to revisit this to", "value) if v is not None: # only replace variable if a non-null", "def _variable_types(self): \"\"\"Return list of standard playbook variable typesd.\"\"\" return self._variable_single_types + self._variable_array_types", "re from collections import OrderedDict from collections.abc import Iterable class PlaybooksBase: \"\"\"TcEx Playbook", "validate and not isinstance(v, bytes): raise RuntimeError('Invalid data provided for Binary.') # if", "self._load_value(value) return value def _read_array(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value in", "({e}).') try: return self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e) return None", "(array) variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array) variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable", "cover \"\"\"Set placeholder for child method.\"\"\" raise NotImplementedError('Implemented in child class') def read(self,", "java apps.\"\"\" try: data = data.decode('utf-8') except UnicodeDecodeError: # pragma: no cover #", "for custom variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for custom variable_pattern += r'[A-Za-z0-9_-]+))'", "if variable_type == 'Binary': # if not isinstance(value, bytes): # value = value.encode('utf-8')", "type replace the # quoted value to ensure the resulting data is loadable", "variable_type == 'KeyValue': if validate and (not isinstance(value, dict) or not self._is_key_value(value)): raise", "r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for custom variable_pattern += r'[A-Za-z0-9_-]+))' # variable type (custom)", "v = self.read(variable) self.log.trace(f'embedded variable: {variable}, value: {v}') if isinstance(v, (dict, list)): v", "the value in Redis if applicable.\"\"\" if key is None: # pragma: no", "variables. * Only String and KeyValueArray variables can have embedded variables. * Variables", "is not None: value = self.tcex.key_value_store.read(self._context, key.strip()) else: self.log.warning('The key field was None.')", "# coerce string values value = self._coerce_string_value(value) if validate and not isinstance(value, str):", "operation for raw data. ..important:: Bytes input will be returned a as string", "def _parse_output_variables(self): \"\"\"Parse the output variables provided to Playbook Class. **Example Variable Format**::", "validate it if variable_type != 'TCEnhancedEntityArray': if validate and (not isinstance(value, Iterable) or", "data: if not self._is_key_value(d): return False return True @staticmethod def _is_tc_entity(data): \"\"\"Return True", "determine data from redis originated as bytes or string. Args: key (str): The", "(e.g. \"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}'] = {'variable': ov} def _read(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create", "retrieved from DB \"\"\" # TODO: need to verify if core still sends", "the wild-wild west, don't validate it if variable_type != 'TCEnhancedEntityArray': if validate and", "data. ..important:: Raw data can only be a byte, str or int. Other", "\"key\": \"string\", \"value\": #App:7979:variable_name!String }] Args: value (str): The value to parsed and", "value, validate=True): \"\"\"Create the value in Redis if applicable.\"\"\" if key is None", "= base64.b64encode(value).decode('utf-8') elif variable_type == 'KeyValue': if validate and (not isinstance(value, dict) or", "PlaybooksBase: \"\"\"TcEx Playbook Module Base Class Args: tcex (TcEx): Instance of TcEx class.", "'value']) def _is_key_value_array(self, data): \"\"\"Return True if provided data has proper structure for", "get variable type from variable value variable_type = self.variable_type(key) if variable_type == 'Binary':", "value = self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) value = self._load_value(value) elif variable_type", "\"\"\"Read method for \"embedded\" variables. .. Note:: The ``read()`` method will automatically determine", "variable_type(self, variable): # pragma: no cover \"\"\"Set placeholder for child method.\"\"\" raise NotImplementedError('Implemented", "# coerce string values value_coerced.append(self._coerce_string_value(v)) value = value_coerced elif variable_type in ['TCEntityArray', 'TCEnhancedEntity',", "array variable types.\"\"\" return [ 'BinaryArray', 'KeyValueArray', 'StringArray', 'TCEntityArray', 'TCEnhancedEntityArray', ] @property def", "resulting data is loadable JSON value = re.sub(f'\"{variable}\"', v, value) if v is", "class PlaybooksBase: \"\"\"TcEx Playbook Module Base Class Args: tcex (TcEx): Instance of TcEx", "# non matching for custom variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for custom", "to the DB. value (bytes|int|string): The data to write to the DB. Returns:", "DB \"\"\" if value is None: # pragma: no cover return value for", "value ({value}) to a string (\"{str(value).lower()}\").') value = str(value).lower() # coerce int to", "value_encoded.append(v) value = value_encoded elif variable_type == 'KeyValueArray': if validate and not self._is_key_value_array(value):", "in double quotes. Args: data (str): The data with embedded variables. Returns: (str):", "in Redis if applicable.\"\"\" if key is None: # pragma: no cover self.log.warning('The", "= base64.b64decode(v) if decode: v = self._decode_binary(v) values.append(v) value = values elif variable_type", "d in data: if not self._is_tc_entity(d): return False return True @staticmethod def _load_value(value):", "(hash). output_variables (list): The requested output variables. \"\"\" def __init__(self, tcex, context, output_variables):", "({e})') elif variable_type == 'StringArray': if embedded: value = self._read_embedded(value) # convert int", "field was None.') return data def read_raw(self, key): \"\"\"Read method of CRUD operation", "for TC Entity.\"\"\" if data is None: return False return all(x in data", "self._is_tc_entity(d): return False return True @staticmethod def _load_value(value): \"\"\"Return the loaded JSON value", "\"\"\"Return a string value from an bool or int.\"\"\" # coerce bool before", "nested dict/list type replace the # quoted value to ensure the resulting data", "read_raw(self, key): \"\"\"Read method of CRUD operation for raw data. ..important:: Bytes input", "self.log.error(e) return None @staticmethod def _decode_binary(data): \"\"\"Return decoded bytes data handling data written", "= None self._output_variables_by_type = None self.log = tcex.log # match full variable self._variable_match", "provided for TcEntityArray.') # self.log.trace(f'pb create - context: {self._context}, key: {key}, value: {value}')", "None if key is not None and value is not None: try: data", "if provided data has proper structure for Key Value Array.\"\"\" for d in", "\"\"\" data = None if key is not None and value is not", "variables = [] for v in re.finditer(self._vars_keyvalue_embedded, data): variables.append(v.group(0)) for var in set(variables):", "\"string\", \"value\": #App:7979:variable_name!String }] Args: value (str): The value to parsed and updated", "\"\"\"Create the value in Redis if applicable.\"\"\" if key is None: # pragma:", "RuntimeError as e: self.log.error(e) else: self.log.warning('The key or value field was None.') return", "have embedded variables. * Variables can only be embedded one level deep. This", "decode=False): \"\"\"Create the value in Redis if applicable.\"\"\" if key is None: self.log.warning('The", "variable_pattern @property def _variable_array_types(self): \"\"\"Return list of standard playbook array variable types.\"\"\" return", "for var in set(variables): # recursion over set to handle duplicates # pull", "if embedded: value = self._read_embedded(value) value = self._load_value(value) elif variable_type == 'String': if", "and b64decode: v = base64.b64decode(v) if decode: v = self._decode_binary(v) values.append(v) value =", "\"\"\"Create method of CRUD operation for raw data. ..important:: Raw data can only", "== 'KeyValueArray': # embedded variable can be unquoted, which breaks JSON. value =", "convert int to str value_coerced = [] for v in self._load_value(value): # coerce", "so that we know it's a list (as opposed to an iterable) if", "isinstance(v, (dict, list)): v = json.dumps(v) # for KeyValueArray with nested dict/list type", "to handle variable references in kv/kvarrays that # are None. Would like to", "provided for TcEntity.') # self.log.trace(f'pb create - context: {self._context}, key: {key}, value: {value}')", "variable type (custom) return variable_pattern @property def _variable_array_types(self): \"\"\"Return list of standard playbook", "str type if isinstance(value, (float, int)): self.log.warning(f'Coercing float/int value ({value}) to a string", "value from the key/value store. \"\"\" try: return json.loads(value, object_pairs_hook=OrderedDict) except ValueError as", "\"string array\", \"value\": #App:7979:variable_name!StringArray }, { \"key\": \"string\", \"value\": #App:7979:variable_name!String }] Args: value", "value) except RuntimeError as e: self.log.error(e) return None def _create_array(self, key, value, validate=True):", "# TODO: need to verify if core still sends improper JSON for KeyValueArrays", "raise NotImplementedError('Implemented in child class') def variable_type(self, variable): # pragma: no cover \"\"\"Set", "case where a variable # is embedded multiple times in the same key", "Results retrieved from DB \"\"\" if value is None: # pragma: no cover", "bytes or string. Args: key (str): The variable to read from the DB.", "Redis if applicable.\"\"\" if key is None: self.log.warning('The key is None.') return None", "(exactly a variable) self._variable_parse = re.compile(self._variable_pattern) # match embedded variables without quotes (#App:7979:variable_name!StringArray)", "is None: self.log.warning('The key or value field is None.') return None # get", "coerce string values value = self._coerce_string_value(value) if validate and not isinstance(value, str): raise", "def _is_key_value(data): \"\"\"Return True if provided data has proper structure for Key Value.\"\"\"", "return value def _read_embedded(self, value): \"\"\"Read method for \"embedded\" variables. .. Note:: The", "variable_type == 'StringArray': if embedded: value = self._read_embedded(value) # convert int to str", "at beginning of String variable_pattern += r':([\\d]+)' # app id (:7979) variable_pattern +=", "which breaks JSON. value = self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) try: value", "still sends improper JSON for KeyValueArrays if data is not None: # pragma:", "key value array. data = data.replace(var, f'\": \"{variable_string}\"') return data def create_raw(self, key,", "variable_type == 'TCEntity': if validate and (not isinstance(value, dict) or not self._is_tc_entity(value)): raise", "updated from the DB. Returns: (str): Results retrieved from DB \"\"\" if value", "provided for String.') elif variable_type == 'TCEntity': if validate and (not isinstance(value, dict)", "provided for StringArray.') value_coerced.append(v) value = value_coerced elif variable_type == 'TCEntityArray': if validate", "v = self._decode_binary(v) values.append(v) value = values elif variable_type == 'KeyValueArray': # embedded", "(str): The variable to read from the DB. Returns: (str): Results retrieved from", "can only be a byte, str or int. Other data structures (dict, list,", "all(x in data for x in ['id', 'value', 'type']) def _is_tc_entity_array(self, data): \"\"\"Return", "embedded variables. * Variables can only be embedded one level deep. This method", "data provided for Binary.') value = base64.b64encode(value).decode('utf-8') elif variable_type == 'KeyValue': if validate", "if value is just the variable reference, # sub None value, else insert", "which breaks JSON. value = self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) value =", "# variable type variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for custom variable_pattern +=", "values value = self._coerce_string_value(value) if validate and not isinstance(value, str): raise RuntimeError('Invalid data", "collections import OrderedDict from collections.abc import Iterable class PlaybooksBase: \"\"\"TcEx Playbook Module Base", "isinstance(v, bytes): # v = v.encode('utf-8') v = base64.b64encode(v).decode('utf-8') value_encoded.append(v) value = value_encoded", "not None: try: data = self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e)", "pull (#App:1441:embedded_string!String) from (\": #App:1441:embedded_string!String) variable_string = re.search(self._variable_parse, var).group(0) # reformat to replace", "get individual parts parsed_variable = self.parse_variable(ov) variable_name = parsed_variable.get('name') variable_type = parsed_variable.get('type') #", "in the same key value array. data = data.replace(var, f'\": \"{variable_string}\"') return data", "# are None. Would like to be able to say if value is", "[\"one\", #App:7979:two!String, \"three\"] Examples 3: Input: [{ \"key\": \"embedded string\", \"value\": \"This input", "return False return all(x in data for x in ['key', 'value']) def _is_key_value_array(self,", "returned from kv store # APP-1030 need to revisit this to handle variable", "= parsed_variable.get('name') variable_type = parsed_variable.get('type') # store the variables in dict by name", "None or value is None: self.log.warning('The key or value field is None.') return", "a string value from an bool or int.\"\"\" # coerce bool before int", "float/int value ({value}) to a string (\"{str(value)}\").') value = str(value) return value def", "improper JSON for KeyValueArrays if data is not None: # pragma: no cover", "Examples:: DB Values #App:7979:variable_name!String: \"embedded \\\\\"variable\\\\\"\" #App:7979:two!String: \"two\" #App:7979:variable_name!StringArray: [\"one\", \"two\", \"three\"] Examples", "a string with value retrieved from DB. If there are no keys/variables the", "don't validate it if variable_type != 'TCEnhancedEntityArray': if validate and (not isinstance(value, Iterable)", "pragma: no cover variables = [] for v in re.finditer(self._vars_keyvalue_embedded, data): variables.append(v.group(0)) for", "'KeyValueArray', 'StringArray', 'TCEntityArray', 'TCEnhancedEntityArray', ] @property def _variable_single_types(self): \"\"\"Return list of standard playbook", "return value for variable in (v.group(0) for v in re.finditer(self._variable_parse, str(value))): v =", "is returned from kv store # APP-1030 need to revisit this to handle", "version of this method that gets the entire list/dict instead of just the", "and not isinstance(v, (type(None), str)): raise RuntimeError('Invalid data provided for StringArray.') value_coerced.append(v) value", "values v = self._coerce_string_value(v) if validate and not isinstance(v, (type(None), str)): raise RuntimeError('Invalid", "Values #App:7979:variable_name!String: \"embedded \\\\\"variable\\\\\"\" #App:7979:two!String: \"two\" #App:7979:variable_name!StringArray: [\"one\", \"two\", \"three\"] Examples 1: Input:", "self._variable_match = re.compile(fr'^{self._variable_pattern}$') # capture variable parts (exactly a variable) self._variable_parse = re.compile(self._variable_pattern)", "if embedded: value = self._read_embedded(value) # coerce string values value = self._coerce_string_value(self._load_value(value)) elif", "non matching for custom variable_pattern += r'[A-Za-z0-9_-]+))' # variable type (custom) return variable_pattern", "Examples 3: Input: [{ \"key\": \"embedded string\", \"value\": \"This input has a embedded", "to be able to say if value is just the variable reference, #", "RuntimeError(f'Failed loading JSON data ({value}). Error: ({e})') elif variable_type == 'StringArray': if embedded:", "variables can have embedded variables. * Variables can only be embedded one level", "CRUD operation for raw data. ..important:: Bytes input will be returned a as", "is not None and b64decode: v = base64.b64decode(v) if decode: v = self._decode_binary(v)", "if v is not None: if validate and not isinstance(v, bytes): raise RuntimeError('Invalid", "Enhanced entity array is the wild-wild west, don't validate it if variable_type !=", "string value from an bool or int.\"\"\" # coerce bool before int as", "# self.log.trace(f'pb create - context: {self._context}, key: {key}, value: {value}') return value def", "output_variables): \"\"\"Initialize the Class properties.\"\"\" self.tcex = tcex self._context = context self._output_variables =", "({value}) to a string (\"{str(value).lower()}\").') value = str(value).lower() # coerce int to str", "method will automatically determine if the input is a variable or needs to", "{value}') try: value = json.dumps(value) except ValueError as e: # pragma: no cover", "e: # pragma: no cover raise RuntimeError(f'Failed to serialize value ({e}).') try: return", "= value_encoded elif variable_type == 'KeyValueArray': if validate and not self._is_key_value_array(value): raise RuntimeError('Invalid", "(type(None), str)): raise RuntimeError('Invalid data provided for StringArray.') value_coerced.append(v) value = value_coerced elif", "# self.log.trace(f'pb create - context: {self._context}, key: {key}, value: {value}') try: value =", "if not self._is_key_value(d): return False return True @staticmethod def _is_tc_entity(data): \"\"\"Return True if", "_read_array(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value in Redis if applicable.\"\"\" if", "if applicable.\"\"\" if key is None: self.log.warning('The key is None.') return None #", "Value Array.\"\"\" for d in data: if not self._is_key_value(d): return False return True", "value = [ *value ] # spread the value so that we know", "Error: ({e})') elif variable_type == 'StringArray': if embedded: value = self._read_embedded(value) # convert", "+= r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for custom", "in self._load_value(value): # coerce string values value_coerced.append(self._coerce_string_value(v)) value = value_coerced elif variable_type in", "to write to the DB. Returns: (str): Result of DB write. \"\"\" data", "def _load_value(value): \"\"\"Return the loaded JSON value or raise an error. Args: value", "and (not isinstance(value, dict) or not self._is_key_value(value)): raise RuntimeError('Invalid data provided for KeyValue.')", "value for variable in (v.group(0) for v in re.finditer(self._variable_parse, str(value))): v = self.read(variable)", "# for KeyValueArray with nested dict/list type replace the # quoted value to", "the input is a variable or needs to be searched for embedded variables.", "data.decode('latin-1') return data @staticmethod def _is_key_value(data): \"\"\"Return True if provided data has proper", "and KeyValueArray variables can have embedded variables. * Variables can only be embedded", "# if not isinstance(value, bytes): # value = value.encode('utf-8') if validate and not", "as e: self.log.error(e) return None if value is None: return value if variable_type", "_load_value(value): \"\"\"Return the loaded JSON value or raise an error. Args: value (str):", "value): \"\"\"Return a string value from an bool or int.\"\"\" # coerce bool", "ov} # store the variables in dict by name-type (e.g. \"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}'] =", "raise RuntimeError(f'Failed loading JSON data ({value}). Error: ({e})') elif variable_type == 'StringArray': if", "automatically covert variables embedded in a string with value retrieved from DB. If", "key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value in Redis if applicable.\"\"\" if key", "list of standard playbook array variable types.\"\"\" return [ 'BinaryArray', 'KeyValueArray', 'StringArray', 'TCEntityArray',", "string values v = self._coerce_string_value(v) if validate and not isinstance(v, (type(None), str)): raise", "str value_coerced = [] for v in self._load_value(value): # coerce string values value_coerced.append(self._coerce_string_value(v))", "input has a embedded #App:7979:variable_name!String\" Examples 2: Input: [\"one\", #App:7979:two!String, \"three\"] Examples 3:", "#App:7979:variable_name!String\" Examples 2: Input: [\"one\", #App:7979:two!String, \"three\"] Examples 3: Input: [{ \"key\": \"embedded", "value in Redis if applicable.\"\"\" if key is None: # pragma: no cover", "way to determine data from redis originated as bytes or string. Args: key", "was None.') return value def parse_variable(self, variable): # pragma: no cover \"\"\"Set placeholder", "embedded variable in double quotes. Args: data (str): The data with embedded variables.", "key.strip()) else: self.log.warning('The key field was None.') return value def parse_variable(self, variable): #", "data is loadable JSON value = re.sub(f'\"{variable}\"', v, value) if v is not", "returned a as string as there is no way to determine data from", "variable references in kv/kvarrays that # are None. Would like to be able", "type from variable value variable_type = self.variable_type(key) if variable_type == 'Binary': # if", "e: self.log.error(e) return None @staticmethod def _decode_binary(data): \"\"\"Return decoded bytes data handling data", "to Playbook Class. **Example Variable Format**:: ['#App:1234:status!String', '#App:1234:status_code!String'] \"\"\" self._output_variables_by_name = {} self._output_variables_by_type", "@staticmethod def _load_value(value): \"\"\"Return the loaded JSON value or raise an error. Args:", "# APP-1030 need to revisit this to handle variable references in kv/kvarrays that", "the key/value store. \"\"\" try: return json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: #", "None if value is None: return value if variable_type == 'Binary': value =", "self._load_value(value): # coerce string values value_coerced.append(self._coerce_string_value(v)) value = value_coerced elif variable_type in ['TCEntityArray',", "JSON value = re.sub(f'\"{variable}\"', v, value) if v is not None: # only", "variable_type == 'KeyValueArray': if validate and not self._is_key_value_array(value): raise RuntimeError('Invalid data provided for", "Class. **Example Variable Format**:: ['#App:1234:status!String', '#App:1234:status_code!String'] \"\"\" self._output_variables_by_name = {} self._output_variables_by_type = {}", "coerce int to str type if isinstance(value, (float, int)): self.log.warning(f'Coercing float/int value ({value})", "KeyValueArrays if data is not None: # pragma: no cover variables = []", "not None: if validate and not isinstance(v, bytes): raise RuntimeError('Invalid data provided for", "variable_type == 'String': # coerce string values value = self._coerce_string_value(value) if validate and", "value (str): The value to parsed and updated from the DB. Returns: (str):", "for {variable_type}.') value = [ *value ] # spread the value so that", "value from an bool or int.\"\"\" # coerce bool before int as python", "DB. If there are no keys/variables the raw string will be returned. Examples::", "bool value ({value}) to a string (\"{str(value).lower()}\").') value = str(value).lower() # coerce int", "['id', 'value', 'type']) def _is_tc_entity_array(self, data): \"\"\"Return True if provided data has proper", "and value is not None: try: data = self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError", "'KeyValue': if validate and (not isinstance(value, dict) or not self._is_key_value(value)): raise RuntimeError('Invalid data", "in child class') def read(self, key, array=False, embedded=True): # pragma: no cover \"\"\"Set", "Base Class Args: tcex (TcEx): Instance of TcEx class. context (str): The Redis", "self.read(variable) self.log.trace(f'embedded variable: {variable}, value: {v}') if isinstance(v, (dict, list)): v = json.dumps(v)", "as e: # pragma: no cover raise RuntimeError(f'Failed to JSON load data \"{value}\"", "value (bytes|int|string): The data to write to the DB. Returns: (str): Result of", "Raise error when data can't be loaded as JSON data. Returns: any: The", "be searched for embedded variables. Embedded variable rules: * Only user input can", "# reformat to replace the correct instance only, handling the case where a", "coerce string values v = self._coerce_string_value(v) if validate and not isinstance(v, (type(None), str)):", "variable: {variable}, value: {v}') if isinstance(v, (dict, list)): v = json.dumps(v) # for", "string will be returned. Examples:: DB Values #App:7979:variable_name!String: \"embedded \\\\\"variable\\\\\"\" #App:7979:two!String: \"two\" #App:7979:variable_name!StringArray:", "class') def variable_type(self, variable): # pragma: no cover \"\"\"Set placeholder for child method.\"\"\"", "#App:7979:two!String, \"three\"] Examples 3: Input: [{ \"key\": \"embedded string\", \"value\": \"This input has", "no cover return value for variable in (v.group(0) for v in re.finditer(self._variable_parse, str(value))):", "variable to get individual parts parsed_variable = self.parse_variable(ov) variable_name = parsed_variable.get('name') variable_type =", "value (str): The data from key/value store. Raises: RuntimeError: Raise error when data", "from DB. If there are no keys/variables the raw string will be returned.", "def _variable_array_types(self): \"\"\"Return list of standard playbook array variable types.\"\"\" return [ 'BinaryArray',", "value = json.loads(value, object_pairs_hook=OrderedDict) values = [] for v in value: if v", "base64.b64decode(value) if decode: value = self._decode_binary(value) elif variable_type == 'KeyValue': # embedded variable", "except ValueError as e: # pragma: no cover raise RuntimeError(f'Failed loading JSON data", "for v in value: if v is not None: if validate and not", "= re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def _coerce_string_value(self, value): \"\"\"Return a string value from an bool or", "'value', 'type']) def _is_tc_entity_array(self, data): \"\"\"Return True if provided data has proper structure", "automatically determine if the input is a variable or needs to be searched", "* Variables can only be embedded one level deep. This method will automatically", "value field was None.') return data def read_raw(self, key): \"\"\"Read method of CRUD", "(custom) return variable_pattern @property def _variable_array_types(self): \"\"\"Return list of standard playbook array variable", "\"two\", \"three\"] Examples 1: Input: \"This input has a embedded #App:7979:variable_name!String\" Examples 2:", "not isinstance(v, bytes): # v = v.encode('utf-8') v = base64.b64encode(v).decode('utf-8') value_encoded.append(v) value =", "# coerce bool before int as python says a bool is an int", "standard playbook variable typesd.\"\"\" return self._variable_single_types + self._variable_array_types def _wrap_embedded_keyvalue(self, data): \"\"\"Wrap keyvalue", "for TcEntityArray.') # self.log.trace(f'pb create - context: {self._context}, key: {key}, value: {value}') try:", "value if variable_type == 'Binary': value = self._load_value(value) if b64decode: value = base64.b64decode(value)", "= self.tcex.key_value_store.read(self._context, key.strip()) except RuntimeError as e: self.log.error(e) return None if value is", "variables without quotes (#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded = re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def _coerce_string_value(self, value): \"\"\"Return a string", "provided for KeyValueArray.') elif variable_type == 'StringArray': value_coerced = [] for v in", "data def create_raw(self, key, value): \"\"\"Create method of CRUD operation for raw data.", "of CRUD operation for raw data. ..important:: Raw data can only be a", "all(x in data for x in ['key', 'value']) def _is_key_value_array(self, data): \"\"\"Return True", "None # get variable type from variable value variable_type = self.variable_type(key) # Enhanced", "_is_key_value(data): \"\"\"Return True if provided data has proper structure for Key Value.\"\"\" if", "string. That would require a kv-specific # version of this method that gets", "not self._is_key_value_array(value): raise RuntimeError('Invalid data provided for KeyValueArray.') elif variable_type == 'StringArray': value_coerced", "None and value is not None: try: data = self.tcex.key_value_store.create(self._context, key.strip(), value) except", "Args: tcex (TcEx): Instance of TcEx class. context (str): The Redis context (hash).", "return None if value is None: return value if variable_type == 'Binary': value", "[] for v in re.finditer(self._vars_keyvalue_embedded, data): variables.append(v.group(0)) for var in set(variables): # recursion", "match full variable self._variable_match = re.compile(fr'^{self._variable_pattern}$') # capture variable parts (exactly a variable)", "for v in self._load_value(value): # coerce string values value_coerced.append(self._coerce_string_value(v)) value = value_coerced elif", "data from key/value store. Raises: RuntimeError: Raise error when data can't be loaded", "[] for v in value: if v is not None: if validate and", "== 'TCEntityArray': if validate and not self._is_tc_entity_array(value): raise RuntimeError('Invalid data provided for TcEntityArray.')", "variable) self._variable_parse = re.compile(self._variable_pattern) # match embedded variables without quotes (#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded =", "is embedded multiple times in the same key value array. data = data.replace(var,", "= tcex.log # match full variable self._variable_match = re.compile(fr'^{self._variable_pattern}$') # capture variable parts", "'TCEnhancedEntityArray': if validate and (not isinstance(value, Iterable) or isinstance(value, (str, dict))): raise RuntimeError(f'Invalid", "is None: self.log.warning('The key is None.') return None # get variable type from", "return [ 'BinaryArray', 'KeyValueArray', 'StringArray', 'TCEntityArray', 'TCEnhancedEntityArray', ] @property def _variable_single_types(self): \"\"\"Return list", "be a byte, str or int. Other data structures (dict, list, etc) must", "placeholder for child method.\"\"\" raise NotImplementedError('Implemented in child class') def variable_type(self, variable): #", "not self._is_key_value(value)): raise RuntimeError('Invalid data provided for KeyValue.') elif variable_type == 'String': #", "parts (exactly a variable) self._variable_parse = re.compile(self._variable_pattern) # match embedded variables without quotes", "[] for v in value: # coerce string values v = self._coerce_string_value(v) if", "provided data has proper structure for TC Entity Array.\"\"\" for d in data:", "if decode: value = self._decode_binary(value) elif variable_type == 'KeyValue': # embedded variable can", "is no way to determine data from redis originated as bytes or string.", "# recursion over set to handle duplicates # pull (#App:1441:embedded_string!String) from (\": #App:1441:embedded_string!String)", "Entity Array.\"\"\" for d in data: if not self._is_tc_entity(d): return False return True", "{'variable': ov} # store the variables in dict by name-type (e.g. \"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}']", "_wrap_embedded_keyvalue(self, data): \"\"\"Wrap keyvalue embedded variable in double quotes. Args: data (str): The", "RuntimeError('Invalid data provided for StringArray.') value_coerced.append(v) value = value_coerced elif variable_type == 'TCEntityArray':", "variable_type == 'BinaryArray': value_encoded = [] for v in value: if v is", "structure for TC Entity.\"\"\" if data is None: return False return all(x in", "in string. That would require a kv-specific # version of this method that", "that we know it's a list (as opposed to an iterable) if variable_type", "def _is_tc_entity_array(self, data): \"\"\"Return True if provided data has proper structure for TC", "try: value = self.tcex.key_value_store.read(self._context, key.strip()) except RuntimeError as e: self.log.error(e) return None if", "if not isinstance(v, bytes): # v = v.encode('utf-8') v = base64.b64encode(v).decode('utf-8') value_encoded.append(v) value", "base64.b64encode(value).decode('utf-8') elif variable_type == 'KeyValue': if validate and (not isinstance(value, dict) or not", "return False return all(x in data for x in ['id', 'value', 'type']) def", "None: try: data = self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e) else:", "# coerce string values value = self._coerce_string_value(self._load_value(value)) elif variable_type == 'TCEntity': value =", "store. \"\"\" try: return json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: # pragma: no", "raise RuntimeError(f'Failed to serialize value ({e}).') try: return self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError", "from variable value variable_type = self.variable_type(key) if variable_type == 'Binary': # if not", "['key', 'value']) def _is_key_value_array(self, data): \"\"\"Return True if provided data has proper structure", "of standard playbook array variable types.\"\"\" return [ 'BinaryArray', 'KeyValueArray', 'StringArray', 'TCEntityArray', 'TCEnhancedEntityArray',", "cover raise RuntimeError(f'Failed to serialize value ({e}).') try: return self.tcex.key_value_store.create(self._context, key.strip(), value) except", "to str value_coerced = [] for v in self._load_value(value): # coerce string values", "CRUD operation for raw data. ..important:: Raw data can only be a byte,", "None: return value if variable_type == 'Binary': value = self._load_value(value) if b64decode: value", "self._vars_keyvalue_embedded = re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def _coerce_string_value(self, value): \"\"\"Return a string value from an bool", "and (not isinstance(value, Iterable) or isinstance(value, (str, dict))): raise RuntimeError(f'Invalid data provided for", "read(self, key, array=False, embedded=True): # pragma: no cover \"\"\"Set placeholder for child method.\"\"\"", "isinstance(value, (str, dict))): raise RuntimeError(f'Invalid data provided for {variable_type}.') value = [ *value", "raw data. ..important:: Bytes input will be returned a as string as there", "v in value: # coerce string values v = self._coerce_string_value(v) if validate and", "will be returned. Examples:: DB Values #App:7979:variable_name!String: \"embedded \\\\\"variable\\\\\"\" #App:7979:two!String: \"two\" #App:7979:variable_name!StringArray: [\"one\",", "as string as there is no way to determine data from redis originated", "standard playbook single variable types.\"\"\" return [ 'Binary', 'KeyValue', 'String', 'TCEntity', 'TCEnhancedEntity', ]", "if key is None or value is None: self.log.warning('The key or value field", "variable types.\"\"\" return [ 'Binary', 'KeyValue', 'String', 'TCEntity', 'TCEnhancedEntity', ] @property def _variable_types(self):", "}, { \"key\": \"string\", \"value\": #App:7979:variable_name!String }] Args: value (str): The value to", "raise NotImplementedError('Implemented in child class') def read(self, key, array=False, embedded=True): # pragma: no", "variable_name = parsed_variable.get('name') variable_type = parsed_variable.get('type') # store the variables in dict by", "Results retrieved from DB. \"\"\" value = None if key is not None:", "KeyValueArray variables can have embedded variables. * Variables can only be embedded one", "data has proper structure for TC Entity.\"\"\" if data is None: return False", "is loadable JSON value = re.sub(f'\"{variable}\"', v, value) if v is not None:", "\"key\": \"embedded string\", \"value\": \"This input has a embedded #App:7979:variable_name!String\" }, { \"key\":", "v in re.finditer(self._variable_parse, str(value))): v = self.read(variable) self.log.trace(f'embedded variable: {variable}, value: {v}') if", "for v in value: if v is not None and b64decode: v =", "handle duplicates # pull (#App:1441:embedded_string!String) from (\": #App:1441:embedded_string!String) variable_string = re.search(self._variable_parse, var).group(0) #", "return value if variable_type == 'Binary': value = self._load_value(value) if b64decode: value =", "= None self.log = tcex.log # match full variable self._variable_match = re.compile(fr'^{self._variable_pattern}$') #", "variable value variable_type = self.variable_type(key) if variable_type == 'Binary': # if not isinstance(value,", "proper structure for TC Entity.\"\"\" if data is None: return False return all(x", "in Redis if applicable.\"\"\" if key is None: self.log.warning('The key is None.') return", "\"\"\" value = None if key is not None: value = self.tcex.key_value_store.read(self._context, key.strip())", "[\"one\", \"two\", \"three\"] Examples 1: Input: \"This input has a embedded #App:7979:variable_name!String\" Examples", "key or value field is None.') return None # get variable type from", "= self._coerce_string_value(self._load_value(value)) elif variable_type == 'TCEntity': value = self._load_value(value) return value def _read_array(self,", "operation for raw data. ..important:: Raw data can only be a byte, str", "value = None if key is not None: value = self.tcex.key_value_store.read(self._context, key.strip()) else:", "to str type self.log.warning(f'Coercing bool value ({value}) to a string (\"{str(value).lower()}\").') value =", "_variable_pattern(self): \"\"\"Regex pattern to match and parse a playbook variable.\"\"\" variable_pattern = r'#([A-Za-z]+)'", "r'#([A-Za-z]+)' # match literal (#App,#Trigger) at beginning of String variable_pattern += r':([\\d]+)' #", "The de-serialized value from the key/value store. \"\"\" try: return json.loads(value, object_pairs_hook=OrderedDict) except", "cover raise RuntimeError(f'Failed to JSON load data \"{value}\" ({e}).') def _parse_output_variables(self): \"\"\"Parse the", "times in the same key value array. data = data.replace(var, f'\": \"{variable_string}\"') return", "cover variables = [] for v in re.finditer(self._vars_keyvalue_embedded, data): variables.append(v.group(0)) for var in", "# non matching for custom variable_pattern += r'[A-Za-z0-9_-]+))' # variable type (custom) return", "value = json.dumps(value) except ValueError as e: # pragma: no cover raise RuntimeError(f'Failed", "are no keys/variables the raw string will be returned. Examples:: DB Values #App:7979:variable_name!String:", "pattern to match and parse a playbook variable.\"\"\" variable_pattern = r'#([A-Za-z]+)' # match", "DB. Returns: (str): Results retrieved from DB. \"\"\" value = None if key", "from (\": #App:1441:embedded_string!String) variable_string = re.search(self._variable_parse, var).group(0) # reformat to replace the correct", "(bytes|int|string): The data to write to the DB. Returns: (str): Result of DB", "field is None.') return None # get variable type from variable value variable_type", "= self._read_embedded(value) # coerce string values value = self._coerce_string_value(self._load_value(value)) elif variable_type == 'TCEntity':", "will be returned a as string as there is no way to determine", "DB write. \"\"\" data = None if key is not None and value", "self.log.warning('The key field was None.') return value def parse_variable(self, variable): # pragma: no", "kv-specific # version of this method that gets the entire list/dict instead of", "int)): self.log.warning(f'Coercing float/int value ({value}) to a string (\"{str(value)}\").') value = str(value) return", "\"\"\"Return list of standard playbook array variable types.\"\"\" return [ 'BinaryArray', 'KeyValueArray', 'StringArray',", "quotes. Args: data (str): The data with embedded variables. Returns: (str): Results retrieved", "(:variable_name) variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array) variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' # variable", "RuntimeError('Invalid data provided for KeyValue.') elif variable_type == 'String': # coerce string values", "\"\"\"Return True if provided data has proper structure for Key Value Array.\"\"\" for", "if key is None: # pragma: no cover self.log.warning('The null value for key", "try: data = self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e) else: self.log.warning('The", "proper structure for Key Value Array.\"\"\" for d in data: if not self._is_key_value(d):", "self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e) else: self.log.warning('The key or value", "value, else insert '' in string. That would require a kv-specific # version", "key): \"\"\"Read method of CRUD operation for raw data. ..important:: Bytes input will", "self._variable_parse = re.compile(self._variable_pattern) # match embedded variables without quotes (#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded = re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}')", "value def parse_variable(self, variable): # pragma: no cover \"\"\"Set placeholder for child method.\"\"\"", "if isinstance(value, (float, int)): self.log.warning(f'Coercing float/int value ({value}) to a string (\"{str(value)}\").') value", "_read(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value in Redis if applicable.\"\"\" if", "is None.') return None # get variable type from variable value variable_type =", "self._context = context self._output_variables = output_variables or [] # properties self._output_variables_by_name = None", "from variable value variable_type = self.variable_type(key) # Enhanced entity array is the wild-wild", "variable_type = self.variable_type(key) # Enhanced entity array is the wild-wild west, don't validate", "= self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) try: value = json.loads(value, object_pairs_hook=OrderedDict) except", "redis originated as bytes or string. Args: key (str): The variable to read", "value to parsed and updated from the DB. Returns: (str): Results retrieved from", "for d in data: if not self._is_key_value(d): return False return True @staticmethod def", "provided data has proper structure for TC Entity.\"\"\" if data is None: return", "# get variable type from variable value variable_type = self.variable_type(key) # Enhanced entity", "an upstream java App data = data.decode('latin-1') return data @staticmethod def _is_key_value(data): \"\"\"Return", "'' in string. That would require a kv-specific # version of this method", "if validate and (not isinstance(value, dict) or not self._is_tc_entity(value)): raise RuntimeError('Invalid data provided", "def _read(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value in Redis if applicable.\"\"\"", "class. context (str): The Redis context (hash). output_variables (list): The requested output variables.", "decode: value = self._decode_binary(value) elif variable_type == 'KeyValue': # embedded variable can be", "playbook variable.\"\"\" variable_pattern = r'#([A-Za-z]+)' # match literal (#App,#Trigger) at beginning of String", "values = [] for v in value: if v is not None and", "ov} def _read(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value in Redis if", "is None: return False return all(x in data for x in ['id', 'value',", "+ self._variable_array_types def _wrap_embedded_keyvalue(self, data): \"\"\"Wrap keyvalue embedded variable in double quotes. Args:", "Args: value (str): The data from key/value store. Raises: RuntimeError: Raise error when", "# variable type (array) variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)'", "v, value) return value @property def _variable_pattern(self): \"\"\"Regex pattern to match and parse", "field was None.') return value def parse_variable(self, variable): # pragma: no cover \"\"\"Set", "int as python says a bool is an int if isinstance(value, bool): #", "verify if core still sends improper JSON for KeyValueArrays if data is not", "value def _create(self, key, value, validate=True): \"\"\"Create the value in Redis if applicable.\"\"\"", "# quoted value to ensure the resulting data is loadable JSON value =", "Playbook Module Base Class Args: tcex (TcEx): Instance of TcEx class. context (str):", "structure for Key Value Array.\"\"\" for d in data: if not self._is_key_value(d): return", "array is the wild-wild west, don't validate it if variable_type != 'TCEnhancedEntityArray': if", "if not self._is_tc_entity(d): return False return True @staticmethod def _load_value(value): \"\"\"Return the loaded", "Raw data can only be a byte, str or int. Other data structures", "if variable_type == 'BinaryArray': value_encoded = [] for v in value: if v", "to match and parse a playbook variable.\"\"\" variable_pattern = r'#([A-Za-z]+)' # match literal", "pragma: no cover raise RuntimeError(f'Failed to JSON load data \"{value}\" ({e}).') def _parse_output_variables(self):", "tcex, context, output_variables): \"\"\"Initialize the Class properties.\"\"\" self.tcex = tcex self._context = context", "\"This input has a embedded #App:7979:variable_name!String\" Examples 2: Input: [\"one\", #App:7979:two!String, \"three\"] Examples", "in self._output_variables: # parse the variable to get individual parts parsed_variable = self.parse_variable(ov)", "needs to be searched for embedded variables. Embedded variable rules: * Only user", "'String', 'TCEntity', 'TCEnhancedEntity', ] @property def _variable_types(self): \"\"\"Return list of standard playbook variable", "**Example Variable Format**:: ['#App:1234:status!String', '#App:1234:status_code!String'] \"\"\" self._output_variables_by_name = {} self._output_variables_by_type = {} for", "None: return False return all(x in data for x in ['key', 'value']) def", "method.\"\"\" raise NotImplementedError('Implemented in child class') def read(self, key, array=False, embedded=True): # pragma:", "# pragma: no cover self.log.warning('The null value for key was provided.') return None", "only, handling the case where a variable # is embedded multiple times in", "def parse_variable(self, variable): # pragma: no cover \"\"\"Set placeholder for child method.\"\"\" raise", "data provided for StringArray.') value_coerced.append(v) value = value_coerced elif variable_type == 'TCEntityArray': if", "from the key/value store. \"\"\" try: return json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e:", "(str): Results retrieved from DB \"\"\" # TODO: need to verify if core", "properties.\"\"\" self.tcex = tcex self._context = context self._output_variables = output_variables or [] #", "elif variable_type == 'KeyValueArray': if validate and not self._is_key_value_array(value): raise RuntimeError('Invalid data provided", "if validate and not isinstance(v, (type(None), str)): raise RuntimeError('Invalid data provided for StringArray.')", "to the DB. Returns: (str): Result of DB write. \"\"\" data = None", "isinstance(value, bytes): # value = value.encode('utf-8') if validate and not isinstance(value, bytes): raise", "decoded bytes data handling data written by java apps.\"\"\" try: data = data.decode('utf-8')", "has proper structure for Key Value Array.\"\"\" for d in data: if not", "If there are no keys/variables the raw string will be returned. Examples:: DB", "full variable self._variable_match = re.compile(fr'^{self._variable_pattern}$') # capture variable parts (exactly a variable) self._variable_parse", "python says a bool is an int if isinstance(value, bool): # coerce bool", "value variable_type = self.variable_type(key) # Enhanced entity array is the wild-wild west, don't", "None self._output_variables_by_type = None self.log = tcex.log # match full variable self._variable_match =", "Note:: The ``read()`` method will automatically determine if the input is a variable", "return False return True @staticmethod def _load_value(value): \"\"\"Return the loaded JSON value or", "({value}) to a string (\"{str(value)}\").') value = str(value) return value def _create(self, key,", "return None def _create_array(self, key, value, validate=True): \"\"\"Create the value in Redis if", "bytes): raise RuntimeError('Invalid data provided for Binary.') value = base64.b64encode(value).decode('utf-8') elif variable_type ==", "value = self._load_value(value) elif variable_type == 'String': if embedded: value = self._read_embedded(value) #", "# coerce int to str type if isinstance(value, (float, int)): self.log.warning(f'Coercing float/int value", "can only be embedded one level deep. This method will automatically covert variables", "= None if key is not None and value is not None: try:", "opposed to an iterable) if variable_type == 'BinaryArray': value_encoded = [] for v", "self._read_embedded(value) try: value = json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: # pragma: no", "variable types.\"\"\" return [ 'BinaryArray', 'KeyValueArray', 'StringArray', 'TCEntityArray', 'TCEnhancedEntityArray', ] @property def _variable_single_types(self):", "cover self.log.warning('The null value for key was provided.') return None # get variable", "Returns: (str): Results retrieved from DB \"\"\" # TODO: need to verify if", "if variable_type != 'TCEnhancedEntityArray': if validate and (not isinstance(value, Iterable) or isinstance(value, (str,", "None @staticmethod def _decode_binary(data): \"\"\"Return decoded bytes data handling data written by java", "variables. .. Note:: The ``read()`` method will automatically determine if the input is", "value = self._decode_binary(value) elif variable_type == 'KeyValue': # embedded variable can be unquoted,", "@property def _variable_array_types(self): \"\"\"Return list of standard playbook array variable types.\"\"\" return [", "variable or needs to be searched for embedded variables. Embedded variable rules: *", "value = self._coerce_string_value(self._load_value(value)) elif variable_type == 'TCEntity': value = self._load_value(value) return value def", "== 'TCEntity': value = self._load_value(value) return value def _read_array(self, key, embedded=True, b64decode=True, decode=False):", "# variable type (custom) return variable_pattern @property def _variable_array_types(self): \"\"\"Return list of standard", "else: self.log.warning('The key or value field was None.') return data def read_raw(self, key):", "# variable type (array) variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array) variable_pattern +=", "# parse the variable to get individual parts parsed_variable = self.parse_variable(ov) variable_name =", "string (\"{str(value).lower()}\").') value = str(value).lower() # coerce int to str type if isinstance(value,", "self._coerce_string_value(value) if validate and not isinstance(value, str): raise RuntimeError('Invalid data provided for String.')", "RuntimeError as e: self.log.error(e) return None @staticmethod def _decode_binary(data): \"\"\"Return decoded bytes data", "(:7979) variable_pattern += r':([A-Za-z0-9_\\.\\-\\[\\]]+)' # variable name (:variable_name) variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' # variable", "re.search(self._variable_parse, var).group(0) # reformat to replace the correct instance only, handling the case", "structure for Key Value.\"\"\" if data is None: return False return all(x in", "v, value) if v is not None: # only replace variable if a", "key.strip()) except RuntimeError as e: self.log.error(e) return None if value is None: return", "\"This input has a embedded #App:7979:variable_name!String\" }, { \"key\": \"string array\", \"value\": #App:7979:variable_name!StringArray", "key is not None and value is not None: try: data = self.tcex.key_value_store.create(self._context,", "# pragma: no cover \"\"\"Set placeholder for child method.\"\"\" raise NotImplementedError('Implemented in child", "a list (as opposed to an iterable) if variable_type == 'BinaryArray': value_encoded =", "self.parse_variable(ov) variable_name = parsed_variable.get('name') variable_type = parsed_variable.get('type') # store the variables in dict", "RuntimeError as e: self.log.error(e) return None if value is None: return value if", "are None. Would like to be able to say if value is just", "is None or value is None: self.log.warning('The key or value field is None.')", "return self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e) return None def _create_array(self,", "data = data.replace(var, f'\": \"{variable_string}\"') return data def create_raw(self, key, value): \"\"\"Create method", "a variable) self._variable_parse = re.compile(self._variable_pattern) # match embedded variables without quotes (#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded", "Framework Playbook module\"\"\" # standard library import base64 import json import re from", "*value ] # spread the value so that we know it's a list", "return None # get variable type from variable value variable_type = self.variable_type(key) try:", "variables.append(v.group(0)) for var in set(variables): # recursion over set to handle duplicates #", "== 'KeyValue': if validate and (not isinstance(value, dict) or not self._is_key_value(value)): raise RuntimeError('Invalid", "+= r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for custom variable_pattern += r'[A-Za-z0-9_-]+))' # variable type", "data provided for String.') elif variable_type == 'TCEntity': if validate and (not isinstance(value,", "to a string (\"{str(value)}\").') value = str(value) return value def _create(self, key, value,", "# pragma: no cover raise RuntimeError(f'Failed to serialize value ({e}).') try: return self.tcex.key_value_store.create(self._context,", "isinstance(value, bytes): raise RuntimeError('Invalid data provided for Binary.') value = base64.b64encode(value).decode('utf-8') elif variable_type", "raise RuntimeError('Invalid data provided for KeyValueArray.') elif variable_type == 'StringArray': value_coerced = []", "or value field is None.') return None # get variable type from variable", "None: if validate and not isinstance(v, bytes): raise RuntimeError('Invalid data provided for Binary.')", "by java apps.\"\"\" try: data = data.decode('utf-8') except UnicodeDecodeError: # pragma: no cover", "Key Value.\"\"\" if data is None: return False return all(x in data for", "\"\"\"Return True if provided data has proper structure for Key Value.\"\"\" if data", "just the variable reference, # sub None value, else insert '' in string.", "the output variables provided to Playbook Class. **Example Variable Format**:: ['#App:1234:status!String', '#App:1234:status_code!String'] \"\"\"", "embedded #App:7979:variable_name!String\" }, { \"key\": \"string array\", \"value\": #App:7979:variable_name!StringArray }, { \"key\": \"string\",", "embedded multiple times in the same key value array. data = data.replace(var, f'\":", "key: {key}, value: {value}') return value def _read_embedded(self, value): \"\"\"Read method for \"embedded\"", "Module Base Class Args: tcex (TcEx): Instance of TcEx class. context (str): The", "try: value = json.dumps(value) except ValueError as e: # pragma: no cover raise", "\"\"\"Return True if provided data has proper structure for TC Entity Array.\"\"\" for", "value: if v is not None: if validate and not isinstance(v, bytes): raise", "\"\"\"Set placeholder for child method.\"\"\" raise NotImplementedError('Implemented in child class') def read(self, key,", "* Only String and KeyValueArray variables can have embedded variables. * Variables can", "returned. Examples:: DB Values #App:7979:variable_name!String: \"embedded \\\\\"variable\\\\\"\" #App:7979:two!String: \"two\" #App:7979:variable_name!StringArray: [\"one\", \"two\", \"three\"]", "raise an error. Args: value (str): The data from key/value store. Raises: RuntimeError:", "typesd.\"\"\" return self._variable_single_types + self._variable_array_types def _wrap_embedded_keyvalue(self, data): \"\"\"Wrap keyvalue embedded variable in", "Would like to be able to say if value is just the variable", "data): \"\"\"Wrap keyvalue embedded variable in double quotes. Args: data (str): The data", "b64decode: v = base64.b64decode(v) if decode: v = self._decode_binary(v) values.append(v) value = values", "no cover raise RuntimeError(f'Failed to serialize value ({e}).') try: return self.tcex.key_value_store.create(self._context, key.strip(), value)", "@property def _variable_single_types(self): \"\"\"Return list of standard playbook single variable types.\"\"\" return [", "dict/list type replace the # quoted value to ensure the resulting data is", "self._output_variables_by_type[f'{variable_name}-{variable_type}'] = {'variable': ov} def _read(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value", "def _create_array(self, key, value, validate=True): \"\"\"Create the value in Redis if applicable.\"\"\" if", "variable type from variable value variable_type = self.variable_type(key) # Enhanced entity array is", "isinstance(value, dict) or not self._is_key_value(value)): raise RuntimeError('Invalid data provided for KeyValue.') elif variable_type", "v = v.encode('utf-8') v = base64.b64encode(v).decode('utf-8') value_encoded.append(v) value = value_encoded elif variable_type ==", "def _decode_binary(data): \"\"\"Return decoded bytes data handling data written by java apps.\"\"\" try:", "(not isinstance(value, Iterable) or isinstance(value, (str, dict))): raise RuntimeError(f'Invalid data provided for {variable_type}.')", "data is None: return False return all(x in data for x in ['key',", "Variables can only be embedded one level deep. This method will automatically covert", "RuntimeError('Invalid data provided for String.') elif variable_type == 'TCEntity': if validate and (not", "elif variable_type == 'String': # coerce string values value = self._coerce_string_value(value) if validate", "if embedded: value = self._read_embedded(value) # convert int to str value_coerced = []", "return json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: # pragma: no cover raise RuntimeError(f'Failed", "ensure the resulting data is loadable JSON value = re.sub(f'\"{variable}\"', v, value) if", "in (v.group(0) for v in re.finditer(self._variable_parse, str(value))): v = self.read(variable) self.log.trace(f'embedded variable: {variable},", "self.tcex.key_value_store.read(self._context, key.strip()) else: self.log.warning('The key field was None.') return value def parse_variable(self, variable):", "if value is None: return value if variable_type == 'Binary': value = self._load_value(value)", "def _create(self, key, value, validate=True): \"\"\"Create the value in Redis if applicable.\"\"\" if", "Embedded variable rules: * Only user input can have embedded variables. * Only", "None: return False return all(x in data for x in ['id', 'value', 'type'])", "= str(value).lower() # coerce int to str type if isinstance(value, (float, int)): self.log.warning(f'Coercing", "data structures (dict, list, etc) must be serialized. Args: key (str): The variable", "RuntimeError as e: self.log.error(e) return None def _create_array(self, key, value, validate=True): \"\"\"Create the", "def variable_type(self, variable): # pragma: no cover \"\"\"Set placeholder for child method.\"\"\" raise", "# embedded variable can be unquoted, which breaks JSON. value = self._wrap_embedded_keyvalue(value) if", "re.compile(self._variable_pattern) # match embedded variables without quotes (#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded = re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def _coerce_string_value(self,", "TcEntity.') # self.log.trace(f'pb create - context: {self._context}, key: {key}, value: {value}') try: value", "(str): Results retrieved from DB. \"\"\" value = None if key is not", "JSON data ({value}). Error: ({e})') elif variable_type == 'StringArray': if embedded: value =", "that gets the entire list/dict instead of just the string. value = re.sub(variable,", "'KeyValue': # embedded variable can be unquoted, which breaks JSON. value = self._wrap_embedded_keyvalue(value)", "context: {self._context}, key: {key}, value: {value}') return value def _read_embedded(self, value): \"\"\"Read method", "validate and not self._is_key_value_array(value): raise RuntimeError('Invalid data provided for KeyValueArray.') elif variable_type ==", "raise RuntimeError(f'Failed to JSON load data \"{value}\" ({e}).') def _parse_output_variables(self): \"\"\"Parse the output", "to JSON load data \"{value}\" ({e}).') def _parse_output_variables(self): \"\"\"Parse the output variables provided", "for TC Entity Array.\"\"\" for d in data: if not self._is_tc_entity(d): return False", "no keys/variables the raw string will be returned. Examples:: DB Values #App:7979:variable_name!String: \"embedded", "or value is None: self.log.warning('The key or value field is None.') return None", "before int as python says a bool is an int if isinstance(value, bool):", "and not isinstance(value, str): raise RuntimeError('Invalid data provided for String.') elif variable_type ==", "is None: return False return all(x in data for x in ['key', 'value'])", "= self._load_value(value) elif variable_type == 'String': if embedded: value = self._read_embedded(value) # coerce", "literal (#App,#Trigger) at beginning of String variable_pattern += r':([\\d]+)' # app id (:7979)", "to verify if core still sends improper JSON for KeyValueArrays if data is", "store. Raises: RuntimeError: Raise error when data can't be loaded as JSON data.", "return variable_pattern @property def _variable_array_types(self): \"\"\"Return list of standard playbook array variable types.\"\"\"", "in set(variables): # recursion over set to handle duplicates # pull (#App:1441:embedded_string!String) from", "in re.finditer(self._vars_keyvalue_embedded, data): variables.append(v.group(0)) for var in set(variables): # recursion over set to", "has proper structure for TC Entity Array.\"\"\" for d in data: if not", "if not isinstance(value, bytes): # value = value.encode('utf-8') if validate and not isinstance(value,", "def _is_tc_entity(data): \"\"\"Return True if provided data has proper structure for TC Entity.\"\"\"", "== 'Binary': value = self._load_value(value) if b64decode: value = base64.b64decode(value) if decode: value", "value): \"\"\"Create method of CRUD operation for raw data. ..important:: Raw data can", "no cover # for data written an upstream java App data = data.decode('latin-1')", "any: The de-serialized value from the key/value store. \"\"\" try: return json.loads(value, object_pairs_hook=OrderedDict)", "\"\"\" def __init__(self, tcex, context, output_variables): \"\"\"Initialize the Class properties.\"\"\" self.tcex = tcex", "child class') def read(self, key, array=False, embedded=True): # pragma: no cover \"\"\"Set placeholder", "= parsed_variable.get('type') # store the variables in dict by name (e.g. \"status_code\") self._output_variables_by_name[variable_name]", "'TCEnhancedEntityArray', ] @property def _variable_single_types(self): \"\"\"Return list of standard playbook single variable types.\"\"\"", "not None: # only replace variable if a non-null value is returned from", "# pragma: no cover return value for variable in (v.group(0) for v in", "if validate and not isinstance(value, str): raise RuntimeError('Invalid data provided for String.') elif", "['#App:1234:status!String', '#App:1234:status_code!String'] \"\"\" self._output_variables_by_name = {} self._output_variables_by_type = {} for ov in self._output_variables:", "int.\"\"\" # coerce bool before int as python says a bool is an", "data is not None: # pragma: no cover variables = [] for v", "value = value_coerced elif variable_type in ['TCEntityArray', 'TCEnhancedEntity', 'TCEnhancedEntityArray']: value = self._load_value(value) #", "try: data = data.decode('utf-8') except UnicodeDecodeError: # pragma: no cover # for data", "data): variables.append(v.group(0)) for var in set(variables): # recursion over set to handle duplicates", "int. Other data structures (dict, list, etc) must be serialized. Args: key (str):", "to read from the DB. Returns: (str): Results retrieved from DB. \"\"\" value", "if embedded: value = self._read_embedded(value) try: value = json.loads(value, object_pairs_hook=OrderedDict) except ValueError as", "\"value\": #App:7979:variable_name!String }] Args: value (str): The value to parsed and updated from", "list)): v = json.dumps(v) # for KeyValueArray with nested dict/list type replace the", "\"\"\"Return the loaded JSON value or raise an error. Args: value (str): The", "Entity.\"\"\" if data is None: return False return all(x in data for x", "string with value retrieved from DB. If there are no keys/variables the raw", "Playbook Class. **Example Variable Format**:: ['#App:1234:status!String', '#App:1234:status_code!String'] \"\"\" self._output_variables_by_name = {} self._output_variables_by_type =", "loadable JSON value = re.sub(f'\"{variable}\"', v, value) if v is not None: #", "self.log.warning('The null value for key was provided.') return None # get variable type", "to str type if isinstance(value, (float, int)): self.log.warning(f'Coercing float/int value ({value}) to a", "RuntimeError('Invalid data provided for TcEntity.') # self.log.trace(f'pb create - context: {self._context}, key: {key},", "(str): The value to parsed and updated from the DB. Returns: (str): Results", "variable_type == 'StringArray': value_coerced = [] for v in value: # coerce string", "level deep. This method will automatically covert variables embedded in a string with", "e: # pragma: no cover raise RuntimeError(f'Failed to JSON load data \"{value}\" ({e}).')", "data: if not self._is_tc_entity(d): return False return True @staticmethod def _load_value(value): \"\"\"Return the", "Input: [{ \"key\": \"embedded string\", \"value\": \"This input has a embedded #App:7979:variable_name!String\" },", "applicable.\"\"\" if key is None or value is None: self.log.warning('The key or value", "byte, str or int. Other data structures (dict, list, etc) must be serialized.", "import re from collections import OrderedDict from collections.abc import Iterable class PlaybooksBase: \"\"\"TcEx", "raise RuntimeError('Invalid data provided for KeyValue.') elif variable_type == 'String': # coerce string", "as bytes or string. Args: key (str): The variable to read from the", "= self._coerce_string_value(value) if validate and not isinstance(value, str): raise RuntimeError('Invalid data provided for", "re.finditer(self._vars_keyvalue_embedded, data): variables.append(v.group(0)) for var in set(variables): # recursion over set to handle", "key is None.') return None # get variable type from variable value variable_type", "if b64decode: value = base64.b64decode(value) if decode: value = self._decode_binary(value) elif variable_type ==", "e: self.log.error(e) else: self.log.warning('The key or value field was None.') return data def", "value for key was provided.') return None # get variable type from variable", "Binary.') value = base64.b64encode(value).decode('utf-8') elif variable_type == 'KeyValue': if validate and (not isinstance(value,", "for embedded variables. Embedded variable rules: * Only user input can have embedded", "or not self._is_key_value(value)): raise RuntimeError('Invalid data provided for KeyValue.') elif variable_type == 'String':", "DB. \"\"\" value = None if key is not None: value = self.tcex.key_value_store.read(self._context,", "type from variable value variable_type = self.variable_type(key) # Enhanced entity array is the", "data.replace(var, f'\": \"{variable_string}\"') return data def create_raw(self, key, value): \"\"\"Create method of CRUD", "{self._context}, key: {key}, value: {value}') try: value = json.dumps(value) except ValueError as e:", "store the variables in dict by name (e.g. \"status_code\") self._output_variables_by_name[variable_name] = {'variable': ov}", "}] Args: value (str): The value to parsed and updated from the DB.", "parts parsed_variable = self.parse_variable(ov) variable_name = parsed_variable.get('name') variable_type = parsed_variable.get('type') # store the", "def _variable_pattern(self): \"\"\"Regex pattern to match and parse a playbook variable.\"\"\" variable_pattern =", "None def _create_array(self, key, value, validate=True): \"\"\"Create the value in Redis if applicable.\"\"\"", "key (str): The variable to read from the DB. Returns: (str): Results retrieved", "# capture variable parts (exactly a variable) self._variable_parse = re.compile(self._variable_pattern) # match embedded", "or [] # properties self._output_variables_by_name = None self._output_variables_by_type = None self.log = tcex.log", "# convert int to str value_coerced = [] for v in self._load_value(value): #", "cover raise RuntimeError(f'Failed loading JSON data ({value}). Error: ({e})') elif variable_type == 'StringArray':", "written an upstream java App data = data.decode('latin-1') return data @staticmethod def _is_key_value(data):", "if validate and not self._is_key_value_array(value): raise RuntimeError('Invalid data provided for KeyValueArray.') elif variable_type", "try: return self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e) return None @staticmethod", "(as opposed to an iterable) if variable_type == 'BinaryArray': value_encoded = [] for", "'BinaryArray': value_encoded = [] for v in value: if v is not None:", "or raise an error. Args: value (str): The data from key/value store. Raises:", "Args: value (str): The value to parsed and updated from the DB. Returns:", "= self._read_embedded(value) value = self._load_value(value) elif variable_type == 'String': if embedded: value =", "{v}') if isinstance(v, (dict, list)): v = json.dumps(v) # for KeyValueArray with nested", "of this method that gets the entire list/dict instead of just the string.", "[] # properties self._output_variables_by_name = None self._output_variables_by_type = None self.log = tcex.log #", "Other data structures (dict, list, etc) must be serialized. Args: key (str): The", "value = self._load_value(value) # self.log.trace(f'pb create - context: {self._context}, key: {key}, value: {value}')", "write. \"\"\" data = None if key is not None and value is", "name (e.g. \"status_code\") self._output_variables_by_name[variable_name] = {'variable': ov} # store the variables in dict", "value retrieved from DB. If there are no keys/variables the raw string will", "for KeyValueArrays if data is not None: # pragma: no cover variables =", "variable_type == 'Binary': value = self._load_value(value) if b64decode: value = base64.b64decode(value) if decode:", "be unquoted, which breaks JSON. value = self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value)", "\"\"\"Read method of CRUD operation for raw data. ..important:: Bytes input will be", "self._load_value(value) # self.log.trace(f'pb create - context: {self._context}, key: {key}, value: {value}') return value", "if a non-null value is returned from kv store # APP-1030 need to", "Only user input can have embedded variables. * Only String and KeyValueArray variables", "Array.\"\"\" for d in data: if not self._is_tc_entity(d): return False return True @staticmethod", "v is not None: # only replace variable if a non-null value is", "try: value = json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: # pragma: no cover", "of CRUD operation for raw data. ..important:: Bytes input will be returned a", "= self._decode_binary(v) values.append(v) value = values elif variable_type == 'KeyValueArray': # embedded variable", "# pragma: no cover raise RuntimeError(f'Failed loading JSON data ({value}). Error: ({e})') elif", "variable to read from the DB. Returns: (str): Results retrieved from DB. \"\"\"", "= self.tcex.key_value_store.read(self._context, key.strip()) else: self.log.warning('The key field was None.') return value def parse_variable(self,", "try: return json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: # pragma: no cover raise", "when data can't be loaded as JSON data. Returns: any: The de-serialized value", "variable name (:variable_name) variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array) variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray'", "single variable types.\"\"\" return [ 'Binary', 'KeyValue', 'String', 'TCEntity', 'TCEnhancedEntity', ] @property def", "= self._load_value(value) if b64decode: value = base64.b64decode(value) if decode: value = self._decode_binary(value) elif", "= self._load_value(value) # self.log.trace(f'pb create - context: {self._context}, key: {key}, value: {value}') return", "(#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded = re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def _coerce_string_value(self, value): \"\"\"Return a string value from an", "variable self._variable_match = re.compile(fr'^{self._variable_pattern}$') # capture variable parts (exactly a variable) self._variable_parse =", "[ 'BinaryArray', 'KeyValueArray', 'StringArray', 'TCEntityArray', 'TCEnhancedEntityArray', ] @property def _variable_single_types(self): \"\"\"Return list of", "'StringArray', 'TCEntityArray', 'TCEnhancedEntityArray', ] @property def _variable_single_types(self): \"\"\"Return list of standard playbook single", "Args: data (str): The data with embedded variables. Returns: (str): Results retrieved from", "if applicable.\"\"\" if key is None or value is None: self.log.warning('The key or", "_create(self, key, value, validate=True): \"\"\"Create the value in Redis if applicable.\"\"\" if key", "data provided for KeyValue.') elif variable_type == 'String': # coerce string values value", "self._output_variables_by_type = {} for ov in self._output_variables: # parse the variable to get", "RuntimeError(f'Invalid data provided for {variable_type}.') value = [ *value ] # spread the", "parse the variable to get individual parts parsed_variable = self.parse_variable(ov) variable_name = parsed_variable.get('name')", "r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for custom variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for", "str(value) return value def _create(self, key, value, validate=True): \"\"\"Create the value in Redis", "# match embedded variables without quotes (#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded = re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def _coerce_string_value(self, value):", "standard library import base64 import json import re from collections import OrderedDict from", "False return all(x in data for x in ['key', 'value']) def _is_key_value_array(self, data):", "parsed and updated from the DB. Returns: (str): Results retrieved from DB \"\"\"", "just the string. value = re.sub(variable, v, value) return value @property def _variable_pattern(self):", "in ['key', 'value']) def _is_key_value_array(self, data): \"\"\"Return True if provided data has proper", "string values value_coerced.append(self._coerce_string_value(v)) value = value_coerced elif variable_type in ['TCEntityArray', 'TCEnhancedEntity', 'TCEnhancedEntityArray']: value", "return value @property def _variable_pattern(self): \"\"\"Regex pattern to match and parse a playbook", "pragma: no cover self.log.warning('The null value for key was provided.') return None #", "it if variable_type != 'TCEnhancedEntityArray': if validate and (not isinstance(value, Iterable) or isinstance(value,", "# get variable type from variable value variable_type = self.variable_type(key) if variable_type ==", "cover \"\"\"Set placeholder for child method.\"\"\" raise NotImplementedError('Implemented in child class') def variable_type(self,", "embedded: value = self._read_embedded(value) try: value = json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e:", "Class Args: tcex (TcEx): Instance of TcEx class. context (str): The Redis context", "capture variable parts (exactly a variable) self._variable_parse = re.compile(self._variable_pattern) # match embedded variables", "(dict, list)): v = json.dumps(v) # for KeyValueArray with nested dict/list type replace", "array=False, embedded=True): # pragma: no cover \"\"\"Set placeholder for child method.\"\"\" raise NotImplementedError('Implemented", "for \"embedded\" variables. .. Note:: The ``read()`` method will automatically determine if the", "# only replace variable if a non-null value is returned from kv store", "'KeyValueArray': if validate and not self._is_key_value_array(value): raise RuntimeError('Invalid data provided for KeyValueArray.') elif", "core still sends improper JSON for KeyValueArrays if data is not None: #", "the entire list/dict instead of just the string. value = re.sub(variable, v, value)", "in dict by name-type (e.g. \"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}'] = {'variable': ov} def _read(self, key,", "{variable}, value: {v}') if isinstance(v, (dict, list)): v = json.dumps(v) # for KeyValueArray", "read from the DB. Returns: (str): Results retrieved from DB. \"\"\" value =", "= self._coerce_string_value(v) if validate and not isinstance(v, (type(None), str)): raise RuntimeError('Invalid data provided", "NotImplementedError('Implemented in child class') def variable_type(self, variable): # pragma: no cover \"\"\"Set placeholder", "TC Entity.\"\"\" if data is None: return False return all(x in data for", "= tcex self._context = context self._output_variables = output_variables or [] # properties self._output_variables_by_name", "java App data = data.decode('latin-1') return data @staticmethod def _is_key_value(data): \"\"\"Return True if", "provided for {variable_type}.') value = [ *value ] # spread the value so", "if the input is a variable or needs to be searched for embedded", "self._output_variables_by_type = None self.log = tcex.log # match full variable self._variable_match = re.compile(fr'^{self._variable_pattern}$')", "for Binary.') value = base64.b64encode(value).decode('utf-8') elif variable_type == 'KeyValue': if validate and (not", "\"value\": \"This input has a embedded #App:7979:variable_name!String\" }, { \"key\": \"string array\", \"value\":", "# v = v.encode('utf-8') v = base64.b64encode(v).decode('utf-8') value_encoded.append(v) value = value_encoded elif variable_type", "list/dict instead of just the string. value = re.sub(variable, v, value) return value", "for v in value: # coerce string values v = self._coerce_string_value(v) if validate", "value to ensure the resulting data is loadable JSON value = re.sub(f'\"{variable}\"', v,", "elif variable_type in ['TCEntityArray', 'TCEnhancedEntity', 'TCEnhancedEntityArray']: value = self._load_value(value) # self.log.trace(f'pb create -", "embedded variables. * Only String and KeyValueArray variables can have embedded variables. *", "import base64 import json import re from collections import OrderedDict from collections.abc import", "validate and not isinstance(value, bytes): raise RuntimeError('Invalid data provided for Binary.') value =", "variables embedded in a string with value retrieved from DB. If there are", "store # APP-1030 need to revisit this to handle variable references in kv/kvarrays", "output variables provided to Playbook Class. **Example Variable Format**:: ['#App:1234:status!String', '#App:1234:status_code!String'] \"\"\" self._output_variables_by_name", "isinstance(v, (type(None), str)): raise RuntimeError('Invalid data provided for StringArray.') value_coerced.append(v) value = value_coerced", "not isinstance(value, str): raise RuntimeError('Invalid data provided for String.') elif variable_type == 'TCEntity':", "variable in double quotes. Args: data (str): The data with embedded variables. Returns:", "bytes): # v = v.encode('utf-8') v = base64.b64encode(v).decode('utf-8') value_encoded.append(v) value = value_encoded elif", "RuntimeError(f'Failed to JSON load data \"{value}\" ({e}).') def _parse_output_variables(self): \"\"\"Parse the output variables", "None if value is None: return value if variable_type == 'BinaryArray': value =", "'StringArray': if embedded: value = self._read_embedded(value) # convert int to str value_coerced =", "self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e) return None def _create_array(self, key,", "!= 'TCEnhancedEntityArray': if validate and (not isinstance(value, Iterable) or isinstance(value, (str, dict))): raise", "bytes): raise RuntimeError('Invalid data provided for Binary.') # if not isinstance(v, bytes): #", "re.finditer(self._variable_parse, str(value))): v = self.read(variable) self.log.trace(f'embedded variable: {variable}, value: {v}') if isinstance(v, (dict,", "self.log.trace(f'embedded variable: {variable}, value: {v}') if isinstance(v, (dict, list)): v = json.dumps(v) #", "data provided for TcEntityArray.') # self.log.trace(f'pb create - context: {self._context}, key: {key}, value:", "applicable.\"\"\" if key is None: self.log.warning('The key is None.') return None # get", "except ValueError as e: # pragma: no cover raise RuntimeError(f'Failed to serialize value", "[ 'Binary', 'KeyValue', 'String', 'TCEntity', 'TCEnhancedEntity', ] @property def _variable_types(self): \"\"\"Return list of", "only be a byte, str or int. Other data structures (dict, list, etc)", "can have embedded variables. * Variables can only be embedded one level deep.", "None.') return None # get variable type from variable value variable_type = self.variable_type(key)", "playbook array variable types.\"\"\" return [ 'BinaryArray', 'KeyValueArray', 'StringArray', 'TCEntityArray', 'TCEnhancedEntityArray', ] @property", "object_pairs_hook=OrderedDict) values = [] for v in value: if v is not None", "recursion over set to handle duplicates # pull (#App:1441:embedded_string!String) from (\": #App:1441:embedded_string!String) variable_string", "data written an upstream java App data = data.decode('latin-1') return data @staticmethod def", "return self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e) return None @staticmethod def", "Input: \"This input has a embedded #App:7979:variable_name!String\" Examples 2: Input: [\"one\", #App:7979:two!String, \"three\"]", "== 'String': if embedded: value = self._read_embedded(value) # coerce string values value =", "string\", \"value\": \"This input has a embedded #App:7979:variable_name!String\" }, { \"key\": \"string array\",", "bool is an int if isinstance(value, bool): # coerce bool to str type", "Iterable) or isinstance(value, (str, dict))): raise RuntimeError(f'Invalid data provided for {variable_type}.') value =", "= self._decode_binary(value) elif variable_type == 'KeyValue': # embedded variable can be unquoted, which", "embedded variables. Returns: (str): Results retrieved from DB \"\"\" # TODO: need to", "value in Redis if applicable.\"\"\" if key is None or value is None:", "isinstance(value, bool): # coerce bool to str type self.log.warning(f'Coercing bool value ({value}) to", "non matching for custom variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for custom variable_pattern", "= self.variable_type(key) if variable_type == 'Binary': # if not isinstance(value, bytes): # value", "{self._context}, key: {key}, value: {value}') return value def _read_embedded(self, value): \"\"\"Read method for", "provided to Playbook Class. **Example Variable Format**:: ['#App:1234:status!String', '#App:1234:status_code!String'] \"\"\" self._output_variables_by_name = {}", "library import base64 import json import re from collections import OrderedDict from collections.abc", "(#App,#Trigger) at beginning of String variable_pattern += r':([\\d]+)' # app id (:7979) variable_pattern", "return None if value is None: return value if variable_type == 'BinaryArray': value", "raise RuntimeError('Invalid data provided for Binary.') value = base64.b64encode(value).decode('utf-8') elif variable_type == 'KeyValue':", "where a variable # is embedded multiple times in the same key value", "a embedded #App:7979:variable_name!String\" Examples 2: Input: [\"one\", #App:7979:two!String, \"three\"] Examples 3: Input: [{", "value = values elif variable_type == 'KeyValueArray': # embedded variable can be unquoted,", "a kv-specific # version of this method that gets the entire list/dict instead", "placeholder for child method.\"\"\" raise NotImplementedError('Implemented in child class') def read(self, key, array=False,", "return None # get variable type from variable value variable_type = self.variable_type(key) #", "rules: * Only user input can have embedded variables. * Only String and", "beginning of String variable_pattern += r':([\\d]+)' # app id (:7979) variable_pattern += r':([A-Za-z0-9_\\.\\-\\[\\]]+)'", "str): raise RuntimeError('Invalid data provided for String.') elif variable_type == 'TCEntity': if validate", ".. Note:: The ``read()`` method will automatically determine if the input is a", "value in Redis if applicable.\"\"\" if key is None: self.log.warning('The key is None.')", "type if isinstance(value, (float, int)): self.log.warning(f'Coercing float/int value ({value}) to a string (\"{str(value)}\").')", "base64.b64encode(v).decode('utf-8') value_encoded.append(v) value = value_encoded elif variable_type == 'KeyValueArray': if validate and not", "'Binary': # if not isinstance(value, bytes): # value = value.encode('utf-8') if validate and", "data = data.decode('latin-1') return data @staticmethod def _is_key_value(data): \"\"\"Return True if provided data", "'TCEntity': value = self._load_value(value) return value def _read_array(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create", "values.append(v) value = values elif variable_type == 'KeyValueArray': # embedded variable can be", "data. ..important:: Bytes input will be returned a as string as there is", "for Key Value.\"\"\" if data is None: return False return all(x in data", "variable_type == 'String': if embedded: value = self._read_embedded(value) # coerce string values value", "Returns: (str): Results retrieved from DB \"\"\" if value is None: # pragma:", "re.sub(variable, v, value) return value @property def _variable_pattern(self): \"\"\"Regex pattern to match and", "= re.compile(fr'^{self._variable_pattern}$') # capture variable parts (exactly a variable) self._variable_parse = re.compile(self._variable_pattern) #", "parsed_variable = self.parse_variable(ov) variable_name = parsed_variable.get('name') variable_type = parsed_variable.get('type') # store the variables", "in value: # coerce string values v = self._coerce_string_value(v) if validate and not", "the Class properties.\"\"\" self.tcex = tcex self._context = context self._output_variables = output_variables or", "== 'BinaryArray': value_encoded = [] for v in value: if v is not", "] # spread the value so that we know it's a list (as", "as JSON data. Returns: any: The de-serialized value from the key/value store. \"\"\"", "value = self.tcex.key_value_store.read(self._context, key.strip()) except RuntimeError as e: self.log.error(e) return None if value", "list, etc) must be serialized. Args: key (str): The variable to write to", "True if provided data has proper structure for TC Entity.\"\"\" if data is", "_is_key_value_array(self, data): \"\"\"Return True if provided data has proper structure for Key Value", "variable type (array) variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' #", "method of CRUD operation for raw data. ..important:: Bytes input will be returned", "insert '' in string. That would require a kv-specific # version of this", "no cover \"\"\"Set placeholder for child method.\"\"\" raise NotImplementedError('Implemented in child class') def", "self.log.error(e) return None if value is None: return value if variable_type == 'Binary':", "if validate and (not isinstance(value, dict) or not self._is_key_value(value)): raise RuntimeError('Invalid data provided", "APP-1030 need to revisit this to handle variable references in kv/kvarrays that #", "is None: # pragma: no cover self.log.warning('The null value for key was provided.')", "DB \"\"\" # TODO: need to verify if core still sends improper JSON", "True if provided data has proper structure for Key Value.\"\"\" if data is", "self._is_tc_entity_array(value): raise RuntimeError('Invalid data provided for TcEntityArray.') # self.log.trace(f'pb create - context: {self._context},", "key/value store. Raises: RuntimeError: Raise error when data can't be loaded as JSON", "value) except RuntimeError as e: self.log.error(e) else: self.log.warning('The key or value field was", "variable_type != 'TCEnhancedEntityArray': if validate and (not isinstance(value, Iterable) or isinstance(value, (str, dict))):", "None # get variable type from variable value variable_type = self.variable_type(key) try: value", "in dict by name (e.g. \"status_code\") self._output_variables_by_name[variable_name] = {'variable': ov} # store the", "UnicodeDecodeError: # pragma: no cover # for data written an upstream java App", "value if variable_type == 'BinaryArray': value = json.loads(value, object_pairs_hook=OrderedDict) values = [] for", "Instance of TcEx class. context (str): The Redis context (hash). output_variables (list): The", "say if value is just the variable reference, # sub None value, else", "user input can have embedded variables. * Only String and KeyValueArray variables can", "None.') return data def read_raw(self, key): \"\"\"Read method of CRUD operation for raw", "value is just the variable reference, # sub None value, else insert ''", "the value in Redis if applicable.\"\"\" if key is None: self.log.warning('The key is", "self._decode_binary(value) elif variable_type == 'KeyValue': # embedded variable can be unquoted, which breaks", "kv store # APP-1030 need to revisit this to handle variable references in", "in ['id', 'value', 'type']) def _is_tc_entity_array(self, data): \"\"\"Return True if provided data has", "self._output_variables = output_variables or [] # properties self._output_variables_by_name = None self._output_variables_by_type = None", "upstream java App data = data.decode('latin-1') return data @staticmethod def _is_key_value(data): \"\"\"Return True", "isinstance(value, dict) or not self._is_tc_entity(value)): raise RuntimeError('Invalid data provided for TcEntity.') # self.log.trace(f'pb", "input can have embedded variables. * Only String and KeyValueArray variables can have", "value_encoded = [] for v in value: if v is not None: if", "values value = self._coerce_string_value(self._load_value(value)) elif variable_type == 'TCEntity': value = self._load_value(value) return value", "NotImplementedError('Implemented in child class') def read(self, key, array=False, embedded=True): # pragma: no cover", "raise RuntimeError('Invalid data provided for StringArray.') value_coerced.append(v) value = value_coerced elif variable_type ==", "coerce string values value_coerced.append(self._coerce_string_value(v)) value = value_coerced elif variable_type in ['TCEntityArray', 'TCEnhancedEntity', 'TCEnhancedEntityArray']:", "and parse a playbook variable.\"\"\" variable_pattern = r'#([A-Za-z]+)' # match literal (#App,#Trigger) at", "App data = data.decode('latin-1') return data @staticmethod def _is_key_value(data): \"\"\"Return True if provided", "id (:7979) variable_pattern += r':([A-Za-z0-9_\\.\\-\\[\\]]+)' # variable name (:variable_name) variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' #", "multiple times in the same key value array. data = data.replace(var, f'\": \"{variable_string}\"')", "\"\"\"Return True if provided data has proper structure for TC Entity.\"\"\" if data", "\"{value}\" ({e}).') def _parse_output_variables(self): \"\"\"Parse the output variables provided to Playbook Class. **Example", "else: self.log.warning('The key field was None.') return value def parse_variable(self, variable): # pragma:", "if variable_type == 'Binary': value = self._load_value(value) if b64decode: value = base64.b64decode(value) if", "embedded: value = self._read_embedded(value) # coerce string values value = self._coerce_string_value(self._load_value(value)) elif variable_type", "'Binary', 'KeyValue', 'String', 'TCEntity', 'TCEnhancedEntity', ] @property def _variable_types(self): \"\"\"Return list of standard", "# match literal (#App,#Trigger) at beginning of String variable_pattern += r':([\\d]+)' # app", "import Iterable class PlaybooksBase: \"\"\"TcEx Playbook Module Base Class Args: tcex (TcEx): Instance", "Redis if applicable.\"\"\" if key is None: # pragma: no cover self.log.warning('The null", "variable type (array) variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array) variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity'", "Result of DB write. \"\"\" data = None if key is not None", "and not isinstance(value, bytes): raise RuntimeError('Invalid data provided for Binary.') value = base64.b64encode(value).decode('utf-8')", "west, don't validate it if variable_type != 'TCEnhancedEntityArray': if validate and (not isinstance(value,", "== 'KeyValueArray': if validate and not self._is_key_value_array(value): raise RuntimeError('Invalid data provided for KeyValueArray.')", "the value so that we know it's a list (as opposed to an", "({value}). Error: ({e})') elif variable_type == 'StringArray': if embedded: value = self._read_embedded(value) #", "except RuntimeError as e: self.log.error(e) return None @staticmethod def _decode_binary(data): \"\"\"Return decoded bytes", "value or raise an error. Args: value (str): The data from key/value store.", "= [] for v in value: if v is not None: if validate", "# get variable type from variable value variable_type = self.variable_type(key) try: value =", "Array.\"\"\" for d in data: if not self._is_key_value(d): return False return True @staticmethod", "not isinstance(v, bytes): raise RuntimeError('Invalid data provided for Binary.') # if not isinstance(v,", "has proper structure for TC Entity.\"\"\" if data is None: return False return", "same key value array. data = data.replace(var, f'\": \"{variable_string}\"') return data def create_raw(self,", "(\": #App:1441:embedded_string!String) variable_string = re.search(self._variable_parse, var).group(0) # reformat to replace the correct instance", "\"key\": \"string array\", \"value\": #App:7979:variable_name!StringArray }, { \"key\": \"string\", \"value\": #App:7979:variable_name!String }] Args:", "_variable_array_types(self): \"\"\"Return list of standard playbook array variable types.\"\"\" return [ 'BinaryArray', 'KeyValueArray',", "collections.abc import Iterable class PlaybooksBase: \"\"\"TcEx Playbook Module Base Class Args: tcex (TcEx):", "This method will automatically covert variables embedded in a string with value retrieved", "variable_type == 'TCEntityArray': if validate and not self._is_tc_entity_array(value): raise RuntimeError('Invalid data provided for", "return value def _read_array(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value in Redis", "True @staticmethod def _is_tc_entity(data): \"\"\"Return True if provided data has proper structure for", "def read_raw(self, key): \"\"\"Read method of CRUD operation for raw data. ..important:: Bytes", "value array. data = data.replace(var, f'\": \"{variable_string}\"') return data def create_raw(self, key, value):", "None: return value if variable_type == 'BinaryArray': value = json.loads(value, object_pairs_hook=OrderedDict) values =", "(dict, list, etc) must be serialized. Args: key (str): The variable to write", "variable_type == 'KeyValueArray': # embedded variable can be unquoted, which breaks JSON. value", "}, { \"key\": \"string array\", \"value\": #App:7979:variable_name!StringArray }, { \"key\": \"string\", \"value\": #App:7979:variable_name!String", "data = self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e) else: self.log.warning('The key", "r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for custom variable_pattern", "to parsed and updated from the DB. Returns: (str): Results retrieved from DB", "self._variable_array_types def _wrap_embedded_keyvalue(self, data): \"\"\"Wrap keyvalue embedded variable in double quotes. Args: data", "self.log.trace(f'pb create - context: {self._context}, key: {key}, value: {value}') return value def _read_embedded(self,", "or int. Other data structures (dict, list, etc) must be serialized. Args: key", "elif variable_type == 'String': if embedded: value = self._read_embedded(value) # coerce string values", "'BinaryArray': value = json.loads(value, object_pairs_hook=OrderedDict) values = [] for v in value: if", "(str): The variable to write to the DB. value (bytes|int|string): The data to", "raise RuntimeError(f'Invalid data provided for {variable_type}.') value = [ *value ] # spread", "a variable # is embedded multiple times in the same key value array.", "method will automatically covert variables embedded in a string with value retrieved from", "# store the variables in dict by name-type (e.g. \"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}'] = {'variable':", "b64decode=True, decode=False): \"\"\"Create the value in Redis if applicable.\"\"\" if key is None:", "def _is_key_value_array(self, data): \"\"\"Return True if provided data has proper structure for Key", "self.tcex.key_value_store.read(self._context, key.strip()) except RuntimeError as e: self.log.error(e) return None if value is None:", "value ({e}).') try: return self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e) return", "know it's a list (as opposed to an iterable) if variable_type == 'BinaryArray':", "value = re.sub(f'\"{variable}\"', v, value) if v is not None: # only replace", "elif variable_type == 'TCEntity': if validate and (not isinstance(value, dict) or not self._is_tc_entity(value)):", "breaks JSON. value = self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) value = self._load_value(value)", "'String': # coerce string values value = self._coerce_string_value(value) if validate and not isinstance(value,", "'TCEnhancedEntity', 'TCEnhancedEntityArray']: value = self._load_value(value) # self.log.trace(f'pb create - context: {self._context}, key: {key},", "can have embedded variables. * Only String and KeyValueArray variables can have embedded", "v in value: if v is not None and b64decode: v = base64.b64decode(v)", "return True @staticmethod def _is_tc_entity(data): \"\"\"Return True if provided data has proper structure", "provided data has proper structure for Key Value Array.\"\"\" for d in data:", "def read(self, key, array=False, embedded=True): # pragma: no cover \"\"\"Set placeholder for child", "r'[A-Za-z0-9_-]+))' # variable type (custom) return variable_pattern @property def _variable_array_types(self): \"\"\"Return list of", "Results retrieved from DB \"\"\" # TODO: need to verify if core still", "Examples 2: Input: [\"one\", #App:7979:two!String, \"three\"] Examples 3: Input: [{ \"key\": \"embedded string\",", "base64.b64decode(v) if decode: v = self._decode_binary(v) values.append(v) value = values elif variable_type ==", "apps.\"\"\" try: data = data.decode('utf-8') except UnicodeDecodeError: # pragma: no cover # for", "value = self.tcex.key_value_store.read(self._context, key.strip()) else: self.log.warning('The key field was None.') return value def", "correct instance only, handling the case where a variable # is embedded multiple", "'StringArray': value_coerced = [] for v in value: # coerce string values v", "or isinstance(value, (str, dict))): raise RuntimeError(f'Invalid data provided for {variable_type}.') value = [", "and updated from the DB. Returns: (str): Results retrieved from DB \"\"\" if", "# pragma: no cover # for data written an upstream java App data", "= {} for ov in self._output_variables: # parse the variable to get individual", "bytes data handling data written by java apps.\"\"\" try: data = data.decode('utf-8') except", "structure for TC Entity Array.\"\"\" for d in data: if not self._is_tc_entity(d): return", "The data with embedded variables. Returns: (str): Results retrieved from DB \"\"\" #", "replace the correct instance only, handling the case where a variable # is", "variable_type == 'KeyValue': # embedded variable can be unquoted, which breaks JSON. value", "pragma: no cover return value for variable in (v.group(0) for v in re.finditer(self._variable_parse,", "context (hash). output_variables (list): The requested output variables. \"\"\" def __init__(self, tcex, context,", "self._coerce_string_value(self._load_value(value)) elif variable_type == 'TCEntity': value = self._load_value(value) return value def _read_array(self, key,", "RuntimeError('Invalid data provided for KeyValueArray.') elif variable_type == 'StringArray': value_coerced = [] for", "variables in dict by name (e.g. \"status_code\") self._output_variables_by_name[variable_name] = {'variable': ov} # store", "var).group(0) # reformat to replace the correct instance only, handling the case where", "@property def _variable_pattern(self): \"\"\"Regex pattern to match and parse a playbook variable.\"\"\" variable_pattern", "= data.decode('utf-8') except UnicodeDecodeError: # pragma: no cover # for data written an", "is not None: # only replace variable if a non-null value is returned", "{ \"key\": \"string array\", \"value\": #App:7979:variable_name!StringArray }, { \"key\": \"string\", \"value\": #App:7979:variable_name!String }]", "method of CRUD operation for raw data. ..important:: Raw data can only be", "type from variable value variable_type = self.variable_type(key) try: value = self.tcex.key_value_store.read(self._context, key.strip()) except", "Redis if applicable.\"\"\" if key is None or value is None: self.log.warning('The key", "False return all(x in data for x in ['id', 'value', 'type']) def _is_tc_entity_array(self,", "if isinstance(value, bool): # coerce bool to str type self.log.warning(f'Coercing bool value ({value})", "v is not None: if validate and not isinstance(v, bytes): raise RuntimeError('Invalid data", "be serialized. Args: key (str): The variable to write to the DB. value", "for child method.\"\"\" raise NotImplementedError('Implemented in child class') def read(self, key, array=False, embedded=True):", "e: # pragma: no cover raise RuntimeError(f'Failed loading JSON data ({value}). Error: ({e})')", "retrieved from DB. \"\"\" value = None if key is not None: value", "cover return value for variable in (v.group(0) for v in re.finditer(self._variable_parse, str(value))): v", "(str): The data from key/value store. Raises: RuntimeError: Raise error when data can't", "an iterable) if variable_type == 'BinaryArray': value_encoded = [] for v in value:", "variable rules: * Only user input can have embedded variables. * Only String", "need to verify if core still sends improper JSON for KeyValueArrays if data", "] @property def _variable_types(self): \"\"\"Return list of standard playbook variable typesd.\"\"\" return self._variable_single_types", "store the variables in dict by name-type (e.g. \"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}'] = {'variable': ov}", "type self.log.warning(f'Coercing bool value ({value}) to a string (\"{str(value).lower()}\").') value = str(value).lower() #", "{} self._output_variables_by_type = {} for ov in self._output_variables: # parse the variable to", "Returns: (str): Results retrieved from DB. \"\"\" value = None if key is", "#App:7979:variable_name!String: \"embedded \\\\\"variable\\\\\"\" #App:7979:two!String: \"two\" #App:7979:variable_name!StringArray: [\"one\", \"two\", \"three\"] Examples 1: Input: \"This", "= [] for v in value: # coerce string values v = self._coerce_string_value(v)", "None: value = self.tcex.key_value_store.read(self._context, key.strip()) else: self.log.warning('The key field was None.') return value", "x in ['key', 'value']) def _is_key_value_array(self, data): \"\"\"Return True if provided data has", "key was provided.') return None # get variable type from variable value variable_type", "value is None: return value if variable_type == 'BinaryArray': value = json.loads(value, object_pairs_hook=OrderedDict)", "variable value variable_type = self.variable_type(key) # Enhanced entity array is the wild-wild west,", "would require a kv-specific # version of this method that gets the entire", "variable_type = self.variable_type(key) try: value = self.tcex.key_value_store.read(self._context, key.strip()) except RuntimeError as e: self.log.error(e)", "(str, dict))): raise RuntimeError(f'Invalid data provided for {variable_type}.') value = [ *value ]", "value = value_coerced elif variable_type == 'TCEntityArray': if validate and not self._is_tc_entity_array(value): raise", "write to the DB. Returns: (str): Result of DB write. \"\"\" data =", "v in value: if v is not None: if validate and not isinstance(v,", "value) return value @property def _variable_pattern(self): \"\"\"Regex pattern to match and parse a", "v = base64.b64encode(v).decode('utf-8') value_encoded.append(v) value = value_encoded elif variable_type == 'KeyValueArray': if validate", "handling data written by java apps.\"\"\" try: data = data.decode('utf-8') except UnicodeDecodeError: #", "return False return True @staticmethod def _is_tc_entity(data): \"\"\"Return True if provided data has", "= self.read(variable) self.log.trace(f'embedded variable: {variable}, value: {v}') if isinstance(v, (dict, list)): v =", "value variable_type = self.variable_type(key) if variable_type == 'Binary': # if not isinstance(value, bytes):", "the string. value = re.sub(variable, v, value) return value @property def _variable_pattern(self): \"\"\"Regex", "tcex.log # match full variable self._variable_match = re.compile(fr'^{self._variable_pattern}$') # capture variable parts (exactly", "raise RuntimeError('Invalid data provided for Binary.') # if not isinstance(v, bytes): # v", "by name-type (e.g. \"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}'] = {'variable': ov} def _read(self, key, embedded=True, b64decode=True,", "import json import re from collections import OrderedDict from collections.abc import Iterable class", "json.dumps(value) except ValueError as e: # pragma: no cover raise RuntimeError(f'Failed to serialize", "coerce bool to str type self.log.warning(f'Coercing bool value ({value}) to a string (\"{str(value).lower()}\").')", "if validate and not isinstance(value, bytes): raise RuntimeError('Invalid data provided for Binary.') value", "return True @staticmethod def _load_value(value): \"\"\"Return the loaded JSON value or raise an", "a bool is an int if isinstance(value, bool): # coerce bool to str", "raw string will be returned. Examples:: DB Values #App:7979:variable_name!String: \"embedded \\\\\"variable\\\\\"\" #App:7979:two!String: \"two\"", "v in re.finditer(self._vars_keyvalue_embedded, data): variables.append(v.group(0)) for var in set(variables): # recursion over set", "null value for key was provided.') return None # get variable type from", "except RuntimeError as e: self.log.error(e) return None def _create_array(self, key, value, validate=True): \"\"\"Create", "with nested dict/list type replace the # quoted value to ensure the resulting", "['TCEntityArray', 'TCEnhancedEntity', 'TCEnhancedEntityArray']: value = self._load_value(value) # self.log.trace(f'pb create - context: {self._context}, key:", "to ensure the resulting data is loadable JSON value = re.sub(f'\"{variable}\"', v, value)", "data def read_raw(self, key): \"\"\"Read method of CRUD operation for raw data. ..important::", "embedded=True): # pragma: no cover \"\"\"Set placeholder for child method.\"\"\" raise NotImplementedError('Implemented in", "name (:variable_name) variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array) variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' #" ]
[ "dtype=tf.int32), }) if is_training: if hvd is not None: d = d.shard(hvd.size(), hvd.rank())", "\"Whether to enable AMP ops. When false, uses TF32 on A100 and FP32", "Unless required by applicable law or agreed to in writing, software # distributed", "is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure to be passed to Estimator.\"\"\" name_to_features", "FLAGS.horovod else FLAGS.learning_rate * hvd.size(), num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False, hvd=None if not FLAGS.horovod else", "%0.2f\", cf_100 * 1000) tf.compat.v1.logging.info(\"Latency Average (ms) = %0.2f\", avg * 1000) tf.compat.v1.logging.info(\"Throughput", "\"Initial checkpoint (usually from a pre-trained BERT model).\") flags.DEFINE_bool( \"do_lower_case\", True, \"Whether to", "a simple classification task on the entire # segment. # # If you", "axis=-1, name='cls_per_example_loss') loss = tf.reduce_mean(per_example_loss, name='cls_loss') return (loss, per_example_loss, logits, probabilities) def get_frozen_tftrt_model(bert_config,", "* 0.90)]) cf_95 = max(time_list[:int(len(time_list) * 0.95)]) cf_99 = max(time_list[:int(len(time_list) * 0.99)]) cf_100", ") frozen_graph = converter.convert() print('Total node count before and after TF-TRT conversion:', num_nodes,", "name='cls_loss') return (loss, per_example_loss, logits, probabilities) def get_frozen_tftrt_model(bert_config, shape, num_labels, use_one_hot_embeddings, init_checkpoint): tf_config", "Colab and # people who depend on it. def input_fn_builder(features, batch_size, seq_length, is_training,", "`do_train`, `do_eval` or `do_predict' must be True.\") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length >", "= len(train_examples) tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record\")] if FLAGS.horovod: tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i)) for", "throughput computation. predict_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) * 0.8)) *", "mode == tf.estimator.ModeKeys.EVAL: dummy_op = tf.no_op() # Need to call mixed precision graph", "seq_length], dtype=tf.int32), \"segment_ids\": tf.constant( all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"label_ids\": tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32), })", "to train.\") flags.DEFINE_string(\"vocab_file\", None, \"The vocabulary file that the BERT model was trained", "= 0 end_index = len(train_examples) tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record\")] if FLAGS.horovod: tmp_filenames =", "tf.compat.v1.OptimizerOptions.ON_1 if FLAGS.amp: tf.enable_resource_variables() run_config = tf.estimator.RunConfig( model_dir=FLAGS.output_dir if master_process else None, session_config=config,", "hvd.size() if hvd.rank() < remainder: start_index = hvd.rank() * (num_examples_per_rank+1) end_index = start_index", "runs\") flags.DEFINE_bool( \"verbose_logging\", False, \"If true, all of the warnings related to data", "config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1 if FLAGS.amp: tf.enable_resource_variables() run_config = tf.estimator.RunConfig( model_dir=FLAGS.output_dir if master_process else", "set.\") flags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for training.\") flags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch size", "Overhead = %0.2f for Sentences = %d\", train_time_wo_overhead, (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size)", "FLAGS.use_trt: trt_graph = get_frozen_tftrt_model(bert_config, input_ids.shape, num_labels, use_one_hot_embeddings, init_checkpoint) (total_loss, per_example_loss, logits, probabilities) =", "FLAGS.amp: loss_scaler = tf.train.experimental.FixedLossScale(1) dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler) eval_metric_ops = metric_fn(per_example_loss, label_ids,", "are expected for a normal SQuAD evaluation.\") def file_based_input_fn_builder(input_file, batch_size, seq_length, is_training, drop_remainder,", "predictions=predictions, num_classes=2, pos_indices=[1]) return { \"eval_accuracy\": accuracy, \"eval_f1\": f1, \"eval_loss\": loss, } else:", "for Sentences = %d\", train_time_elapsed, num_train_steps * global_batch_size) tf.compat.v1.logging.info(\"Total Training Time W/O Overhead", "master_process else None, save_summary_steps=FLAGS.save_checkpoints_steps if master_process else None, log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1) if master_process: tf.compat.v1.logging.info(\"*****", "\", *NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape, init_string) frozen_graph", "%d because the BERT model \" \"was only trained up to sequence length", "`input_fn` closure to be passed to Estimator.\"\"\" name_to_features = { \"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64),", "get_frozen_tftrt_model(bert_config, input_ids.shape, num_labels, use_one_hot_embeddings, init_checkpoint) (total_loss, per_example_loss, logits, probabilities) = tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids, 'input_mask':input_mask,", "gradient update\" \"Global batch size = num_accumulation_steps * train_batch_size\") flags.DEFINE_bool(\"amp\", True, \"Whether to", "0.5 MCC_op = tf.group(FN_op, TN_op, TP_op, FP_op, tf.identity(MCC, name=\"MCC\")) return {\"MCC\": (MCC, MCC_op)}", "logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) return output_spec (total_loss, per_example_loss, logits, probabilities)", "os.path.join(FLAGS.output_dir, \"test_results.tsv\") with tf.io.gfile.GFile(output_predict_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Predict results *****\") for prediction", "f1, \"eval_loss\": loss, } else: accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss)", "\"eval_accuracy\": accuracy, \"eval_loss\": loss, } tf.compat.v1.logging.info(\"*** Features ***\") tf.compat.v1.logging.info(\"*** Features ***\") for name", "tf.compat.v1.logging.info(\"Latency Average (ms) = %0.2f\", avg * 1000) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\",", "vocabulary file that the BERT model was trained on.\") flags.DEFINE_string( \"output_dir\", None, \"The", "loss from estimator\") flags.DEFINE_integer(\"iterations_per_loop\", 1000, \"How many steps to make in each estimator", "'segment_ids') label_ids = tf.placeholder(tf.int32, (None), 'label_ids') create_model(bert_config, False, input_ids, input_mask, segment_ids, label_ids, num_labels,", "None, \"The input data dir. Should contain the .tsv files (or other data", "collections import csv import os import modeling import optimization import tokenization import tensorflow", "[] for feature in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id) def input_fn(): \"\"\"The actual", "Average (sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file = os.path.join(FLAGS.output_dir,", "= training_hooks[-1].total_time avg_sentences_per_second = num_train_steps * global_batch_size * 1.0 / train_time_elapsed ss_sentences_per_second =", "(ms) = %0.2f\", cf_100 * 1000) tf.compat.v1.logging.info(\"Latency Average (ms) = %0.2f\", avg *", "\"A number of warnings are expected for a normal SQuAD evaluation.\") def file_based_input_fn_builder(input_file,", "from tensorflow.python.compiler.tensorrt import trt_convert as trt converter = trt.TrtGraphConverter( input_graph_def=frozen_graph, nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096 <<", "but the TPU only supports tf.int32. # So cast all int64 to int32.", "This function is not used by this file but is still used by", "((TP + FP) * (TP + FN) * (TN + FP) * (TN", "as np import tf_metrics flags = tf.flags FLAGS = flags.FLAGS ## Required parameters", "flags.DEFINE_bool(\"use_trt\", False, \"Whether to use TF-TRT\") flags.DEFINE_float(\"num_train_epochs\", 3.0, \"Total number of training epochs", "= modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32) # In the demo,", "eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) else: dummy_op", "in throughput computation. eval_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) * 0.8))", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "label_ids = features[\"label_ids\"] is_training = (mode == tf.estimator.ModeKeys.TRAIN) if not is_training and FLAGS.use_trt:", "tf.trainable_variables() (assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\") tf.compat.v1.logging.info(\"**** Trainable Variables", "init_checkpoint and (hvd is None or hvd.rank() == 0): (assignment_map, initialized_variable_names ) =", "sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) * 0.8)) * FLAGS.eval_batch_size avg = np.mean(time_list)", "mode=mode, loss=total_loss, train_op=train_op) elif mode == tf.estimator.ModeKeys.EVAL: dummy_op = tf.no_op() # Need to", "\"Sequences longer than this will be truncated, and sequences shorter \" \"than this", "* 0.8)]) num_sentences = (int(len(time_list) * 0.8)) * FLAGS.eval_batch_size avg = np.mean(time_list) cf_50", "= tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs,", "d = tf.data.TFRecordDataset(input_file) if is_training: if hvd is not None: d = d.shard(hvd.size(),", "input_ids, input_mask, segment_ids, labels, num_labels, use_one_hot_embeddings): \"\"\"Creates a classification model.\"\"\" model = modeling.BertModel(", "tf_metrics.f1(labels=label_ids, predictions=predictions, num_classes=2, pos_indices=[1]) return { \"eval_accuracy\": accuracy, \"eval_f1\": f1, \"eval_loss\": loss, }", "So cast all int64 to int32. for name in list(example.keys()): t = example[name]", "= time.time() - train_start_time train_time_wo_overhead = training_hooks[-1].total_time avg_sentences_per_second = num_train_steps * global_batch_size *", "%0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") if __name__ == \"__main__\": flags.mark_flag_as_required(\"data_dir\") flags.mark_flag_as_required(\"task_name\")", "\"\" if var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" else: init_string = \",", "assignment_map) tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\") tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in tvars: init_string =", "FLAGS.learning_rate * hvd.size(), num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False, hvd=None if not FLAGS.horovod else hvd) estimator", "False predict_input_fn = file_based_input_fn_builder( input_file=predict_file, batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder) predict_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time", "fp16 to enable graph rewrite if FLAGS.amp: loss_scaler = tf.train.experimental.FixedLossScale(1) dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite(", "right way to load data is with TFRecordReader. d = tf.data.Dataset.from_tensor_slices({ \"input_ids\": tf.constant(", "CORPORATION. All rights reserved. # Copyright 2018 The Google AI Language Team Authors.", "\"fp16\" if FLAGS.amp else \"fp32\") tf.compat.v1.logging.info(\"Latency Confidence Level 50 (ms) = %0.2f\", cf_50", "LogEvalRunHook, LogTrainRunHook, setup_xla_flags from utils.gpu_affinity import set_affinity import utils.dllogger_class from dllogger import Verbosity", "When false, uses TF32 on A100 and FP32 on V100 GPUS.\") flags.DEFINE_bool(\"use_xla\", True,", "hvd.size() > 1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1 if FLAGS.amp: tf.enable_resource_variables() run_config", "if str(n.op) == 'TRTEngineOp'])) with tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\") as f: f.write(frozen_graph.SerializeToString()) return frozen_graph def", "data dir. Should contain the .tsv files (or other data files) \" \"for", "= 10% of training.\") flags.DEFINE_integer(\"save_checkpoints_steps\", 1000, \"How often to save the model checkpoint.\")", "tf.trainable_variables() initialized_variable_names = {} if init_checkpoint and (hvd is None or hvd.rank() ==", "output_spec = None if mode == tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss, learning_rate, num_train_steps,", "tf.estimator.ModeKeys.EVAL: dummy_op = tf.no_op() # Need to call mixed precision graph rewrite if", "avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)]) cf_90 = max(time_list[:int(len(time_list) * 0.90)])", "# pylint: disable=unused-argument \"\"\"The `model_fn` for Estimator.\"\"\" def metric_fn(per_example_loss, label_ids, logits): predictions =", "(num_examples_per_rank+1) end_index = start_index + num_examples_per_rank + 1 else: start_index = hvd.rank() *", "enable XLA JIT compilation.\") flags.DEFINE_bool(\"horovod\", False, \"Whether to use Horovod for multi-gpu runs\")", "tf.placeholder(tf.int32, shape, 'input_mask') segment_ids = tf.placeholder(tf.int32, shape, 'segment_ids') label_ids = tf.placeholder(tf.int32, (None), 'label_ids')", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "shape=[num_examples, seq_length], dtype=tf.int32), \"label_ids\": tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32), }) if is_training: if hvd is", "output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=probabilities) return output_spec return model_fn # This function is", "Features ***\") tf.compat.v1.logging.info(\"*** Features ***\") for name in sorted(features.keys()): tf.compat.v1.logging.info(\" name = %s,", "than this will be truncated, and sequences shorter \" \"than this will be", "input_ids.shape, num_labels, use_one_hot_embeddings, init_checkpoint) (total_loss, per_example_loss, logits, probabilities) = tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids,", "the License. \"\"\"BERT finetuning runner.\"\"\" from __future__ import absolute_import from __future__ import division", "tf.compat.v1.logging.info(\"Multi-GPU training with TF Horovod\") tf.compat.v1.logging.info(\"hvd.size() = %d hvd.rank() = %d\", hvd.size(), hvd.rank())", "0.8)) * FLAGS.predict_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)]) cf_90 =", "modeling import optimization import tokenization import tensorflow as tf import horovod.tensorflow as hvd", "to use Horovod for multi-gpu runs\") flags.DEFINE_bool( \"verbose_logging\", False, \"If true, all of", "= time.time() - predict_start_time time_list = predict_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in", "FP_op = tf.metrics.false_positives(labels=label_ids, predictions=predictions) TP, TP_op = tf.metrics.true_positives(labels=label_ids, predictions=predictions) TN, TN_op = tf.metrics.true_negatives(labels=label_ids,", "processors[task_name]() label_list = processor.get_labels() tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) master_process = True training_hooks", "tf.compat.v1.logging.info(' {}: {}'.format(key, getattr(FLAGS, key))) tf.compat.v1.logging.info(\"**************************\") train_examples = None num_train_steps = None num_warmup_steps", "Authors. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "model.get_pooled_output() hidden_size = output_layer.shape[-1].value output_weights = tf.get_variable( \"output_weights\", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias =", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "converter = trt.TrtGraphConverter( input_graph_def=frozen_graph, nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096 << 20) - 1000, precision_mode = \"FP16\"", "50 (ms) = %0.2f\", cf_50 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 90 (ms) =", "modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\") tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in", "= str(hvd.local_rank()) set_affinity(hvd.local_rank()) if hvd.size() > 1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1", "output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, train_op=train_op) elif mode == tf.estimator.ModeKeys.EVAL: dummy_op = tf.no_op()", "tf.int64), \"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64), \"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"label_ids\": tf.io.FixedLenFeature([], tf.int64), } def _decode_record(record,", "maximum_cached_engines=1000 ) frozen_graph = converter.convert() print('Total node count before and after TF-TRT conversion:',", "per_example_loss, logits, probabilities) = tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids, 'label_ids':label_ids}, return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0', 'loss/cls_logits:0', 'loss/cls_probabilities:0'],", "one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1, name='cls_per_example_loss') loss", "time.time() output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\") with tf.io.gfile.GFile(output_predict_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Predict results", "tf.constant( all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32), \"segment_ids\": tf.constant( all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"label_ids\": tf.constant(all_label_ids,", "modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if FLAGS.verbose_logging: tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in", "\"FP16\" if FLAGS.amp else \"FP32\", minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000 ) frozen_graph = converter.convert() print('Total", "LogTrainRunHook, setup_xla_flags from utils.gpu_affinity import set_affinity import utils.dllogger_class from dllogger import Verbosity from", "for Estimator.\"\"\" def metric_fn(per_example_loss, label_ids, logits): predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) if task_name", "We do # not use Dataset.from_generator() because that uses tf.py_func which is #", "this will be truncated, and sequences shorter \" \"than this will be padded.\")", "size = %d\", FLAGS.eval_batch_size) eval_drop_remainder = False eval_input_fn = file_based_input_fn_builder( input_file=eval_file, batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length,", "only supports tf.int64, but the TPU only supports tf.int32. # So cast all", "writer: tf.compat.v1.logging.info(\"***** Eval results *****\") for key in sorted(result.keys()): dllogging.logger.log(step=(), data={key: float(result[key])}, verbosity=Verbosity.DEFAULT)", "hvd, False, FLAGS.amp, FLAGS.num_accumulation_steps, FLAGS.optimizer_type) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, train_op=train_op) elif mode", "for name in list(example.keys()): t = example[name] if t.dtype == tf.int64: t =", "= tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler) eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode,", "enable graph rewrite if FLAGS.amp: loss_scaler = tf.train.experimental.FixedLossScale(1) dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler)", "passed to Estimator.\"\"\" all_input_ids = [] all_input_mask = [] all_segment_ids = [] all_label_ids", "printed. \" \"A number of warnings are expected for a normal SQuAD evaluation.\")", "str(n.op) == 'TRTEngineOp'])) with tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\") as f: f.write(frozen_graph.SerializeToString()) return frozen_graph def model_fn_builder(task_name,", "model architecture.\") flags.DEFINE_string(\"task_name\", None, \"The name of the task to train.\") flags.DEFINE_string(\"vocab_file\", None,", "= len(train_examples) // hvd.size() remainder = len(train_examples) % hvd.size() if hvd.rank() < remainder:", "tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1, name='cls_per_example_loss') loss = tf.reduce_mean(per_example_loss,", "\"The name of the task to train.\") flags.DEFINE_string(\"vocab_file\", None, \"The vocabulary file that", "return output_spec (total_loss, per_example_loss, logits, probabilities) = create_model( bert_config, is_training, input_ids, input_mask, segment_ids,", "loss_scaler) eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) else:", "False for cased models.\") flags.DEFINE_integer( \"max_seq_length\", 128, \"The maximum total input sequence length", "of warnings are expected for a normal SQuAD evaluation.\") def file_based_input_fn_builder(input_file, batch_size, seq_length,", "= os.path.join(FLAGS.output_dir, \"test_results.tsv\") with tf.io.gfile.GFile(output_predict_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Predict results *****\") for", "for uncased \" \"models and False for cased models.\") flags.DEFINE_integer( \"max_seq_length\", 128, \"The", "## Required parameters flags.DEFINE_string( \"data_dir\", None, \"The input data dir. Should contain the", "if FLAGS.do_train: file_based_convert_examples_to_features( train_examples[start_index:end_index], label_list, FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"***** Running training *****\") tf.compat.v1.logging.info(\"", "if not FLAGS.horovod else FLAGS.learning_rate * hvd.size(), num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False, hvd=None if not", "all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id) def input_fn(): \"\"\"The actual input function.\"\"\" num_examples = len(features) #", "(sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") if __name__ == \"__main__\":", "tf_sess.graph.as_graph_def(), output_node_names) num_nodes = len(frozen_graph.node) print('Converting graph using TensorFlow-TensorRT...') from tensorflow.python.compiler.tensorrt import trt_convert", "= num_train_steps * global_batch_size * 1.0 / train_time_elapsed ss_sentences_per_second = (training_hooks[-1].count - training_hooks[-1].skipped)", "avg * 1000) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT)", "8, \"Total batch size for eval.\") flags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch size for predict.\")", "None training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25)) if FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps = int(", "output_bias = tf.get_variable( \"output_bias\", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope(\"loss\"): if is_training: # I.e., 0.1", "files) \" \"for the task.\") flags.DEFINE_string( \"bert_config_file\", None, \"The config json file corresponding", "\"segment_ids\": tf.constant( all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"label_ids\": tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32), }) if is_training:", "in FLAGS.__flags.keys(): tf.compat.v1.logging.info(' {}: {}'.format(key, getattr(FLAGS, key))) tf.compat.v1.logging.info(\"**************************\") train_examples = None num_train_steps =", "remainder: start_index = hvd.rank() * (num_examples_per_rank+1) end_index = start_index + num_examples_per_rank + 1", "tf.Session(config=tf_config) as tf_sess: input_ids = tf.placeholder(tf.int32, shape, 'input_ids') input_mask = tf.placeholder(tf.int32, shape, 'input_mask')", "var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" else: init_string = \", *NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\"", "tf.compat.v1.logging.info(\"**************************\") train_examples = None num_train_steps = None num_warmup_steps = None training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps,", "optimization import tokenization import tensorflow as tf import horovod.tensorflow as hvd import time", "%0.2f for Sentences = %d\", predict_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on TEST SET\")", "a record to a TensorFlow example.\"\"\" example = tf.parse_single_example(record, name_to_features) # tf.Example only", "if var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\" name = %s, shape", "%s%s\", var.name, var.shape, init_string) frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(), output_node_names) num_nodes = len(frozen_graph.node) print('Converting", "shape = %s%s\", var.name, var.shape, init_string) output_spec = None if mode == tf.estimator.ModeKeys.TRAIN:", "node count before and after TF-TRT conversion:', num_nodes, '->', len(frozen_graph.node)) print('TRT node count:',", "training with TF Horovod\") tf.compat.v1.logging.info(\"hvd.size() = %d hvd.rank() = %d\", hvd.size(), hvd.rank()) global_batch_size", "csv import os import modeling import optimization import tokenization import tensorflow as tf", "reading and shuffling. # For eval, we want no shuffling and parallel reading", "rewrite if fp16 to enable graph rewrite if FLAGS.amp: dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0))", "Confidence Level 90 (ms) = %0.2f\", cf_90 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 95", "predictions=probabilities) return output_spec return model_fn # This function is not used by this", "flags.DEFINE_float( \"warmup_proportion\", 0.1, \"Proportion of training to perform linear learning rate warmup for.", "(MCC, MCC_op)} elif task_name == \"mrpc\": accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss =", "(TP * TN - FP * FN) / ((TP + FP) * (TP", "not use this file except in compliance with the License. # You may", "example def input_fn(): \"\"\"The actual input function.\"\"\" # For training, we want a", "is_training: if hvd is not None: d = d.shard(hvd.size(), hvd.rank()) d = d.repeat()", "1, \"Number of accumulation steps before gradient update\" \"Global batch size = num_accumulation_steps", "= %0.2f\", ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\") if FLAGS.do_eval and master_process: eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_file =", "+ \"\\n\" writer.write(output_line) predict_time_elapsed = time.time() - predict_start_time time_list = predict_hooks[-1].time_list time_list.sort() #", "Time W/O Overhead = %0.2f for Sentences = %d\", train_time_wo_overhead, (training_hooks[-1].count - training_hooks[-1].skipped)", "config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32) # In the demo, we are", "optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps, hvd, False, FLAGS.amp, FLAGS.num_accumulation_steps, FLAGS.optimizer_type) output_spec = tf.estimator.EstimatorSpec(", "train_op=train_op) elif mode == tf.estimator.ModeKeys.EVAL: dummy_op = tf.no_op() # Need to call mixed", "pos_indices=[1]) return { \"eval_accuracy\": accuracy, \"eval_f1\": f1, \"eval_loss\": loss, } else: accuracy =", "= processor.get_labels() tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) master_process = True training_hooks = []", "* import numpy as np import tf_metrics flags = tf.flags FLAGS = flags.FLAGS", "per_example_loss, logits, probabilities) = create_model( bert_config, is_training, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings)", "function is not used by this file but is still used by the", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "if not is_training and FLAGS.use_trt: trt_graph = get_frozen_tftrt_model(bert_config, input_ids.shape, num_labels, use_one_hot_embeddings, init_checkpoint) (total_loss,", "= time.time() result = estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks) eval_time_elapsed = time.time() - eval_start_time time_list =", "= len(features) # This is for demo purposes and does NOT scale to", "*****\") for key in sorted(result.keys()): dllogging.logger.log(step=(), data={key: float(result[key])}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\" %s = %s\",", "to make in each estimator call.\") flags.DEFINE_integer(\"num_accumulation_steps\", 1, \"Number of accumulation steps before", "people who depend on it. def input_fn_builder(features, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates", "use sequence length %d because the BERT model \" \"was only trained up", "True training_hooks = [] global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps hvd_rank = 0 config", "not FLAGS.horovod else hvd) train_start_time = time.time() estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks) train_time_elapsed = time.time()", "eval_start_time time_list = eval_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in throughput computation. eval_time_wo_overhead", "= %0.2f for Sentences = %d\", predict_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on TEST", "maximum total input sequence length after WordPiece tokenization. \" \"Sequences longer than this", "= tf.trainable_variables() (assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\") tf.compat.v1.logging.info(\"**** Trainable", "agreed to in writing, software # distributed under the License is distributed on", "labels, mode, params): # pylint: disable=unused-argument \"\"\"The `model_fn` for Estimator.\"\"\" def metric_fn(per_example_loss, label_ids,", "predictions=predictions) elif mode == tf.estimator.ModeKeys.EVAL: eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec(", "all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"input_mask\": tf.constant( all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32), \"segment_ids\": tf.constant( all_segment_ids,", "is for demo purposes and does NOT scale to large data sets. We", "master_process else None, log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1) if master_process: tf.compat.v1.logging.info(\"***** Configuaration *****\") for key in", "\"Cannot use sequence length %d because the BERT model \" \"was only trained", "tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler) eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss,", "tf.flags FLAGS = flags.FLAGS ## Required parameters flags.DEFINE_string( \"data_dir\", None, \"The input data", "if FLAGS.amp else \"fp32\") tf.compat.v1.logging.info(\"Latency Confidence Level 50 (ms) = %0.2f\", cf_50 *", "and FP32 on V100 GPUS.\") flags.DEFINE_bool(\"use_xla\", True, \"Whether to enable XLA JIT compilation.\")", "== tf.estimator.ModeKeys.TRAIN) if not is_training and FLAGS.use_trt: trt_graph = get_frozen_tftrt_model(bert_config, input_ids.shape, num_labels, use_one_hot_embeddings,", "for the specific language governing permissions and # limitations under the License. \"\"\"BERT", "hvd.rank()) global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps * hvd.size() master_process = (hvd.rank() == 0)", "Level 90 (ms) = %0.2f\", cf_90 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 95 (ms)", "on A100 and FP32 on V100 GPUS.\") flags.DEFINE_bool(\"use_xla\", True, \"Whether to enable XLA", "= metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) else: dummy_op =", "as tf_sess: input_ids = tf.placeholder(tf.int32, shape, 'input_ids') input_mask = tf.placeholder(tf.int32, shape, 'input_mask') segment_ids", "%d\", hvd.size(), hvd.rank()) global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps * hvd.size() master_process = (hvd.rank()", "# For eval, we want no shuffling and parallel reading doesn't matter. d", "tensorflow.python.compiler.tensorrt import trt_convert as trt converter = trt.TrtGraphConverter( input_graph_def=frozen_graph, nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096 << 20)", "tf.compat.v1.logging.info(\"Latency Confidence Level 50 (ms) = %0.2f\", cf_50 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level", "0): (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if FLAGS.verbose_logging: tf.compat.v1.logging.info(\"**** Trainable", "getattr(FLAGS, key))) tf.compat.v1.logging.info(\"**************************\") train_examples = None num_train_steps = None num_warmup_steps = None training_hooks.append(LogTrainRunHook(global_batch_size,", "tf.int64, but the TPU only supports tf.int32. # So cast all int64 to", "d.repeat() d = d.shuffle(buffer_size=100) d = d.apply( tf.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size,", "Time = %0.2f for Sentences = %d\", train_time_elapsed, num_train_steps * global_batch_size) tf.compat.v1.logging.info(\"Total Training", "from utils.gpu_affinity import set_affinity import utils.dllogger_class from dllogger import Verbosity from utils.create_glue_data import", "in sorted(features.keys()): tf.compat.v1.logging.info(\" name = %s, shape = %s\" % (name, features[name].shape)) input_ids", "not FLAGS.do_predict: raise ValueError( \"At least one of `do_train`, `do_eval` or `do_predict' must", "task_name == \"mrpc\": accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) f1 =", "using TensorFlow-TensorRT...') from tensorflow.python.compiler.tensorrt import trt_convert as trt converter = trt.TrtGraphConverter( input_graph_def=frozen_graph, nodes_blacklist=output_node_names,", "Num examples = %d\", len(predict_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size) predict_drop_remainder =", "num_sentences = (int(len(time_list) * 0.8)) * FLAGS.predict_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list)", "import tokenization import tensorflow as tf import horovod.tensorflow as hvd import time from", "shuffling and parallel reading doesn't matter. d = tf.data.TFRecordDataset(input_file) if is_training: if hvd", "# So cast all int64 to int32. for name in list(example.keys()): t =", "* 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 100 (ms) = %0.2f\", cf_100 * 1000) tf.compat.v1.logging.info(\"Latency", "= tf.metrics.mean(values=per_example_loss) f1 = tf_metrics.f1(labels=label_ids, predictions=predictions, num_classes=2, pos_indices=[1]) return { \"eval_accuracy\": accuracy, \"eval_f1\":", "if fp16 to enable graph rewrite if FLAGS.amp: loss_scaler = tf.train.experimental.FixedLossScale(1) dummy_op =", "probabilities) = tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids, 'label_ids':label_ids}, return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0', 'loss/cls_logits:0', 'loss/cls_probabilities:0'], name='') if", "import utils.dllogger_class from dllogger import Verbosity from utils.create_glue_data import * import numpy as", "(ms) = %0.2f\", cf_99 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 100 (ms) = %0.2f\",", "start_index = 0 end_index = len(train_examples) tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record\")] if FLAGS.horovod: tmp_filenames", "training *****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(train_examples)) tf.compat.v1.logging.info(\" Batch size = %d\",", "a pre-trained BERT model).\") flags.DEFINE_bool( \"do_lower_case\", True, \"Whether to lower case the input", "Verbosity from utils.create_glue_data import * import numpy as np import tf_metrics flags =", "= (int(len(time_list) * 0.8)) * FLAGS.eval_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) *", "case the input text. Should be True for uncased \" \"models and False", "(FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower() if task_name not in processors: raise ValueError(\"Task", "to use TF-TRT\") flags.DEFINE_float(\"num_train_epochs\", 3.0, \"Total number of training epochs to perform.\") flags.DEFINE_float(", "tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"***** Running training *****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(train_examples)) tf.compat.v1.logging.info(\" Batch", "Inference Time = %0.2f for Sentences = %d\", predict_time_elapsed, predict_hooks[-1].count * FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total", "to in writing, software # distributed under the License is distributed on an", "shape, 'input_ids') input_mask = tf.placeholder(tf.int32, shape, 'input_mask') segment_ids = tf.placeholder(tf.int32, shape, 'segment_ids') label_ids", "name of the task to train.\") flags.DEFINE_string(\"vocab_file\", None, \"The vocabulary file that the", "* 1.0 / train_time_elapsed ss_sentences_per_second = (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size * 1.0", "implied. # See the License for the specific language governing permissions and #", "= processor.get_test_examples(FLAGS.data_dir) predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\") file_based_convert_examples_to_features(predict_examples, label_list, FLAGS.max_seq_length, tokenizer, predict_file) tf.compat.v1.logging.info(\"***** Running", ".tsv files (or other data files) \" \"for the task.\") flags.DEFINE_string( \"bert_config_file\", None,", "train_op = optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps, hvd, False, FLAGS.amp, FLAGS.num_accumulation_steps, FLAGS.optimizer_type) output_spec", "tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) else: dummy_op = tf.no_op() # Need to call mixed", "print(\"LOADED!\") tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in tvars: init_string = \"\" if", "num_classes=2, pos_indices=[1]) return { \"eval_accuracy\": accuracy, \"eval_f1\": f1, \"eval_loss\": loss, } else: accuracy", "num_steps_ignore_xla=25)) if FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps = int( len(train_examples) / global_batch_size *", "bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower() if task_name not in processors: raise ValueError(\"Task not", "writer: tf.compat.v1.logging.info(\"***** Predict results *****\") for prediction in estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks, yield_single_examples=False): output_line =", "uses TF32 on A100 and FP32 on V100 GPUS.\") flags.DEFINE_bool(\"use_xla\", True, \"Whether to", "var.name, var.shape, init_string) frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(), output_node_names) num_nodes = len(frozen_graph.node) print('Converting graph", "with TFRecordReader. d = tf.data.Dataset.from_tensor_slices({ \"input_ids\": tf.constant( all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"input_mask\": tf.constant(", "= time.time() output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\") with tf.io.gfile.GFile(output_predict_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Predict", "W/O Overhead = %0.2f for Sentences = %d\", train_time_wo_overhead, (training_hooks[-1].count - training_hooks[-1].skipped) *", "if mode == tf.estimator.ModeKeys.PREDICT: predictions = {\"probabilities\": probabilities} output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=predictions)", "name in list(example.keys()): t = example[name] if t.dtype == tf.int64: t = tf.to_int32(t)", "minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000 ) frozen_graph = converter.convert() print('Total node count before and after", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "* 1000) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\")", "eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences = %d\", eval_time_elapsed, eval_hooks[-1].count", "(mode == tf.estimator.ModeKeys.TRAIN) if not is_training and FLAGS.use_trt: trt_graph = get_frozen_tftrt_model(bert_config, input_ids.shape, num_labels,", "print loss from estimator\") flags.DEFINE_integer(\"iterations_per_loop\", 1000, \"How many steps to make in each", "\"input_mask\": tf.constant( all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32), \"segment_ids\": tf.constant( all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"label_ids\":", "__future__ import division from __future__ import print_function import collections import csv import os", "None or hvd.rank() == 0): (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map)", "= %d\", len(train_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.train_batch_size) tf.compat.v1.logging.info(\" Num steps =", "file_based_input_fn_builder( input_file=predict_file, batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder) predict_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time = time.time() output_predict_file", "predict_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) * 0.8)) * FLAGS.predict_batch_size avg", "* (TN + FN)) ** 0.5 MCC_op = tf.group(FN_op, TN_op, TP_op, FP_op, tf.identity(MCC,", "tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if FLAGS.horovod: hvd.init() processors = { \"cola\": ColaProcessor, \"mnli\":", "Training Time W/O Overhead = %0.2f for Sentences = %d\", train_time_wo_overhead, (training_hooks[-1].count -", "%d\", len(predict_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size) predict_drop_remainder = False predict_input_fn =", "I.e., 0.1 dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer, output_weights, transpose_b=True) logits", "[num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope(\"loss\"): if is_training: # I.e., 0.1 dropout output_layer = tf.nn.dropout(output_layer,", "tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\") tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in tvars: init_string = \"\"", "%d\", FLAGS.predict_batch_size) predict_drop_remainder = False predict_input_fn = file_based_input_fn_builder( input_file=predict_file, batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder)", "and False for cased models.\") flags.DEFINE_integer( \"max_seq_length\", 128, \"The maximum total input sequence", "# See the License for the specific language governing permissions and # limitations", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "= %s, shape = %s%s\", var.name, var.shape, init_string) output_spec = None if mode", "/ predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences = %d\", predict_time_elapsed,", "== \"mrpc\": accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) f1 = tf_metrics.f1(labels=label_ids,", "fp16 to enable graph rewrite if FLAGS.amp: dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0)) output_spec =", "(TP + FN) * (TN + FP) * (TN + FN)) ** 0.5", "perform.\") flags.DEFINE_float( \"warmup_proportion\", 0.1, \"Proportion of training to perform linear learning rate warmup", "95 (ms) = %0.2f\", cf_95 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 99 (ms) =", "FLAGS.amp: tf.enable_resource_variables() run_config = tf.estimator.RunConfig( model_dir=FLAGS.output_dir if master_process else None, session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps if", "\" \"for the task.\") flags.DEFINE_string( \"bert_config_file\", None, \"The config json file corresponding to", "tf.int64), \"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"label_ids\": tf.io.FixedLenFeature([], tf.int64), } def _decode_record(record, name_to_features): \"\"\"Decodes a", "\"eval_loss\": loss, } else: accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) return", "hooks=eval_hooks) eval_time_elapsed = time.time() - eval_start_time time_list = eval_hooks[-1].time_list time_list.sort() # Removing outliers", "\"Total number of training epochs to perform.\") flags.DEFINE_float( \"warmup_proportion\", 0.1, \"Proportion of training", "= tf.no_op() # Need to call mixed precision graph rewrite if fp16 to", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "return input_fn def main(_): setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if FLAGS.horovod: hvd.init() processors", "you may not use this file except in compliance with the License. #", "tokenization. \" \"Sequences longer than this will be truncated, and sequences shorter \"", "accumulation steps before gradient update\" \"Global batch size = num_accumulation_steps * train_batch_size\") flags.DEFINE_bool(\"amp\",", "def _decode_record(record, name_to_features): \"\"\"Decodes a record to a TensorFlow example.\"\"\" example = tf.parse_single_example(record,", "predictions=predictions) MCC = (TP * TN - FP * FN) / ((TP +", "hvd.rank() == 0): (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if FLAGS.verbose_logging:", "== tf.int64: t = tf.to_int32(t) example[name] = t return example def input_fn(): \"\"\"The", "ss_sentences_per_second = num_sentences * 1.0 / eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f", "= num_sentences * 1.0 / predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for", "batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True, hvd=None if not FLAGS.horovod else hvd) train_start_time = time.time()", "return frozen_graph def model_fn_builder(task_name, bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_one_hot_embeddings, hvd=None): \"\"\"Returns", "will be truncated, and sequences shorter \" \"than this will be padded.\") flags.DEFINE_bool(\"do_train\",", "bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate if not FLAGS.horovod else FLAGS.learning_rate * hvd.size(), num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps,", "\"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64), \"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"label_ids\": tf.io.FixedLenFeature([], tf.int64), }", "use_one_hot_embeddings, init_checkpoint): tf_config = tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth = True output_node_names = ['loss/cls_loss', 'loss/cls_per_example_loss', 'loss/cls_logits',", "TensorFlow example.\"\"\" example = tf.parse_single_example(record, name_to_features) # tf.Example only supports tf.int64, but the", "import LogEvalRunHook, LogTrainRunHook, setup_xla_flags from utils.gpu_affinity import set_affinity import utils.dllogger_class from dllogger import", "shape = %s\" % (name, features[name].shape)) input_ids = features[\"input_ids\"] input_mask = features[\"input_mask\"] segment_ids", "as tf import horovod.tensorflow as hvd import time from utils.utils import LogEvalRunHook, LogTrainRunHook,", "runner.\"\"\" from __future__ import absolute_import from __future__ import division from __future__ import print_function", "per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1, name='cls_per_example_loss') loss = tf.reduce_mean(per_example_loss, name='cls_loss') return (loss,", "name = %s, shape = %s\" % (name, features[name].shape)) input_ids = features[\"input_ids\"] input_mask", "} tf.compat.v1.logging.info(\"*** Features ***\") tf.compat.v1.logging.info(\"*** Features ***\") for name in sorted(features.keys()): tf.compat.v1.logging.info(\" name", "in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\" name = %s, shape = %s%s\",", "True, \"Whether to enable XLA JIT compilation.\") flags.DEFINE_bool(\"horovod\", False, \"Whether to use Horovod", "\"for the task.\") flags.DEFINE_string( \"bert_config_file\", None, \"The config json file corresponding to the", "= os.path.join(FLAGS.output_dir, \"eval.tf_record\") file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file) tf.compat.v1.logging.info(\"***** Running evaluation *****\")", "= file_based_input_fn_builder( input_file=eval_file, batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder) eval_hooks = [LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time = time.time()", "100 (ms) = %0.2f\", cf_100 * 1000) tf.compat.v1.logging.info(\"Latency Average (ms) = %0.2f\", avg", "results *****\") for prediction in estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks, yield_single_examples=False): output_line = \"\\t\".join( str(class_probability) for", "for name in sorted(features.keys()): tf.compat.v1.logging.info(\" name = %s, shape = %s\" % (name,", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "time.time() - predict_start_time time_list = predict_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in throughput", "= tf.parse_single_example(record, name_to_features) # tf.Example only supports tf.int64, but the TPU only supports", "processors: raise ValueError(\"Task not found: %s\" % (task_name)) processor = processors[task_name]() label_list =", "initializer=tf.zeros_initializer()) with tf.variable_scope(\"loss\"): if is_training: # I.e., 0.1 dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)", "WordPiece tokenization. \" \"Sequences longer than this will be truncated, and sequences shorter", "= tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, train_op=train_op) elif mode == tf.estimator.ModeKeys.EVAL: dummy_op = tf.no_op() #", "predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\") file_based_convert_examples_to_features(predict_examples, label_list, FLAGS.max_seq_length, tokenizer, predict_file) tf.compat.v1.logging.info(\"***** Running prediction*****\") tf.compat.v1.logging.info(\"", "else None, save_summary_steps=FLAGS.save_checkpoints_steps if master_process else None, log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1) if master_process: tf.compat.v1.logging.info(\"***** Configuaration", "{}'.format(key, getattr(FLAGS, key))) tf.compat.v1.logging.info(\"**************************\") train_examples = None num_train_steps = None num_warmup_steps = None", "to lower case the input text. Should be True for uncased \" \"models", "= %d\", predict_time_elapsed, predict_hooks[-1].count * FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f", "doesn't matter. d = tf.data.TFRecordDataset(input_file) if is_training: if hvd is not None: d", "1000) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") if", "for Sentences = %d\", eval_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on EVAL set\") tf.compat.v1.logging.info(\"Batch", "- 1000, precision_mode = \"FP16\" if FLAGS.amp else \"FP32\", minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000 )", "input_file=predict_file, batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder) predict_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time = time.time() output_predict_file =", "tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") if __name__", "nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096 << 20) - 1000, precision_mode = \"FP16\" if FLAGS.amp else \"FP32\",", "\"label_ids\": tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32), }) if is_training: if hvd is not None: d", "*****\") for key in FLAGS.__flags.keys(): tf.compat.v1.logging.info(' {}: {}'.format(key, getattr(FLAGS, key))) tf.compat.v1.logging.info(\"**************************\") train_examples =", "large data sets. We do # not use Dataset.from_generator() because that uses tf.py_func", "\"xnli\": XnliProcessor, } if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict: raise", "not found: %s\" % (task_name)) processor = processors[task_name]() label_list = processor.get_labels() tokenizer =", "0.8)) * FLAGS.eval_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)]) cf_90 =", "\"\" if var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\" name = %s,", "tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\") as f: f.write(frozen_graph.SerializeToString()) return frozen_graph def model_fn_builder(task_name, bert_config, num_labels, init_checkpoint, learning_rate,", "(TN + FN)) ** 0.5 MCC_op = tf.group(FN_op, TN_op, TP_op, FP_op, tf.identity(MCC, name=\"MCC\"))", "keep_prob=0.9) logits = tf.matmul(output_layer, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias, name='cls_logits') probabilities =", "TFRecordReader. d = tf.data.Dataset.from_tensor_slices({ \"input_ids\": tf.constant( all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"input_mask\": tf.constant( all_input_mask,", "* (num_examples_per_rank+1) end_index = start_index + num_examples_per_rank + 1 else: start_index = hvd.rank()", "tf.estimator.ModeKeys.TRAIN) if not is_training and FLAGS.use_trt: trt_graph = get_frozen_tftrt_model(bert_config, input_ids.shape, num_labels, use_one_hot_embeddings, init_checkpoint)", "permissions and # limitations under the License. \"\"\"BERT finetuning runner.\"\"\" from __future__ import", "processor.get_dev_examples(FLAGS.data_dir) eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\") file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file) tf.compat.v1.logging.info(\"***** Running", "TF Horovod\") tf.compat.v1.logging.info(\"hvd.size() = %d hvd.rank() = %d\", hvd.size(), hvd.rank()) global_batch_size = FLAGS.train_batch_size", "on.\") flags.DEFINE_string( \"output_dir\", None, \"The output directory where the model checkpoints will be", "= tf.metrics.false_positives(labels=label_ids, predictions=predictions) TP, TP_op = tf.metrics.true_positives(labels=label_ids, predictions=predictions) TN, TN_op = tf.metrics.true_negatives(labels=label_ids, predictions=predictions)", "\"mrpc\": accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) f1 = tf_metrics.f1(labels=label_ids, predictions=predictions,", "num_examples = len(features) # This is for demo purposes and does NOT scale", "evaluation *****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(eval_examples)) tf.compat.v1.logging.info(\" Batch size = %d\",", "do_lower_case=FLAGS.do_lower_case) master_process = True training_hooks = [] global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps hvd_rank", "on the dev set.\") flags.DEFINE_bool( \"do_predict\", False, \"Whether to run the model in", "= %d\", predict_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on TEST SET\") tf.compat.v1.logging.info(\"Batch size =", "cased models.\") flags.DEFINE_integer( \"max_seq_length\", 128, \"The maximum total input sequence length after WordPiece", "= [os.path.join(FLAGS.output_dir, \"train.tf_record\")] if FLAGS.horovod: tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i)) for i in range(hvd.size())]", "= tf.nn.softmax(logits, axis=-1, name='cls_probabilities') log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)", "dummy_op = tf.no_op() # Need to call mixed precision graph rewrite if fp16", "for Sentences = %d\", train_time_wo_overhead, (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec)", "= [] global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps hvd_rank = 0 config = tf.compat.v1.ConfigProto()", "= max(time_list[:int(len(time_list) * 0.90)]) cf_95 = max(time_list[:int(len(time_list) * 0.95)]) cf_99 = max(time_list[:int(len(time_list) *", "2019 NVIDIA CORPORATION. All rights reserved. # Copyright 2018 The Google AI Language", "size = num_accumulation_steps * train_batch_size\") flags.DEFINE_bool(\"amp\", True, \"Whether to enable AMP ops. When", "tf.int64), \"label_ids\": tf.io.FixedLenFeature([], tf.int64), } def _decode_record(record, name_to_features): \"\"\"Decodes a record to a", "# Removing outliers (init/warmup) in throughput computation. predict_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences", "= int( len(train_examples) / global_batch_size * FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion) start_index", "graph rewrite if FLAGS.amp: loss_scaler = tf.train.experimental.FixedLossScale(1) dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler) eval_metric_ops", "= num_sentences * 1.0 / eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for", "as trt converter = trt.TrtGraphConverter( input_graph_def=frozen_graph, nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096 << 20) - 1000, precision_mode", "task_name = FLAGS.task_name.lower() if task_name not in processors: raise ValueError(\"Task not found: %s\"", "None, session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process else None, save_summary_steps=FLAGS.save_checkpoints_steps if master_process else None, log_step_count_steps=FLAGS.display_loss_steps,", "= modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\") tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var", "run_config = tf.estimator.RunConfig( model_dir=FLAGS.output_dir if master_process else None, session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process else", "else FLAGS.learning_rate * hvd.size(), num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False, hvd=None if not FLAGS.horovod else hvd)", "= tf.placeholder(tf.int32, shape, 'input_ids') input_mask = tf.placeholder(tf.int32, shape, 'input_mask') segment_ids = tf.placeholder(tf.int32, shape,", "# In the demo, we are doing a simple classification task on the", "from __future__ import absolute_import from __future__ import division from __future__ import print_function import", "FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps = int( len(train_examples) / global_batch_size * FLAGS.num_train_epochs) num_warmup_steps", "Inference Time = %0.2f for Sentences = %d\", eval_time_elapsed, eval_hooks[-1].count * FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total", "eval_metric_ops=eval_metric_ops) return output_spec (total_loss, per_example_loss, logits, probabilities) = create_model( bert_config, is_training, input_ids, input_mask,", "want a lot of parallel reading and shuffling. # For eval, we want", "+ FN)) ** 0.5 MCC_op = tf.group(FN_op, TN_op, TP_op, FP_op, tf.identity(MCC, name=\"MCC\")) return", "hvd.size(), hvd.rank()) global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps * hvd.size() master_process = (hvd.rank() ==", "t = tf.to_int32(t) example[name] = t return example def input_fn(): \"\"\"The actual input", "probabilities} output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=predictions) elif mode == tf.estimator.ModeKeys.EVAL: eval_metric_ops = metric_fn(per_example_loss,", "Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\" if FLAGS.amp else \"fp32\") tf.compat.v1.logging.info(\"Latency", "FLAGS.do_eval and master_process: eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\") file_based_convert_examples_to_features( eval_examples, label_list,", "logits): predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) if task_name == \"cola\": FN, FN_op =", "def model_fn_builder(task_name, bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_one_hot_embeddings, hvd=None): \"\"\"Returns `model_fn` closure", "= tf.reduce_mean(per_example_loss, name='cls_loss') return (loss, per_example_loss, logits, probabilities) def get_frozen_tftrt_model(bert_config, shape, num_labels, use_one_hot_embeddings,", "n in frozen_graph.node if str(n.op) == 'TRTEngineOp'])) with tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\") as f: f.write(frozen_graph.SerializeToString())", "* 1.0 / predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences =", "output_node_names) num_nodes = len(frozen_graph.node) print('Converting graph using TensorFlow-TensorRT...') from tensorflow.python.compiler.tensorrt import trt_convert as", "results *****\") for key in sorted(result.keys()): dllogging.logger.log(step=(), data={key: float(result[key])}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\" %s =", "is_training=False, drop_remainder=predict_drop_remainder) predict_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time = time.time() output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\") with", "= create_model( bert_config, is_training, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables()", "predict_time_elapsed, predict_hooks[-1].count * FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f for Sentences", "tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids, 'label_ids':label_ids}, return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0', 'loss/cls_logits:0', 'loss/cls_probabilities:0'], name='') if mode ==", "(or other data files) \" \"for the task.\") flags.DEFINE_string( \"bert_config_file\", None, \"The config", "= tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(), output_node_names) num_nodes = len(frozen_graph.node) print('Converting graph using TensorFlow-TensorRT...') from tensorflow.python.compiler.tensorrt", "task_name == \"cola\": FN, FN_op = tf.metrics.false_negatives(labels=label_ids, predictions=predictions) FP, FP_op = tf.metrics.false_positives(labels=label_ids, predictions=predictions)", "print_function import collections import csv import os import modeling import optimization import tokenization", "tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0)) output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=probabilities) return output_spec return model_fn # This", "(ms) = %0.2f\", avg * 1000) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(),", "the model checkpoints will be written.\") ## Other parameters flags.DEFINE_string( \"dllog_path\", \"/results/bert_dllog.json\", \"filename", "instead. output_layer = model.get_pooled_output() hidden_size = output_layer.shape[-1].value output_weights = tf.get_variable( \"output_weights\", [num_labels, hidden_size],", "d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return d return input_fn def main(_): setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging", "Copyright 2018 The Google AI Language Team Authors. # # Licensed under the", "if FLAGS.do_eval and master_process: eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\") file_based_convert_examples_to_features( eval_examples,", "= FLAGS.train_batch_size * FLAGS.num_accumulation_steps hvd_rank = 0 config = tf.compat.v1.ConfigProto() if FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU", "= False eval_input_fn = file_based_input_fn_builder( input_file=eval_file, batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder) eval_hooks = [LogEvalRunHook(FLAGS.eval_batch_size)]", "= d.shard(hvd.size(), hvd.rank()) d = d.repeat() d = d.shuffle(buffer_size=100) d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder)", "== tf.estimator.ModeKeys.EVAL: dummy_op = tf.no_op() # Need to call mixed precision graph rewrite", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) return { \"eval_accuracy\": accuracy, \"eval_loss\": loss, } tf.compat.v1.logging.info(\"***", "\"Total batch size for predict.\") flags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate for Adam.\")", "written.\") ## Other parameters flags.DEFINE_string( \"dllog_path\", \"/results/bert_dllog.json\", \"filename where dllogger writes to\") flags.DEFINE_string(", "learning_rate, num_train_steps, num_warmup_steps, hvd, False, FLAGS.amp, FLAGS.num_accumulation_steps, FLAGS.optimizer_type) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss,", "input_mask, segment_ids, labels, num_labels, use_one_hot_embeddings): \"\"\"Creates a classification model.\"\"\" model = modeling.BertModel( config=bert_config,", "elif mode == tf.estimator.ModeKeys.EVAL: eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode,", "Estimator.\"\"\" name_to_features = { \"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64), \"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64),", "/ train_time_elapsed ss_sentences_per_second = (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size * 1.0 / train_time_wo_overhead", "on TEST SET\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length)", "input text. Should be True for uncased \" \"models and False for cased", "EVAL set\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision", "\"/results/bert_dllog.json\", \"filename where dllogger writes to\") flags.DEFINE_string( \"optimizer_type\", \"lamb\", \"Optimizer type : adam", "size for predict.\") flags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate for Adam.\") flags.DEFINE_bool(\"use_trt\", False,", "len(train_examples) // hvd.size() remainder = len(train_examples) % hvd.size() if hvd.rank() < remainder: start_index", "0) hvd_rank = hvd.rank() config.gpu_options.visible_device_list = str(hvd.local_rank()) set_affinity(hvd.local_rank()) if hvd.size() > 1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0))", "(sentences/sec) = %0.2f\", ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\") if FLAGS.do_eval and master_process: eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_file", "compilation.\") flags.DEFINE_bool(\"horovod\", False, \"Whether to use Horovod for multi-gpu runs\") flags.DEFINE_bool( \"verbose_logging\", False,", "epochs to perform.\") flags.DEFINE_float( \"warmup_proportion\", 0.1, \"Proportion of training to perform linear learning", "passed to Estimator.\"\"\" name_to_features = { \"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64), \"segment_ids\":", "__future__ import print_function import collections import csv import os import modeling import optimization", "model.get_sequence_output() # instead. output_layer = model.get_pooled_output() hidden_size = output_layer.shape[-1].value output_weights = tf.get_variable( \"output_weights\",", "predictions = {\"probabilities\": probabilities} output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=predictions) elif mode == tf.estimator.ModeKeys.EVAL:", "3.0, \"Total number of training epochs to perform.\") flags.DEFINE_float( \"warmup_proportion\", 0.1, \"Proportion of", "%s\" % (name, features[name].shape)) input_ids = features[\"input_ids\"] input_mask = features[\"input_mask\"] segment_ids = features[\"segment_ids\"]", "num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() initialized_variable_names = {} if init_checkpoint and (hvd is", "32, \"Total batch size for training.\") flags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch size for eval.\")", "dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1, name='cls_per_example_loss') loss = tf.reduce_mean(per_example_loss, name='cls_loss') return", "conversion:', num_nodes, '->', len(frozen_graph.node)) print('TRT node count:', len([1 for n in frozen_graph.node if", "tf.io.FixedLenFeature([seq_length], tf.int64), \"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64), \"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"label_ids\": tf.io.FixedLenFeature([], tf.int64), } def", "the task to train.\") flags.DEFINE_string(\"vocab_file\", None, \"The vocabulary file that the BERT model", "all int64 to int32. for name in list(example.keys()): t = example[name] if t.dtype", "= tf.metrics.true_negatives(labels=label_ids, predictions=predictions) MCC = (TP * TN - FP * FN) /", "= { \"cola\": ColaProcessor, \"mnli\": MnliProcessor, \"mrpc\": MrpcProcessor, \"xnli\": XnliProcessor, } if not", "log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels *", "max(time_list[:int(len(time_list) * 0.99)]) cf_100 = max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second = num_sentences * 1.0", "the entire # segment. # # If you want to use the token-level", "(hvd is None or hvd.rank() == 0): (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)", "parallel reading doesn't matter. d = tf.data.TFRecordDataset(input_file) if is_training: if hvd is not", "*NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape, init_string) frozen_graph =", "See the License for the specific language governing permissions and # limitations under", "sorted(features.keys()): tf.compat.v1.logging.info(\" name = %s, shape = %s\" % (name, features[name].shape)) input_ids =", "= [os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i)) for i in range(hvd.size())] num_examples_per_rank = len(train_examples) // hvd.size() remainder", "False, \"Whether to run the model in inference mode on the test set.\")", "in prediction) + \"\\n\" writer.write(output_line) predict_time_elapsed = time.time() - predict_start_time time_list = predict_hooks[-1].time_list", "d = d.apply( tf.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder)) return d return", "task to train.\") flags.DEFINE_string(\"vocab_file\", None, \"The vocabulary file that the BERT model was", "limitations under the License. \"\"\"BERT finetuning runner.\"\"\" from __future__ import absolute_import from __future__", "{\"probabilities\": probabilities} output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=predictions) elif mode == tf.estimator.ModeKeys.EVAL: eval_metric_ops =", "tf.compat.v1.logging.info(\"***** Eval results *****\") for key in sorted(result.keys()): dllogging.logger.log(step=(), data={key: float(result[key])}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "# Need to call mixed precision graph rewrite if fp16 to enable graph", "length %d\" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower() if task_name not in", "MnliProcessor, \"mrpc\": MrpcProcessor, \"xnli\": XnliProcessor, } if not FLAGS.do_train and not FLAGS.do_eval and", "= os.path.join(FLAGS.output_dir, \"eval_results.txt\") with tf.io.gfile.GFile(output_eval_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Eval results *****\") for", "data={key: float(result[key])}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\" %s = %s\", key, str(result[key])) writer.write(\"%s = %s\\n\" %", "call.\") flags.DEFINE_integer(\"num_accumulation_steps\", 1, \"Number of accumulation steps before gradient update\" \"Global batch size", "adam or lamb\") flags.DEFINE_string( \"init_checkpoint\", None, \"Initial checkpoint (usually from a pre-trained BERT", "name_to_features = { \"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64), \"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"label_ids\":", "ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") if __name__ == \"__main__\": flags.mark_flag_as_required(\"data_dir\") flags.mark_flag_as_required(\"task_name\") flags.mark_flag_as_required(\"vocab_file\") flags.mark_flag_as_required(\"bert_config_file\") flags.mark_flag_as_required(\"output_dir\") tf.compat.v1.app.run()", "= %s%s\", var.name, var.shape, init_string) frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(), output_node_names) num_nodes = len(frozen_graph.node)", "FLAGS.amp: dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0)) output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=probabilities) return output_spec return", "enable graph rewrite if FLAGS.amp: dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0)) output_spec = tf.estimator.EstimatorSpec( mode=mode,", "TPU only supports tf.int32. # So cast all int64 to int32. for name", "tvars = tf.trainable_variables() initialized_variable_names = {} if init_checkpoint and (hvd is None or", "segment_ids = tf.placeholder(tf.int32, shape, 'segment_ids') label_ids = tf.placeholder(tf.int32, (None), 'label_ids') create_model(bert_config, False, input_ids,", "0.90)]) cf_95 = max(time_list[:int(len(time_list) * 0.95)]) cf_99 = max(time_list[:int(len(time_list) * 0.99)]) cf_100 =", "start_index + (num_examples_per_rank) model_fn = model_fn_builder( task_name=task_name, bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate if not", "float(result[key])}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\" %s = %s\", key, str(result[key])) writer.write(\"%s = %s\\n\" % (key,", "1.0 / train_time_wo_overhead if master_process: tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Training Time = %0.2f for Sentences", "for Sentences = %d\", eval_time_elapsed, eval_hooks[-1].count * FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead", "raise ValueError(\"Task not found: %s\" % (task_name)) processor = processors[task_name]() label_list = processor.get_labels()", "the pre-trained BERT model. \" \"This specifies the model architecture.\") flags.DEFINE_string(\"task_name\", None, \"The", "FLAGS.do_predict and master_process: predict_examples = processor.get_test_examples(FLAGS.data_dir) predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\") file_based_convert_examples_to_features(predict_examples, label_list, FLAGS.max_seq_length,", "specifies the model architecture.\") flags.DEFINE_string(\"task_name\", None, \"The name of the task to train.\")", "FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion) start_index = 0 end_index = len(train_examples) tmp_filenames", "model_fn_builder( task_name=task_name, bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate if not FLAGS.horovod else FLAGS.learning_rate * hvd.size(),", "FLAGS.eval_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)]) cf_90 = max(time_list[:int(len(time_list) *", "of the task to train.\") flags.DEFINE_string(\"vocab_file\", None, \"The vocabulary file that the BERT", "examples = %d\", len(predict_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size) predict_drop_remainder = False", "None, \"The config json file corresponding to the pre-trained BERT model. \" \"This", "init_checkpoint): tf_config = tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth = True output_node_names = ['loss/cls_loss', 'loss/cls_per_example_loss', 'loss/cls_logits', 'loss/cls_probabilities']", "= tf.trainable_variables() initialized_variable_names = {} if init_checkpoint and (hvd is None or hvd.rank()", "num_labels, use_one_hot_embeddings, init_checkpoint): tf_config = tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth = True output_node_names = ['loss/cls_loss', 'loss/cls_per_example_loss',", "max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second = num_sentences * 1.0 / eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference", "name=\"MCC\")) return {\"MCC\": (MCC, MCC_op)} elif task_name == \"mrpc\": accuracy = tf.metrics.accuracy( labels=label_ids,", "it. def input_fn_builder(features, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure to", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "and shuffling. # For eval, we want no shuffling and parallel reading doesn't", "output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias,", "For training, we want a lot of parallel reading and shuffling. # For", "doing a simple classification task on the entire # segment. # # If", "many steps to make in each estimator call.\") flags.DEFINE_integer(\"num_accumulation_steps\", 1, \"Number of accumulation", "'input_ids') input_mask = tf.placeholder(tf.int32, shape, 'input_mask') segment_ids = tf.placeholder(tf.int32, shape, 'segment_ids') label_ids =", "per_example_loss, logits, probabilities) def get_frozen_tftrt_model(bert_config, shape, num_labels, use_one_hot_embeddings, init_checkpoint): tf_config = tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth", "predictions=predictions) FP, FP_op = tf.metrics.false_positives(labels=label_ids, predictions=predictions) TP, TP_op = tf.metrics.true_positives(labels=label_ids, predictions=predictions) TN, TN_op", "import trt_convert as trt converter = trt.TrtGraphConverter( input_graph_def=frozen_graph, nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096 << 20) -", "None, \"The vocabulary file that the BERT model was trained on.\") flags.DEFINE_string( \"output_dir\",", "logits, probabilities) def get_frozen_tftrt_model(bert_config, shape, num_labels, use_one_hot_embeddings, init_checkpoint): tf_config = tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth =", "estimator\") flags.DEFINE_integer(\"iterations_per_loop\", 1000, \"How many steps to make in each estimator call.\") flags.DEFINE_integer(\"num_accumulation_steps\",", "lot of parallel reading and shuffling. # For eval, we want no shuffling", "{} if init_checkpoint and (hvd is None or hvd.rank() == 0): (assignment_map, initialized_variable_names", "and parallel reading doesn't matter. d = tf.data.TFRecordDataset(input_file) if is_training: if hvd is", "predict_time_elapsed = time.time() - predict_start_time time_list = predict_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup)", "Inference Statistics on TEST SET\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence Length =", "init_string = \"\" if var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\" name", "estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks) eval_time_elapsed = time.time() - eval_start_time time_list = eval_hooks[-1].time_list time_list.sort() # Removing", "Estimator.\"\"\" all_input_ids = [] all_input_mask = [] all_segment_ids = [] all_label_ids = []", "create_model(bert_config, False, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() (assignment_map, initialized_variable_names)", "the test set.\") flags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for training.\") flags.DEFINE_integer(\"eval_batch_size\", 8, \"Total", "num_sentences * 1.0 / predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences", "0 end_index = len(train_examples) tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record\")] if FLAGS.horovod: tmp_filenames = [os.path.join(FLAGS.output_dir,", "flags.DEFINE_bool(\"do_eval\", False, \"Whether to run eval on the dev set.\") flags.DEFINE_bool( \"do_predict\", False,", "90 (ms) = %0.2f\", cf_90 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 95 (ms) =", "name_to_features): \"\"\"Decodes a record to a TensorFlow example.\"\"\" example = tf.parse_single_example(record, name_to_features) #", "input_fn def create_model(bert_config, is_training, input_ids, input_mask, segment_ids, labels, num_labels, use_one_hot_embeddings): \"\"\"Creates a classification", "are doing a simple classification task on the entire # segment. # #", "mode=mode, predictions=probabilities) return output_spec return model_fn # This function is not used by", "converter.convert() print('Total node count before and after TF-TRT conversion:', num_nodes, '->', len(frozen_graph.node)) print('TRT", "hvd) train_start_time = time.time() estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks) train_time_elapsed = time.time() - train_start_time train_time_wo_overhead", "time_list.sort() # Removing outliers (init/warmup) in throughput computation. eval_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)])", "elif mode == tf.estimator.ModeKeys.EVAL: dummy_op = tf.no_op() # Need to call mixed precision", "0.1, \"Proportion of training to perform linear learning rate warmup for. \" \"E.g.,", "= \"\\t\".join( str(class_probability) for class_probability in prediction) + \"\\n\" writer.write(output_line) predict_time_elapsed = time.time()", "label_list = processor.get_labels() tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) master_process = True training_hooks =", "to enable XLA JIT compilation.\") flags.DEFINE_bool(\"horovod\", False, \"Whether to use Horovod for multi-gpu", "\"eval.tf_record\") file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file) tf.compat.v1.logging.info(\"***** Running evaluation *****\") tf.compat.v1.logging.info(\" Num", "print('Converting graph using TensorFlow-TensorRT...') from tensorflow.python.compiler.tensorrt import trt_convert as trt converter = trt.TrtGraphConverter(", "actual input function.\"\"\" # For training, we want a lot of parallel reading", "flags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate for Adam.\") flags.DEFINE_bool(\"use_trt\", False, \"Whether to use", "flags.DEFINE_string( \"dllog_path\", \"/results/bert_dllog.json\", \"filename where dllogger writes to\") flags.DEFINE_string( \"optimizer_type\", \"lamb\", \"Optimizer type", "\"E.g., 0.1 = 10% of training.\") flags.DEFINE_integer(\"save_checkpoints_steps\", 1000, \"How often to save the", "flags.DEFINE_integer(\"display_loss_steps\", 10, \"How often to print loss from estimator\") flags.DEFINE_integer(\"iterations_per_loop\", 1000, \"How many", "throughput computation. eval_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) * 0.8)) *", "depend on it. def input_fn_builder(features, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn`", "\"filename where dllogger writes to\") flags.DEFINE_string( \"optimizer_type\", \"lamb\", \"Optimizer type : adam or", "if task_name not in processors: raise ValueError(\"Task not found: %s\" % (task_name)) processor", "and sequences shorter \" \"than this will be padded.\") flags.DEFINE_bool(\"do_train\", False, \"Whether to", "# instead. output_layer = model.get_pooled_output() hidden_size = output_layer.shape[-1].value output_weights = tf.get_variable( \"output_weights\", [num_labels,", "= tf.compat.v1.ConfigProto() if FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU training with TF Horovod\") tf.compat.v1.logging.info(\"hvd.size() = %d hvd.rank()", "Level 95 (ms) = %0.2f\", cf_95 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 99 (ms)", "%0.2f\", cf_95 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 99 (ms) = %0.2f\", cf_99 *", "Should be True for uncased \" \"models and False for cased models.\") flags.DEFINE_integer(", "= None if mode == tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps,", "Confidence Level 50 (ms) = %0.2f\", cf_50 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 90", "\"output_bias\", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope(\"loss\"): if is_training: # I.e., 0.1 dropout output_layer =", "be True.\") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError( \"Cannot use", "ops. When false, uses TF32 on A100 and FP32 on V100 GPUS.\") flags.DEFINE_bool(\"use_xla\",", "with tf.variable_scope(\"loss\"): if is_training: # I.e., 0.1 dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits", "len(train_examples) % hvd.size() if hvd.rank() < remainder: start_index = hvd.rank() * (num_examples_per_rank+1) end_index", "KIND, either express or implied. # See the License for the specific language", "= len(train_examples) % hvd.size() if hvd.rank() < remainder: start_index = hvd.rank() * (num_examples_per_rank+1)", "train_time_wo_overhead if master_process: tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Training Time = %0.2f for Sentences = %d\",", "Level 50 (ms) = %0.2f\", cf_50 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 90 (ms)", "mode == tf.estimator.ModeKeys.EVAL: eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss,", "= tf.estimator.EstimatorSpec( mode=mode, predictions=probabilities) return output_spec return model_fn # This function is not", "t.dtype == tf.int64: t = tf.to_int32(t) example[name] = t return example def input_fn():", "or lamb\") flags.DEFINE_string( \"init_checkpoint\", None, \"Initial checkpoint (usually from a pre-trained BERT model).\")", "model in inference mode on the test set.\") flags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size", "1000, precision_mode = \"FP16\" if FLAGS.amp else \"FP32\", minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000 ) frozen_graph", "\"eval_results.txt\") with tf.io.gfile.GFile(output_eval_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Eval results *****\") for key in", "input function.\"\"\" # For training, we want a lot of parallel reading and", "\"The vocabulary file that the BERT model was trained on.\") flags.DEFINE_string( \"output_dir\", None,", "tf.compat.v1.logging.info(\"***** Running training *****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(train_examples)) tf.compat.v1.logging.info(\" Batch size", "steps to make in each estimator call.\") flags.DEFINE_integer(\"num_accumulation_steps\", 1, \"Number of accumulation steps", "* FN) / ((TP + FP) * (TP + FN) * (TN +", "train_start_time = time.time() estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks) train_time_elapsed = time.time() - train_start_time train_time_wo_overhead =", "len(train_examples) / global_batch_size * FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion) start_index = 0", "task_name=task_name, bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate if not FLAGS.horovod else FLAGS.learning_rate * hvd.size(), num_train_steps=num_train_steps,", "= True training_hooks = [] global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps hvd_rank = 0", "if FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps = int( len(train_examples) / global_batch_size * FLAGS.num_train_epochs)", "features[\"segment_ids\"] label_ids = features[\"label_ids\"] is_training = (mode == tf.estimator.ModeKeys.TRAIN) if not is_training and", "var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\" name = %s, shape =", "== \"cola\": FN, FN_op = tf.metrics.false_negatives(labels=label_ids, predictions=predictions) FP, FP_op = tf.metrics.false_positives(labels=label_ids, predictions=predictions) TP,", "set_affinity import utils.dllogger_class from dllogger import Verbosity from utils.create_glue_data import * import numpy", "flags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\") flags.DEFINE_bool(\"do_eval\", False, \"Whether to run eval on", "supports tf.int32. # So cast all int64 to int32. for name in list(example.keys()):", "init_string = \"\" if var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" else: init_string", "d = d.repeat() d = d.shuffle(buffer_size=100) d = d.apply( tf.contrib.data.map_and_batch( lambda record: _decode_record(record,", "tf.int32. # So cast all int64 to int32. for name in list(example.keys()): t", "model checkpoints will be written.\") ## Other parameters flags.DEFINE_string( \"dllog_path\", \"/results/bert_dllog.json\", \"filename where", "\"test_results.tsv\") with tf.io.gfile.GFile(output_predict_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Predict results *****\") for prediction in", "import * import numpy as np import tf_metrics flags = tf.flags FLAGS =", "> bert_config.max_position_embeddings: raise ValueError( \"Cannot use sequence length %d because the BERT model", "flags.DEFINE_bool(\"use_xla\", True, \"Whether to enable XLA JIT compilation.\") flags.DEFINE_bool(\"horovod\", False, \"Whether to use", "ANY KIND, either express or implied. # See the License for the specific", "if is_training: if hvd is not None: d = d.shard(hvd.size(), hvd.rank()) d =", "%s, shape = %s\" % (name, features[name].shape)) input_ids = features[\"input_ids\"] input_mask = features[\"input_mask\"]", "logits, probabilities) = create_model( bert_config, is_training, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars", "uses tf.py_func which is # not TPU compatible. The right way to load", "* TN - FP * FN) / ((TP + FP) * (TP +", "if FLAGS.do_predict and master_process: predict_examples = processor.get_test_examples(FLAGS.data_dir) predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\") file_based_convert_examples_to_features(predict_examples, label_list,", "%d\" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower() if task_name not in processors:", "models.\") flags.DEFINE_integer( \"max_seq_length\", 128, \"The maximum total input sequence length after WordPiece tokenization.", "and not FLAGS.do_predict: raise ValueError( \"At least one of `do_train`, `do_eval` or `do_predict'", "for key in FLAGS.__flags.keys(): tf.compat.v1.logging.info(' {}: {}'.format(key, getattr(FLAGS, key))) tf.compat.v1.logging.info(\"**************************\") train_examples = None", "all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id) def input_fn(): \"\"\"The actual input function.\"\"\" num_examples = len(features)", "a lot of parallel reading and shuffling. # For eval, we want no", "hvd.rank()) d = d.repeat() d = d.shuffle(buffer_size=100) d = d.apply( tf.contrib.data.map_and_batch( lambda record:", "= %s, shape = %s%s\", var.name, var.shape, init_string) frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(), output_node_names)", "str(result[key]))) if FLAGS.do_predict and master_process: predict_examples = processor.get_test_examples(FLAGS.data_dir) predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\") file_based_convert_examples_to_features(predict_examples,", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "output_spec return model_fn # This function is not used by this file but", "rights reserved. # Copyright 2018 The Google AI Language Team Authors. # #", "FN) / ((TP + FP) * (TP + FN) * (TN + FP)", "size = %d\", FLAGS.predict_batch_size) predict_drop_remainder = False predict_input_fn = file_based_input_fn_builder( input_file=predict_file, batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length,", "json file corresponding to the pre-trained BERT model. \" \"This specifies the model", "FLAGS = flags.FLAGS ## Required parameters flags.DEFINE_string( \"data_dir\", None, \"The input data dir.", "= %0.2f\", avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\") if FLAGS.do_eval and", "batch size for predict.\") flags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate for Adam.\") flags.DEFINE_bool(\"use_trt\",", "\"train.tf_record{}\".format(i)) for i in range(hvd.size())] num_examples_per_rank = len(train_examples) // hvd.size() remainder = len(train_examples)", "= tf.metrics.mean(values=per_example_loss) return { \"eval_accuracy\": accuracy, \"eval_loss\": loss, } tf.compat.v1.logging.info(\"*** Features ***\") tf.compat.v1.logging.info(\"***", "* global_batch_size) tf.compat.v1.logging.info(\"Total Training Time W/O Overhead = %0.2f for Sentences = %d\",", "= tf.train.experimental.FixedLossScale(1) dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler) eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec", "return model_fn # This function is not used by this file but is", "for demo purposes and does NOT scale to large data sets. We do", "tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) with overhead = %0.2f\", avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\",", "predict_input_fn = file_based_input_fn_builder( input_file=predict_file, batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder) predict_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time =", "contain the .tsv files (or other data files) \" \"for the task.\") flags.DEFINE_string(", "= tf.group(FN_op, TN_op, TP_op, FP_op, tf.identity(MCC, name=\"MCC\")) return {\"MCC\": (MCC, MCC_op)} elif task_name", "= output_layer.shape[-1].value output_weights = tf.get_variable( \"output_weights\", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable( \"output_bias\",", "FLAGS.do_predict: raise ValueError( \"At least one of `do_train`, `do_eval` or `do_predict' must be", "training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1 if FLAGS.amp: tf.enable_resource_variables() run_config = tf.estimator.RunConfig( model_dir=FLAGS.output_dir", "flags.DEFINE_bool( \"verbose_logging\", False, \"If true, all of the warnings related to data processing", "use_one_hot_embeddings=False, hvd=None if not FLAGS.horovod else hvd) estimator = tf.estimator.Estimator( model_fn=model_fn, config=run_config) if", "hooks=predict_hooks, yield_single_examples=False): output_line = \"\\t\".join( str(class_probability) for class_probability in prediction) + \"\\n\" writer.write(output_line)", "expected for a normal SQuAD evaluation.\") def file_based_input_fn_builder(input_file, batch_size, seq_length, is_training, drop_remainder, hvd=None):", "size for training.\") flags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch size for eval.\") flags.DEFINE_integer(\"predict_batch_size\", 8, \"Total", "%d\", eval_time_elapsed, eval_hooks[-1].count * FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f for", "0.8)]) num_sentences = (int(len(time_list) * 0.8)) * FLAGS.eval_batch_size avg = np.mean(time_list) cf_50 =", "is not used by this file but is still used by the Colab", "tf.compat.v1.logging.info(\"Latency Confidence Level 99 (ms) = %0.2f\", cf_99 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level", "the Colab and # people who depend on it. def input_fn_builder(features, batch_size, seq_length,", "seq_length], dtype=tf.int32), \"input_mask\": tf.constant( all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32), \"segment_ids\": tf.constant( all_segment_ids, shape=[num_examples, seq_length],", "if fp16 to enable graph rewrite if FLAGS.amp: dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0)) output_spec", "pre-trained BERT model. \" \"This specifies the model architecture.\") flags.DEFINE_string(\"task_name\", None, \"The name", "\" \"than this will be padded.\") flags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\") flags.DEFINE_bool(\"do_eval\",", "= time.time() estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks) train_time_elapsed = time.time() - train_start_time train_time_wo_overhead = training_hooks[-1].total_time", "dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if FLAGS.horovod: hvd.init() processors = { \"cola\": ColaProcessor, \"mnli\": MnliProcessor,", "tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(), output_node_names) num_nodes = len(frozen_graph.node) print('Converting graph using TensorFlow-TensorRT...') from tensorflow.python.compiler.tensorrt import", "label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) else: dummy_op = tf.no_op() #", "run eval on the dev set.\") flags.DEFINE_bool( \"do_predict\", False, \"Whether to run the", "len(frozen_graph.node)) print('TRT node count:', len([1 for n in frozen_graph.node if str(n.op) == 'TRTEngineOp']))", "= %d\", FLAGS.predict_batch_size) predict_drop_remainder = False predict_input_fn = file_based_input_fn_builder( input_file=predict_file, batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length, is_training=False,", "2018 The Google AI Language Team Authors. # # Licensed under the Apache", "the model in inference mode on the test set.\") flags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch", "processing will be printed. \" \"A number of warnings are expected for a", "estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks) train_time_elapsed = time.time() - train_start_time train_time_wo_overhead = training_hooks[-1].total_time avg_sentences_per_second =", "call mixed precision graph rewrite if fp16 to enable graph rewrite if FLAGS.amp:", "set.\") flags.DEFINE_bool( \"do_predict\", False, \"Whether to run the model in inference mode on", "tf.compat.v1.logging.info(\"Latency Confidence Level 95 (ms) = %0.2f\", cf_95 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level", "(assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\") tf.compat.v1.logging.info(\"**** Trainable Variables ****\")", "f: f.write(frozen_graph.SerializeToString()) return frozen_graph def model_fn_builder(task_name, bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_one_hot_embeddings,", "not is_training and FLAGS.use_trt: trt_graph = get_frozen_tftrt_model(bert_config, input_ids.shape, num_labels, use_one_hot_embeddings, init_checkpoint) (total_loss, per_example_loss,", "num_warmup_steps, hvd, False, FLAGS.amp, FLAGS.num_accumulation_steps, FLAGS.optimizer_type) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, train_op=train_op) elif", "import absolute_import from __future__ import division from __future__ import print_function import collections import", "for predict.\") flags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate for Adam.\") flags.DEFINE_bool(\"use_trt\", False, \"Whether", "= [] all_input_mask = [] all_segment_ids = [] all_label_ids = [] for feature", "tf.estimator.RunConfig( model_dir=FLAGS.output_dir if master_process else None, session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process else None, save_summary_steps=FLAGS.save_checkpoints_steps", "from estimator\") flags.DEFINE_integer(\"iterations_per_loop\", 1000, \"How many steps to make in each estimator call.\")", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "drop_remainder=eval_drop_remainder) eval_hooks = [LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time = time.time() result = estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks) eval_time_elapsed =", "graph rewrite if fp16 to enable graph rewrite if FLAGS.amp: loss_scaler = tf.train.experimental.FixedLossScale(1)", "governing permissions and # limitations under the License. \"\"\"BERT finetuning runner.\"\"\" from __future__", "= tf.estimator.RunConfig( model_dir=FLAGS.output_dir if master_process else None, session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process else None,", "to perform.\") flags.DEFINE_float( \"warmup_proportion\", 0.1, \"Proportion of training to perform linear learning rate", "accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) f1 = tf_metrics.f1(labels=label_ids, predictions=predictions, num_classes=2,", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "least one of `do_train`, `do_eval` or `do_predict' must be True.\") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)", "start_index = hvd.rank() * (num_examples_per_rank+1) end_index = start_index + num_examples_per_rank + 1 else:", "output_layer = model.get_pooled_output() hidden_size = output_layer.shape[-1].value output_weights = tf.get_variable( \"output_weights\", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02))", "main(_): setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if FLAGS.horovod: hvd.init() processors = { \"cola\":", "flags.DEFINE_string( \"init_checkpoint\", None, \"Initial checkpoint (usually from a pre-trained BERT model).\") flags.DEFINE_bool( \"do_lower_case\",", "{ \"cola\": ColaProcessor, \"mnli\": MnliProcessor, \"mrpc\": MrpcProcessor, \"xnli\": XnliProcessor, } if not FLAGS.do_train", "FLAGS.horovod else hvd) estimator = tf.estimator.Estimator( model_fn=model_fn, config=run_config) if FLAGS.do_train: file_based_convert_examples_to_features( train_examples[start_index:end_index], label_list,", "\"The initial learning rate for Adam.\") flags.DEFINE_bool(\"use_trt\", False, \"Whether to use TF-TRT\") flags.DEFINE_float(\"num_train_epochs\",", "applicable law or agreed to in writing, software # distributed under the License", "% (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower() if task_name not in processors: raise", "lambda record: _decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder)) return d return input_fn def create_model(bert_config, is_training,", "training, we want a lot of parallel reading and shuffling. # For eval,", "%0.2f for Sentences = %d\", train_time_elapsed, num_train_steps * global_batch_size) tf.compat.v1.logging.info(\"Total Training Time W/O", "False, \"Whether to use TF-TRT\") flags.DEFINE_float(\"num_train_epochs\", 3.0, \"Total number of training epochs to", "= %0.2f\", avg * 1000) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\":", "1.0 / predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences = %d\",", "* global_batch_size) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) with overhead = %0.2f\", avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec)", "\"The maximum total input sequence length after WordPiece tokenization. \" \"Sequences longer than", "tf.io.gfile.GFile(output_eval_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Eval results *****\") for key in sorted(result.keys()): dllogging.logger.log(step=(),", "be written.\") ## Other parameters flags.DEFINE_string( \"dllog_path\", \"/results/bert_dllog.json\", \"filename where dllogger writes to\")", "tf.get_variable( \"output_bias\", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope(\"loss\"): if is_training: # I.e., 0.1 dropout output_layer", "hooks=training_hooks) train_time_elapsed = time.time() - train_start_time train_time_wo_overhead = training_hooks[-1].total_time avg_sentences_per_second = num_train_steps *", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "eval, we want no shuffling and parallel reading doesn't matter. d = tf.data.TFRecordDataset(input_file)", "= ['loss/cls_loss', 'loss/cls_per_example_loss', 'loss/cls_logits', 'loss/cls_probabilities'] with tf.Session(config=tf_config) as tf_sess: input_ids = tf.placeholder(tf.int32, shape,", "= tf_metrics.f1(labels=label_ids, predictions=predictions, num_classes=2, pos_indices=[1]) return { \"eval_accuracy\": accuracy, \"eval_f1\": f1, \"eval_loss\": loss,", "True, \"Whether to enable AMP ops. When false, uses TF32 on A100 and", "input_file=tmp_filenames, batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True, hvd=None if not FLAGS.horovod else hvd) train_start_time =", "of parallel reading and shuffling. # For eval, we want no shuffling and", "= features[\"label_ids\"] is_training = (mode == tf.estimator.ModeKeys.TRAIN) if not is_training and FLAGS.use_trt: trt_graph", "* FLAGS.num_accumulation_steps hvd_rank = 0 config = tf.compat.v1.ConfigProto() if FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU training with", "loss=total_loss, eval_metric_ops=eval_metric_ops) else: dummy_op = tf.no_op() # Need to call mixed precision graph", "Confidence Level 100 (ms) = %0.2f\", cf_100 * 1000) tf.compat.v1.logging.info(\"Latency Average (ms) =", "input_fn def main(_): setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if FLAGS.horovod: hvd.init() processors =", "frozen_graph def model_fn_builder(task_name, bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_one_hot_embeddings, hvd=None): \"\"\"Returns `model_fn`", "`do_predict' must be True.\") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError(", "writing, software # distributed under the License is distributed on an \"AS IS\"", "d = tf.data.Dataset.from_tensor_slices({ \"input_ids\": tf.constant( all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"input_mask\": tf.constant( all_input_mask, shape=[num_examples,", "W/O Overhead = %0.2f for Sentences = %d\", eval_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics", "shuffling. # For eval, we want no shuffling and parallel reading doesn't matter.", "str(result[key])) writer.write(\"%s = %s\\n\" % (key, str(result[key]))) if FLAGS.do_predict and master_process: predict_examples =", "scale to large data sets. We do # not use Dataset.from_generator() because that", "%0.2f for Sentences = %d\", train_time_wo_overhead, (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size) tf.compat.v1.logging.info(\"Throughput Average", "1000) tf.compat.v1.logging.info(\"Latency Confidence Level 90 (ms) = %0.2f\", cf_90 * 1000) tf.compat.v1.logging.info(\"Latency Confidence", "FLAGS.max_seq_length, tokenizer, predict_file) tf.compat.v1.logging.info(\"***** Running prediction*****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(predict_examples)) tf.compat.v1.logging.info(\"", "output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\") with tf.io.gfile.GFile(output_predict_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Predict results *****\")", "os.path.join(FLAGS.output_dir, \"predict.tf_record\") file_based_convert_examples_to_features(predict_examples, label_list, FLAGS.max_seq_length, tokenizer, predict_file) tf.compat.v1.logging.info(\"***** Running prediction*****\") tf.compat.v1.logging.info(\" Num examples", "do # not use Dataset.from_generator() because that uses tf.py_func which is # not", "flags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch size for eval.\") flags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch size for", "compliance with the License. # You may obtain a copy of the License", "\"How often to save the model checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\", 10, \"How often to print", "we want a lot of parallel reading and shuffling. # For eval, we", "training_hooks[-1].skipped) * global_batch_size) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) with overhead = %0.2f\", avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput Average", "20) - 1000, precision_mode = \"FP16\" if FLAGS.amp else \"FP32\", minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000", "def input_fn(): \"\"\"The actual input function.\"\"\" num_examples = len(features) # This is for", "flags.DEFINE_string(\"task_name\", None, \"The name of the task to train.\") flags.DEFINE_string(\"vocab_file\", None, \"The vocabulary", "that the BERT model was trained on.\") flags.DEFINE_string( \"output_dir\", None, \"The output directory", "FP, FP_op = tf.metrics.false_positives(labels=label_ids, predictions=predictions) TP, TP_op = tf.metrics.true_positives(labels=label_ids, predictions=predictions) TN, TN_op =", "- train_start_time train_time_wo_overhead = training_hooks[-1].total_time avg_sentences_per_second = num_train_steps * global_batch_size * 1.0 /", "* train_batch_size\") flags.DEFINE_bool(\"amp\", True, \"Whether to enable AMP ops. When false, uses TF32", "predictions=predictions) TN, TN_op = tf.metrics.true_negatives(labels=label_ids, predictions=predictions) MCC = (TP * TN - FP", "= %d\", FLAGS.train_batch_size) tf.compat.v1.logging.info(\" Num steps = %d\", num_train_steps) train_input_fn = file_based_input_fn_builder( input_file=tmp_filenames,", "\"The output directory where the model checkpoints will be written.\") ## Other parameters", "tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, train_op=train_op) elif mode == tf.estimator.ModeKeys.EVAL: dummy_op = tf.no_op() # Need", "Sentences = %d\", train_time_elapsed, num_train_steps * global_batch_size) tf.compat.v1.logging.info(\"Total Training Time W/O Overhead =", "= features[\"segment_ids\"] label_ids = features[\"label_ids\"] is_training = (mode == tf.estimator.ModeKeys.TRAIN) if not is_training", "= d.shuffle(buffer_size=100) d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return d return input_fn def main(_): setup_xla_flags()", "tf.compat.v1.ConfigProto() if FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU training with TF Horovod\") tf.compat.v1.logging.info(\"hvd.size() = %d hvd.rank() =", "all_label_ids.append(feature.label_id) def input_fn(): \"\"\"The actual input function.\"\"\" num_examples = len(features) # This is", "to Estimator.\"\"\" all_input_ids = [] all_input_mask = [] all_segment_ids = [] all_label_ids =", "= max(time_list[:int(len(time_list) * 0.50)]) cf_90 = max(time_list[:int(len(time_list) * 0.90)]) cf_95 = max(time_list[:int(len(time_list) *", "def main(_): setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if FLAGS.horovod: hvd.init() processors = {", "of training epochs to perform.\") flags.DEFINE_float( \"warmup_proportion\", 0.1, \"Proportion of training to perform", "uncased \" \"models and False for cased models.\") flags.DEFINE_integer( \"max_seq_length\", 128, \"The maximum", "be True for uncased \" \"models and False for cased models.\") flags.DEFINE_integer( \"max_seq_length\",", "loss=total_loss, train_op=train_op) elif mode == tf.estimator.ModeKeys.EVAL: dummy_op = tf.no_op() # Need to call", "tf.estimator.EstimatorSpec( mode=mode, predictions=probabilities) return output_spec return model_fn # This function is not used", "> 1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1 if FLAGS.amp: tf.enable_resource_variables() run_config =", "in inference mode on the test set.\") flags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for", "FN)) ** 0.5 MCC_op = tf.group(FN_op, TN_op, TP_op, FP_op, tf.identity(MCC, name=\"MCC\")) return {\"MCC\":", "to enable graph rewrite if FLAGS.amp: dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0)) output_spec = tf.estimator.EstimatorSpec(", "dtype=tf.int32), \"label_ids\": tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32), }) if is_training: if hvd is not None:", "\"\"\"The actual input function.\"\"\" # For training, we want a lot of parallel", "finetuning runner.\"\"\" from __future__ import absolute_import from __future__ import division from __future__ import", "before and after TF-TRT conversion:', num_nodes, '->', len(frozen_graph.node)) print('TRT node count:', len([1 for", "label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() (assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map)", "if FLAGS.verbose_logging: tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in tvars: init_string = \"\"", "label_ids, logits): predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) if task_name == \"cola\": FN, FN_op", "hvd.size() master_process = (hvd.rank() == 0) hvd_rank = hvd.rank() config.gpu_options.visible_device_list = str(hvd.local_rank()) set_affinity(hvd.local_rank())", "if master_process: tf.compat.v1.logging.info(\"***** Configuaration *****\") for key in FLAGS.__flags.keys(): tf.compat.v1.logging.info(' {}: {}'.format(key, getattr(FLAGS,", "Removing outliers (init/warmup) in throughput computation. eval_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences =", "1)]) ss_sentences_per_second = num_sentences * 1.0 / predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time =", "up to sequence length %d\" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower() if", "if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1 if FLAGS.amp: tf.enable_resource_variables() run_config = tf.estimator.RunConfig( model_dir=FLAGS.output_dir if", "%0.2f\", avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\") if FLAGS.do_eval and master_process:", "task_name not in processors: raise ValueError(\"Task not found: %s\" % (task_name)) processor =", "for a normal SQuAD evaluation.\") def file_based_input_fn_builder(input_file, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates", "initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" else: init_string = \", *NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\" name =", "from dllogger import Verbosity from utils.create_glue_data import * import numpy as np import", "\", *INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape, init_string) output_spec", "(the \"License\"); # you may not use this file except in compliance with", "number of training epochs to perform.\") flags.DEFINE_float( \"warmup_proportion\", 0.1, \"Proportion of training to", "but is still used by the Colab and # people who depend on", "(training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) with overhead = %0.2f\", avg_sentences_per_second)", "eval_drop_remainder = False eval_input_fn = file_based_input_fn_builder( input_file=eval_file, batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder) eval_hooks =", "# Unless required by applicable law or agreed to in writing, software #", "%d\", num_train_steps) train_input_fn = file_based_input_fn_builder( input_file=tmp_filenames, batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True, hvd=None if not", "model).\") flags.DEFINE_bool( \"do_lower_case\", True, \"Whether to lower case the input text. Should be", "TP, TP_op = tf.metrics.true_positives(labels=label_ids, predictions=predictions) TN, TN_op = tf.metrics.true_negatives(labels=label_ids, predictions=predictions) MCC = (TP", "* 1000) tf.compat.v1.logging.info(\"Latency Average (ms) = %0.2f\", avg * 1000) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec)", "with tf.io.gfile.GFile(output_eval_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Eval results *****\") for key in sorted(result.keys()):", "by applicable law or agreed to in writing, software # distributed under the", "on the entire # segment. # # If you want to use the", "probabilities) def get_frozen_tftrt_model(bert_config, shape, num_labels, use_one_hot_embeddings, init_checkpoint): tf_config = tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth = True", "label_list, FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"***** Running training *****\") tf.compat.v1.logging.info(\" Num examples = %d\",", "pylint: disable=unused-argument \"\"\"The `model_fn` for Estimator.\"\"\" def metric_fn(per_example_loss, label_ids, logits): predictions = tf.argmax(logits,", "flags.DEFINE_string( \"output_dir\", None, \"The output directory where the model checkpoints will be written.\")", "import modeling import optimization import tokenization import tensorflow as tf import horovod.tensorflow as", "model checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\", 10, \"How often to print loss from estimator\") flags.DEFINE_integer(\"iterations_per_loop\", 1000,", "input_fn_builder(features, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure to be passed", "longer than this will be truncated, and sequences shorter \" \"than this will", "supports tf.int64, but the TPU only supports tf.int32. # So cast all int64", "%0.2f\", ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\") if FLAGS.do_eval and master_process: eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_file = os.path.join(FLAGS.output_dir,", "file except in compliance with the License. # You may obtain a copy", "flags.DEFINE_integer(\"save_checkpoints_steps\", 1000, \"How often to save the model checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\", 10, \"How often", "examples = %d\", len(train_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.train_batch_size) tf.compat.v1.logging.info(\" Num steps", "log_probs, axis=-1, name='cls_per_example_loss') loss = tf.reduce_mean(per_example_loss, name='cls_loss') return (loss, per_example_loss, logits, probabilities) def", "predict_file) tf.compat.v1.logging.info(\"***** Running prediction*****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(predict_examples)) tf.compat.v1.logging.info(\" Batch size", "you want to use the token-level output, use model.get_sequence_output() # instead. output_layer =", "input_fn(): \"\"\"The actual input function.\"\"\" # For training, we want a lot of", "if master_process else None, session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process else None, save_summary_steps=FLAGS.save_checkpoints_steps if master_process", "= file_based_input_fn_builder( input_file=tmp_filenames, batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True, hvd=None if not FLAGS.horovod else hvd)", "learning rate warmup for. \" \"E.g., 0.1 = 10% of training.\") flags.DEFINE_integer(\"save_checkpoints_steps\", 1000,", "eval_time_elapsed, eval_hooks[-1].count * FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f for Sentences", "/ train_time_wo_overhead if master_process: tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Training Time = %0.2f for Sentences =", "writer.write(\"%s = %s\\n\" % (key, str(result[key]))) if FLAGS.do_predict and master_process: predict_examples = processor.get_test_examples(FLAGS.data_dir)", "eval_time_elapsed = time.time() - eval_start_time time_list = eval_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup)", "hvd=None): \"\"\"Creates an `input_fn` closure to be passed to Estimator.\"\"\" name_to_features = {", "d.shard(hvd.size(), hvd.rank()) d = d.repeat() d = d.shuffle(buffer_size=100) d = d.apply( tf.contrib.data.map_and_batch( lambda", "*INIT_FROM_CKPT*\" else: init_string = \", *NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\" name = %s, shape = %s%s\",", "GPUS.\") flags.DEFINE_bool(\"use_xla\", True, \"Whether to enable XLA JIT compilation.\") flags.DEFINE_bool(\"horovod\", False, \"Whether to", "axis=-1, name='cls_probabilities') log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss =", "Removing outliers (init/warmup) in throughput computation. predict_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences =", "= None num_train_steps = None num_warmup_steps = None training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25)) if", "if task_name == \"cola\": FN, FN_op = tf.metrics.false_negatives(labels=label_ids, predictions=predictions) FP, FP_op = tf.metrics.false_positives(labels=label_ids,", "architecture.\") flags.DEFINE_string(\"task_name\", None, \"The name of the task to train.\") flags.DEFINE_string(\"vocab_file\", None, \"The", "processors = { \"cola\": ColaProcessor, \"mnli\": MnliProcessor, \"mrpc\": MrpcProcessor, \"xnli\": XnliProcessor, } if", "cf_99 = max(time_list[:int(len(time_list) * 0.99)]) cf_100 = max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second = num_sentences", "% hvd.size() if hvd.rank() < remainder: start_index = hvd.rank() * (num_examples_per_rank+1) end_index =", "True output_node_names = ['loss/cls_loss', 'loss/cls_per_example_loss', 'loss/cls_logits', 'loss/cls_probabilities'] with tf.Session(config=tf_config) as tf_sess: input_ids =", "= max(time_list[:int(len(time_list) * 0.95)]) cf_99 = max(time_list[:int(len(time_list) * 0.99)]) cf_100 = max(time_list[:int(len(time_list) *", "dllogger writes to\") flags.DEFINE_string( \"optimizer_type\", \"lamb\", \"Optimizer type : adam or lamb\") flags.DEFINE_string(", "and (hvd is None or hvd.rank() == 0): (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars,", "os.path.join(FLAGS.output_dir, \"eval.tf_record\") file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file) tf.compat.v1.logging.info(\"***** Running evaluation *****\") tf.compat.v1.logging.info(\"", "hvd is not None: d = d.shard(hvd.size(), hvd.rank()) d = d.repeat() d =", "normal SQuAD evaluation.\") def file_based_input_fn_builder(input_file, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn`", "= %d\", train_time_elapsed, num_train_steps * global_batch_size) tf.compat.v1.logging.info(\"Total Training Time W/O Overhead = %0.2f", "'input_mask') segment_ids = tf.placeholder(tf.int32, shape, 'segment_ids') label_ids = tf.placeholder(tf.int32, (None), 'label_ids') create_model(bert_config, False,", "FP) * (TN + FN)) ** 0.5 MCC_op = tf.group(FN_op, TN_op, TP_op, FP_op,", "if hvd.rank() < remainder: start_index = hvd.rank() * (num_examples_per_rank+1) end_index = start_index +", "Other parameters flags.DEFINE_string( \"dllog_path\", \"/results/bert_dllog.json\", \"filename where dllogger writes to\") flags.DEFINE_string( \"optimizer_type\", \"lamb\",", "tf.variable_scope(\"loss\"): if is_training: # I.e., 0.1 dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits =", "for eval.\") flags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch size for predict.\") flags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial", "-tf.reduce_sum(one_hot_labels * log_probs, axis=-1, name='cls_per_example_loss') loss = tf.reduce_mean(per_example_loss, name='cls_loss') return (loss, per_example_loss, logits,", "= d.repeat() d = d.shuffle(buffer_size=100) d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return d return input_fn", "FLAGS.train_batch_size * FLAGS.num_accumulation_steps * hvd.size() master_process = (hvd.rank() == 0) hvd_rank = hvd.rank()", "tf.compat.v1.logging.info(\"Total Training Time = %0.2f for Sentences = %d\", train_time_elapsed, num_train_steps * global_batch_size)", "(sentences/sec) with overhead = %0.2f\", avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\")", "%d hvd.rank() = %d\", hvd.size(), hvd.rank()) global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps * hvd.size()", "output_layer.shape[-1].value output_weights = tf.get_variable( \"output_weights\", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable( \"output_bias\", [num_labels],", "corresponding to the pre-trained BERT model. \" \"This specifies the model architecture.\") flags.DEFINE_string(\"task_name\",", "len(eval_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size) eval_drop_remainder = False eval_input_fn = file_based_input_fn_builder(", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "num_sentences = (int(len(time_list) * 0.8)) * FLAGS.eval_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list)", "because that uses tf.py_func which is # not TPU compatible. The right way", "= %0.2f for Sentences = %d\", train_time_elapsed, num_train_steps * global_batch_size) tf.compat.v1.logging.info(\"Total Training Time", "eval_hooks = [LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time = time.time() result = estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks) eval_time_elapsed = time.time()", "use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32) # In the demo, we are doing a simple classification task", "logits = tf.matmul(output_layer, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias, name='cls_logits') probabilities = tf.nn.softmax(logits,", "text. Should be True for uncased \" \"models and False for cased models.\")", "of training to perform linear learning rate warmup for. \" \"E.g., 0.1 =", "Language Team Authors. # # Licensed under the Apache License, Version 2.0 (the", "= d.shard(hvd.size(), hvd.rank()) d = d.repeat() d = d.shuffle(buffer_size=100) d = d.apply( tf.contrib.data.map_and_batch(", "= num_accumulation_steps * train_batch_size\") flags.DEFINE_bool(\"amp\", True, \"Whether to enable AMP ops. When false,", "t return example def input_fn(): \"\"\"The actual input function.\"\"\" # For training, we", "Level 100 (ms) = %0.2f\", cf_100 * 1000) tf.compat.v1.logging.info(\"Latency Average (ms) = %0.2f\",", "train.\") flags.DEFINE_string(\"vocab_file\", None, \"The vocabulary file that the BERT model was trained on.\")", "0.8)]) num_sentences = (int(len(time_list) * 0.8)) * FLAGS.predict_batch_size avg = np.mean(time_list) cf_50 =", "= [] all_label_ids = [] for feature in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id)", "outliers (init/warmup) in throughput computation. eval_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list)", "XLA JIT compilation.\") flags.DEFINE_bool(\"horovod\", False, \"Whether to use Horovod for multi-gpu runs\") flags.DEFINE_bool(", "V100 GPUS.\") flags.DEFINE_bool(\"use_xla\", True, \"Whether to enable XLA JIT compilation.\") flags.DEFINE_bool(\"horovod\", False, \"Whether", "= flags.FLAGS ## Required parameters flags.DEFINE_string( \"data_dir\", None, \"The input data dir. Should", "f1 = tf_metrics.f1(labels=label_ids, predictions=predictions, num_classes=2, pos_indices=[1]) return { \"eval_accuracy\": accuracy, \"eval_f1\": f1, \"eval_loss\":", "num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False, hvd=None if not FLAGS.horovod else hvd) estimator = tf.estimator.Estimator( model_fn=model_fn,", "training.\") flags.DEFINE_integer(\"save_checkpoints_steps\", 1000, \"How often to save the model checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\", 10, \"How", "shape, num_labels, use_one_hot_embeddings, init_checkpoint): tf_config = tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth = True output_node_names = ['loss/cls_loss',", "init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate if not FLAGS.horovod else FLAGS.learning_rate * hvd.size(), num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False, hvd=None", "not FLAGS.horovod else FLAGS.learning_rate * hvd.size(), num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False, hvd=None if not FLAGS.horovod", "with tf.io.gfile.GFile(output_predict_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Predict results *****\") for prediction in estimator.predict(input_fn=predict_input_fn,", "* FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f for Sentences = %d\",", "__future__ import absolute_import from __future__ import division from __future__ import print_function import collections", "= processors[task_name]() label_list = processor.get_labels() tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) master_process = True", "cf_100 = max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second = num_sentences * 1.0 / eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\")", "label_list, FLAGS.max_seq_length, tokenizer, eval_file) tf.compat.v1.logging.info(\"***** Running evaluation *****\") tf.compat.v1.logging.info(\" Num examples = %d\",", "in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" else: init_string = \", *NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\" name", "all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id) def input_fn(): \"\"\"The actual input function.\"\"\" num_examples = len(features) # This", "NOT scale to large data sets. We do # not use Dataset.from_generator() because", "= tf.estimator.Estimator( model_fn=model_fn, config=run_config) if FLAGS.do_train: file_based_convert_examples_to_features( train_examples[start_index:end_index], label_list, FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"*****", "key))) tf.compat.v1.logging.info(\"**************************\") train_examples = None num_train_steps = None num_warmup_steps = None training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank,", "all_segment_ids = [] all_label_ids = [] for feature in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids)", "= %d\", eval_time_elapsed, eval_hooks[-1].count * FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f", "d.repeat() d = d.shuffle(buffer_size=100) d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return d return input_fn def", "*INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape, init_string) output_spec =", "input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() (assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars,", "(None), 'label_ids') create_model(bert_config, False, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables()", "TN_op, TP_op, FP_op, tf.identity(MCC, name=\"MCC\")) return {\"MCC\": (MCC, MCC_op)} elif task_name == \"mrpc\":", "FLAGS.warmup_proportion) start_index = 0 end_index = len(train_examples) tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record\")] if FLAGS.horovod:", "eval_hooks[-1].count * FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f for Sentences =", "model_fn_builder(task_name, bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_one_hot_embeddings, hvd=None): \"\"\"Returns `model_fn` closure for", "is not None: d = d.shard(hvd.size(), hvd.rank()) d = d.repeat() d = d.shuffle(buffer_size=100)", "NVIDIA CORPORATION. All rights reserved. # Copyright 2018 The Google AI Language Team", "eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file) tf.compat.v1.logging.info(\"***** Running evaluation *****\") tf.compat.v1.logging.info(\" Num examples =", "token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32) # In the demo, we are doing a simple classification", "optimization.LAMBOptimizer(learning_rate=0.0)) output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=probabilities) return output_spec return model_fn # This function", "model_fn(features, labels, mode, params): # pylint: disable=unused-argument \"\"\"The `model_fn` for Estimator.\"\"\" def metric_fn(per_example_loss,", "list(example.keys()): t = example[name] if t.dtype == tf.int64: t = tf.to_int32(t) example[name] =", "init_checkpoint) (total_loss, per_example_loss, logits, probabilities) = tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids, 'label_ids':label_ids}, return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0',", "loss = tf.metrics.mean(values=per_example_loss) f1 = tf_metrics.f1(labels=label_ids, predictions=predictions, num_classes=2, pos_indices=[1]) return { \"eval_accuracy\": accuracy,", "name = %s, shape = %s%s\", var.name, var.shape, init_string) frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(),", "flags.DEFINE_string( \"bert_config_file\", None, \"The config json file corresponding to the pre-trained BERT model.", "8, \"Total batch size for predict.\") flags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate for", "flags.DEFINE_bool(\"amp\", True, \"Whether to enable AMP ops. When false, uses TF32 on A100", "%s\", key, str(result[key])) writer.write(\"%s = %s\\n\" % (key, str(result[key]))) if FLAGS.do_predict and master_process:", "frozen_graph = converter.convert() print('Total node count before and after TF-TRT conversion:', num_nodes, '->',", "BERT model. \" \"This specifies the model architecture.\") flags.DEFINE_string(\"task_name\", None, \"The name of", "that uses tf.py_func which is # not TPU compatible. The right way to", "master_process = (hvd.rank() == 0) hvd_rank = hvd.rank() config.gpu_options.visible_device_list = str(hvd.local_rank()) set_affinity(hvd.local_rank()) if", "time from utils.utils import LogEvalRunHook, LogTrainRunHook, setup_xla_flags from utils.gpu_affinity import set_affinity import utils.dllogger_class", "\"If true, all of the warnings related to data processing will be printed.", "to save the model checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\", 10, \"How often to print loss from", "+ FN) * (TN + FP) * (TN + FN)) ** 0.5 MCC_op", "else hvd) train_start_time = time.time() estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks) train_time_elapsed = time.time() - train_start_time", "train_batch_size\") flags.DEFINE_bool(\"amp\", True, \"Whether to enable AMP ops. When false, uses TF32 on", "Average (sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") if __name__ ==", "= %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\" if FLAGS.amp else \"fp32\") tf.compat.v1.logging.info(\"Latency Confidence", "d = d.shuffle(buffer_size=100) d = d.apply( tf.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder))", "num_nodes, '->', len(frozen_graph.node)) print('TRT node count:', len([1 for n in frozen_graph.node if str(n.op)", "tf.estimator.EstimatorSpec( mode=mode, predictions=predictions) elif mode == tf.estimator.ModeKeys.EVAL: eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec", "tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in tvars: init_string = \"\" if var.name", "= tf.metrics.true_positives(labels=label_ids, predictions=predictions) TN, TN_op = tf.metrics.true_negatives(labels=label_ids, predictions=predictions) MCC = (TP * TN", "tf.compat.v1.logging.info(\"Latency Confidence Level 100 (ms) = %0.2f\", cf_100 * 1000) tf.compat.v1.logging.info(\"Latency Average (ms)", "flags.DEFINE_bool(\"horovod\", False, \"Whether to use Horovod for multi-gpu runs\") flags.DEFINE_bool( \"verbose_logging\", False, \"If", "transpose_b=True) logits = tf.nn.bias_add(logits, output_bias, name='cls_logits') probabilities = tf.nn.softmax(logits, axis=-1, name='cls_probabilities') log_probs =", "steps before gradient update\" \"Global batch size = num_accumulation_steps * train_batch_size\") flags.DEFINE_bool(\"amp\", True,", "= %0.2f\", cf_90 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 95 (ms) = %0.2f\", cf_95", "all_input_mask = [] all_segment_ids = [] all_label_ids = [] for feature in features:", "warnings related to data processing will be printed. \" \"A number of warnings", "ss_sentences_per_second = (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size * 1.0 / train_time_wo_overhead if master_process:", "- training_hooks[-1].skipped) * global_batch_size) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) with overhead = %0.2f\", avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput", "ValueError( \"At least one of `do_train`, `do_eval` or `do_predict' must be True.\") bert_config", "for feature in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id) def input_fn(): \"\"\"The actual input", "# # If you want to use the token-level output, use model.get_sequence_output() #", "\"mnli\": MnliProcessor, \"mrpc\": MrpcProcessor, \"xnli\": XnliProcessor, } if not FLAGS.do_train and not FLAGS.do_eval", "1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1 if FLAGS.amp: tf.enable_resource_variables() run_config = tf.estimator.RunConfig(", "the warnings related to data processing will be printed. \" \"A number of", "features[\"input_ids\"] input_mask = features[\"input_mask\"] segment_ids = features[\"segment_ids\"] label_ids = features[\"label_ids\"] is_training = (mode", "= %d\", num_train_steps) train_input_fn = file_based_input_fn_builder( input_file=tmp_filenames, batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True, hvd=None if", "tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences = %d\", eval_time_elapsed, eval_hooks[-1].count *", "cf_50 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 90 (ms) = %0.2f\", cf_90 * 1000)", "logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) else: dummy_op = tf.no_op() # Need", "= {} if init_checkpoint and (hvd is None or hvd.rank() == 0): (assignment_map,", "if t.dtype == tf.int64: t = tf.to_int32(t) example[name] = t return example def", "tf_config.gpu_options.allow_growth = True output_node_names = ['loss/cls_loss', 'loss/cls_per_example_loss', 'loss/cls_logits', 'loss/cls_probabilities'] with tf.Session(config=tf_config) as tf_sess:", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "= tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids, 'label_ids':label_ids}, return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0', 'loss/cls_logits:0', 'loss/cls_probabilities:0'], name='') if mode", "log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1) if master_process: tf.compat.v1.logging.info(\"***** Configuaration *****\") for key in FLAGS.__flags.keys(): tf.compat.v1.logging.info(' {}:", "computation. eval_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) * 0.8)) * FLAGS.eval_batch_size", "this will be padded.\") flags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\") flags.DEFINE_bool(\"do_eval\", False, \"Whether", "False, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() (assignment_map, initialized_variable_names) =", "Num steps = %d\", num_train_steps) train_input_fn = file_based_input_fn_builder( input_file=tmp_filenames, batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True,", "token-level output, use model.get_sequence_output() # instead. output_layer = model.get_pooled_output() hidden_size = output_layer.shape[-1].value output_weights", "(init/warmup) in throughput computation. eval_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) *", "XnliProcessor, } if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict: raise ValueError(", "{ \"eval_accuracy\": accuracy, \"eval_loss\": loss, } tf.compat.v1.logging.info(\"*** Features ***\") tf.compat.v1.logging.info(\"*** Features ***\") for", "get_frozen_tftrt_model(bert_config, shape, num_labels, use_one_hot_embeddings, init_checkpoint): tf_config = tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth = True output_node_names =", "avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\") if FLAGS.do_eval and master_process: eval_examples", "* FLAGS.eval_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)]) cf_90 = max(time_list[:int(len(time_list)", "= [] all_segment_ids = [] all_label_ids = [] for feature in features: all_input_ids.append(feature.input_ids)", "% (task_name)) processor = processors[task_name]() label_list = processor.get_labels() tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)", "to int32. for name in list(example.keys()): t = example[name] if t.dtype == tf.int64:", "tf.estimator.ModeKeys.PREDICT: predictions = {\"probabilities\": probabilities} output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=predictions) elif mode ==", "%d\", FLAGS.train_batch_size) tf.compat.v1.logging.info(\" Num steps = %d\", num_train_steps) train_input_fn = file_based_input_fn_builder( input_file=tmp_filenames, batch_size=FLAGS.train_batch_size,", "* hvd.size() master_process = (hvd.rank() == 0) hvd_rank = hvd.rank() config.gpu_options.visible_device_list = str(hvd.local_rank())", "= optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps, hvd, False, FLAGS.amp, FLAGS.num_accumulation_steps, FLAGS.optimizer_type) output_spec =", "* (TN + FP) * (TN + FN)) ** 0.5 MCC_op = tf.group(FN_op,", "ValueError( \"Cannot use sequence length %d because the BERT model \" \"was only", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "create_model( bert_config, is_training, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() initialized_variable_names", "\"data_dir\", None, \"The input data dir. Should contain the .tsv files (or other", "writes to\") flags.DEFINE_string( \"optimizer_type\", \"lamb\", \"Optimizer type : adam or lamb\") flags.DEFINE_string( \"init_checkpoint\",", "FP32 on V100 GPUS.\") flags.DEFINE_bool(\"use_xla\", True, \"Whether to enable XLA JIT compilation.\") flags.DEFINE_bool(\"horovod\",", "d return input_fn def create_model(bert_config, is_training, input_ids, input_mask, segment_ids, labels, num_labels, use_one_hot_embeddings): \"\"\"Creates", "tvars: init_string = \"\" if var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\"", "FLAGS.amp, FLAGS.num_accumulation_steps, FLAGS.optimizer_type) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, train_op=train_op) elif mode == tf.estimator.ModeKeys.EVAL:", "the TPU only supports tf.int32. # So cast all int64 to int32. for", "all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"label_ids\": tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32), }) if is_training: if hvd", "tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\" if FLAGS.amp else \"fp32\") tf.compat.v1.logging.info(\"Latency Confidence Level 50 (ms)", "else: accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) return { \"eval_accuracy\": accuracy,", "hvd.rank() < remainder: start_index = hvd.rank() * (num_examples_per_rank+1) end_index = start_index + num_examples_per_rank", "[] all_segment_ids = [] all_label_ids = [] for feature in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask)", "1000, \"How often to save the model checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\", 10, \"How often to", "%s = %s\", key, str(result[key])) writer.write(\"%s = %s\\n\" % (key, str(result[key]))) if FLAGS.do_predict", "simple classification task on the entire # segment. # # If you want", "\"\"\"The `model_fn` for Estimator.\"\"\" def metric_fn(per_example_loss, label_ids, logits): predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)", "= sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) * 0.8)) * FLAGS.eval_batch_size avg =", "predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) if task_name == \"cola\": FN, FN_op = tf.metrics.false_negatives(labels=label_ids,", "purposes and does NOT scale to large data sets. We do # not", "False, FLAGS.amp, FLAGS.num_accumulation_steps, FLAGS.optimizer_type) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, train_op=train_op) elif mode ==", "as writer: tf.compat.v1.logging.info(\"***** Eval results *****\") for key in sorted(result.keys()): dllogging.logger.log(step=(), data={key: float(result[key])},", "return d return input_fn def create_model(bert_config, is_training, input_ids, input_mask, segment_ids, labels, num_labels, use_one_hot_embeddings):", "\"\"\"Creates an `input_fn` closure to be passed to Estimator.\"\"\" all_input_ids = [] all_input_mask", "count:', len([1 for n in frozen_graph.node if str(n.op) == 'TRTEngineOp'])) with tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\")", "the BERT model was trained on.\") flags.DEFINE_string( \"output_dir\", None, \"The output directory where", "FLAGS.verbose_logging: tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in tvars: init_string = \"\" if", "tf.train.experimental.FixedLossScale(1) dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler) eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec =", "d.shuffle(buffer_size=100) d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return d return input_fn def main(_): setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)", "FLAGS.eval_batch_size) eval_drop_remainder = False eval_input_fn = file_based_input_fn_builder( input_file=eval_file, batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder) eval_hooks", "A100 and FP32 on V100 GPUS.\") flags.DEFINE_bool(\"use_xla\", True, \"Whether to enable XLA JIT", "tf.compat.v1.logging.info(\" name = %s, shape = %s\" % (name, features[name].shape)) input_ids = features[\"input_ids\"]", "number of warnings are expected for a normal SQuAD evaluation.\") def file_based_input_fn_builder(input_file, batch_size,", "%0.2f\", cf_99 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 100 (ms) = %0.2f\", cf_100 *", "*****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(eval_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size)", "\"output_dir\", None, \"The output directory where the model checkpoints will be written.\") ##", "(usually from a pre-trained BERT model).\") flags.DEFINE_bool( \"do_lower_case\", True, \"Whether to lower case", "output_weights = tf.get_variable( \"output_weights\", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable( \"output_bias\", [num_labels], initializer=tf.zeros_initializer())", "function.\"\"\" # For training, we want a lot of parallel reading and shuffling.", "checkpoints will be written.\") ## Other parameters flags.DEFINE_string( \"dllog_path\", \"/results/bert_dllog.json\", \"filename where dllogger", "flags.DEFINE_string( \"optimizer_type\", \"lamb\", \"Optimizer type : adam or lamb\") flags.DEFINE_string( \"init_checkpoint\", None, \"Initial", "the BERT model \" \"was only trained up to sequence length %d\" %", "tf.compat.v1.logging.info(\"Latency Confidence Level 90 (ms) = %0.2f\", cf_90 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level", "the License for the specific language governing permissions and # limitations under the", "} def _decode_record(record, name_to_features): \"\"\"Decodes a record to a TensorFlow example.\"\"\" example =", "len(frozen_graph.node) print('Converting graph using TensorFlow-TensorRT...') from tensorflow.python.compiler.tensorrt import trt_convert as trt converter =", "TP_op = tf.metrics.true_positives(labels=label_ids, predictions=predictions) TN, TN_op = tf.metrics.true_negatives(labels=label_ids, predictions=predictions) MCC = (TP *", "num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_one_hot_embeddings, hvd=None): \"\"\"Returns `model_fn` closure for Estimator.\"\"\" def", "flags.DEFINE_bool( \"do_predict\", False, \"Whether to run the model in inference mode on the", "cf_95 = max(time_list[:int(len(time_list) * 0.95)]) cf_99 = max(time_list[:int(len(time_list) * 0.99)]) cf_100 = max(time_list[:int(len(time_list)", "** 0.5 MCC_op = tf.group(FN_op, TN_op, TP_op, FP_op, tf.identity(MCC, name=\"MCC\")) return {\"MCC\": (MCC,", "%0.2f for Sentences = %d\", eval_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on EVAL set\")", "initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\") tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for", "`model_fn` closure for Estimator.\"\"\" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument \"\"\"The", "for Sentences = %d\", predict_time_elapsed, predict_hooks[-1].count * FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead", "tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences = %d\", predict_time_elapsed, predict_hooks[-1].count *", "0 config = tf.compat.v1.ConfigProto() if FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU training with TF Horovod\") tf.compat.v1.logging.info(\"hvd.size() =", "if mode == tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps, hvd, False,", "writer.write(output_line) predict_time_elapsed = time.time() - predict_start_time time_list = predict_hooks[-1].time_list time_list.sort() # Removing outliers", "0.50)]) cf_90 = max(time_list[:int(len(time_list) * 0.90)]) cf_95 = max(time_list[:int(len(time_list) * 0.95)]) cf_99 =", "= {\"probabilities\": probabilities} output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=predictions) elif mode == tf.estimator.ModeKeys.EVAL: eval_metric_ops", "use_one_hot_embeddings) tvars = tf.trainable_variables() (assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\")", "time_list = predict_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in throughput computation. predict_time_wo_overhead =", "print('TRT node count:', len([1 for n in frozen_graph.node if str(n.op) == 'TRTEngineOp'])) with", "FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\" if FLAGS.amp else", "one of `do_train`, `do_eval` or `do_predict' must be True.\") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "_decode_record(record, name_to_features): \"\"\"Decodes a record to a TensorFlow example.\"\"\" example = tf.parse_single_example(record, name_to_features)", "0.99)]) cf_100 = max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second = num_sentences * 1.0 / eval_time_wo_overhead", "1.0 / train_time_elapsed ss_sentences_per_second = (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size * 1.0 /", "linear learning rate warmup for. \" \"E.g., 0.1 = 10% of training.\") flags.DEFINE_integer(\"save_checkpoints_steps\",", "config json file corresponding to the pre-trained BERT model. \" \"This specifies the", "to run training.\") flags.DEFINE_bool(\"do_eval\", False, \"Whether to run eval on the dev set.\")", "file_based_input_fn_builder(input_file, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure to be passed", "want to use the token-level output, use model.get_sequence_output() # instead. output_layer = model.get_pooled_output()", "%s, shape = %s%s\", var.name, var.shape, init_string) output_spec = None if mode ==", "d = d.repeat() d = d.shuffle(buffer_size=100) d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return d return", "count before and after TF-TRT conversion:', num_nodes, '->', len(frozen_graph.node)) print('TRT node count:', len([1", "%d\", FLAGS.eval_batch_size) eval_drop_remainder = False eval_input_fn = file_based_input_fn_builder( input_file=eval_file, batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder)", "padded.\") flags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\") flags.DEFINE_bool(\"do_eval\", False, \"Whether to run eval", "and after TF-TRT conversion:', num_nodes, '->', len(frozen_graph.node)) print('TRT node count:', len([1 for n", "be printed. \" \"A number of warnings are expected for a normal SQuAD", "Need to call mixed precision graph rewrite if fp16 to enable graph rewrite", "training.\") flags.DEFINE_bool(\"do_eval\", False, \"Whether to run eval on the dev set.\") flags.DEFINE_bool( \"do_predict\",", "test set.\") flags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for training.\") flags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch", "{\"MCC\": (MCC, MCC_op)} elif task_name == \"mrpc\": accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss", "who depend on it. def input_fn_builder(features, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an", "Time = %0.2f for Sentences = %d\", eval_time_elapsed, eval_hooks[-1].count * FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total Inference", "%s, shape = %s%s\", var.name, var.shape, init_string) frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(), output_node_names) num_nodes", "tf.compat.v1.logging.info(\" Num examples = %d\", len(predict_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size) predict_drop_remainder", "+ 1 else: start_index = hvd.rank() * num_examples_per_rank + remainder end_index = start_index", "= False predict_input_fn = file_based_input_fn_builder( input_file=predict_file, batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder) predict_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)]", "# This is for demo purposes and does NOT scale to large data", "FLAGS.predict_batch_size) predict_drop_remainder = False predict_input_fn = file_based_input_fn_builder( input_file=predict_file, batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder) predict_hooks", "flags.DEFINE_bool( \"do_lower_case\", True, \"Whether to lower case the input text. Should be True", "(loss, per_example_loss, logits, probabilities) def get_frozen_tftrt_model(bert_config, shape, num_labels, use_one_hot_embeddings, init_checkpoint): tf_config = tf.compat.v1.ConfigProto()", "size for eval.\") flags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch size for predict.\") flags.DEFINE_float(\"learning_rate\", 5e-5, \"The", "Version 2.0 (the \"License\"); # you may not use this file except in", "\"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64), \"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"label_ids\": tf.io.FixedLenFeature([], tf.int64), } def _decode_record(record, name_to_features):", "\"train.tf_record\")] if FLAGS.horovod: tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i)) for i in range(hvd.size())] num_examples_per_rank =", "(task_name)) processor = processors[task_name]() label_list = processor.get_labels() tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) master_process", "keep_checkpoint_max=1) if master_process: tf.compat.v1.logging.info(\"***** Configuaration *****\") for key in FLAGS.__flags.keys(): tf.compat.v1.logging.info(' {}: {}'.format(key,", "tf_sess: input_ids = tf.placeholder(tf.int32, shape, 'input_ids') input_mask = tf.placeholder(tf.int32, shape, 'input_mask') segment_ids =", "tokenizer, eval_file) tf.compat.v1.logging.info(\"***** Running evaluation *****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(eval_examples)) tf.compat.v1.logging.info(\"", "train_time_elapsed, num_train_steps * global_batch_size) tf.compat.v1.logging.info(\"Total Training Time W/O Overhead = %0.2f for Sentences", "= %d\", len(eval_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size) eval_drop_remainder = False eval_input_fn", "= time.time() - eval_start_time time_list = eval_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in", "flags.DEFINE_string(\"vocab_file\", None, \"The vocabulary file that the BERT model was trained on.\") flags.DEFINE_string(", "None num_warmup_steps = None training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25)) if FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir)", "if FLAGS.amp: dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0)) output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=probabilities) return output_spec", "Training Time = %0.2f for Sentences = %d\", train_time_elapsed, num_train_steps * global_batch_size) tf.compat.v1.logging.info(\"Total", "master_process: predict_examples = processor.get_test_examples(FLAGS.data_dir) predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\") file_based_convert_examples_to_features(predict_examples, label_list, FLAGS.max_seq_length, tokenizer, predict_file)", "\"\"\"The actual input function.\"\"\" num_examples = len(features) # This is for demo purposes", "= tf.compat.v1.OptimizerOptions.ON_1 if FLAGS.amp: tf.enable_resource_variables() run_config = tf.estimator.RunConfig( model_dir=FLAGS.output_dir if master_process else None,", "label_list, FLAGS.max_seq_length, tokenizer, predict_file) tf.compat.v1.logging.info(\"***** Running prediction*****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(predict_examples))", "node count:', len([1 for n in frozen_graph.node if str(n.op) == 'TRTEngineOp'])) with tf.io.gfile.GFile(\"frozen_modelTRT.pb\",", "where the model checkpoints will be written.\") ## Other parameters flags.DEFINE_string( \"dllog_path\", \"/results/bert_dllog.json\",", "compute_type=tf.float32) # In the demo, we are doing a simple classification task on", "= d.repeat() d = d.shuffle(buffer_size=100) d = d.apply( tf.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features),", "else None, log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1) if master_process: tf.compat.v1.logging.info(\"***** Configuaration *****\") for key in FLAGS.__flags.keys():", "the model checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\", 10, \"How often to print loss from estimator\") flags.DEFINE_integer(\"iterations_per_loop\",", "time.time() result = estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks) eval_time_elapsed = time.time() - eval_start_time time_list = eval_hooks[-1].time_list", "= (hvd.rank() == 0) hvd_rank = hvd.rank() config.gpu_options.visible_device_list = str(hvd.local_rank()) set_affinity(hvd.local_rank()) if hvd.size()", "Inference Statistics on EVAL set\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence Length =", "dev set.\") flags.DEFINE_bool( \"do_predict\", False, \"Whether to run the model in inference mode", "%d\", FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\" if FLAGS.amp", "not TPU compatible. The right way to load data is with TFRecordReader. d", "'->', len(frozen_graph.node)) print('TRT node count:', len([1 for n in frozen_graph.node if str(n.op) ==", "None: d = d.shard(hvd.size(), hvd.rank()) d = d.repeat() d = d.shuffle(buffer_size=100) d =", "bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError( \"Cannot use sequence length", "raise ValueError( \"Cannot use sequence length %d because the BERT model \" \"was", "cf_100 = max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second = num_sentences * 1.0 / predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\")", "\"verbose_logging\", False, \"If true, all of the warnings related to data processing will", "def model_fn(features, labels, mode, params): # pylint: disable=unused-argument \"\"\"The `model_fn` for Estimator.\"\"\" def", "master_process: tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Training Time = %0.2f for Sentences = %d\", train_time_elapsed, num_train_steps", "max_steps=num_train_steps, hooks=training_hooks) train_time_elapsed = time.time() - train_start_time train_time_wo_overhead = training_hooks[-1].total_time avg_sentences_per_second = num_train_steps", "train_time_wo_overhead = training_hooks[-1].total_time avg_sentences_per_second = num_train_steps * global_batch_size * 1.0 / train_time_elapsed ss_sentences_per_second", "predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences = %d\", predict_time_elapsed, predict_hooks[-1].count", "# not use Dataset.from_generator() because that uses tf.py_func which is # not TPU", "assignment_map) if FLAGS.verbose_logging: tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in tvars: init_string =", "not FLAGS.do_eval and not FLAGS.do_predict: raise ValueError( \"At least one of `do_train`, `do_eval`", "on V100 GPUS.\") flags.DEFINE_bool(\"use_xla\", True, \"Whether to enable XLA JIT compilation.\") flags.DEFINE_bool(\"horovod\", False,", "Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved. # Copyright 2018 The Google", "result = estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks) eval_time_elapsed = time.time() - eval_start_time time_list = eval_hooks[-1].time_list time_list.sort()", "truncated, and sequences shorter \" \"than this will be padded.\") flags.DEFINE_bool(\"do_train\", False, \"Whether", "for multi-gpu runs\") flags.DEFINE_bool( \"verbose_logging\", False, \"If true, all of the warnings related", "num_sentences * 1.0 / eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences", "predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) f1 = tf_metrics.f1(labels=label_ids, predictions=predictions, num_classes=2, pos_indices=[1]) return { \"eval_accuracy\":", "segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() (assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint,", "flags.DEFINE_integer( \"max_seq_length\", 128, \"The maximum total input sequence length after WordPiece tokenization. \"", "bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_one_hot_embeddings, hvd=None): \"\"\"Returns `model_fn` closure for Estimator.\"\"\"", "= d.shuffle(buffer_size=100) d = d.apply( tf.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder)) return", "np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)]) cf_90 = max(time_list[:int(len(time_list) * 0.90)]) cf_95 =", "loss = tf.metrics.mean(values=per_example_loss) return { \"eval_accuracy\": accuracy, \"eval_loss\": loss, } tf.compat.v1.logging.info(\"*** Features ***\")", "None if mode == tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps, hvd,", "d.shuffle(buffer_size=100) d = d.apply( tf.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder)) return d", "outliers (init/warmup) in throughput computation. predict_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list)", "Adam.\") flags.DEFINE_bool(\"use_trt\", False, \"Whether to use TF-TRT\") flags.DEFINE_float(\"num_train_epochs\", 3.0, \"Total number of training", "to print loss from estimator\") flags.DEFINE_integer(\"iterations_per_loop\", 1000, \"How many steps to make in", "trt converter = trt.TrtGraphConverter( input_graph_def=frozen_graph, nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096 << 20) - 1000, precision_mode =", "Confidence Level 95 (ms) = %0.2f\", cf_95 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 99", "%0.2f\", avg * 1000) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second},", "hvd.rank()) d = d.repeat() d = d.shuffle(buffer_size=100) d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return d", "# If you want to use the token-level output, use model.get_sequence_output() # instead.", "= (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size * 1.0 / train_time_wo_overhead if master_process: tf.compat.v1.logging.info(\"-----------------------------\")", "tf.compat.v1.logging.info(\"***** Predict results *****\") for prediction in estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks, yield_single_examples=False): output_line = \"\\t\".join(", "len(train_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.train_batch_size) tf.compat.v1.logging.info(\" Num steps = %d\", num_train_steps)", "\" \"A number of warnings are expected for a normal SQuAD evaluation.\") def", "examples = %d\", len(eval_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size) eval_drop_remainder = False", "* 0.8)) * FLAGS.predict_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)]) cf_90", "= metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) return output_spec (total_loss,", "Level 99 (ms) = %0.2f\", cf_99 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 100 (ms)", "tf.reduce_mean(per_example_loss, name='cls_loss') return (loss, per_example_loss, logits, probabilities) def get_frozen_tftrt_model(bert_config, shape, num_labels, use_one_hot_embeddings, init_checkpoint):", "other data files) \" \"for the task.\") flags.DEFINE_string( \"bert_config_file\", None, \"The config json", "num_accumulation_steps * train_batch_size\") flags.DEFINE_bool(\"amp\", True, \"Whether to enable AMP ops. When false, uses", "train_input_fn = file_based_input_fn_builder( input_file=tmp_filenames, batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True, hvd=None if not FLAGS.horovod else", "with overhead = %0.2f\", avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\") if", "\"\\t\".join( str(class_probability) for class_probability in prediction) + \"\\n\" writer.write(output_line) predict_time_elapsed = time.time() -", "License. \"\"\"BERT finetuning runner.\"\"\" from __future__ import absolute_import from __future__ import division from", "os.path.join(FLAGS.output_dir, \"eval_results.txt\") with tf.io.gfile.GFile(output_eval_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Eval results *****\") for key", "horovod.tensorflow as hvd import time from utils.utils import LogEvalRunHook, LogTrainRunHook, setup_xla_flags from utils.gpu_affinity", "= %0.2f for Sentences = %d\", train_time_wo_overhead, (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size) tf.compat.v1.logging.info(\"Throughput", "as writer: tf.compat.v1.logging.info(\"***** Predict results *****\") for prediction in estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks, yield_single_examples=False): output_line", "= modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError( \"Cannot use sequence length %d", "is # not TPU compatible. The right way to load data is with", "we want no shuffling and parallel reading doesn't matter. d = tf.data.TFRecordDataset(input_file) if", "* (TP + FN) * (TN + FP) * (TN + FN)) **", "def input_fn(): \"\"\"The actual input function.\"\"\" # For training, we want a lot", "Num examples = %d\", len(train_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.train_batch_size) tf.compat.v1.logging.info(\" Num", "else: init_string = \", *NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\" name = %s, shape = %s%s\", var.name,", "1000) tf.compat.v1.logging.info(\"Latency Confidence Level 99 (ms) = %0.2f\", cf_99 * 1000) tf.compat.v1.logging.info(\"Latency Confidence", "predict.\") flags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate for Adam.\") flags.DEFINE_bool(\"use_trt\", False, \"Whether to", "because the BERT model \" \"was only trained up to sequence length %d\"", "data is with TFRecordReader. d = tf.data.Dataset.from_tensor_slices({ \"input_ids\": tf.constant( all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32),", "= tf.get_variable( \"output_bias\", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope(\"loss\"): if is_training: # I.e., 0.1 dropout", "and not FLAGS.do_eval and not FLAGS.do_predict: raise ValueError( \"At least one of `do_train`,", "== tf.estimator.ModeKeys.EVAL: eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops)", "name='cls_logits') probabilities = tf.nn.softmax(logits, axis=-1, name='cls_probabilities') log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels,", "= %d hvd.rank() = %d\", hvd.size(), hvd.rank()) global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps *", "model_fn = model_fn_builder( task_name=task_name, bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate if not FLAGS.horovod else FLAGS.learning_rate", "\" \"E.g., 0.1 = 10% of training.\") flags.DEFINE_integer(\"save_checkpoints_steps\", 1000, \"How often to save", "[os.path.join(FLAGS.output_dir, \"train.tf_record\")] if FLAGS.horovod: tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i)) for i in range(hvd.size())] num_examples_per_rank", "%d\", eval_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on EVAL set\") tf.compat.v1.logging.info(\"Batch size = %d\",", "file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file) tf.compat.v1.logging.info(\"***** Running evaluation *****\") tf.compat.v1.logging.info(\" Num examples", "tf.io.FixedLenFeature([], tf.int64), } def _decode_record(record, name_to_features): \"\"\"Decodes a record to a TensorFlow example.\"\"\"", "multi-gpu runs\") flags.DEFINE_bool( \"verbose_logging\", False, \"If true, all of the warnings related to", "\" \"Sequences longer than this will be truncated, and sequences shorter \" \"than", "max_workspace_size_bytes=(4096 << 20) - 1000, precision_mode = \"FP16\" if FLAGS.amp else \"FP32\", minimum_segment_size=4,", "import numpy as np import tf_metrics flags = tf.flags FLAGS = flags.FLAGS ##", "precision graph rewrite if fp16 to enable graph rewrite if FLAGS.amp: dummy_op =", "task on the entire # segment. # # If you want to use", "<< 20) - 1000, precision_mode = \"FP16\" if FLAGS.amp else \"FP32\", minimum_segment_size=4, is_dynamic_op=True,", "Features ***\") for name in sorted(features.keys()): tf.compat.v1.logging.info(\" name = %s, shape = %s\"", "%d\", predict_time_elapsed, predict_hooks[-1].count * FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f for", "data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") if __name__ == \"__main__\": flags.mark_flag_as_required(\"data_dir\") flags.mark_flag_as_required(\"task_name\") flags.mark_flag_as_required(\"vocab_file\") flags.mark_flag_as_required(\"bert_config_file\") flags.mark_flag_as_required(\"output_dir\")", "output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias, name='cls_logits') probabilities = tf.nn.softmax(logits, axis=-1, name='cls_probabilities') log_probs", "tf.compat.v1.logging.info(\"Total Training Time W/O Overhead = %0.2f for Sentences = %d\", train_time_wo_overhead, (training_hooks[-1].count", "% (name, features[name].shape)) input_ids = features[\"input_ids\"] input_mask = features[\"input_mask\"] segment_ids = features[\"segment_ids\"] label_ids", "%d\", train_time_wo_overhead, (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) with overhead =", "False, \"Whether to run training.\") flags.DEFINE_bool(\"do_eval\", False, \"Whether to run eval on the", "to be passed to Estimator.\"\"\" name_to_features = { \"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"input_mask\": tf.io.FixedLenFeature([seq_length],", "import os import modeling import optimization import tokenization import tensorflow as tf import", "FLAGS.do_eval and not FLAGS.do_predict: raise ValueError( \"At least one of `do_train`, `do_eval` or", "\"mrpc\": MrpcProcessor, \"xnli\": XnliProcessor, } if not FLAGS.do_train and not FLAGS.do_eval and not", "start_index = hvd.rank() * num_examples_per_rank + remainder end_index = start_index + (num_examples_per_rank) model_fn", "prediction) + \"\\n\" writer.write(output_line) predict_time_elapsed = time.time() - predict_start_time time_list = predict_hooks[-1].time_list time_list.sort()", "or `do_predict' must be True.\") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise", "flags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for training.\") flags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch size for", "int( len(train_examples) / global_batch_size * FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion) start_index =", "OF ANY KIND, either express or implied. # See the License for the", "tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32), }) if is_training: if hvd is not None: d =", "- eval_start_time time_list = eval_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in throughput computation.", "tf.metrics.true_negatives(labels=label_ids, predictions=predictions) MCC = (TP * TN - FP * FN) / ((TP", "= hvd.rank() * num_examples_per_rank + remainder end_index = start_index + (num_examples_per_rank) model_fn =", "(c) 2019 NVIDIA CORPORATION. All rights reserved. # Copyright 2018 The Google AI", "True.\") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError( \"Cannot use sequence", "= d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return d return input_fn def main(_): setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging =", "init_string = \", *NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape,", "to large data sets. We do # not use Dataset.from_generator() because that uses", "trained on.\") flags.DEFINE_string( \"output_dir\", None, \"The output directory where the model checkpoints will", "warmup for. \" \"E.g., 0.1 = 10% of training.\") flags.DEFINE_integer(\"save_checkpoints_steps\", 1000, \"How often", "sequence length %d because the BERT model \" \"was only trained up to", "= tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth = True output_node_names = ['loss/cls_loss', 'loss/cls_per_example_loss', 'loss/cls_logits', 'loss/cls_probabilities'] with tf.Session(config=tf_config)", "used by the Colab and # people who depend on it. def input_fn_builder(features,", "%d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\" if FLAGS.amp else \"fp32\") tf.compat.v1.logging.info(\"Latency Confidence Level", "is still used by the Colab and # people who depend on it.", "(sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\")", "flags.FLAGS ## Required parameters flags.DEFINE_string( \"data_dir\", None, \"The input data dir. Should contain", "+ num_examples_per_rank + 1 else: start_index = hvd.rank() * num_examples_per_rank + remainder end_index", "use the token-level output, use model.get_sequence_output() # instead. output_layer = model.get_pooled_output() hidden_size =", "precision_mode = \"FP16\" if FLAGS.amp else \"FP32\", minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000 ) frozen_graph =", "total input sequence length after WordPiece tokenization. \" \"Sequences longer than this will", "in estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks, yield_single_examples=False): output_line = \"\\t\".join( str(class_probability) for class_probability in prediction) +", "modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32) # In the demo, we", "size = %d\", FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\"", "remainder end_index = start_index + (num_examples_per_rank) model_fn = model_fn_builder( task_name=task_name, bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint,", "num_train_steps, num_warmup_steps, use_one_hot_embeddings, hvd=None): \"\"\"Returns `model_fn` closure for Estimator.\"\"\" def model_fn(features, labels, mode,", "in sorted(result.keys()): dllogging.logger.log(step=(), data={key: float(result[key])}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\" %s = %s\", key, str(result[key])) writer.write(\"%s", "\"Whether to run training.\") flags.DEFINE_bool(\"do_eval\", False, \"Whether to run eval on the dev", "d.shard(hvd.size(), hvd.rank()) d = d.repeat() d = d.shuffle(buffer_size=100) d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return", "num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion) start_index = 0 end_index = len(train_examples) tmp_filenames =", "processor = processors[task_name]() label_list = processor.get_labels() tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) master_process =", "train_time_elapsed = time.time() - train_start_time train_time_wo_overhead = training_hooks[-1].total_time avg_sentences_per_second = num_train_steps * global_batch_size", "in processors: raise ValueError(\"Task not found: %s\" % (task_name)) processor = processors[task_name]() label_list", "tf.metrics.mean(values=per_example_loss) return { \"eval_accuracy\": accuracy, \"eval_loss\": loss, } tf.compat.v1.logging.info(\"*** Features ***\") tf.compat.v1.logging.info(\"*** Features", "where dllogger writes to\") flags.DEFINE_string( \"optimizer_type\", \"lamb\", \"Optimizer type : adam or lamb\")", "tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\") if FLAGS.do_eval and master_process: eval_examples =", "output_node_names = ['loss/cls_loss', 'loss/cls_per_example_loss', 'loss/cls_logits', 'loss/cls_probabilities'] with tf.Session(config=tf_config) as tf_sess: input_ids = tf.placeholder(tf.int32,", "to use the token-level output, use model.get_sequence_output() # instead. output_layer = model.get_pooled_output() hidden_size", "for var in tvars: init_string = \"\" if var.name in initialized_variable_names: init_string =", "file_based_input_fn_builder( input_file=tmp_filenames, batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True, hvd=None if not FLAGS.horovod else hvd) train_start_time", "frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(), output_node_names) num_nodes = len(frozen_graph.node) print('Converting graph using TensorFlow-TensorRT...') from", "tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Training Time = %0.2f for Sentences = %d\", train_time_elapsed, num_train_steps *", "tf.data.Dataset.from_tensor_slices({ \"input_ids\": tf.constant( all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"input_mask\": tf.constant( all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32),", "tvars = tf.trainable_variables() (assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\") tf.compat.v1.logging.info(\"****", "classification model.\"\"\" model = modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32) #", "model_dir=FLAGS.output_dir if master_process else None, session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process else None, save_summary_steps=FLAGS.save_checkpoints_steps if", "save the model checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\", 10, \"How often to print loss from estimator\")", "= features[\"input_mask\"] segment_ids = features[\"segment_ids\"] label_ids = features[\"label_ids\"] is_training = (mode == tf.estimator.ModeKeys.TRAIN)", "is None or hvd.rank() == 0): (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint,", "to call mixed precision graph rewrite if fp16 to enable graph rewrite if", "predict_examples = processor.get_test_examples(FLAGS.data_dir) predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\") file_based_convert_examples_to_features(predict_examples, label_list, FLAGS.max_seq_length, tokenizer, predict_file) tf.compat.v1.logging.info(\"*****", "ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") if __name__ == \"__main__\": flags.mark_flag_as_required(\"data_dir\") flags.mark_flag_as_required(\"task_name\") flags.mark_flag_as_required(\"vocab_file\")", "a classification model.\"\"\" model = modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32)", "if FLAGS.amp: tf.enable_resource_variables() run_config = tf.estimator.RunConfig( model_dir=FLAGS.output_dir if master_process else None, session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps", "for n in frozen_graph.node if str(n.op) == 'TRTEngineOp'])) with tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\") as f:", "%d\", train_time_elapsed, num_train_steps * global_batch_size) tf.compat.v1.logging.info(\"Total Training Time W/O Overhead = %0.2f for", "= FLAGS.train_batch_size * FLAGS.num_accumulation_steps * hvd.size() master_process = (hvd.rank() == 0) hvd_rank =", "hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable( \"output_bias\", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope(\"loss\"): if is_training: #", "by the Colab and # people who depend on it. def input_fn_builder(features, batch_size,", "only trained up to sequence length %d\" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) task_name =", "None, \"The name of the task to train.\") flags.DEFINE_string(\"vocab_file\", None, \"The vocabulary file", "metric_fn(per_example_loss, label_ids, logits): predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) if task_name == \"cola\": FN,", "tf.matmul(output_layer, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias, name='cls_logits') probabilities = tf.nn.softmax(logits, axis=-1, name='cls_probabilities')", "file_based_input_fn_builder( input_file=eval_file, batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder) eval_hooks = [LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time = time.time() result", "tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size) predict_drop_remainder = False predict_input_fn = file_based_input_fn_builder( input_file=predict_file,", "'label_ids':label_ids}, return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0', 'loss/cls_logits:0', 'loss/cls_probabilities:0'], name='') if mode == tf.estimator.ModeKeys.PREDICT: predictions = {\"probabilities\":", "Sentences = %d\", train_time_wo_overhead, (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) with", "tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\") with tf.io.gfile.GFile(output_eval_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Eval results", "For eval, we want no shuffling and parallel reading doesn't matter. d =", "features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id) def input_fn(): \"\"\"The actual input function.\"\"\" num_examples =", "== tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps, hvd, False, FLAGS.amp, FLAGS.num_accumulation_steps,", "= %d\", eval_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on EVAL set\") tf.compat.v1.logging.info(\"Batch size =", "the specific language governing permissions and # limitations under the License. \"\"\"BERT finetuning", "FLAGS.__flags.keys(): tf.compat.v1.logging.info(' {}: {}'.format(key, getattr(FLAGS, key))) tf.compat.v1.logging.info(\"**************************\") train_examples = None num_train_steps = None", "or agreed to in writing, software # distributed under the License is distributed", "if is_training: # I.e., 0.1 dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer,", "{}: {}'.format(key, getattr(FLAGS, key))) tf.compat.v1.logging.info(\"**************************\") train_examples = None num_train_steps = None num_warmup_steps =", "FLAGS.predict_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)]) cf_90 = max(time_list[:int(len(time_list) *", "Running prediction*****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(predict_examples)) tf.compat.v1.logging.info(\" Batch size = %d\",", "output_type=tf.int32) if task_name == \"cola\": FN, FN_op = tf.metrics.false_negatives(labels=label_ids, predictions=predictions) FP, FP_op =", "\"Proportion of training to perform linear learning rate warmup for. \" \"E.g., 0.1", "input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32) # In the demo, we are doing a", "shape=[num_examples, seq_length], dtype=tf.int32), \"input_mask\": tf.constant( all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32), \"segment_ids\": tf.constant( all_segment_ids, shape=[num_examples,", "\"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"label_ids\": tf.io.FixedLenFeature([], tf.int64), } def _decode_record(record, name_to_features): \"\"\"Decodes a record", "tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences = %d\", eval_time_elapsed, eval_hooks[-1].count * FLAGS.eval_batch_size)", "input_fn(): \"\"\"The actual input function.\"\"\" num_examples = len(features) # This is for demo", "shorter \" \"than this will be padded.\") flags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\")", "vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) master_process = True training_hooks = [] global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps", "SQuAD evaluation.\") def file_based_input_fn_builder(input_file, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure", "parameters flags.DEFINE_string( \"data_dir\", None, \"The input data dir. Should contain the .tsv files", "of the warnings related to data processing will be printed. \" \"A number", "tf.constant( all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"input_mask\": tf.constant( all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32), \"segment_ids\": tf.constant(", "mode on the test set.\") flags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for training.\") flags.DEFINE_integer(\"eval_batch_size\",", "key in sorted(result.keys()): dllogging.logger.log(step=(), data={key: float(result[key])}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\" %s = %s\", key, str(result[key]))", "initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if FLAGS.verbose_logging: tf.compat.v1.logging.info(\"**** Trainable Variables ****\")", "tf.py_func which is # not TPU compatible. The right way to load data", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "(total_loss, per_example_loss, logits, probabilities) = create_model( bert_config, is_training, input_ids, input_mask, segment_ids, label_ids, num_labels,", "output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\") with tf.io.gfile.GFile(output_eval_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Eval results *****\")", "* 0.95)]) cf_99 = max(time_list[:int(len(time_list) * 0.99)]) cf_100 = max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second", "cf_95 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 99 (ms) = %0.2f\", cf_99 * 1000)", "%0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\") with tf.io.gfile.GFile(output_eval_file,", "len([1 for n in frozen_graph.node if str(n.op) == 'TRTEngineOp'])) with tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\") as", "labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) f1 = tf_metrics.f1(labels=label_ids, predictions=predictions, num_classes=2, pos_indices=[1]) return {", "} else: accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) return { \"eval_accuracy\":", ": adam or lamb\") flags.DEFINE_string( \"init_checkpoint\", None, \"Initial checkpoint (usually from a pre-trained", "to data processing will be printed. \" \"A number of warnings are expected", "License. # You may obtain a copy of the License at # #", "cf_99 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 100 (ms) = %0.2f\", cf_100 * 1000)", "shape = %s%s\", var.name, var.shape, init_string) frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(), output_node_names) num_nodes =", "accuracy, \"eval_loss\": loss, } tf.compat.v1.logging.info(\"*** Features ***\") tf.compat.v1.logging.info(\"*** Features ***\") for name in", "mode == tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps, hvd, False, FLAGS.amp,", "Sentences = %d\", predict_time_elapsed, predict_hooks[-1].count * FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead =", "loss, } tf.compat.v1.logging.info(\"*** Features ***\") tf.compat.v1.logging.info(\"*** Features ***\") for name in sorted(features.keys()): tf.compat.v1.logging.info(\"", "* global_batch_size * 1.0 / train_time_elapsed ss_sentences_per_second = (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size", "Confidence Level 99 (ms) = %0.2f\", cf_99 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 100", "an `input_fn` closure to be passed to Estimator.\"\"\" all_input_ids = [] all_input_mask =", "task.\") flags.DEFINE_string( \"bert_config_file\", None, \"The config json file corresponding to the pre-trained BERT", "TF-TRT\") flags.DEFINE_float(\"num_train_epochs\", 3.0, \"Total number of training epochs to perform.\") flags.DEFINE_float( \"warmup_proportion\", 0.1,", "graph rewrite if fp16 to enable graph rewrite if FLAGS.amp: dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite(", "rewrite if FLAGS.amp: dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0)) output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=probabilities) return", "init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\") tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in tvars:", "name='') if mode == tf.estimator.ModeKeys.PREDICT: predictions = {\"probabilities\": probabilities} output_spec = tf.estimator.EstimatorSpec( mode=mode,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "None, save_summary_steps=FLAGS.save_checkpoints_steps if master_process else None, log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1) if master_process: tf.compat.v1.logging.info(\"***** Configuaration *****\")", "* 0.8)) * FLAGS.eval_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)]) cf_90", "and # people who depend on it. def input_fn_builder(features, batch_size, seq_length, is_training, drop_remainder,", "if FLAGS.horovod: hvd.init() processors = { \"cola\": ColaProcessor, \"mnli\": MnliProcessor, \"mrpc\": MrpcProcessor, \"xnli\":", "enable AMP ops. When false, uses TF32 on A100 and FP32 on V100", "***\") for name in sorted(features.keys()): tf.compat.v1.logging.info(\" name = %s, shape = %s\" %", "num_train_steps) train_input_fn = file_based_input_fn_builder( input_file=tmp_filenames, batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True, hvd=None if not FLAGS.horovod", "checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\", 10, \"How often to print loss from estimator\") flags.DEFINE_integer(\"iterations_per_loop\", 1000, \"How", "Trainable Variables ****\") for var in tvars: init_string = \"\" if var.name in", "input_mask = features[\"input_mask\"] segment_ids = features[\"segment_ids\"] label_ids = features[\"label_ids\"] is_training = (mode ==", "\"The input data dir. Should contain the .tsv files (or other data files)", "1000) tf.compat.v1.logging.info(\"Latency Confidence Level 95 (ms) = %0.2f\", cf_95 * 1000) tf.compat.v1.logging.info(\"Latency Confidence", "tf.identity(MCC, name=\"MCC\")) return {\"MCC\": (MCC, MCC_op)} elif task_name == \"mrpc\": accuracy = tf.metrics.accuracy(", "data sets. We do # not use Dataset.from_generator() because that uses tf.py_func which", "training.\") flags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch size for eval.\") flags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch size", "\"Whether to run eval on the dev set.\") flags.DEFINE_bool( \"do_predict\", False, \"Whether to", "dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits,", "disable=unused-argument \"\"\"The `model_fn` for Estimator.\"\"\" def metric_fn(per_example_loss, label_ids, logits): predictions = tf.argmax(logits, axis=-1,", "num_examples_per_rank = len(train_examples) // hvd.size() remainder = len(train_examples) % hvd.size() if hvd.rank() <", "Time = %0.2f for Sentences = %d\", predict_time_elapsed, predict_hooks[-1].count * FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total Inference", "License, Version 2.0 (the \"License\"); # you may not use this file except", "Running training *****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(train_examples)) tf.compat.v1.logging.info(\" Batch size =", "\"eval_accuracy\": accuracy, \"eval_f1\": f1, \"eval_loss\": loss, } else: accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions)", "num_warmup_steps, use_one_hot_embeddings, hvd=None): \"\"\"Returns `model_fn` closure for Estimator.\"\"\" def model_fn(features, labels, mode, params):", "= tf.estimator.EstimatorSpec( mode=mode, predictions=predictions) elif mode == tf.estimator.ModeKeys.EVAL: eval_metric_ops = metric_fn(per_example_loss, label_ids, logits)", "the token-level output, use model.get_sequence_output() # instead. output_layer = model.get_pooled_output() hidden_size = output_layer.shape[-1].value", "before gradient update\" \"Global batch size = num_accumulation_steps * train_batch_size\") flags.DEFINE_bool(\"amp\", True, \"Whether", "hvd_rank, FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25)) if FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps = int( len(train_examples) /", "predict_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time = time.time() output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\") with tf.io.gfile.GFile(output_predict_file, \"w\")", "d = d.shard(hvd.size(), hvd.rank()) d = d.repeat() d = d.shuffle(buffer_size=100) d = d.apply(", "mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) else: dummy_op = tf.no_op() # Need to call mixed precision", "= tf.placeholder(tf.int32, shape, 'input_mask') segment_ids = tf.placeholder(tf.int32, shape, 'segment_ids') label_ids = tf.placeholder(tf.int32, (None),", "= %d\", train_time_wo_overhead, (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) with overhead", "in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id) def input_fn(): \"\"\"The actual input function.\"\"\" num_examples", "optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler) eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops)", "= trt.TrtGraphConverter( input_graph_def=frozen_graph, nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096 << 20) - 1000, precision_mode = \"FP16\" if", "be truncated, and sequences shorter \" \"than this will be padded.\") flags.DEFINE_bool(\"do_train\", False,", "tf.io.FixedLenFeature([seq_length], tf.int64), \"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"label_ids\": tf.io.FixedLenFeature([], tf.int64), } def _decode_record(record, name_to_features): \"\"\"Decodes", "tf.compat.v1.logging.info(\" %s = %s\", key, str(result[key])) writer.write(\"%s = %s\\n\" % (key, str(result[key]))) if", "FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError( \"Cannot use sequence length %d because the BERT", "[num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable( \"output_bias\", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope(\"loss\"): if is_training:", "%d\", len(eval_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size) eval_drop_remainder = False eval_input_fn =", "global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps hvd_rank = 0 config = tf.compat.v1.ConfigProto() if FLAGS.horovod:", "def input_fn_builder(features, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure to be", "function.\"\"\" num_examples = len(features) # This is for demo purposes and does NOT", "Inference Time W/O Overhead = %0.2f for Sentences = %d\", eval_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "BERT model \" \"was only trained up to sequence length %d\" % (FLAGS.max_seq_length,", "length after WordPiece tokenization. \" \"Sequences longer than this will be truncated, and", "to run eval on the dev set.\") flags.DEFINE_bool( \"do_predict\", False, \"Whether to run", "Batch size = %d\", FLAGS.predict_batch_size) predict_drop_remainder = False predict_input_fn = file_based_input_fn_builder( input_file=predict_file, batch_size=FLAGS.predict_batch_size,", "FLAGS.num_accumulation_steps hvd_rank = 0 config = tf.compat.v1.ConfigProto() if FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU training with TF", "if FLAGS.horovod: tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i)) for i in range(hvd.size())] num_examples_per_rank = len(train_examples)", "= features[\"input_ids\"] input_mask = features[\"input_mask\"] segment_ids = features[\"segment_ids\"] label_ids = features[\"label_ids\"] is_training =", "the model architecture.\") flags.DEFINE_string(\"task_name\", None, \"The name of the task to train.\") flags.DEFINE_string(\"vocab_file\",", "tf.metrics.false_negatives(labels=label_ids, predictions=predictions) FP, FP_op = tf.metrics.false_positives(labels=label_ids, predictions=predictions) TP, TP_op = tf.metrics.true_positives(labels=label_ids, predictions=predictions) TN,", "tf.argmax(logits, axis=-1, output_type=tf.int32) if task_name == \"cola\": FN, FN_op = tf.metrics.false_negatives(labels=label_ids, predictions=predictions) FP,", "all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32), \"segment_ids\": tf.constant( all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"label_ids\": tf.constant(all_label_ids, shape=[num_examples],", "in throughput computation. predict_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) * 0.8))", "axis=-1, output_type=tf.int32) if task_name == \"cola\": FN, FN_op = tf.metrics.false_negatives(labels=label_ids, predictions=predictions) FP, FP_op", "to perform linear learning rate warmup for. \" \"E.g., 0.1 = 10% of", "}) if is_training: if hvd is not None: d = d.shard(hvd.size(), hvd.rank()) d", "if init_checkpoint and (hvd is None or hvd.rank() == 0): (assignment_map, initialized_variable_names )", "example[name] = t return example def input_fn(): \"\"\"The actual input function.\"\"\" # For", "\"Total batch size for training.\") flags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch size for eval.\") flags.DEFINE_integer(\"predict_batch_size\",", "Time W/O Overhead = %0.2f for Sentences = %d\", eval_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference", "elif task_name == \"mrpc\": accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) f1", "size = %d\", FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\"", "Statistics on TEST SET\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\",", "eval_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in throughput computation. eval_time_wo_overhead = sum(time_list[:int(len(time_list) *", "tf.estimator.Estimator( model_fn=model_fn, config=run_config) if FLAGS.do_train: file_based_convert_examples_to_features( train_examples[start_index:end_index], label_list, FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"***** Running", "if master_process else None, save_summary_steps=FLAGS.save_checkpoints_steps if master_process else None, log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1) if master_process:", "in list(example.keys()): t = example[name] if t.dtype == tf.int64: t = tf.to_int32(t) example[name]", "= t return example def input_fn(): \"\"\"The actual input function.\"\"\" # For training,", "sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) * 0.8)) * FLAGS.predict_batch_size avg = np.mean(time_list)", "Inference Time W/O Overhead = %0.2f for Sentences = %d\", predict_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary", "for Sentences = %d\", predict_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on TEST SET\") tf.compat.v1.logging.info(\"Batch", "= %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\") with", "= predict_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in throughput computation. predict_time_wo_overhead = sum(time_list[:int(len(time_list)", "= hvd.rank() config.gpu_options.visible_device_list = str(hvd.local_rank()) set_affinity(hvd.local_rank()) if hvd.size() > 1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if FLAGS.use_xla:", "prediction*****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(predict_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size)", "flags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch size for predict.\") flags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate", "logits, probabilities) = tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids, 'label_ids':label_ids}, return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0', 'loss/cls_logits:0', 'loss/cls_probabilities:0'], name='')", "if not FLAGS.horovod else hvd) train_start_time = time.time() estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks) train_time_elapsed =", "or implied. # See the License for the specific language governing permissions and", "else: dummy_op = tf.no_op() # Need to call mixed precision graph rewrite if", "if var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" else: init_string = \", *NOTTTTTTTTTTTTTTTTTTTTT\"", "= start_index + num_examples_per_rank + 1 else: start_index = hvd.rank() * num_examples_per_rank +", "eval_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on EVAL set\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.eval_batch_size)", "precision graph rewrite if fp16 to enable graph rewrite if FLAGS.amp: loss_scaler =", "W/O Overhead = %0.2f for Sentences = %d\", predict_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics", "= None num_warmup_steps = None training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25)) if FLAGS.do_train: train_examples =", "is_training=True, drop_remainder=True, hvd=None if not FLAGS.horovod else hvd) train_start_time = time.time() estimator.train(input_fn=train_input_fn, max_steps=num_train_steps,", "data files) \" \"for the task.\") flags.DEFINE_string( \"bert_config_file\", None, \"The config json file", "\"Global batch size = num_accumulation_steps * train_batch_size\") flags.DEFINE_bool(\"amp\", True, \"Whether to enable AMP", "hvd=None): \"\"\"Creates an `input_fn` closure to be passed to Estimator.\"\"\" all_input_ids = []", "processor.get_labels() tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) master_process = True training_hooks = [] global_batch_size", "= (int(len(time_list) * 0.8)) * FLAGS.predict_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) *", "tf.enable_resource_variables() run_config = tf.estimator.RunConfig( model_dir=FLAGS.output_dir if master_process else None, session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process", "return { \"eval_accuracy\": accuracy, \"eval_loss\": loss, } tf.compat.v1.logging.info(\"*** Features ***\") tf.compat.v1.logging.info(\"*** Features ***\")", "\" \"was only trained up to sequence length %d\" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir)", "axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1, name='cls_per_example_loss')", "hvd) estimator = tf.estimator.Estimator( model_fn=model_fn, config=run_config) if FLAGS.do_train: file_based_convert_examples_to_features( train_examples[start_index:end_index], label_list, FLAGS.max_seq_length, tokenizer,", "coding=utf-8 # Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved. # Copyright 2018", "len(predict_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size) predict_drop_remainder = False predict_input_fn = file_based_input_fn_builder(", "global_batch_size * 1.0 / train_time_elapsed ss_sentences_per_second = (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size *", "BERT model was trained on.\") flags.DEFINE_string( \"output_dir\", None, \"The output directory where the", "batch size for training.\") flags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch size for eval.\") flags.DEFINE_integer(\"predict_batch_size\", 8,", "FP) * (TP + FN) * (TN + FP) * (TN + FN))", "will be padded.\") flags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\") flags.DEFINE_bool(\"do_eval\", False, \"Whether to", "[os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i)) for i in range(hvd.size())] num_examples_per_rank = len(train_examples) // hvd.size() remainder =", "verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\" %s = %s\", key, str(result[key])) writer.write(\"%s = %s\\n\" % (key, str(result[key])))", "str(class_probability) for class_probability in prediction) + \"\\n\" writer.write(output_line) predict_time_elapsed = time.time() - predict_start_time", "else: start_index = hvd.rank() * num_examples_per_rank + remainder end_index = start_index + (num_examples_per_rank)", "tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.train_batch_size) tf.compat.v1.logging.info(\" Num steps = %d\", num_train_steps) train_input_fn", "* 1.0 / eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences =", "dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0)) output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=probabilities) return output_spec return model_fn", "/ eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences = %d\", eval_time_elapsed,", "for class_probability in prediction) + \"\\n\" writer.write(output_line) predict_time_elapsed = time.time() - predict_start_time time_list", "= model.get_pooled_output() hidden_size = output_layer.shape[-1].value output_weights = tf.get_variable( \"output_weights\", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias", "tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) return output_spec (total_loss, per_example_loss, logits, probabilities) = create_model( bert_config,", "for cased models.\") flags.DEFINE_integer( \"max_seq_length\", 128, \"The maximum total input sequence length after", "init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_one_hot_embeddings, hvd=None): \"\"\"Returns `model_fn` closure for Estimator.\"\"\" def model_fn(features,", "Horovod for multi-gpu runs\") flags.DEFINE_bool( \"verbose_logging\", False, \"If true, all of the warnings", "import print_function import collections import csv import os import modeling import optimization import", "to a TensorFlow example.\"\"\" example = tf.parse_single_example(record, name_to_features) # tf.Example only supports tf.int64,", "= modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if FLAGS.verbose_logging: tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var", "eval_metric_ops=eval_metric_ops) else: dummy_op = tf.no_op() # Need to call mixed precision graph rewrite", "output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) return output_spec (total_loss, per_example_loss, logits, probabilities) =", "of `do_train`, `do_eval` or `do_predict' must be True.\") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length", "tf_config = tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth = True output_node_names = ['loss/cls_loss', 'loss/cls_per_example_loss', 'loss/cls_logits', 'loss/cls_probabilities'] with", "is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32) # In the demo, we are doing", "'loss/cls_probabilities'] with tf.Session(config=tf_config) as tf_sess: input_ids = tf.placeholder(tf.int32, shape, 'input_ids') input_mask = tf.placeholder(tf.int32,", "not FLAGS.horovod else hvd) estimator = tf.estimator.Estimator( model_fn=model_fn, config=run_config) if FLAGS.do_train: file_based_convert_examples_to_features( train_examples[start_index:end_index],", "// hvd.size() remainder = len(train_examples) % hvd.size() if hvd.rank() < remainder: start_index =", "## Other parameters flags.DEFINE_string( \"dllog_path\", \"/results/bert_dllog.json\", \"filename where dllogger writes to\") flags.DEFINE_string( \"optimizer_type\",", "= eval_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in throughput computation. eval_time_wo_overhead = sum(time_list[:int(len(time_list)", "model.\"\"\" model = modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32) # In", "time.time() - eval_start_time time_list = eval_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in throughput", "%0.2f\", cf_90 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 95 (ms) = %0.2f\", cf_95 *", "name_to_features), batch_size=batch_size, drop_remainder=drop_remainder)) return d return input_fn def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,", "closure to be passed to Estimator.\"\"\" name_to_features = { \"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"input_mask\":", "input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() initialized_variable_names = {} if init_checkpoint", "use this file except in compliance with the License. # You may obtain", "* 1)]) ss_sentences_per_second = num_sentences * 1.0 / predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time", "'input_mask':input_mask, 'segment_ids':segment_ids, 'label_ids':label_ids}, return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0', 'loss/cls_logits:0', 'loss/cls_probabilities:0'], name='') if mode == tf.estimator.ModeKeys.PREDICT: predictions", "%s\", \"fp16\" if FLAGS.amp else \"fp32\") tf.compat.v1.logging.info(\"Latency Confidence Level 50 (ms) = %0.2f\",", "# This function is not used by this file but is still used", "%0.2f for Sentences = %d\", eval_time_elapsed, eval_hooks[-1].count * FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O", "all_input_ids = [] all_input_mask = [] all_segment_ids = [] all_label_ids = [] for", "for Adam.\") flags.DEFINE_bool(\"use_trt\", False, \"Whether to use TF-TRT\") flags.DEFINE_float(\"num_train_epochs\", 3.0, \"Total number of", "****\") for var in tvars: init_string = \"\" if var.name in initialized_variable_names: init_string", "utils.create_glue_data import * import numpy as np import tf_metrics flags = tf.flags FLAGS", "seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure to be passed to Estimator.\"\"\"", "tf.compat.v1.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape, init_string) frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess,", "lower case the input text. Should be True for uncased \" \"models and", "to enable graph rewrite if FLAGS.amp: loss_scaler = tf.train.experimental.FixedLossScale(1) dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0),", "mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) return output_spec (total_loss, per_example_loss, logits, probabilities) = create_model( bert_config, is_training,", "FLAGS.num_accumulation_steps * hvd.size() master_process = (hvd.rank() == 0) hvd_rank = hvd.rank() config.gpu_options.visible_device_list =", "name='cls_per_example_loss') loss = tf.reduce_mean(per_example_loss, name='cls_loss') return (loss, per_example_loss, logits, probabilities) def get_frozen_tftrt_model(bert_config, shape,", "'loss/cls_per_example_loss', 'loss/cls_logits', 'loss/cls_probabilities'] with tf.Session(config=tf_config) as tf_sess: input_ids = tf.placeholder(tf.int32, shape, 'input_ids') input_mask", "Configuaration *****\") for key in FLAGS.__flags.keys(): tf.compat.v1.logging.info(' {}: {}'.format(key, getattr(FLAGS, key))) tf.compat.v1.logging.info(\"**************************\") train_examples", "%d\", FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\" if FLAGS.amp", "load data is with TFRecordReader. d = tf.data.Dataset.from_tensor_slices({ \"input_ids\": tf.constant( all_input_ids, shape=[num_examples, seq_length],", "record: _decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder)) return d return input_fn def create_model(bert_config, is_training, input_ids,", "max(time_list[:int(len(time_list) * 0.50)]) cf_90 = max(time_list[:int(len(time_list) * 0.90)]) cf_95 = max(time_list[:int(len(time_list) * 0.95)])", "is_training, input_ids, input_mask, segment_ids, labels, num_labels, use_one_hot_embeddings): \"\"\"Creates a classification model.\"\"\" model =", "mode == tf.estimator.ModeKeys.PREDICT: predictions = {\"probabilities\": probabilities} output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=predictions) elif", "feature in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id) def input_fn(): \"\"\"The actual input function.\"\"\"", "True for uncased \" \"models and False for cased models.\") flags.DEFINE_integer( \"max_seq_length\", 128,", "tf.placeholder(tf.int32, (None), 'label_ids') create_model(bert_config, False, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars =", "= tf.flags FLAGS = flags.FLAGS ## Required parameters flags.DEFINE_string( \"data_dir\", None, \"The input", "mode=mode, predictions=predictions) elif mode == tf.estimator.ModeKeys.EVAL: eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec =", "} if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict: raise ValueError( \"At", "labels, num_labels, use_one_hot_embeddings): \"\"\"Creates a classification model.\"\"\" model = modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids,", "\"\"\"Creates an `input_fn` closure to be passed to Estimator.\"\"\" name_to_features = { \"input_ids\":", "= tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0)) output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=probabilities) return output_spec return model_fn #", "output, use model.get_sequence_output() # instead. output_layer = model.get_pooled_output() hidden_size = output_layer.shape[-1].value output_weights =", "% (key, str(result[key]))) if FLAGS.do_predict and master_process: predict_examples = processor.get_test_examples(FLAGS.data_dir) predict_file = os.path.join(FLAGS.output_dir,", "\"Whether to lower case the input text. Should be True for uncased \"", "d = d.shard(hvd.size(), hvd.rank()) d = d.repeat() d = d.shuffle(buffer_size=100) d = d.batch(batch_size=batch_size,", "dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") if __name__ == \"__main__\": flags.mark_flag_as_required(\"data_dir\") flags.mark_flag_as_required(\"task_name\") flags.mark_flag_as_required(\"vocab_file\") flags.mark_flag_as_required(\"bert_config_file\")", "= sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) * 0.8)) * FLAGS.predict_batch_size avg =", "True, \"Whether to lower case the input text. Should be True for uncased", "Num examples = %d\", len(eval_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size) eval_drop_remainder =", "len(features) # This is for demo purposes and does NOT scale to large", "tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f for Sentences = %d\", eval_time_wo_overhead, num_sentences)", "Average (sentences/sec) = %0.2f\", ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\") if FLAGS.do_eval and master_process: eval_examples = processor.get_dev_examples(FLAGS.data_dir)", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError( \"Cannot use sequence length %d because the", "sorted(result.keys()): dllogging.logger.log(step=(), data={key: float(result[key])}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\" %s = %s\", key, str(result[key])) writer.write(\"%s =", "verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\") with tf.io.gfile.GFile(output_eval_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Eval", "= %s%s\", var.name, var.shape, init_string) output_spec = None if mode == tf.estimator.ModeKeys.TRAIN: train_op", "initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable( \"output_bias\", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope(\"loss\"): if is_training: # I.e.,", "dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler) eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec(", "int32. for name in list(example.keys()): t = example[name] if t.dtype == tf.int64: t", "= tf.data.Dataset.from_tensor_slices({ \"input_ids\": tf.constant( all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"input_mask\": tf.constant( all_input_mask, shape=[num_examples, seq_length],", "loss=total_loss, eval_metric_ops=eval_metric_ops) return output_spec (total_loss, per_example_loss, logits, probabilities) = create_model( bert_config, is_training, input_ids,", "= %0.2f\", cf_100 * 1000) tf.compat.v1.logging.info(\"Latency Average (ms) = %0.2f\", avg * 1000)", "ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\") if FLAGS.do_eval and master_process: eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\")", "example[name] if t.dtype == tf.int64: t = tf.to_int32(t) example[name] = t return example", "\"than this will be padded.\") flags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\") flags.DEFINE_bool(\"do_eval\", False,", "+ FP) * (TP + FN) * (TN + FP) * (TN +", "tf.compat.v1.logging.info(\"*** Features ***\") for name in sorted(features.keys()): tf.compat.v1.logging.info(\" name = %s, shape =", "+ (num_examples_per_rank) model_fn = model_fn_builder( task_name=task_name, bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate if not FLAGS.horovod", "Batch size = %d\", FLAGS.eval_batch_size) eval_drop_remainder = False eval_input_fn = file_based_input_fn_builder( input_file=eval_file, batch_size=FLAGS.eval_batch_size,", "to the pre-trained BERT model. \" \"This specifies the model architecture.\") flags.DEFINE_string(\"task_name\", None,", "is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure to be passed to Estimator.\"\"\" all_input_ids", "Team Authors. # # Licensed under the Apache License, Version 2.0 (the \"License\");", "= hvd.rank() * (num_examples_per_rank+1) end_index = start_index + num_examples_per_rank + 1 else: start_index", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "and does NOT scale to large data sets. We do # not use", "features[\"label_ids\"] is_training = (mode == tf.estimator.ModeKeys.TRAIN) if not is_training and FLAGS.use_trt: trt_graph =", "master_process = True training_hooks = [] global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps hvd_rank =", "use model.get_sequence_output() # instead. output_layer = model.get_pooled_output() hidden_size = output_layer.shape[-1].value output_weights = tf.get_variable(", "if not FLAGS.horovod else hvd) estimator = tf.estimator.Estimator( model_fn=model_fn, config=run_config) if FLAGS.do_train: file_based_convert_examples_to_features(", "'label_ids') create_model(bert_config, False, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() (assignment_map,", "label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() initialized_variable_names = {} if init_checkpoint and (hvd", "input sequence length after WordPiece tokenization. \" \"Sequences longer than this will be", "* num_examples_per_rank + remainder end_index = start_index + (num_examples_per_rank) model_fn = model_fn_builder( task_name=task_name,", "* 1)]) ss_sentences_per_second = num_sentences * 1.0 / eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time", "[] all_label_ids = [] for feature in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id) def", "tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if FLAGS.verbose_logging: tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in tvars: init_string", "tf.placeholder(tf.int32, shape, 'segment_ids') label_ids = tf.placeholder(tf.int32, (None), 'label_ids') create_model(bert_config, False, input_ids, input_mask, segment_ids,", "= %d\", FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\" if", "from __future__ import division from __future__ import print_function import collections import csv import", "* FLAGS.warmup_proportion) start_index = 0 end_index = len(train_examples) tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record\")] if", "sequence length %d\" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower() if task_name not", "from __future__ import print_function import collections import csv import os import modeling import", "run the model in inference mode on the test set.\") flags.DEFINE_integer(\"train_batch_size\", 32, \"Total", "# For training, we want a lot of parallel reading and shuffling. #", "tf.compat.v1.logging.info(\"Summary Inference Statistics on TEST SET\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence Length", "each estimator call.\") flags.DEFINE_integer(\"num_accumulation_steps\", 1, \"Number of accumulation steps before gradient update\" \"Global", "= example[name] if t.dtype == tf.int64: t = tf.to_int32(t) example[name] = t return", "tf.compat.v1.logging.info(\"***** Configuaration *****\") for key in FLAGS.__flags.keys(): tf.compat.v1.logging.info(' {}: {}'.format(key, getattr(FLAGS, key))) tf.compat.v1.logging.info(\"**************************\")", "drop_remainder=drop_remainder)) return d return input_fn def create_model(bert_config, is_training, input_ids, input_mask, segment_ids, labels, num_labels,", "overhead = %0.2f\", avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\") if FLAGS.do_eval", "not use Dataset.from_generator() because that uses tf.py_func which is # not TPU compatible.", "if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict: raise ValueError( \"At least", "with the License. # You may obtain a copy of the License at", "10, \"How often to print loss from estimator\") flags.DEFINE_integer(\"iterations_per_loop\", 1000, \"How many steps", "is_training=False, drop_remainder=eval_drop_remainder) eval_hooks = [LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time = time.time() result = estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks) eval_time_elapsed", "remainder = len(train_examples) % hvd.size() if hvd.rank() < remainder: start_index = hvd.rank() *", "FLAGS.num_accumulation_steps, FLAGS.optimizer_type) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, train_op=train_op) elif mode == tf.estimator.ModeKeys.EVAL: dummy_op", "specific language governing permissions and # limitations under the License. \"\"\"BERT finetuning runner.\"\"\"", "num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False, hvd=None if not FLAGS.horovod else hvd) estimator = tf.estimator.Estimator( model_fn=model_fn, config=run_config)", "tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias, name='cls_logits') probabilities", "name in sorted(features.keys()): tf.compat.v1.logging.info(\" name = %s, shape = %s\" % (name, features[name].shape))", "\"\\n\" writer.write(output_line) predict_time_elapsed = time.time() - predict_start_time time_list = predict_hooks[-1].time_list time_list.sort() # Removing", "0.1 = 10% of training.\") flags.DEFINE_integer(\"save_checkpoints_steps\", 1000, \"How often to save the model", "tf.compat.v1.logging.info(\"*** Features ***\") tf.compat.v1.logging.info(\"*** Features ***\") for name in sorted(features.keys()): tf.compat.v1.logging.info(\" name =", "record to a TensorFlow example.\"\"\" example = tf.parse_single_example(record, name_to_features) # tf.Example only supports", "= \"FP16\" if FLAGS.amp else \"FP32\", minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000 ) frozen_graph = converter.convert()", "TN_op = tf.metrics.true_negatives(labels=label_ids, predictions=predictions) MCC = (TP * TN - FP * FN)", "tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i)) for i in range(hvd.size())] num_examples_per_rank = len(train_examples) // hvd.size()", "= (TP * TN - FP * FN) / ((TP + FP) *", "law or agreed to in writing, software # distributed under the License is", "use Horovod for multi-gpu runs\") flags.DEFINE_bool( \"verbose_logging\", False, \"If true, all of the", "graph using TensorFlow-TensorRT...') from tensorflow.python.compiler.tensorrt import trt_convert as trt converter = trt.TrtGraphConverter( input_graph_def=frozen_graph,", "1.0 / eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences = %d\",", "checkpoint (usually from a pre-trained BERT model).\") flags.DEFINE_bool( \"do_lower_case\", True, \"Whether to lower", "(num_examples_per_rank) model_fn = model_fn_builder( task_name=task_name, bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate if not FLAGS.horovod else", "tf.group(FN_op, TN_op, TP_op, FP_op, tf.identity(MCC, name=\"MCC\")) return {\"MCC\": (MCC, MCC_op)} elif task_name ==", "run training.\") flags.DEFINE_bool(\"do_eval\", False, \"Whether to run eval on the dev set.\") flags.DEFINE_bool(", "Average (sentences/sec) with overhead = %0.2f\", avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second)", "input_ids = tf.placeholder(tf.int32, shape, 'input_ids') input_mask = tf.placeholder(tf.int32, shape, 'input_mask') segment_ids = tf.placeholder(tf.int32,", "# Removing outliers (init/warmup) in throughput computation. eval_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences", "init_string) output_spec = None if mode == tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss, learning_rate,", "name='cls_probabilities') log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels", "(ms) = %0.2f\", cf_50 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 90 (ms) = %0.2f\",", "TEST SET\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision", "way to load data is with TFRecordReader. d = tf.data.Dataset.from_tensor_slices({ \"input_ids\": tf.constant( all_input_ids,", "/ ((TP + FP) * (TP + FN) * (TN + FP) *", "create_model(bert_config, is_training, input_ids, input_mask, segment_ids, labels, num_labels, use_one_hot_embeddings): \"\"\"Creates a classification model.\"\"\" model", "tokenizer, tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"***** Running training *****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(train_examples)) tf.compat.v1.logging.info(\"", "= converter.convert() print('Total node count before and after TF-TRT conversion:', num_nodes, '->', len(frozen_graph.node))", "import horovod.tensorflow as hvd import time from utils.utils import LogEvalRunHook, LogTrainRunHook, setup_xla_flags from", "input_file=eval_file, batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder) eval_hooks = [LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time = time.time() result =", "str(hvd.local_rank()) set_affinity(hvd.local_rank()) if hvd.size() > 1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1 if", "var in tvars: init_string = \"\" if var.name in initialized_variable_names: init_string = \",", "FLAGS.horovod: tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i)) for i in range(hvd.size())] num_examples_per_rank = len(train_examples) //", "= np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)]) cf_90 = max(time_list[:int(len(time_list) * 0.90)]) cf_95", "model was trained on.\") flags.DEFINE_string( \"output_dir\", None, \"The output directory where the model", "import tf_metrics flags = tf.flags FLAGS = flags.FLAGS ## Required parameters flags.DEFINE_string( \"data_dir\",", "\"eval_loss\": loss, } tf.compat.v1.logging.info(\"*** Features ***\") tf.compat.v1.logging.info(\"*** Features ***\") for name in sorted(features.keys()):", "hidden_size = output_layer.shape[-1].value output_weights = tf.get_variable( \"output_weights\", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable(", "in compliance with the License. # You may obtain a copy of the", "initialized_variable_names = {} if init_checkpoint and (hvd is None or hvd.rank() == 0):", "the task.\") flags.DEFINE_string( \"bert_config_file\", None, \"The config json file corresponding to the pre-trained", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "Sentences = %d\", eval_time_elapsed, eval_hooks[-1].count * FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead =", "bert_config.max_position_embeddings: raise ValueError( \"Cannot use sequence length %d because the BERT model \"", "flags.DEFINE_string( \"data_dir\", None, \"The input data dir. Should contain the .tsv files (or", "often to save the model checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\", 10, \"How often to print loss", "num_train_steps * global_batch_size * 1.0 / train_time_elapsed ss_sentences_per_second = (training_hooks[-1].count - training_hooks[-1].skipped) *", "In the demo, we are doing a simple classification task on the entire", "tf.constant( all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"label_ids\": tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32), }) if is_training: if", "perform linear learning rate warmup for. \" \"E.g., 0.1 = 10% of training.\")", "to load data is with TFRecordReader. d = tf.data.Dataset.from_tensor_slices({ \"input_ids\": tf.constant( all_input_ids, shape=[num_examples,", "(name, features[name].shape)) input_ids = features[\"input_ids\"] input_mask = features[\"input_mask\"] segment_ids = features[\"segment_ids\"] label_ids =", "return { \"eval_accuracy\": accuracy, \"eval_f1\": f1, \"eval_loss\": loss, } else: accuracy = tf.metrics.accuracy(", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "= None training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25)) if FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps =", "Average (ms) = %0.2f\", avg * 1000) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second)", "Estimator.\"\"\" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument \"\"\"The `model_fn` for Estimator.\"\"\"", "Required parameters flags.DEFINE_string( \"data_dir\", None, \"The input data dir. Should contain the .tsv", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "tf.parse_single_example(record, name_to_features) # tf.Example only supports tf.int64, but the TPU only supports tf.int32.", "== 'TRTEngineOp'])) with tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\") as f: f.write(frozen_graph.SerializeToString()) return frozen_graph def model_fn_builder(task_name, bert_config,", "(ms) = %0.2f\", cf_90 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 95 (ms) = %0.2f\",", "cf_90 = max(time_list[:int(len(time_list) * 0.90)]) cf_95 = max(time_list[:int(len(time_list) * 0.95)]) cf_99 = max(time_list[:int(len(time_list)", "dir. Should contain the .tsv files (or other data files) \" \"for the", "segment_ids, labels, num_labels, use_one_hot_embeddings): \"\"\"Creates a classification model.\"\"\" model = modeling.BertModel( config=bert_config, is_training=is_training,", "train_examples[start_index:end_index], label_list, FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"***** Running training *****\") tf.compat.v1.logging.info(\" Num examples =", "FN) * (TN + FP) * (TN + FN)) ** 0.5 MCC_op =", "files (or other data files) \" \"for the task.\") flags.DEFINE_string( \"bert_config_file\", None, \"The", "= tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1, name='cls_per_example_loss') loss =", "eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) return output_spec", "np import tf_metrics flags = tf.flags FLAGS = flags.FLAGS ## Required parameters flags.DEFINE_string(", "def metric_fn(per_example_loss, label_ids, logits): predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) if task_name == \"cola\":", "FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU training with TF Horovod\") tf.compat.v1.logging.info(\"hvd.size() = %d hvd.rank() = %d\", hvd.size(),", "Variables ****\") for var in tvars: init_string = \"\" if var.name in initialized_variable_names:", "\"dllog_path\", \"/results/bert_dllog.json\", \"filename where dllogger writes to\") flags.DEFINE_string( \"optimizer_type\", \"lamb\", \"Optimizer type :", "tf.nn.bias_add(logits, output_bias, name='cls_logits') probabilities = tf.nn.softmax(logits, axis=-1, name='cls_probabilities') log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels", "1000) tf.compat.v1.logging.info(\"Latency Confidence Level 100 (ms) = %0.2f\", cf_100 * 1000) tf.compat.v1.logging.info(\"Latency Average", "hvd.rank() config.gpu_options.visible_device_list = str(hvd.local_rank()) set_affinity(hvd.local_rank()) if hvd.size() > 1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level", "example.\"\"\" example = tf.parse_single_example(record, name_to_features) # tf.Example only supports tf.int64, but the TPU", "10% of training.\") flags.DEFINE_integer(\"save_checkpoints_steps\", 1000, \"How often to save the model checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\",", "true, all of the warnings related to data processing will be printed. \"", "= (mode == tf.estimator.ModeKeys.TRAIN) if not is_training and FLAGS.use_trt: trt_graph = get_frozen_tftrt_model(bert_config, input_ids.shape,", "if FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU training with TF Horovod\") tf.compat.v1.logging.info(\"hvd.size() = %d hvd.rank() = %d\",", "tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file =", "AMP ops. When false, uses TF32 on A100 and FP32 on V100 GPUS.\")", "does NOT scale to large data sets. We do # not use Dataset.from_generator()", "tf.compat.v1.logging.info(\"hvd.size() = %d hvd.rank() = %d\", hvd.size(), hvd.rank()) global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps", "else hvd) estimator = tf.estimator.Estimator( model_fn=model_fn, config=run_config) if FLAGS.do_train: file_based_convert_examples_to_features( train_examples[start_index:end_index], label_list, FLAGS.max_seq_length,", "and master_process: eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\") file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length,", "predict_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in throughput computation. predict_time_wo_overhead = sum(time_list[:int(len(time_list) *", "= FLAGS.task_name.lower() if task_name not in processors: raise ValueError(\"Task not found: %s\" %", "num_nodes = len(frozen_graph.node) print('Converting graph using TensorFlow-TensorRT...') from tensorflow.python.compiler.tensorrt import trt_convert as trt", "setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if FLAGS.horovod: hvd.init() processors = { \"cola\": ColaProcessor,", "'TRTEngineOp'])) with tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\") as f: f.write(frozen_graph.SerializeToString()) return frozen_graph def model_fn_builder(task_name, bert_config, num_labels,", "often to print loss from estimator\") flags.DEFINE_integer(\"iterations_per_loop\", 1000, \"How many steps to make", "of accumulation steps before gradient update\" \"Global batch size = num_accumulation_steps * train_batch_size\")", "tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\",", "closure to be passed to Estimator.\"\"\" all_input_ids = [] all_input_mask = [] all_segment_ids", "predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) return { \"eval_accuracy\": accuracy, \"eval_loss\": loss, } tf.compat.v1.logging.info(\"*** Features", "FN, FN_op = tf.metrics.false_negatives(labels=label_ids, predictions=predictions) FP, FP_op = tf.metrics.false_positives(labels=label_ids, predictions=predictions) TP, TP_op =", "%0.2f for Sentences = %d\", predict_time_elapsed, predict_hooks[-1].count * FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O", "*****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(train_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.train_batch_size)", "* FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f for Sentences = %d\",", "Predict results *****\") for prediction in estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks, yield_single_examples=False): output_line = \"\\t\".join( str(class_probability)", "ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\") with tf.io.gfile.GFile(output_eval_file, \"w\")", "- training_hooks[-1].skipped) * global_batch_size * 1.0 / train_time_wo_overhead if master_process: tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Training", "= %s\", key, str(result[key])) writer.write(\"%s = %s\\n\" % (key, str(result[key]))) if FLAGS.do_predict and", "= %d\", FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\" if", "not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict: raise ValueError( \"At least one", "is_training: # I.e., 0.1 dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer, output_weights,", "Sentences = %d\", predict_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on TEST SET\") tf.compat.v1.logging.info(\"Batch size", "== 0): (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if FLAGS.verbose_logging: tf.compat.v1.logging.info(\"****", "= tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) return output_spec (total_loss, per_example_loss, logits, probabilities) = create_model(", "range(hvd.size())] num_examples_per_rank = len(train_examples) // hvd.size() remainder = len(train_examples) % hvd.size() if hvd.rank()", "logits = tf.nn.bias_add(logits, output_bias, name='cls_logits') probabilities = tf.nn.softmax(logits, axis=-1, name='cls_probabilities') log_probs = tf.nn.log_softmax(logits,", "global_batch_size * 1.0 / train_time_wo_overhead if master_process: tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Training Time = %0.2f", "tf.io.FixedLenFeature([seq_length], tf.int64), \"label_ids\": tf.io.FixedLenFeature([], tf.int64), } def _decode_record(record, name_to_features): \"\"\"Decodes a record to", "save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process else None, save_summary_steps=FLAGS.save_checkpoints_steps if master_process else None, log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1) if", "tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1,", "config = tf.compat.v1.ConfigProto() if FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU training with TF Horovod\") tf.compat.v1.logging.info(\"hvd.size() = %d", "file corresponding to the pre-trained BERT model. \" \"This specifies the model architecture.\")", "tf.to_int32(t) example[name] = t return example def input_fn(): \"\"\"The actual input function.\"\"\" #", "= model_fn_builder( task_name=task_name, bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate if not FLAGS.horovod else FLAGS.learning_rate *", "still used by the Colab and # people who depend on it. def", "num_train_steps = int( len(train_examples) / global_batch_size * FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)", "***\") tf.compat.v1.logging.info(\"*** Features ***\") for name in sorted(features.keys()): tf.compat.v1.logging.info(\" name = %s, shape", "for training.\") flags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch size for eval.\") flags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch", "\"optimizer_type\", \"lamb\", \"Optimizer type : adam or lamb\") flags.DEFINE_string( \"init_checkpoint\", None, \"Initial checkpoint", "the input text. Should be True for uncased \" \"models and False for", "is_dynamic_op=True, maximum_cached_engines=1000 ) frozen_graph = converter.convert() print('Total node count before and after TF-TRT", "FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25)) if FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps = int( len(train_examples) / global_batch_size", "config=run_config) if FLAGS.do_train: file_based_convert_examples_to_features( train_examples[start_index:end_index], label_list, FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"***** Running training *****\")", "shape, 'input_mask') segment_ids = tf.placeholder(tf.int32, shape, 'segment_ids') label_ids = tf.placeholder(tf.int32, (None), 'label_ids') create_model(bert_config,", "name_to_features) # tf.Example only supports tf.int64, but the TPU only supports tf.int32. #", "'segment_ids':segment_ids, 'label_ids':label_ids}, return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0', 'loss/cls_logits:0', 'loss/cls_probabilities:0'], name='') if mode == tf.estimator.ModeKeys.PREDICT: predictions =", "ss_sentences_per_second = num_sentences * 1.0 / predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f", "false, uses TF32 on A100 and FP32 on V100 GPUS.\") flags.DEFINE_bool(\"use_xla\", True, \"Whether", "return input_fn def create_model(bert_config, is_training, input_ids, input_mask, segment_ids, labels, num_labels, use_one_hot_embeddings): \"\"\"Creates a", "init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if FLAGS.verbose_logging: tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in tvars:", "evaluation.\") def file_based_input_fn_builder(input_file, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure to", "yield_single_examples=False): output_line = \"\\t\".join( str(class_probability) for class_probability in prediction) + \"\\n\" writer.write(output_line) predict_time_elapsed", "num_examples_per_rank + remainder end_index = start_index + (num_examples_per_rank) model_fn = model_fn_builder( task_name=task_name, bert_config=bert_config,", "AI Language Team Authors. # # Licensed under the Apache License, Version 2.0", "tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) master_process = True training_hooks = [] global_batch_size =", "None, \"The output directory where the model checkpoints will be written.\") ## Other", "import collections import csv import os import modeling import optimization import tokenization import", "tf import horovod.tensorflow as hvd import time from utils.utils import LogEvalRunHook, LogTrainRunHook, setup_xla_flags", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "Overhead = %0.2f for Sentences = %d\", eval_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on", "*****\") for prediction in estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks, yield_single_examples=False): output_line = \"\\t\".join( str(class_probability) for class_probability", "use TF-TRT\") flags.DEFINE_float(\"num_train_epochs\", 3.0, \"Total number of training epochs to perform.\") flags.DEFINE_float( \"warmup_proportion\",", "global_batch_size) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) with overhead = %0.2f\", avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) =", "= %d\", len(predict_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size) predict_drop_remainder = False predict_input_fn", "to sequence length %d\" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower() if task_name", "be padded.\") flags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\") flags.DEFINE_bool(\"do_eval\", False, \"Whether to run", "print('Total node count before and after TF-TRT conversion:', num_nodes, '->', len(frozen_graph.node)) print('TRT node", "\"output_weights\", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable( \"output_bias\", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope(\"loss\"): if", "ColaProcessor, \"mnli\": MnliProcessor, \"mrpc\": MrpcProcessor, \"xnli\": XnliProcessor, } if not FLAGS.do_train and not", "output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) else: dummy_op = tf.no_op() # Need to", "d.apply( tf.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder)) return d return input_fn def", "label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) return output_spec (total_loss, per_example_loss, logits,", "actual input function.\"\"\" num_examples = len(features) # This is for demo purposes and", "flags.DEFINE_integer(\"num_accumulation_steps\", 1, \"Number of accumulation steps before gradient update\" \"Global batch size =", "input_ids = features[\"input_ids\"] input_mask = features[\"input_mask\"] segment_ids = features[\"segment_ids\"] label_ids = features[\"label_ids\"] is_training", "= int(num_train_steps * FLAGS.warmup_proportion) start_index = 0 end_index = len(train_examples) tmp_filenames = [os.path.join(FLAGS.output_dir,", "+ remainder end_index = start_index + (num_examples_per_rank) model_fn = model_fn_builder( task_name=task_name, bert_config=bert_config, num_labels=len(label_list),", "global_batch_size * FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion) start_index = 0 end_index =", "Horovod\") tf.compat.v1.logging.info(\"hvd.size() = %d hvd.rank() = %d\", hvd.size(), hvd.rank()) global_batch_size = FLAGS.train_batch_size *", "FLAGS.amp else \"fp32\") tf.compat.v1.logging.info(\"Latency Confidence Level 50 (ms) = %0.2f\", cf_50 * 1000)", "cast all int64 to int32. for name in list(example.keys()): t = example[name] if", "# limitations under the License. \"\"\"BERT finetuning runner.\"\"\" from __future__ import absolute_import from", "%s\" % (task_name)) processor = processors[task_name]() label_list = processor.get_labels() tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file,", "\"Whether to use Horovod for multi-gpu runs\") flags.DEFINE_bool( \"verbose_logging\", False, \"If true, all", "probabilities) = create_model( bert_config, is_training, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars =", "seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True, hvd=None if not FLAGS.horovod else hvd) train_start_time = time.time() estimator.train(input_fn=train_input_fn,", "this file except in compliance with the License. # You may obtain a", "dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\") with tf.io.gfile.GFile(output_eval_file, \"w\") as", "False, \"If true, all of the warnings related to data processing will be", "tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size) eval_drop_remainder = False eval_input_fn = file_based_input_fn_builder( input_file=eval_file,", "tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) f1 = tf_metrics.f1(labels=label_ids, predictions=predictions, num_classes=2, pos_indices=[1]) return", "# tf.Example only supports tf.int64, but the TPU only supports tf.int32. # So", "SET\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision =", "sequences shorter \" \"than this will be padded.\") flags.DEFINE_bool(\"do_train\", False, \"Whether to run", "is_training, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() initialized_variable_names = {}", "tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\") tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in tvars: init_string", "output_line = \"\\t\".join( str(class_probability) for class_probability in prediction) + \"\\n\" writer.write(output_line) predict_time_elapsed =", "* 0.50)]) cf_90 = max(time_list[:int(len(time_list) * 0.90)]) cf_95 = max(time_list[:int(len(time_list) * 0.95)]) cf_99", "features[name].shape)) input_ids = features[\"input_ids\"] input_mask = features[\"input_mask\"] segment_ids = features[\"segment_ids\"] label_ids = features[\"label_ids\"]", "train_start_time train_time_wo_overhead = training_hooks[-1].total_time avg_sentences_per_second = num_train_steps * global_batch_size * 1.0 / train_time_elapsed", "training to perform linear learning rate warmup for. \" \"E.g., 0.1 = 10%", "\"fp32\") tf.compat.v1.logging.info(\"Latency Confidence Level 50 (ms) = %0.2f\", cf_50 * 1000) tf.compat.v1.logging.info(\"Latency Confidence", "\"predict.tf_record\") file_based_convert_examples_to_features(predict_examples, label_list, FLAGS.max_seq_length, tokenizer, predict_file) tf.compat.v1.logging.info(\"***** Running prediction*****\") tf.compat.v1.logging.info(\" Num examples =", "TN - FP * FN) / ((TP + FP) * (TP + FN)", "input function.\"\"\" num_examples = len(features) # This is for demo purposes and does", "= %0.2f\", cf_95 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 99 (ms) = %0.2f\", cf_99", "len(train_examples) tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record\")] if FLAGS.horovod: tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i)) for i", "_decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder)) return d return input_fn def create_model(bert_config, is_training, input_ids, input_mask,", "* global_batch_size * 1.0 / train_time_wo_overhead if master_process: tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Training Time =", "in tvars: init_string = \"\" if var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\"", "dtype=tf.int32), \"segment_ids\": tf.constant( all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"label_ids\": tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32), }) if", "i in range(hvd.size())] num_examples_per_rank = len(train_examples) // hvd.size() remainder = len(train_examples) % hvd.size()", "'loss/cls_logits:0', 'loss/cls_probabilities:0'], name='') if mode == tf.estimator.ModeKeys.PREDICT: predictions = {\"probabilities\": probabilities} output_spec =", "to enable AMP ops. When false, uses TF32 on A100 and FP32 on", "input_mask = tf.placeholder(tf.int32, shape, 'input_mask') segment_ids = tf.placeholder(tf.int32, shape, 'segment_ids') label_ids = tf.placeholder(tf.int32,", "drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure to be passed to Estimator.\"\"\" all_input_ids =", "hvd_rank = hvd.rank() config.gpu_options.visible_device_list = str(hvd.local_rank()) set_affinity(hvd.local_rank()) if hvd.size() > 1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if", "learning_rate=FLAGS.learning_rate if not FLAGS.horovod else FLAGS.learning_rate * hvd.size(), num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False, hvd=None if", "import tensorflow as tf import horovod.tensorflow as hvd import time from utils.utils import", "if hvd is not None: d = d.shard(hvd.size(), hvd.rank()) d = d.repeat() d", "metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) else: dummy_op = tf.no_op()", "initial learning rate for Adam.\") flags.DEFINE_bool(\"use_trt\", False, \"Whether to use TF-TRT\") flags.DEFINE_float(\"num_train_epochs\", 3.0,", "estimator = tf.estimator.Estimator( model_fn=model_fn, config=run_config) if FLAGS.do_train: file_based_convert_examples_to_features( train_examples[start_index:end_index], label_list, FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank])", "avg_sentences_per_second = num_train_steps * global_batch_size * 1.0 / train_time_elapsed ss_sentences_per_second = (training_hooks[-1].count -", "drop_remainder=True, hvd=None if not FLAGS.horovod else hvd) train_start_time = time.time() estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks)", "If you want to use the token-level output, use model.get_sequence_output() # instead. output_layer", "[] all_input_mask = [] all_segment_ids = [] all_label_ids = [] for feature in", "for prediction in estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks, yield_single_examples=False): output_line = \"\\t\".join( str(class_probability) for class_probability in", "os import modeling import optimization import tokenization import tensorflow as tf import horovod.tensorflow", "rewrite if FLAGS.amp: loss_scaler = tf.train.experimental.FixedLossScale(1) dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler) eval_metric_ops =", "inference mode on the test set.\") flags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for training.\")", "else \"FP32\", minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000 ) frozen_graph = converter.convert() print('Total node count before", "hvd.init() processors = { \"cola\": ColaProcessor, \"mnli\": MnliProcessor, \"mrpc\": MrpcProcessor, \"xnli\": XnliProcessor, }", "segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() initialized_variable_names = {} if init_checkpoint and", "'loss/cls_probabilities:0'], name='') if mode == tf.estimator.ModeKeys.PREDICT: predictions = {\"probabilities\": probabilities} output_spec = tf.estimator.EstimatorSpec(", "ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\") with tf.io.gfile.GFile(output_eval_file, \"w\") as writer: tf.compat.v1.logging.info(\"*****", "< remainder: start_index = hvd.rank() * (num_examples_per_rank+1) end_index = start_index + num_examples_per_rank +", "file that the BERT model was trained on.\") flags.DEFINE_string( \"output_dir\", None, \"The output", "\"How often to print loss from estimator\") flags.DEFINE_integer(\"iterations_per_loop\", 1000, \"How many steps to", "{ \"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64), \"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"label_ids\": tf.io.FixedLenFeature([], tf.int64),", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "end_index = len(train_examples) tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record\")] if FLAGS.horovod: tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i))", "num_train_steps * global_batch_size) tf.compat.v1.logging.info(\"Total Training Time W/O Overhead = %0.2f for Sentences =", "* log_probs, axis=-1, name='cls_per_example_loss') loss = tf.reduce_mean(per_example_loss, name='cls_loss') return (loss, per_example_loss, logits, probabilities)", "the dev set.\") flags.DEFINE_bool( \"do_predict\", False, \"Whether to run the model in inference", "with tf.Session(config=tf_config) as tf_sess: input_ids = tf.placeholder(tf.int32, shape, 'input_ids') input_mask = tf.placeholder(tf.int32, shape,", "f.write(frozen_graph.SerializeToString()) return frozen_graph def model_fn_builder(task_name, bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_one_hot_embeddings, hvd=None):", "was trained on.\") flags.DEFINE_string( \"output_dir\", None, \"The output directory where the model checkpoints", "FN_op = tf.metrics.false_negatives(labels=label_ids, predictions=predictions) FP, FP_op = tf.metrics.false_positives(labels=label_ids, predictions=predictions) TP, TP_op = tf.metrics.true_positives(labels=label_ids,", "= tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) master_process = True training_hooks = [] global_batch_size = FLAGS.train_batch_size", "hvd=None if not FLAGS.horovod else hvd) estimator = tf.estimator.Estimator( model_fn=model_fn, config=run_config) if FLAGS.do_train:", "FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1 if FLAGS.amp: tf.enable_resource_variables() run_config = tf.estimator.RunConfig( model_dir=FLAGS.output_dir if master_process", "= \"\" if var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\" name =", "var.name, var.shape, init_string) output_spec = None if mode == tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer(", "hvd=None): \"\"\"Returns `model_fn` closure for Estimator.\"\"\" def model_fn(features, labels, mode, params): # pylint:", "tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\" if FLAGS.amp else \"fp32\")", "import csv import os import modeling import optimization import tokenization import tensorflow as", "= [LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time = time.time() result = estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks) eval_time_elapsed = time.time() -", "sequence length after WordPiece tokenization. \" \"Sequences longer than this will be truncated,", "shape=[num_examples, seq_length], dtype=tf.int32), \"segment_ids\": tf.constant( all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"label_ids\": tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32),", "session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process else None, save_summary_steps=FLAGS.save_checkpoints_steps if master_process else None, log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1)", "on the test set.\") flags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for training.\") flags.DEFINE_integer(\"eval_batch_size\", 8,", "lamb\") flags.DEFINE_string( \"init_checkpoint\", None, \"Initial checkpoint (usually from a pre-trained BERT model).\") flags.DEFINE_bool(", "data processing will be printed. \" \"A number of warnings are expected for", "global_batch_size) tf.compat.v1.logging.info(\"Total Training Time W/O Overhead = %0.2f for Sentences = %d\", train_time_wo_overhead,", "required by applicable law or agreed to in writing, software # distributed under", "in frozen_graph.node if str(n.op) == 'TRTEngineOp'])) with tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\") as f: f.write(frozen_graph.SerializeToString()) return", "= 0 config = tf.compat.v1.ConfigProto() if FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU training with TF Horovod\") tf.compat.v1.logging.info(\"hvd.size()", "training_hooks[-1].total_time avg_sentences_per_second = num_train_steps * global_batch_size * 1.0 / train_time_elapsed ss_sentences_per_second = (training_hooks[-1].count", "accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) return { \"eval_accuracy\": accuracy, \"eval_loss\":", "99 (ms) = %0.2f\", cf_99 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 100 (ms) =", "tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\",", "set\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision =", "tokenizer, predict_file) tf.compat.v1.logging.info(\"***** Running prediction*****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(predict_examples)) tf.compat.v1.logging.info(\" Batch", "output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=predictions) elif mode == tf.estimator.ModeKeys.EVAL: eval_metric_ops = metric_fn(per_example_loss, label_ids,", "shape, 'segment_ids') label_ids = tf.placeholder(tf.int32, (None), 'label_ids') create_model(bert_config, False, input_ids, input_mask, segment_ids, label_ids,", "accuracy, \"eval_f1\": f1, \"eval_loss\": loss, } else: accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss", "return example def input_fn(): \"\"\"The actual input function.\"\"\" # For training, we want", "Dataset.from_generator() because that uses tf.py_func which is # not TPU compatible. The right", "to run the model in inference mode on the test set.\") flags.DEFINE_integer(\"train_batch_size\", 32,", "'loss/cls_per_example_loss:0', 'loss/cls_logits:0', 'loss/cls_probabilities:0'], name='') if mode == tf.estimator.ModeKeys.PREDICT: predictions = {\"probabilities\": probabilities} output_spec", "tokenization import tensorflow as tf import horovod.tensorflow as hvd import time from utils.utils", "tf.compat.v1.logging.info(\"***** Running prediction*****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(predict_examples)) tf.compat.v1.logging.info(\" Batch size =", "FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f for Sentences = %d\", eval_time_wo_overhead,", "time_list.sort() # Removing outliers (init/warmup) in throughput computation. predict_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)])", "= tf.placeholder(tf.int32, shape, 'segment_ids') label_ids = tf.placeholder(tf.int32, (None), 'label_ids') create_model(bert_config, False, input_ids, input_mask,", "tf.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder)) return d return input_fn def create_model(bert_config,", "be passed to Estimator.\"\"\" all_input_ids = [] all_input_mask = [] all_segment_ids = []", "FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\" if FLAGS.amp else", "to Estimator.\"\"\" name_to_features = { \"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64), \"segment_ids\": tf.io.FixedLenFeature([seq_length],", "int64 to int32. for name in list(example.keys()): t = example[name] if t.dtype ==", "= get_frozen_tftrt_model(bert_config, input_ids.shape, num_labels, use_one_hot_embeddings, init_checkpoint) (total_loss, per_example_loss, logits, probabilities) = tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids,", "\"was only trained up to sequence length %d\" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) task_name", "= [] for feature in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id) def input_fn(): \"\"\"The", "num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on TEST SET\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence", "num_warmup_steps = None training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25)) if FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "\"warmup_proportion\", 0.1, \"Proportion of training to perform linear learning rate warmup for. \"", "raise ValueError( \"At least one of `do_train`, `do_eval` or `do_predict' must be True.\")", "key in FLAGS.__flags.keys(): tf.compat.v1.logging.info(' {}: {}'.format(key, getattr(FLAGS, key))) tf.compat.v1.logging.info(\"**************************\") train_examples = None num_train_steps", "tf.nn.softmax(logits, axis=-1, name='cls_probabilities') log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss", "import optimization import tokenization import tensorflow as tf import horovod.tensorflow as hvd import", "MCC = (TP * TN - FP * FN) / ((TP + FP)", "input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() initialized_variable_names = {} if", "\"Optimizer type : adam or lamb\") flags.DEFINE_string( \"init_checkpoint\", None, \"Initial checkpoint (usually from", "= [LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time = time.time() output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\") with tf.io.gfile.GFile(output_predict_file, \"w\") as", "setup_xla_flags from utils.gpu_affinity import set_affinity import utils.dllogger_class from dllogger import Verbosity from utils.create_glue_data", "as hvd import time from utils.utils import LogEvalRunHook, LogTrainRunHook, setup_xla_flags from utils.gpu_affinity import", "hvd.rank() = %d\", hvd.size(), hvd.rank()) global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps * hvd.size() master_process", "dllogging.logger.log(step=(), data={key: float(result[key])}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\" %s = %s\", key, str(result[key])) writer.write(\"%s = %s\\n\"", "we are doing a simple classification task on the entire # segment. #", "(total_loss, per_example_loss, logits, probabilities) = tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids, 'label_ids':label_ids}, return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0', 'loss/cls_logits:0',", "trained up to sequence length %d\" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower()", "Time W/O Overhead = %0.2f for Sentences = %d\", predict_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference", "trt.TrtGraphConverter( input_graph_def=frozen_graph, nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096 << 20) - 1000, precision_mode = \"FP16\" if FLAGS.amp", "utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if FLAGS.horovod: hvd.init() processors = { \"cola\": ColaProcessor, \"mnli\": MnliProcessor, \"mrpc\": MrpcProcessor,", "= max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second = num_sentences * 1.0 / predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total", "frozen_graph.node if str(n.op) == 'TRTEngineOp'])) with tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\") as f: f.write(frozen_graph.SerializeToString()) return frozen_graph", "tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record\")] if FLAGS.horovod: tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i)) for i in", "tf.compat.v1.logging.info(\" Num examples = %d\", len(eval_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size) eval_drop_remainder", "= True output_node_names = ['loss/cls_loss', 'loss/cls_per_example_loss', 'loss/cls_logits', 'loss/cls_probabilities'] with tf.Session(config=tf_config) as tf_sess: input_ids", "sets. We do # not use Dataset.from_generator() because that uses tf.py_func which is", "training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25)) if FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps = int( len(train_examples)", "1)]) ss_sentences_per_second = num_sentences * 1.0 / eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time =", "hvd.rank() * num_examples_per_rank + remainder end_index = start_index + (num_examples_per_rank) model_fn = model_fn_builder(", "= %0.2f for Sentences = %d\", predict_time_elapsed, predict_hooks[-1].count * FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total Inference Time", "this file but is still used by the Colab and # people who", "and FLAGS.use_trt: trt_graph = get_frozen_tftrt_model(bert_config, input_ids.shape, num_labels, use_one_hot_embeddings, init_checkpoint) (total_loss, per_example_loss, logits, probabilities)", "import time from utils.utils import LogEvalRunHook, LogTrainRunHook, setup_xla_flags from utils.gpu_affinity import set_affinity import", "use Dataset.from_generator() because that uses tf.py_func which is # not TPU compatible. The", "\"Whether to run the model in inference mode on the test set.\") flags.DEFINE_integer(\"train_batch_size\",", "\"do_predict\", False, \"Whether to run the model in inference mode on the test", "in range(hvd.size())] num_examples_per_rank = len(train_examples) // hvd.size() remainder = len(train_examples) % hvd.size() if", "import Verbosity from utils.create_glue_data import * import numpy as np import tf_metrics flags", "use_one_hot_embeddings): \"\"\"Creates a classification model.\"\"\" model = modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids,", "* 1.0 / train_time_wo_overhead if master_process: tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Training Time = %0.2f for", "[LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time = time.time() output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\") with tf.io.gfile.GFile(output_predict_file, \"w\") as writer:", "segment. # # If you want to use the token-level output, use model.get_sequence_output()", "= tf.to_int32(t) example[name] = t return example def input_fn(): \"\"\"The actual input function.\"\"\"", "is_training and FLAGS.use_trt: trt_graph = get_frozen_tftrt_model(bert_config, input_ids.shape, num_labels, use_one_hot_embeddings, init_checkpoint) (total_loss, per_example_loss, logits,", "= start_index + (num_examples_per_rank) model_fn = model_fn_builder( task_name=task_name, bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate if", "\"\"\"Decodes a record to a TensorFlow example.\"\"\" example = tf.parse_single_example(record, name_to_features) # tf.Example", "size = %d\", FLAGS.train_batch_size) tf.compat.v1.logging.info(\" Num steps = %d\", num_train_steps) train_input_fn = file_based_input_fn_builder(", "tf.data.TFRecordDataset(input_file) if is_training: if hvd is not None: d = d.shard(hvd.size(), hvd.rank()) d", "(TN + FP) * (TN + FN)) ** 0.5 MCC_op = tf.group(FN_op, TN_op,", "tf.compat.v1.logging.info(\" Num steps = %d\", num_train_steps) train_input_fn = file_based_input_fn_builder( input_file=tmp_filenames, batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length, is_training=True,", "(int(len(time_list) * 0.8)) * FLAGS.predict_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)])", "= %d\", hvd.size(), hvd.rank()) global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps * hvd.size() master_process =", "= %d\", FLAGS.eval_batch_size) eval_drop_remainder = False eval_input_fn = file_based_input_fn_builder( input_file=eval_file, batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length, is_training=False,", "= %0.2f\", cf_99 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 100 (ms) = %0.2f\", cf_100", "global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps * hvd.size() master_process = (hvd.rank() == 0) hvd_rank", "* FLAGS.predict_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)]) cf_90 = max(time_list[:int(len(time_list)", "\"bert_config_file\", None, \"The config json file corresponding to the pre-trained BERT model. \"", "= tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) else: dummy_op = tf.no_op() # Need to call", "for key in sorted(result.keys()): dllogging.logger.log(step=(), data={key: float(result[key])}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\" %s = %s\", key,", "entire # segment. # # If you want to use the token-level output,", "FLAGS.amp else \"FP32\", minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000 ) frozen_graph = converter.convert() print('Total node count", "\"eval_f1\": f1, \"eval_loss\": loss, } else: accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss =", "def create_model(bert_config, is_training, input_ids, input_mask, segment_ids, labels, num_labels, use_one_hot_embeddings): \"\"\"Creates a classification model.\"\"\"", "language governing permissions and # limitations under the License. \"\"\"BERT finetuning runner.\"\"\" from", "5e-5, \"The initial learning rate for Adam.\") flags.DEFINE_bool(\"use_trt\", False, \"Whether to use TF-TRT\")", "tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) master_process = True training_hooks = [] global_batch_size = FLAGS.train_batch_size *", "tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f for Sentences = %d\", predict_time_wo_overhead, num_sentences)", "related to data processing will be printed. \" \"A number of warnings are", "model_fn # This function is not used by this file but is still", "# I.e., 0.1 dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer, output_weights, transpose_b=True)", "# you may not use this file except in compliance with the License.", "Eval results *****\") for key in sorted(result.keys()): dllogging.logger.log(step=(), data={key: float(result[key])}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\" %s", "used by this file but is still used by the Colab and #", "`input_fn` closure to be passed to Estimator.\"\"\" all_input_ids = [] all_input_mask = []", "division from __future__ import print_function import collections import csv import os import modeling", "reading doesn't matter. d = tf.data.TFRecordDataset(input_file) if is_training: if hvd is not None:", "MCC_op = tf.group(FN_op, TN_op, TP_op, FP_op, tf.identity(MCC, name=\"MCC\")) return {\"MCC\": (MCC, MCC_op)} elif", "model = modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32) # In the", "\"do_lower_case\", True, \"Whether to lower case the input text. Should be True for", "utils.dllogger_class from dllogger import Verbosity from utils.create_glue_data import * import numpy as np", "tf.metrics.mean(values=per_example_loss) f1 = tf_metrics.f1(labels=label_ids, predictions=predictions, num_classes=2, pos_indices=[1]) return { \"eval_accuracy\": accuracy, \"eval_f1\": f1,", "cf_90 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 95 (ms) = %0.2f\", cf_95 * 1000)", "batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder) eval_hooks = [LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time = time.time() result = estimator.evaluate(input_fn=eval_input_fn,", "learning_rate, num_train_steps, num_warmup_steps, use_one_hot_embeddings, hvd=None): \"\"\"Returns `model_fn` closure for Estimator.\"\"\" def model_fn(features, labels,", "\"lamb\", \"Optimizer type : adam or lamb\") flags.DEFINE_string( \"init_checkpoint\", None, \"Initial checkpoint (usually", "hvd_rank = 0 config = tf.compat.v1.ConfigProto() if FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU training with TF Horovod\")", "num_examples_per_rank + 1 else: start_index = hvd.rank() * num_examples_per_rank + remainder end_index =", "graph rewrite if FLAGS.amp: dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0)) output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=probabilities)", "max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second = num_sentences * 1.0 / predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference", "config.gpu_options.visible_device_list = str(hvd.local_rank()) set_affinity(hvd.local_rank()) if hvd.size() > 1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level =", "# people who depend on it. def input_fn_builder(features, batch_size, seq_length, is_training, drop_remainder, hvd=None):", "d return input_fn def main(_): setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if FLAGS.horovod: hvd.init()", "computation. predict_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) * 0.8)) * FLAGS.predict_batch_size", "return (loss, per_example_loss, logits, probabilities) def get_frozen_tftrt_model(bert_config, shape, num_labels, use_one_hot_embeddings, init_checkpoint): tf_config =", "predict_hooks[-1].count * FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f for Sentences =", "shape=[num_examples], dtype=tf.int32), }) if is_training: if hvd is not None: d = d.shard(hvd.size(),", "output_bias, name='cls_logits') probabilities = tf.nn.softmax(logits, axis=-1, name='cls_probabilities') log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels =", "num_train_steps, num_warmup_steps, hvd, False, FLAGS.amp, FLAGS.num_accumulation_steps, FLAGS.optimizer_type) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, train_op=train_op)", "tf.compat.v1.logging.info(\"***** Running evaluation *****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(eval_examples)) tf.compat.v1.logging.info(\" Batch size", "tf.io.gfile.GFile(output_predict_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Predict results *****\") for prediction in estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks,", "hvd.rank() * (num_examples_per_rank+1) end_index = start_index + num_examples_per_rank + 1 else: start_index =", "\"cola\": ColaProcessor, \"mnli\": MnliProcessor, \"mrpc\": MrpcProcessor, \"xnli\": XnliProcessor, } if not FLAGS.do_train and", "Batch size = %d\", FLAGS.train_batch_size) tf.compat.v1.logging.info(\" Num steps = %d\", num_train_steps) train_input_fn =", "This is for demo purposes and does NOT scale to large data sets.", "utils.gpu_affinity import set_affinity import utils.dllogger_class from dllogger import Verbosity from utils.create_glue_data import *", "(training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size * 1.0 / train_time_wo_overhead if master_process: tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total", "predict_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on TEST SET\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.predict_batch_size)", "an `input_fn` closure to be passed to Estimator.\"\"\" name_to_features = { \"input_ids\": tf.io.FixedLenFeature([seq_length],", "is_training = (mode == tf.estimator.ModeKeys.TRAIN) if not is_training and FLAGS.use_trt: trt_graph = get_frozen_tftrt_model(bert_config,", "* FLAGS.num_accumulation_steps * hvd.size() master_process = (hvd.rank() == 0) hvd_rank = hvd.rank() config.gpu_options.visible_device_list", "= \", *INIT_FROM_CKPT*\" else: init_string = \", *NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\" name = %s, shape", "FLAGS.horovod else hvd) train_start_time = time.time() estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks) train_time_elapsed = time.time() -", "output directory where the model checkpoints will be written.\") ## Other parameters flags.DEFINE_string(", "None num_train_steps = None num_warmup_steps = None training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25)) if FLAGS.do_train:", "TF32 on A100 and FP32 on V100 GPUS.\") flags.DEFINE_bool(\"use_xla\", True, \"Whether to enable", "= tf.metrics.false_negatives(labels=label_ids, predictions=predictions) FP, FP_op = tf.metrics.false_positives(labels=label_ids, predictions=predictions) TP, TP_op = tf.metrics.true_positives(labels=label_ids, predictions=predictions)", "depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1, name='cls_per_example_loss') loss = tf.reduce_mean(per_example_loss, name='cls_loss')", "key, str(result[key])) writer.write(\"%s = %s\\n\" % (key, str(result[key]))) if FLAGS.do_predict and master_process: predict_examples", "init_string) frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(), output_node_names) num_nodes = len(frozen_graph.node) print('Converting graph using TensorFlow-TensorRT...')", "tf.Example only supports tf.int64, but the TPU only supports tf.int32. # So cast", "FLAGS.train_batch_size * FLAGS.num_accumulation_steps hvd_rank = 0 config = tf.compat.v1.ConfigProto() if FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU training", "= tf.nn.bias_add(logits, output_bias, name='cls_logits') probabilities = tf.nn.softmax(logits, axis=-1, name='cls_probabilities') log_probs = tf.nn.log_softmax(logits, axis=-1)", "parameters flags.DEFINE_string( \"dllog_path\", \"/results/bert_dllog.json\", \"filename where dllogger writes to\") flags.DEFINE_string( \"optimizer_type\", \"lamb\", \"Optimizer", "TP_op, FP_op, tf.identity(MCC, name=\"MCC\")) return {\"MCC\": (MCC, MCC_op)} elif task_name == \"mrpc\": accuracy", "eval_start_time = time.time() result = estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks) eval_time_elapsed = time.time() - eval_start_time time_list", "['loss/cls_loss', 'loss/cls_per_example_loss', 'loss/cls_logits', 'loss/cls_probabilities'] with tf.Session(config=tf_config) as tf_sess: input_ids = tf.placeholder(tf.int32, shape, 'input_ids')", "License for the specific language governing permissions and # limitations under the License.", "not in processors: raise ValueError(\"Task not found: %s\" % (task_name)) processor = processors[task_name]()", "None, log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1) if master_process: tf.compat.v1.logging.info(\"***** Configuaration *****\") for key in FLAGS.__flags.keys(): tf.compat.v1.logging.info('", "class_probability in prediction) + \"\\n\" writer.write(output_line) predict_time_elapsed = time.time() - predict_start_time time_list =", "= %s\\n\" % (key, str(result[key]))) if FLAGS.do_predict and master_process: predict_examples = processor.get_test_examples(FLAGS.data_dir) predict_file", "processor.get_train_examples(FLAGS.data_dir) num_train_steps = int( len(train_examples) / global_batch_size * FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps *", "= \", *NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape, init_string)", "learning rate for Adam.\") flags.DEFINE_bool(\"use_trt\", False, \"Whether to use TF-TRT\") flags.DEFINE_float(\"num_train_epochs\", 3.0, \"Total", "def get_frozen_tftrt_model(bert_config, shape, num_labels, use_one_hot_embeddings, init_checkpoint): tf_config = tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth = True output_node_names", "train_time_wo_overhead, (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) with overhead = %0.2f\",", "else \"fp32\") tf.compat.v1.logging.info(\"Latency Confidence Level 50 (ms) = %0.2f\", cf_50 * 1000) tf.compat.v1.logging.info(\"Latency", "tf.metrics.false_positives(labels=label_ids, predictions=predictions) TP, TP_op = tf.metrics.true_positives(labels=label_ids, predictions=predictions) TN, TN_op = tf.metrics.true_negatives(labels=label_ids, predictions=predictions) MCC", "\"License\"); # you may not use this file except in compliance with the", "input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32) # In the demo, we are doing a simple", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "The right way to load data is with TFRecordReader. d = tf.data.Dataset.from_tensor_slices({ \"input_ids\":", "model. \" \"This specifies the model architecture.\") flags.DEFINE_string(\"task_name\", None, \"The name of the", "128, \"The maximum total input sequence length after WordPiece tokenization. \" \"Sequences longer", "demo, we are doing a simple classification task on the entire # segment.", "JIT compilation.\") flags.DEFINE_bool(\"horovod\", False, \"Whether to use Horovod for multi-gpu runs\") flags.DEFINE_bool( \"verbose_logging\",", "seq_length], dtype=tf.int32), \"label_ids\": tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32), }) if is_training: if hvd is not", "train_examples = None num_train_steps = None num_warmup_steps = None training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25))", "= %0.2f for Sentences = %d\", eval_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on EVAL", "label_ids = tf.placeholder(tf.int32, (None), 'label_ids') create_model(bert_config, False, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings)", "file_based_convert_examples_to_features(predict_examples, label_list, FLAGS.max_seq_length, tokenizer, predict_file) tf.compat.v1.logging.info(\"***** Running prediction*****\") tf.compat.v1.logging.info(\" Num examples = %d\",", "= tf.argmax(logits, axis=-1, output_type=tf.int32) if task_name == \"cola\": FN, FN_op = tf.metrics.false_negatives(labels=label_ids, predictions=predictions)", "num_labels, use_one_hot_embeddings): \"\"\"Creates a classification model.\"\"\" model = modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask,", "return {\"MCC\": (MCC, MCC_op)} elif task_name == \"mrpc\": accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions)", "use_one_hot_embeddings) tvars = tf.trainable_variables() initialized_variable_names = {} if init_checkpoint and (hvd is None", "FLAGS.optimizer_type) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, train_op=train_op) elif mode == tf.estimator.ModeKeys.EVAL: dummy_op =", "update\" \"Global batch size = num_accumulation_steps * train_batch_size\") flags.DEFINE_bool(\"amp\", True, \"Whether to enable", "tf.get_variable( \"output_weights\", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable( \"output_bias\", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope(\"loss\"):", "# Copyright 2018 The Google AI Language Team Authors. # # Licensed under", "Estimator.\"\"\" def metric_fn(per_example_loss, label_ids, logits): predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) if task_name ==", "= tf.data.TFRecordDataset(input_file) if is_training: if hvd is not None: d = d.shard(hvd.size(), hvd.rank())", "cf_100 * 1000) tf.compat.v1.logging.info(\"Latency Average (ms) = %0.2f\", avg * 1000) tf.compat.v1.logging.info(\"Throughput Average", "bert_config, is_training, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() initialized_variable_names =", "utils.utils import LogEvalRunHook, LogTrainRunHook, setup_xla_flags from utils.gpu_affinity import set_affinity import utils.dllogger_class from dllogger", "file_based_convert_examples_to_features( train_examples[start_index:end_index], label_list, FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"***** Running training *****\") tf.compat.v1.logging.info(\" Num examples", "%d\", len(train_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.train_batch_size) tf.compat.v1.logging.info(\" Num steps = %d\",", "1000) tf.compat.v1.logging.info(\"Latency Average (ms) = %0.2f\", avg * 1000) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) =", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "file but is still used by the Colab and # people who depend", "= os.path.join(FLAGS.output_dir, \"predict.tf_record\") file_based_convert_examples_to_features(predict_examples, label_list, FLAGS.max_seq_length, tokenizer, predict_file) tf.compat.v1.logging.info(\"***** Running prediction*****\") tf.compat.v1.logging.info(\" Num", "in writing, software # distributed under the License is distributed on an \"AS", "cf_50 = max(time_list[:int(len(time_list) * 0.50)]) cf_90 = max(time_list[:int(len(time_list) * 0.90)]) cf_95 = max(time_list[:int(len(time_list)", "tf.compat.v1.logging.info(\" Num examples = %d\", len(train_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.train_batch_size) tf.compat.v1.logging.info(\"", "total_loss, learning_rate, num_train_steps, num_warmup_steps, hvd, False, FLAGS.amp, FLAGS.num_accumulation_steps, FLAGS.optimizer_type) output_spec = tf.estimator.EstimatorSpec( mode=mode,", "model \" \"was only trained up to sequence length %d\" % (FLAGS.max_seq_length, bert_config.max_position_embeddings))", "All rights reserved. # Copyright 2018 The Google AI Language Team Authors. #", "Running evaluation *****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(eval_examples)) tf.compat.v1.logging.info(\" Batch size =", "drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure to be passed to Estimator.\"\"\" name_to_features =", "\"\"\"Creates a classification model.\"\"\" model = modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings,", "train_time_elapsed ss_sentences_per_second = (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size * 1.0 / train_time_wo_overhead if", "= max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second = num_sentences * 1.0 / eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total", "\"w\") as writer: tf.compat.v1.logging.info(\"***** Predict results *****\") for prediction in estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks, yield_single_examples=False):", "= %s\" % (name, features[name].shape)) input_ids = features[\"input_ids\"] input_mask = features[\"input_mask\"] segment_ids =", "= file_based_input_fn_builder( input_file=predict_file, batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder) predict_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time = time.time()", "batch size = num_accumulation_steps * train_batch_size\") flags.DEFINE_bool(\"amp\", True, \"Whether to enable AMP ops.", "TN, TN_op = tf.metrics.true_negatives(labels=label_ids, predictions=predictions) MCC = (TP * TN - FP *", "trt_graph = get_frozen_tftrt_model(bert_config, input_ids.shape, num_labels, use_one_hot_embeddings, init_checkpoint) (total_loss, per_example_loss, logits, probabilities) = tf.import_graph_def(trt_graph,", "0.99)]) cf_100 = max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second = num_sentences * 1.0 / predict_time_wo_overhead", "Overhead = %0.2f for Sentences = %d\", predict_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on", "1 else: start_index = hvd.rank() * num_examples_per_rank + remainder end_index = start_index +", "save_summary_steps=FLAGS.save_checkpoints_steps if master_process else None, log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1) if master_process: tf.compat.v1.logging.info(\"***** Configuaration *****\") for", "warnings are expected for a normal SQuAD evaluation.\") def file_based_input_fn_builder(input_file, batch_size, seq_length, is_training,", "after WordPiece tokenization. \" \"Sequences longer than this will be truncated, and sequences", "(init/warmup) in throughput computation. predict_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) *", "[LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time = time.time() result = estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks) eval_time_elapsed = time.time() - eval_start_time", "The Google AI Language Team Authors. # # Licensed under the Apache License,", "end_index = start_index + num_examples_per_rank + 1 else: start_index = hvd.rank() * num_examples_per_rank", "= \", *INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape, init_string)", "\"At least one of `do_train`, `do_eval` or `do_predict' must be True.\") bert_config =", "on EVAL set\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length)", "\"Total batch size for eval.\") flags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch size for predict.\") flags.DEFINE_float(\"learning_rate\",", "mode, params): # pylint: disable=unused-argument \"\"\"The `model_fn` for Estimator.\"\"\" def metric_fn(per_example_loss, label_ids, logits):", "def file_based_input_fn_builder(input_file, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure to be", "FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict: raise ValueError( \"At least one of", "FLAGS.train_batch_size) tf.compat.v1.logging.info(\" Num steps = %d\", num_train_steps) train_input_fn = file_based_input_fn_builder( input_file=tmp_filenames, batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length,", "after TF-TRT conversion:', num_nodes, '->', len(frozen_graph.node)) print('TRT node count:', len([1 for n in", "\"The config json file corresponding to the pre-trained BERT model. \" \"This specifies", "FLAGS.max_seq_length, tokenizer, eval_file) tf.compat.v1.logging.info(\"***** Running evaluation *****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(eval_examples))", "TF-TRT conversion:', num_nodes, '->', len(frozen_graph.node)) print('TRT node count:', len([1 for n in frozen_graph.node", "/ global_batch_size * FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion) start_index = 0 end_index", "numpy as np import tf_metrics flags = tf.flags FLAGS = flags.FLAGS ## Required", "the .tsv files (or other data files) \" \"for the task.\") flags.DEFINE_string( \"bert_config_file\",", "Google AI Language Team Authors. # # Licensed under the Apache License, Version", "\"wb\") as f: f.write(frozen_graph.SerializeToString()) return frozen_graph def model_fn_builder(task_name, bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps,", "predict_drop_remainder = False predict_input_fn = file_based_input_fn_builder( input_file=predict_file, batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder) predict_hooks =", "\" \"models and False for cased models.\") flags.DEFINE_integer( \"max_seq_length\", 128, \"The maximum total", "* 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 99 (ms) = %0.2f\", cf_99 * 1000) tf.compat.v1.logging.info(\"Latency", "== tf.estimator.ModeKeys.PREDICT: predictions = {\"probabilities\": probabilities} output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=predictions) elif mode", "tf.compat.v1.logging.info(\"Summary Inference Statistics on EVAL set\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence Length", "FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f for Sentences = %d\", predict_time_wo_overhead,", "`model_fn` for Estimator.\"\"\" def metric_fn(per_example_loss, label_ids, logits): predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) if", "FLAGS.task_name.lower() if task_name not in processors: raise ValueError(\"Task not found: %s\" % (task_name))", "rate warmup for. \" \"E.g., 0.1 = 10% of training.\") flags.DEFINE_integer(\"save_checkpoints_steps\", 1000, \"How", "FP_op, tf.identity(MCC, name=\"MCC\")) return {\"MCC\": (MCC, MCC_op)} elif task_name == \"mrpc\": accuracy =", "False, \"Whether to use Horovod for multi-gpu runs\") flags.DEFINE_bool( \"verbose_logging\", False, \"If true,", "tensorflow as tf import horovod.tensorflow as hvd import time from utils.utils import LogEvalRunHook,", "and master_process: predict_examples = processor.get_test_examples(FLAGS.data_dir) predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\") file_based_convert_examples_to_features(predict_examples, label_list, FLAGS.max_seq_length, tokenizer,", "training epochs to perform.\") flags.DEFINE_float( \"warmup_proportion\", 0.1, \"Proportion of training to perform linear", ") = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if FLAGS.verbose_logging: tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for", "mixed precision graph rewrite if fp16 to enable graph rewrite if FLAGS.amp: loss_scaler", "(hvd.rank() == 0) hvd_rank = hvd.rank() config.gpu_options.visible_device_list = str(hvd.local_rank()) set_affinity(hvd.local_rank()) if hvd.size() >", "master_process: eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\") file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer,", "init_string = \", *INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape,", "batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure to be passed to", "a normal SQuAD evaluation.\") def file_based_input_fn_builder(input_file, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an", "of training.\") flags.DEFINE_integer(\"save_checkpoints_steps\", 1000, \"How often to save the model checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\", 10,", "input data dir. Should contain the .tsv files (or other data files) \"", "= %s, shape = %s\" % (name, features[name].shape)) input_ids = features[\"input_ids\"] input_mask =", "2.0 (the \"License\"); # you may not use this file except in compliance", "1000) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file", "input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids, 'label_ids':label_ids}, return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0', 'loss/cls_logits:0', 'loss/cls_probabilities:0'], name='') if mode == tf.estimator.ModeKeys.PREDICT:", "seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder) predict_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time = time.time() output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\")", "= len(frozen_graph.node) print('Converting graph using TensorFlow-TensorRT...') from tensorflow.python.compiler.tensorrt import trt_convert as trt converter", "\"init_checkpoint\", None, \"Initial checkpoint (usually from a pre-trained BERT model).\") flags.DEFINE_bool( \"do_lower_case\", True,", "by this file but is still used by the Colab and # people", "set_affinity(hvd.local_rank()) if hvd.size() > 1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1 if FLAGS.amp:", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "import division from __future__ import print_function import collections import csv import os import", "= max(time_list[:int(len(time_list) * 0.99)]) cf_100 = max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second = num_sentences *", "# # Unless required by applicable law or agreed to in writing, software", "\"This specifies the model architecture.\") flags.DEFINE_string(\"task_name\", None, \"The name of the task to", "steps = %d\", num_train_steps) train_input_fn = file_based_input_fn_builder( input_file=tmp_filenames, batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True, hvd=None", "express or implied. # See the License for the specific language governing permissions", "\"input_ids\": tf.constant( all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"input_mask\": tf.constant( all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32), \"segment_ids\":", "MrpcProcessor, \"xnli\": XnliProcessor, } if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict:", "= tf.get_variable( \"output_weights\", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable( \"output_bias\", [num_labels], initializer=tf.zeros_initializer()) with", "tf.compat.v1.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape, init_string) output_spec = None", "type : adam or lamb\") flags.DEFINE_string( \"init_checkpoint\", None, \"Initial checkpoint (usually from a", "eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\") file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)", "input_graph_def=frozen_graph, nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096 << 20) - 1000, precision_mode = \"FP16\" if FLAGS.amp else", "if master_process else None, log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1) if master_process: tf.compat.v1.logging.info(\"***** Configuaration *****\") for key", "input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() (assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)", "* 0.8)]) num_sentences = (int(len(time_list) * 0.8)) * FLAGS.predict_batch_size avg = np.mean(time_list) cf_50", "d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return d return input_fn def main(_): setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path)", "demo purposes and does NOT scale to large data sets. We do #", "* 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 90 (ms) = %0.2f\", cf_90 * 1000) tf.compat.v1.logging.info(\"Latency", "var.shape, init_string) output_spec = None if mode == tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss,", "seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder) eval_hooks = [LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time = time.time() result = estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks)", "either express or implied. # See the License for the specific language governing", "return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0', 'loss/cls_logits:0', 'loss/cls_probabilities:0'], name='') if mode == tf.estimator.ModeKeys.PREDICT: predictions = {\"probabilities\": probabilities}", "to be passed to Estimator.\"\"\" all_input_ids = [] all_input_mask = [] all_segment_ids =", "loss, } else: accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) return {", "eval_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) * 0.8)) * FLAGS.eval_batch_size avg", "\"label_ids\": tf.io.FixedLenFeature([], tf.int64), } def _decode_record(record, name_to_features): \"\"\"Decodes a record to a TensorFlow", "use_one_hot_embeddings, init_checkpoint) (total_loss, per_example_loss, logits, probabilities) = tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids, 'label_ids':label_ids}, return_elements=['loss/cls_loss:0',", "hvd.size() remainder = len(train_examples) % hvd.size() if hvd.rank() < remainder: start_index = hvd.rank()", "if FLAGS.amp else \"FP32\", minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000 ) frozen_graph = converter.convert() print('Total node", "predict_start_time = time.time() output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\") with tf.io.gfile.GFile(output_predict_file, \"w\") as writer: tf.compat.v1.logging.info(\"*****", "num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate if not FLAGS.horovod else FLAGS.learning_rate * hvd.size(), num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False,", "want no shuffling and parallel reading doesn't matter. d = tf.data.TFRecordDataset(input_file) if is_training:", "if FLAGS.amp: loss_scaler = tf.train.experimental.FixedLossScale(1) dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler) eval_metric_ops = metric_fn(per_example_loss,", "processor.get_test_examples(FLAGS.data_dir) predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\") file_based_convert_examples_to_features(predict_examples, label_list, FLAGS.max_seq_length, tokenizer, predict_file) tf.compat.v1.logging.info(\"***** Running prediction*****\")", "name = %s, shape = %s%s\", var.name, var.shape, init_string) output_spec = None if", "the demo, we are doing a simple classification task on the entire #", "dtype=tf.int32), \"input_mask\": tf.constant( all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32), \"segment_ids\": tf.constant( all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32),", "from utils.create_glue_data import * import numpy as np import tf_metrics flags = tf.flags", "tf.int64), } def _decode_record(record, name_to_features): \"\"\"Decodes a record to a TensorFlow example.\"\"\" example", "as f: f.write(frozen_graph.SerializeToString()) return frozen_graph def model_fn_builder(task_name, bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps,", "for i in range(hvd.size())] num_examples_per_rank = len(train_examples) // hvd.size() remainder = len(train_examples) %", "tf.no_op() # Need to call mixed precision graph rewrite if fp16 to enable", "data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\") with tf.io.gfile.GFile(output_eval_file, \"w\") as writer:", "\"Number of accumulation steps before gradient update\" \"Global batch size = num_accumulation_steps *", "1000, \"How many steps to make in each estimator call.\") flags.DEFINE_integer(\"num_accumulation_steps\", 1, \"Number", "master_process: tf.compat.v1.logging.info(\"***** Configuaration *****\") for key in FLAGS.__flags.keys(): tf.compat.v1.logging.info(' {}: {}'.format(key, getattr(FLAGS, key)))", "example = tf.parse_single_example(record, name_to_features) # tf.Example only supports tf.int64, but the TPU only", "eval on the dev set.\") flags.DEFINE_bool( \"do_predict\", False, \"Whether to run the model", "= tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias, name='cls_logits')", "= tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) f1 = tf_metrics.f1(labels=label_ids, predictions=predictions, num_classes=2, pos_indices=[1])", "* 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 95 (ms) = %0.2f\", cf_95 * 1000) tf.compat.v1.logging.info(\"Latency", "classification task on the entire # segment. # # If you want to", "the License. # You may obtain a copy of the License at #", "rewrite if fp16 to enable graph rewrite if FLAGS.amp: loss_scaler = tf.train.experimental.FixedLossScale(1) dummy_op", "train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps = int( len(train_examples) / global_batch_size * FLAGS.num_train_epochs) num_warmup_steps =", "be passed to Estimator.\"\"\" name_to_features = { \"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64),", "no shuffling and parallel reading doesn't matter. d = tf.data.TFRecordDataset(input_file) if is_training: if", "= %s\", \"fp16\" if FLAGS.amp else \"fp32\") tf.compat.v1.logging.info(\"Latency Confidence Level 50 (ms) =", "\" \"This specifies the model architecture.\") flags.DEFINE_string(\"task_name\", None, \"The name of the task", "eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\") file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file) tf.compat.v1.logging.info(\"***** Running evaluation", "under the License. \"\"\"BERT finetuning runner.\"\"\" from __future__ import absolute_import from __future__ import", "not None: d = d.shard(hvd.size(), hvd.rank()) d = d.repeat() d = d.shuffle(buffer_size=100) d", "= tf.placeholder(tf.int32, (None), 'label_ids') create_model(bert_config, False, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars", "modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError( \"Cannot use sequence length %d because", "will be printed. \" \"A number of warnings are expected for a normal", "TensorFlow-TensorRT...') from tensorflow.python.compiler.tensorrt import trt_convert as trt converter = trt.TrtGraphConverter( input_graph_def=frozen_graph, nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096", "tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) return { \"eval_accuracy\": accuracy, \"eval_loss\": loss, }", "init_string = \", *INIT_FROM_CKPT*\" else: init_string = \", *NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\" name = %s,", "%s\\n\" % (key, str(result[key]))) if FLAGS.do_predict and master_process: predict_examples = processor.get_test_examples(FLAGS.data_dir) predict_file =", "all_label_ids = [] for feature in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id) def input_fn():", "dllogger import Verbosity from utils.create_glue_data import * import numpy as np import tf_metrics", "tvars: init_string = \"\" if var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" else:", "0.95)]) cf_99 = max(time_list[:int(len(time_list) * 0.99)]) cf_100 = max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second =", "# Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved. # Copyright 2018 The", "\"\"\"BERT finetuning runner.\"\"\" from __future__ import absolute_import from __future__ import division from __future__", "import set_affinity import utils.dllogger_class from dllogger import Verbosity from utils.create_glue_data import * import", "= tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) return { \"eval_accuracy\": accuracy, \"eval_loss\": loss,", "= %0.2f for Sentences = %d\", eval_time_elapsed, eval_hooks[-1].count * FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total Inference Time", "FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\" if FLAGS.amp else \"fp32\") tf.compat.v1.logging.info(\"Latency Confidence Level 50", "\"w\") as writer: tf.compat.v1.logging.info(\"***** Eval results *****\") for key in sorted(result.keys()): dllogging.logger.log(step=(), data={key:", "FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"***** Running training *****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(train_examples))", "eval_file) tf.compat.v1.logging.info(\"***** Running evaluation *****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(eval_examples)) tf.compat.v1.logging.info(\" Batch", "num_labels, use_one_hot_embeddings, init_checkpoint) (total_loss, per_example_loss, logits, probabilities) = tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids, 'label_ids':label_ids},", "\"max_seq_length\", 128, \"The maximum total input sequence length after WordPiece tokenization. \" \"Sequences", "FLAGS.do_train: file_based_convert_examples_to_features( train_examples[start_index:end_index], label_list, FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"***** Running training *****\") tf.compat.v1.logging.info(\" Num", "{ \"eval_accuracy\": accuracy, \"eval_f1\": f1, \"eval_loss\": loss, } else: accuracy = tf.metrics.accuracy( labels=label_ids,", "tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences = %d\", predict_time_elapsed, predict_hooks[-1].count * FLAGS.predict_batch_size)", "\"models and False for cased models.\") flags.DEFINE_integer( \"max_seq_length\", 128, \"The maximum total input", "a TensorFlow example.\"\"\" example = tf.parse_single_example(record, name_to_features) # tf.Example only supports tf.int64, but", "time.time() - train_start_time train_time_wo_overhead = training_hooks[-1].total_time avg_sentences_per_second = num_train_steps * global_batch_size * 1.0", "matter. d = tf.data.TFRecordDataset(input_file) if is_training: if hvd is not None: d =", "else None, session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process else None, save_summary_steps=FLAGS.save_checkpoints_steps if master_process else None,", "with TF Horovod\") tf.compat.v1.logging.info(\"hvd.size() = %d hvd.rank() = %d\", hvd.size(), hvd.rank()) global_batch_size =", "for Estimator.\"\"\" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument \"\"\"The `model_fn` for", "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "t = example[name] if t.dtype == tf.int64: t = tf.to_int32(t) example[name] = t", "= utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if FLAGS.horovod: hvd.init() processors = { \"cola\": ColaProcessor, \"mnli\": MnliProcessor, \"mrpc\":", "\"Whether to enable XLA JIT compilation.\") flags.DEFINE_bool(\"horovod\", False, \"Whether to use Horovod for", "predictions=predictions) TP, TP_op = tf.metrics.true_positives(labels=label_ids, predictions=predictions) TN, TN_op = tf.metrics.true_negatives(labels=label_ids, predictions=predictions) MCC =", "batch size for eval.\") flags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch size for predict.\") flags.DEFINE_float(\"learning_rate\", 5e-5,", "predict_start_time time_list = predict_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in throughput computation. predict_time_wo_overhead", "= d.apply( tf.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder)) return d return input_fn", "tf.metrics.true_positives(labels=label_ids, predictions=predictions) TN, TN_op = tf.metrics.true_negatives(labels=label_ids, predictions=predictions) MCC = (TP * TN -", "tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth = True output_node_names = ['loss/cls_loss', 'loss/cls_per_example_loss', 'loss/cls_logits', 'loss/cls_probabilities'] with tf.Session(config=tf_config) as", "trt_convert as trt converter = trt.TrtGraphConverter( input_graph_def=frozen_graph, nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096 << 20) - 1000,", "parallel reading and shuffling. # For eval, we want no shuffling and parallel", "\"cola\": FN, FN_op = tf.metrics.false_negatives(labels=label_ids, predictions=predictions) FP, FP_op = tf.metrics.false_positives(labels=label_ids, predictions=predictions) TP, TP_op", "var.shape, init_string) frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(), output_node_names) num_nodes = len(frozen_graph.node) print('Converting graph using", "(int(len(time_list) * 0.8)) * FLAGS.eval_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)])", "BERT model).\") flags.DEFINE_bool( \"do_lower_case\", True, \"Whether to lower case the input text. Should", "or hvd.rank() == 0): (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if", "drop_remainder=drop_remainder) return d return input_fn def main(_): setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if", "= -tf.reduce_sum(one_hot_labels * log_probs, axis=-1, name='cls_per_example_loss') loss = tf.reduce_mean(per_example_loss, name='cls_loss') return (loss, per_example_loss,", "* FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion) start_index = 0 end_index = len(train_examples)", "eval_input_fn = file_based_input_fn_builder( input_file=eval_file, batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder) eval_hooks = [LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time =", "loss_scaler = tf.train.experimental.FixedLossScale(1) dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler) eval_metric_ops = metric_fn(per_example_loss, label_ids, logits)", "metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) return output_spec (total_loss, per_example_loss,", "tf.io.gfile.makedirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower() if task_name not in processors: raise ValueError(\"Task not found:", "with tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\") as f: f.write(frozen_graph.SerializeToString()) return frozen_graph def model_fn_builder(task_name, bert_config, num_labels, init_checkpoint,", "mixed precision graph rewrite if fp16 to enable graph rewrite if FLAGS.amp: dummy_op", "TPU compatible. The right way to load data is with TFRecordReader. d =", "Should contain the .tsv files (or other data files) \" \"for the task.\")", "master_process else None, session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process else None, save_summary_steps=FLAGS.save_checkpoints_steps if master_process else", "%d\", predict_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on TEST SET\") tf.compat.v1.logging.info(\"Batch size = %d\",", "(assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if FLAGS.verbose_logging: tf.compat.v1.logging.info(\"**** Trainable Variables", "flags = tf.flags FLAGS = flags.FLAGS ## Required parameters flags.DEFINE_string( \"data_dir\", None, \"The", "= processor.get_train_examples(FLAGS.data_dir) num_train_steps = int( len(train_examples) / global_batch_size * FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps", "- FP * FN) / ((TP + FP) * (TP + FN) *", "only supports tf.int32. # So cast all int64 to int32. for name in", "= \"\" if var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" else: init_string =", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "params): # pylint: disable=unused-argument \"\"\"The `model_fn` for Estimator.\"\"\" def metric_fn(per_example_loss, label_ids, logits): predictions", "(key, str(result[key]))) if FLAGS.do_predict and master_process: predict_examples = processor.get_test_examples(FLAGS.data_dir) predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\")", "= { \"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64), \"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"label_ids\": tf.io.FixedLenFeature([],", "and # limitations under the License. \"\"\"BERT finetuning runner.\"\"\" from __future__ import absolute_import", "rate for Adam.\") flags.DEFINE_bool(\"use_trt\", False, \"Whether to use TF-TRT\") flags.DEFINE_float(\"num_train_epochs\", 3.0, \"Total number", "FLAGS.horovod: hvd.init() processors = { \"cola\": ColaProcessor, \"mnli\": MnliProcessor, \"mrpc\": MrpcProcessor, \"xnli\": XnliProcessor,", "is with TFRecordReader. d = tf.data.Dataset.from_tensor_slices({ \"input_ids\": tf.constant( all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"input_mask\":", "= estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks) eval_time_elapsed = time.time() - eval_start_time time_list = eval_hooks[-1].time_list time_list.sort() #", "(ms) = %0.2f\", cf_95 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 99 (ms) = %0.2f\",", "False, \"Whether to run eval on the dev set.\") flags.DEFINE_bool( \"do_predict\", False, \"Whether", "estimator call.\") flags.DEFINE_integer(\"num_accumulation_steps\", 1, \"Number of accumulation steps before gradient update\" \"Global batch", "= %0.2f\", cf_50 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 90 (ms) = %0.2f\", cf_90", "training_hooks = [] global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps hvd_rank = 0 config =", "[] global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps hvd_rank = 0 config = tf.compat.v1.ConfigProto() if", "== 0) hvd_rank = hvd.rank() config.gpu_options.visible_device_list = str(hvd.local_rank()) set_affinity(hvd.local_rank()) if hvd.size() > 1:", "closure for Estimator.\"\"\" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument \"\"\"The `model_fn`", "length %d because the BERT model \" \"was only trained up to sequence", "\"FP32\", minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000 ) frozen_graph = converter.convert() print('Total node count before and", "\", *INIT_FROM_CKPT*\" else: init_string = \", *NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\" name = %s, shape =", "+ FP) * (TN + FN)) ** 0.5 MCC_op = tf.group(FN_op, TN_op, TP_op,", "must be True.\") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError( \"Cannot", "FP * FN) / ((TP + FP) * (TP + FN) * (TN", "hvd import time from utils.utils import LogEvalRunHook, LogTrainRunHook, setup_xla_flags from utils.gpu_affinity import set_affinity", "return output_spec return model_fn # This function is not used by this file", "num_train_steps = None num_warmup_steps = None training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25)) if FLAGS.do_train: train_examples", "training_hooks[-1].skipped) * global_batch_size * 1.0 / train_time_wo_overhead if master_process: tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Training Time", "will be written.\") ## Other parameters flags.DEFINE_string( \"dllog_path\", \"/results/bert_dllog.json\", \"filename where dllogger writes", "0.1 dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer, output_weights, transpose_b=True) logits =", "int(num_train_steps * FLAGS.warmup_proportion) start_index = 0 end_index = len(train_examples) tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record\")]", "tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps, hvd, False, FLAGS.amp, FLAGS.num_accumulation_steps, FLAGS.optimizer_type)", "flags.DEFINE_integer(\"iterations_per_loop\", 1000, \"How many steps to make in each estimator call.\") flags.DEFINE_integer(\"num_accumulation_steps\", 1,", "compatible. The right way to load data is with TFRecordReader. d = tf.data.Dataset.from_tensor_slices({", "drop_remainder=predict_drop_remainder) predict_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time = time.time() output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\") with tf.io.gfile.GFile(output_predict_file,", "if master_process: tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Training Time = %0.2f for Sentences = %d\", train_time_elapsed,", "found: %s\" % (task_name)) processor = processors[task_name]() label_list = processor.get_labels() tokenizer = tokenization.FullTokenizer(", "start_index + num_examples_per_rank + 1 else: start_index = hvd.rank() * num_examples_per_rank + remainder", "- predict_start_time time_list = predict_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in throughput computation.", "= tf.matmul(output_layer, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias, name='cls_logits') probabilities = tf.nn.softmax(logits, axis=-1,", "hvd.size(), num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False, hvd=None if not FLAGS.horovod else hvd) estimator = tf.estimator.Estimator(", "num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() (assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf_sess.run(tf.global_variables_initializer())", "return d return input_fn def main(_): setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if FLAGS.horovod:", "if hvd.size() > 1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1 if FLAGS.amp: tf.enable_resource_variables()", "segment_ids = features[\"segment_ids\"] label_ids = features[\"label_ids\"] is_training = (mode == tf.estimator.ModeKeys.TRAIN) if not", "except in compliance with the License. # You may obtain a copy of", "tf.int64: t = tf.to_int32(t) example[name] = t return example def input_fn(): \"\"\"The actual", "# not TPU compatible. The right way to load data is with TFRecordReader.", "not used by this file but is still used by the Colab and", "loss = tf.reduce_mean(per_example_loss, name='cls_loss') return (loss, per_example_loss, logits, probabilities) def get_frozen_tftrt_model(bert_config, shape, num_labels,", "time_list = eval_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in throughput computation. eval_time_wo_overhead =", "directory where the model checkpoints will be written.\") ## Other parameters flags.DEFINE_string( \"dllog_path\",", "tf.placeholder(tf.int32, shape, 'input_ids') input_mask = tf.placeholder(tf.int32, shape, 'input_mask') segment_ids = tf.placeholder(tf.int32, shape, 'segment_ids')", "* hvd.size(), num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False, hvd=None if not FLAGS.horovod else hvd) estimator =", "num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on EVAL set\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence", "\"Whether to use TF-TRT\") flags.DEFINE_float(\"num_train_epochs\", 3.0, \"Total number of training epochs to perform.\")", "absolute_import from __future__ import division from __future__ import print_function import collections import csv", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "which is # not TPU compatible. The right way to load data is", "`do_eval` or `do_predict' must be True.\") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length > bert_config.max_position_embeddings:", "tf.compat.v1.logging.info(\"-----------------------------\") if FLAGS.do_eval and master_process: eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\") file_based_convert_examples_to_features(", "\"\"\"Returns `model_fn` closure for Estimator.\"\"\" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument", "use_one_hot_embeddings, hvd=None): \"\"\"Returns `model_fn` closure for Estimator.\"\"\" def model_fn(features, labels, mode, params): #", "reserved. # Copyright 2018 The Google AI Language Team Authors. # # Licensed", "tf.estimator.ModeKeys.EVAL: eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) return", "model_fn=model_fn, config=run_config) if FLAGS.do_train: file_based_convert_examples_to_features( train_examples[start_index:end_index], label_list, FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"***** Running training", "%0.2f\", cf_50 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 90 (ms) = %0.2f\", cf_90 *", "MCC_op)} elif task_name == \"mrpc\": accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss)", "probabilities = tf.nn.softmax(logits, axis=-1, name='cls_probabilities') log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels,", "for. \" \"E.g., 0.1 = 10% of training.\") flags.DEFINE_integer(\"save_checkpoints_steps\", 1000, \"How often to", "eval.\") flags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch size for predict.\") flags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning", "features[\"input_mask\"] segment_ids = features[\"segment_ids\"] label_ids = features[\"label_ids\"] is_training = (mode == tf.estimator.ModeKeys.TRAIN) if", "%s%s\", var.name, var.shape, init_string) output_spec = None if mode == tf.estimator.ModeKeys.TRAIN: train_op =", "Statistics on EVAL set\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\",", "tf_metrics flags = tf.flags FLAGS = flags.FLAGS ## Required parameters flags.DEFINE_string( \"data_dir\", None,", "max(time_list[:int(len(time_list) * 0.95)]) cf_99 = max(time_list[:int(len(time_list) * 0.99)]) cf_100 = max(time_list[:int(len(time_list) * 1)])", "ValueError(\"Task not found: %s\" % (task_name)) processor = processors[task_name]() label_list = processor.get_labels() tokenizer", "# segment. # # If you want to use the token-level output, use", "batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder) predict_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time = time.time() output_predict_file = os.path.join(FLAGS.output_dir,", "make in each estimator call.\") flags.DEFINE_integer(\"num_accumulation_steps\", 1, \"Number of accumulation steps before gradient", "output_spec (total_loss, per_example_loss, logits, probabilities) = create_model( bert_config, is_training, input_ids, input_mask, segment_ids, label_ids,", "from utils.utils import LogEvalRunHook, LogTrainRunHook, setup_xla_flags from utils.gpu_affinity import set_affinity import utils.dllogger_class from", "max(time_list[:int(len(time_list) * 0.90)]) cf_95 = max(time_list[:int(len(time_list) * 0.95)]) cf_99 = max(time_list[:int(len(time_list) * 0.99)])", "\"How many steps to make in each estimator call.\") flags.DEFINE_integer(\"num_accumulation_steps\", 1, \"Number of", "'loss/cls_logits', 'loss/cls_probabilities'] with tf.Session(config=tf_config) as tf_sess: input_ids = tf.placeholder(tf.int32, shape, 'input_ids') input_mask =", "= processor.get_dev_examples(FLAGS.data_dir) eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\") file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file) tf.compat.v1.logging.info(\"*****", "estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks, yield_single_examples=False): output_line = \"\\t\".join( str(class_probability) for class_probability in prediction) + \"\\n\"", "# coding=utf-8 # Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved. # Copyright", "batch_size=batch_size, drop_remainder=drop_remainder)) return d return input_fn def create_model(bert_config, is_training, input_ids, input_mask, segment_ids, labels,", "initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\" name = %s, shape = %s%s\", var.name,", "from a pre-trained BERT model).\") flags.DEFINE_bool( \"do_lower_case\", True, \"Whether to lower case the", "d = d.shuffle(buffer_size=100) d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return d return input_fn def main(_):", "None, \"Initial checkpoint (usually from a pre-trained BERT model).\") flags.DEFINE_bool( \"do_lower_case\", True, \"Whether", "end_index = start_index + (num_examples_per_rank) model_fn = model_fn_builder( task_name=task_name, bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate", "in each estimator call.\") flags.DEFINE_integer(\"num_accumulation_steps\", 1, \"Number of accumulation steps before gradient update\"", "on it. def input_fn_builder(features, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure", "= %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") if __name__ == \"__main__\": flags.mark_flag_as_required(\"data_dir\")", "flags.DEFINE_float(\"num_train_epochs\", 3.0, \"Total number of training epochs to perform.\") flags.DEFINE_float( \"warmup_proportion\", 0.1, \"Proportion", "* 0.99)]) cf_100 = max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second = num_sentences * 1.0 /", "prediction in estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks, yield_single_examples=False): output_line = \"\\t\".join( str(class_probability) for class_probability in prediction)", "to\") flags.DEFINE_string( \"optimizer_type\", \"lamb\", \"Optimizer type : adam or lamb\") flags.DEFINE_string( \"init_checkpoint\", None,", "time.time() estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks) train_time_elapsed = time.time() - train_start_time train_time_wo_overhead = training_hooks[-1].total_time avg_sentences_per_second", "Sentences = %d\", eval_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on EVAL set\") tf.compat.v1.logging.info(\"Batch size", "hvd=None if not FLAGS.horovod else hvd) train_start_time = time.time() estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks) train_time_elapsed", "False eval_input_fn = file_based_input_fn_builder( input_file=eval_file, batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder) eval_hooks = [LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time", "all of the warnings related to data processing will be printed. \" \"A", "pre-trained BERT model).\") flags.DEFINE_bool( \"do_lower_case\", True, \"Whether to lower case the input text." ]
[ "| Student.objects.filter(programme = \"PhD\") assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(acad_approval =", "no in excel file roll_no - details of student from file first_name -", "def get_context(request): \"\"\" This function gets basic gata from database to send to", "get_faculty_list() courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type,", "dele.delete() curriculum = Curriculum.objects.select_related().filter(branch = request.POST['branch']).filter(batch = request.POST['batch']).filter(programme= request.POST['programme']) courses = Course.objects.all() course_type", "timetable = Timetable.objects.all() # exam_t = Exam_timetable.objects.all() procedures_context = acad_proced_global_context() try: examTtForm =", "\"\"\" # to remove a convenor/coconvenor from the position # @param: # request", "# return HttpResponseRedirect('/aims/')# #################################################### # # ##########covenors and coconvenors################## # @csrf_exempt def add_convenor(request):", "@login_required def add_timetable(request): \"\"\" acad-admin can upload the time table(any type of) of", "file programme - details of student from file batch - details of student", "= Calendar.objects.all() # this_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # next_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # courses =", "context) # # ---------------------senator------------------ # @csrf_exempt def senator(request): # \"\"\" # to add", "pk, # 'designation': designation, # } # return JsonResponse(data)# ###################################################### # # ##########Senate", "required to check if the student is available # mother - mother's name", "from form.REQUEST course_code - course_code from form.REQUEST course_name - course-name from form.REQUEST course_id", "request_batch = request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme'] request_sem = request.POST['sem'] except", "# curr_course = Curriculum.objects.filter(curriculum_id=curr_id) # grades = Grades.objects.filter(curriculum_id=curr_course) # context= { # 'grades':", "metadata about the requested page # @variables: # name - the name of", "= ExtraInfo.objects.get(id=request.POST.get('rollno')) # programme = request.POST.get('programme') # batch = request.POST.get('batch') # ph =", "id to be deleted # \"\"\" # if request.method == \"POST\": # data", "# s = Grades.objects.filter(student_id=id, sem=sem) # for p in s: # if (str(p.course_id)", "- workbook of xlsx file title - formatting variable of title the workbook", "# \"\"\" # It deletes the grade of the student # @param: #", "= \"\" calendar = \"\" this_sem_courses = \"\" next_sem_courses = \"\" courses =", "Students @param: request - contains metadata about the requested page @variables: batch -", "# ph = request.POST.get('phoneno') # if not Student.objects.filter(id=roll).exists(): # db = Student() #", "course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)] if \"optional_\"+str(i) in request.POST: optional=True else: optional=False course_type=request.POST[\"course_type_\"+str(i)] except Exception", "hDes: # if des.designation == s or des.designation == c: # designation =", "# sem.save() # return HttpResponse(\"Worked\") def view_course(request): # if request.method == \"POST\": #", "Student.objects.get(id=student) # s.father_name=father # s.mother_name=mother # s.hall_no = hall # s.room_no = room", "- contains metadata about the requested page # pk - the primary key", "# if des.designation == s or des.designation == c: # designation = des.designation.name", "requested page @variables: current_user - get user from request user_details - extract details", "the webpage this_sem_course - tha data of thsi semester courses next_sem_courses - the", "as e: from_date=\"\" to_date=\"\" desc=\"\" pass c = Calendar( from_date=from_date, to_date=to_date, description=desc) c.save()", "# desig_id - mother 's name of the student # acadadmin - student's", "= book.add_format({'bold': False, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) sheet = book.add_worksheet() title_text", "user = User.objects.create_user( username=roll_no, password='<PASSWORD>', first_name=first_name, last_name=last_name, email=email, ) einfo = ExtraInfo.objects.create( id=roll_no,", "str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st", "user # acadadmin - deatils of the acad admin # father - father's", "# choices = request.POST.getlist('choice') # for i in choices: # course = Course.objects.all().filter(course_id=i).first()", "designation of request user \"\"\" try: current_user = get_object_or_404(User, username=request.user.username) user_details = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first()", "event. c = object to save new event to the academic calendar. \"\"\"", "the requested page. @variables: request_batch - Batch from form request_branch - Branch from", "course_type=request.POST[\"course_type\"] except Exception as e: id=\"\" programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\"", "sex=sex, date_of_birth=dob, address=address, phone_no=phone_no, user_type='student', department=department, ) sem=1 stud_data = Student.objects.create( id=einfo, programme", "'align': 'center', 'valign': 'vcenter'}) subtitle = book.add_format({'bold': True, 'font_size': 15, 'align': 'center', 'valign':", "where the student will become # convenor or coconvenor # hDes - holdsDesignation", "{ 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','2'] } examTtForm = ExamTimetableForm() if request.method", "# context= { # 'courses': courses, # 'course_type': course_type, # 'curriculum_course': curriculum_courses, #", "== 'POST': i=0 new_curr=[] while True: if \"semester_\"+str(i) in request.POST: try: programme=request.POST['AddProgramme'] batch=request.POST['AddBatch']", "None: hall_no=3 else: hall_no=int(hall_no) programme_name=request.POST['Programme'] batch_year=request.POST['Batch'] batch = Batch.objects.all().filter(name = programme_name, discipline__acronym =", "of the student to be displayed in the webpage # \"\"\" s =", "time now - get current time year - getcurrent year batch - gets", "that stores the # information that the particular student is a convenor/coconvenor to", "'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','2'] } examTtForm = ExamTimetableForm() if request.method ==", "the designation of the user. # user_details - to get the details of", "procedures_context['lists'], 'date': procedures_context['date'], 'query_option1': procedures_context['query_option1'], 'query_option2': procedures_context['query_option2'], 'course_verification_date' : procedures_context['course_verification_date'], 'submitted_course_list' : procedures_context['submitted_course_list'],", "acad_proced_global_context() try: examTtForm = ExamTimetableForm() acadTtForm = AcademicTimetableForm() calendar = Calendar.objects.all() this_sem_courses =", "student is available # mother - mother's name of the student # add", "return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context)", "else: title='Mr.' dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13", "excel file having data excel - excel file sheet - sheet no in", "hDes.delete() # return HttpResponseRedirect('/aims/') # else: # return HttpResponseRedirect('/aims/')# #################################################### # # ##########covenors", "return render(request, \"ais/ais.html\", context) # # ---------------------senator------------------ # @csrf_exempt def senator(request): # \"\"\"", "requested page # pk - the primary key of the student's record in", "return render(request, 'ais/ais.html', context) @login_required def next_curriculum(request): \"\"\" This function is used to", "contains metadata about the requested page # @variables: # current_user - father's name", "timetable from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') timetable = Timetable.objects.all() exam_t =", "temporary variables for final output b - temporary variables for final output c", "# return HttpResponseRedirect('/aims/') return HttpResponseRedirect('/aims/') def confirm_grades(request): # if user_check(request): # return HttpResponseRedirect('/academic-procedures/')", "datetime.datetime(*to_date).date() get_calendar_details = Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description = desc get_calendar_details.from_date = from_date get_calendar_details.to_date = to_date", "break i+=1 Curriculum.objects.bulk_create(new_curr) curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme) courses =", "no # \"\"\" current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id", "- data of delete dictionary in post request timetable - all timetable from", "= acad_proced_global_context() try: examTtForm = ExamTimetableForm() acadTtForm = AcademicTimetableForm() calendar = Calendar.objects.all() this_sem_courses", "course - gets the course curr_key - gets the curriculum from database obj", "i.save() # return HttpResponseRedirect('/academic-procedures/') def min_cred(request): # \"\"\" # to set minimum credit", "# student - the list students that is a senator # hDes -", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') try: batch = request.POST['batch'] course = Courses.objects.get(id =", "sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st = 'attachment;", "# p = Designation.objects.get(name='Co Convenor') # if request.method == 'POST': # rollno =", "# @param: # request - contains metadata about the requested page # pk", "#print (temp) # print (current_user) # acadadmin = temp.working # k = str(user_details).split()", "Courses.objects.get(id = request.POST['course']) obj = course_registration.objects.all().filter(course_id = course) except Exception as e: batch=\"\"", "class Convenor - the extraInfo objects that holds the designation as a convenor", "= ExtraInfo.objects.get(id=roll.id) # db.name = name.upper() # db.id = roll # db.batch =", "t = Meeting.objects.get(id=data) # t.delete() return HttpResponseRedirect('/aims/') # # ###################################################### # # ##########Student", "render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def delete_curriculum(request): \"\"\" This function", "student to be hidden in the webpage # \"\"\" # s = get_object_or_404(Designation,", "optional=\"\" course_type=\"\" pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme entry.batch=batch entry.branch=branch entry.sem=sem entry.course_code=course_code entry.course_id=course_id entry.credits=credits entry.optional=optional entry.course_type=course_type", "objects that holds the designation as a coconvenor meetings - the all meeting", "type of user. It checkes the authentication of the user. @param: request -", "request.POST: if str(i)+\"_fac\" in request.POST: if request.POST[str(i)+\"_fac\"] == \"\" : logging.warning(\"No faculty\") else:", "# return HttpResponse(\"Data Does Not Exist\") # return HttpResponse(\"Data Deleted Successfully\") def add_advanced_profile(request):", "'2': new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id,", "rollno, etc of a student # @param: # request - contains metadata about", "temp = HoldsDesignation.objects.all().filter(designation = desig_id).first() # print (temp) # print (current_user) # acadadmin", "the given pk # hDes - the holdDesignation object that stores the #", "file dob - details of student from file fathers_name - details of student", "the username of the logged in user # user_details - the details of", "attendance - all the attendance objects of the students context - the datas", "= [1, 3, 5, 7] # examTtForm = ExamTimetableForm() # acadTtForm = AcademicTimetableForm()", "request.method == \"POST\": data = request.POST['delete'] t = Timetable.objects.get(time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\")", "= batch).filter(programme= programme) courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses': courses,", "p - designation object of Co Convenor # result - the data that", "gets the curriculum from database obj - get stdents data from database ans", "# e.delete() # u.delete() # return JsonResponse(data)# ######################################################### # ''' # # view", "the courses in curriculum course_type - list the type of courses \"\"\" if", "rendered titletext - formatting variable of title text dep - temporary variables z", "database exam_t - all exam timetable from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "Designation.objects.all().filter(name='Upper Division Clerk') # temp = HoldsDesignation.objects.all().filter(designation = desig_id).first() # print (temp) #", "= d[0] # course = d[2] # sem = int(d[3]) # if request.method", "render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def edit_curriculum(request): \"\"\" This function", "= request.POST['sem'] except Exception as e: request_batch = \"\" request_branch = \"\" request_programme", "of the student # @param: # request - contains metadata about the requested", "current user # acadadmin - deatils of the acad admin # father -", "The ending date for the academic caldendar event. desc - Description for the", "else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def add_exam_timetable(request): \"\"\"", "page. @param: request - contains metadata about the requested page @variables: senates -", "i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type,", "if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST': #", "student object of the student # \"\"\" e = get_object_or_404(ExtraInfo, id=pk) # user", "subject of which the grade has to be added sem - semester of", "= Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() acadadmin = temp.working k", "delete dictionary in post request t - Object of Exam time table to", "current year batch - batch form form curriculum - curriculum details form database", "- the student object from the requested rollno # \"\"\" current_user = get_object_or_404(User,", "= Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) if request.POST['option'] == '1': new_curriculum=[] for i", "\"\"\" This function is used to check the type of user. It checkes", "course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme entry.batch=batch entry.branch=branch entry.sem=sem entry.course_code=course_code entry.course_id=course_id entry.credits=credits", ") new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) elif request.POST['option'] == '2': new_curriculum=[] for i in curriculum: ins=Curriculum(", "grade to be added in the student course - course ofwhich the grade", "= Timetable.objects.all() # exam_t = Exam_timetable.objects.all() procedures_context = acad_proced_global_context() try: examTtForm = ExamTimetableForm()", "Curriculum.objects.bulk_create(new_curriculum) elif request.POST['option'] == '2': new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1,", "- data of the student to be displayed in teh webpage # \"\"\"", "user=user, title=title, sex=sex, date_of_birth=dob, address=address, phone_no=phone_no, user_type='student', department=department, ) sem=1 stud_data = Student.objects.create(", "\"\" acadTtForm = \"\" calendar = \"\" this_sem_courses = \"\" next_sem_courses = \"\"", "batch=batch_year, batch_id = batch, father_name = fathers_name, mother_name = mothers_name, cpi = 0,", "webpage # \"\"\" s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') # if", "form required to add exam timetable Dean - the extraInfo objects that holds", "= request.POST.get('phoneno') # if not Student.objects.filter(id=roll).exists(): # db = Student() # st =", "Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() acadadmin = temp.working k = str(user_details).split() final_user", "hDes.user = extraInfo.user # hDes.working = extraInfo.user # if result == \"Convenor\": #", "contains metadata about the requested page @variables: acadTtForm - the form to add", "request.POST: # s = get_object_or_404(Designation, name=\"Senator\") # student = get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0]) # hDes", "course_list_2 = [2, 4, 6, 8] else: course_list_2 = [1, 3, 5, 7]", "sem_for_generate_sheet() if(course_list[0]==1): course_list_2 = [2, 4, 6, 8] else: course_list_2 = [1, 3,", "of student from file category - details of student from file phone_no -", "the course curr_key - gets the curriculum from database obj - get stdents", "in post request timetable - all timetable from database exam_t - all exam", "Attendance Sheet def sem_for_generate_sheet(): \"\"\" This function generates semester grade sheet @variables: now", "in registeration table \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['2','1'] }", "optional=False course_type=request.POST[\"course_type_\"+str(i)] except Exception as e: programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\"", "\"\"\" to generate Course List of Registered Students @param: request - contains metadata", "deleted # t - the minute object received from id to be deleted", "context) @login_required def add_timetable(request): \"\"\" acad-admin can upload the time table(any type of)", "get curriculum details reg - create registeration object in registeration table \"\"\" if", "- data of delete dictionary in post request t - Object of time", "about the requested page. # @variables: # choices - selected addtional courses by", "# s = get_object_or_404(Designation, name=\"Senator\") # student = get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0]) # hDes =", "get stdents data from database ans - Formatted Array to be converted to", "# if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST'", "object in registeration table \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['2','1']", "courses: reg=course_registration( course_id = c, semester_id=sem_id, student_id=stud_data ) new_reg.append(reg) course_registration.objects.bulk_create(new_reg) else: return render(request,", "= data.split(\"-\") # id = d[0] # course = d[2] # sem =", "= Batch.objects.all().filter(name = programme_name, discipline__acronym = dept, year = batch_year).first() user = User.objects.create_user(", "hall_no=3 else: hall_no=int(hall_no) programme_name=request.POST['Programme'] batch_year=request.POST['Batch'] batch = Batch.objects.all().filter(name = programme_name, discipline__acronym = dept,", "course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"] if request.POST['optional'] == \"on\": optional=True else: optional=False course_type=request.POST[\"course_type\"] except", "except Exception as e: request_batch = \"\" request_branch = \"\" request_programme = \"\"", "of delete dictionary in post request timetable - all timetable from database exam_t", "Calendar.objects.all() # this_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # next_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # courses = Course.objects.all()", "user_details - to get the details of the required user. # \"\"\" #", "about the requested page # @variables: # data - the id of the", "credits=\"\" optional=\"\" course_type=\"\" pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme entry.batch=batch entry.branch=branch entry.sem=sem entry.course_code=course_code entry.course_id=course_id entry.credits=credits entry.optional=optional", "e - the extraInfo objects of the student # user - the User", "adds the advance profile information like hall no, room no, # profile picture,", "request.method == 'POST': # rollno = request.POST.get('rollno_convenor') # extraInfo = ExtraInfo.objects.get(id=rollno) # s", "the requested page # @variables: # current_user - father's name of the student", "# @variables: # current_user - details of the current user. # desig_id -", "from form request_programme - Programme from form request_sem - Semester from form curriculum", "xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) for i in range(sheet.nrows): roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value) if sex", "sem) course_slots = CourseSlot.objects.all().filter(semester = sem_id) courses = [] for course_slot in course_slots:", "# stu = arr[0] # if Student.objects.get(id=stu): # s = Student.objects.get(id=stu) # s.father_name", "and store data in databsae. User must be logged in and must be", "students context - the datas to be displayed in the webpage \"\"\" if", "def delete_basic_profile(request, pk): # \"\"\" # Deletes the student from the database #", ": assistant_list, 'assistant_approve_list' : assistant_approve_list, 'assistant_list_length' : assistant_list_length, 'tab_id': ['1','1'], 'context': procedures_context['context'], 'lists':", "to be deleted # data - data of the student to be hidden", "curriculum for new batch. It checkes the authentication of the user and also", "sheet.set_column('D:D',15) sheet.set_column('E:E',15) k = 4 num = 1 for i in data: sheet.write_number('A'+str(k),num,normaltext)", "the semester. @param: request - contains metadata about the requested page. @variables: acadTtForm", "sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',50) sheet.set_column('D:D',15) sheet.set_column('E:E',15) k = 4", "return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": data = request.POST['delete'] t = Exam_timetable.objects.get(exam_time_table=data) t.delete()", "file title - formatting variable of title the workbook subtitle - formatting variable", "# pk - the primary key of the student's record in the database", "get_object_or_404(User, username = e.user.username) # s = get_object_or_404(Student, id=e) # data = {", "ExamTimetableForm() # acadTtForm = AcademicTimetableForm() # calendar = Calendar.objects.all() # this_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True)", "#Curriculum.objects.all() else: if int(request_sem) == 0: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme=", "- details of the user # sem - current semester of the student", "io Bytes object to write to xlsx file book - workbook of xlsx", "# if(Grades.objects.filter(student_id=id, sem=sem)): # s = Grades.objects.filter(student_id=id, sem=sem) # for p in s:", "HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() acadadmin = temp.working k = str(user_details).split() final_user = k[2] except", "appended into one data - Formated data for context m - counter for", "(temp) # print (current_user) # acadadmin = temp.working # k = str(user_details).split() #", "of the student # \"\"\" e = get_object_or_404(ExtraInfo, id=pk) # user = get_object_or_404(User,", "and request.FILES: # form = MinuteForm(request.POST, request.FILES) # if form.is_valid(): # form.save() #", "from database courses_type - get course types from database \"\"\" if user_check(request): return", "# examTtForm = ExamTimetableForm() # acadTtForm = AcademicTimetableForm() # calendar = Calendar.objects.all() #", "the student object with the given pk # hDes - the holdDesignation object", "request_branch = \"\" request_programme = \"\" request_sem = \"\" #for checking if the", "obj: registered_students.add(stu.student_id) students = Student.objects.filter(batch_id = batch_id) for stu in students: if stu", "sem[year-int(request_batch)] sem+=1 curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code') faculty_list = get_faculty_list()", "render(request, \"ais/ais.html\", context) return render(request, 'ais/ais.html', context) @login_required def next_curriculum(request): \"\"\" This function", "the previous Description. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context= {", "- the phone number of the student # \"\"\" if request.method == \"POST\":", "22, 'align': 'center', 'valign': 'vcenter'}) subtitle = book.add_format({'bold': True, 'font_size': 15, 'align': 'center',", "first_name - details of student from file last_name - details of student from", "hold_des = HoldsDesignation.objects.create( user=user, working=user, designation=desig, ) sem_id = Semester.objects.get(curriculum = batch.curriculum, semester_no", "= \"\" # s.hall_no = 1 # s.room_no = \"\" # s.save() #", "student from file mothers_name - details of student from file category - details", "return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) #Generate Attendance Sheet def sem_for_generate_sheet():", "of the new senator # data - data of the student to be", "render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def float_course_submit(request): \"\"\" to float", "- Object of Exam time table to be deleted \"\"\" if user_check(request): return", "- Programme from form request_sem - Semester from form \"\"\" if user_check(request): return", "procedures_context['batch_grade_data'], 'batch_branch_data' : procedures_context['batch_branch_data'], 'assistant_flag' : assistant_flag, 'hod_flag' : hod_flag, 'account_flag' : account_flag", "from_date = datetime.datetime(*from_date).date() to_date = to_date[0].split('-') to_date = [int(i) for i in to_date]", "- the designation object that contains senator # student - the list students", "return JsonResponse(data)# ###################################################### # # ##########Senate meeting Minute################## # @csrf_exempt def addMinute(request): #", "'curriculum_course': curriculum_courses, # } # return render(request, \"ais/ais.html\", context) # else: # return", "set minimum credit for a current semester that a student must take #", "return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1'] } if request.method == \"POST\": i=1 while", "= request.POST['course']) obj = course_registration.objects.all().filter(course_id = course) except Exception as e: batch=\"\" course=\"\"", "request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem= request_sem) # context={ # 'courses' : courses, # 'course_type'", "\"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('not registered') data.append(z) for i in registered_students: z = [] z.append(m)", "requested page @variables: programme - programme from form.REQUEST batch - batch from form.REQUEST", "data is stored in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','2']", "= str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp = str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext) k+=1 book.close() output.seek(0) response", "to remove a senator from the position # @param: # request - contains", "exam_t = Exam_timetable.objects.all() procedures_context = acad_proced_global_context() try: examTtForm = ExamTimetableForm() acadTtForm = AcademicTimetableForm()", "datetime month - current month \"\"\" now = datetime.datetime.now() month = int(now.month) if", "requested page @variables: senates - the extraInfo objects that holds the designation as", "co convenor # student - the student object with the given pk #", "extraInfo object of the student with that rollno # s - designation object", "student senator # @param: # request - contains metadata about the requested page", "# hDes.designation = s # hDes.save() # student = Student.objects.get(id=extraInfo) # data =", "details of student from file category - details of student from file phone_no", "sem_cred.append(request.POST.getlist(sem)[0]) # for i in range(1, 9): # sem = MinimumCredits.objects.all().filter(semester=i).first() # sem.credits", "Co Convenor # result - the data that contains where the student will", "# result = request.POST.get('designation') # hDes = HoldsDesignation() # hDes.user = extraInfo.user #", "= Course.objects.all() # course_type = Constants.COURSE_TYPE # timetable = Timetable.objects.all() # exam_t =", "contains metadata about the requested page @variables: current_user - get user from request", "the # information that the particular student is a convenor/coconvenor to be deleted", "obj=\"\" registered_courses = [] for i in obj: if i.student_id.batch_id.year == int(batch): registered_courses.append(i)", "\"\"\" # to add a new student senator # @param: # request -", "# programme - the programme the student is enrolled in # ph -", "'curriculum': curriculum, 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\",", "instructor_id=inst, chief_inst=False, ) new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst) else: break i+=1 return render(request, \"ais/ais.html\", context) #", "sem_for_generate_sheet(): \"\"\" This function generates semester grade sheet @variables: now - current datetime", "sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"] if request.POST['optional'] == \"on\": optional=True else: optional=False course_type=request.POST[\"course_type\"]", "- contains metadata about the requested page. @variables: data - data of delete", "details of student from file last_name - details of student from file email", "# s - the student object from the requested rollno # \"\"\" current_user", "ExamTimetableForm() if request.method == 'POST' and request.FILES: examTtForm = ExamTimetableForm(request.POST, request.FILES) if examTtForm.is_valid():", "contains metadata about the requested page. # @variables: # sem_cred = Get credit", "else: flot = Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated = True flot.save() new_curr_inst=[] for c,i in enumerate(request.POST.getlist(str(i)+'_fac')):", "request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] from_date = from_date[0].split('-') from_date = [int(i) for i in", "about the requested page # @variables: # s - the designation object that", "user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','2'] } if request.method == 'POST': i=0 new_curr=[]", "is # holding the convenor/coconvenor designation # student - the student object of", "CourseSlot.objects.all().filter(semester = sem_id) courses = [] for course_slot in course_slots: courses += course_slot.courses.all()", "@variables: request_batch - Batch from form request_branch - Branch from form request_programme -", "basic profile information like username,password, name, # rollno, etc of a student #", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context= { 'academic_calendar' :calendar, 'tab_id'", "for i in registered_courses: k = [] k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department) ans.append(k) ans.sort()", "= Curriculum.objects.filter(branch = branch).filter(batch = batch).filter(programme= programme).filter(sem = sem) # print(curriculum_courses) # courses", "# @csrf_exempt def deleteSenator(request, pk): # \"\"\" # to remove a senator from", "k[2] # if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method ==", "MinuteForm from .models import (Calendar, Course, Exam_timetable, Grades, Curriculum_Instructor,Constants, Meeting, Student, Student_attendance, Timetable,Curriculum)", "request - contains metadata about the requested page. @variables: profiles - gets the", "s.room_no = \"\" # s.save() # else: # return HttpResponse(\"Data Does Not Exist\")", "for i in from_date] from_date = datetime.datetime(*from_date).date() to_date = to_date[0].split('-') to_date = [int(i)", "# acadmic admin to update the additional courses # @param: # request -", "(Calendar, Course, Exam_timetable, Grades, Curriculum_Instructor,Constants, Meeting, Student, Student_attendance, Timetable,Curriculum) from applications.programme_curriculum.models import (CourseSlot,", "of student from file user - new user created in database einfo -", "# if not student: # data = {} # return JsonResponse(data) # else:", "of the student # s - the student object of the student #", "batch course - gets the course curr_key - gets the curriculum from database", "num = 1 for i in data: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] a,b,c,d,e", "Clerk') # temp = HoldsDesignation.objects.all().filter(designation = desig_id).first() # print (temp) # print (current_user)", "# course_type = Constants.COURSE_TYPE # context= { # 'courses': courses, # 'course_type': course_type,", "int(now.month) if month >= 7 and month <= 12: return [1, 3, 5,", "if month >= 7 and month <= 12: return [1, 3, 5, 7]", "the requested page # @variables: # data - the id of the minute", "User must be logged in and must be acadadmin @param: request - contains", "batch. It checkes the authentication of the user and also fetches the available", "function is used to see curriculum and edit entries in a curriculum. It", "is stored in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] }", ") new_reg.append(reg) course_registration.objects.bulk_create(new_reg) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) def", "# sem_cred.append(request.POST.getlist(sem)[0]) # for i in range(1, 9): # sem = MinimumCredits.objects.all().filter(semester=i).first() #", "title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',60) sheet.set_column('D:D',15) sheet.set_column('E:E',30)", "k = str(user_details).split() # print(k) # final_user = k[2] # if (str(acadadmin) !=", "the students context - the datas to be displayed in the webpage \"\"\"", "c: # designation = des.designation.name # des.delete() # data = { # 'id':", "- contains metadata about the requested page # @variables: # data - the", "metadata about the requested page @variables: batch - gets the batch course -", "= batch # db.programme = programme # st.phone_no = ph # db.save() #", "= ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first()", "that the particular student is a senator # \"\"\" pass # if request.POST:", "= [] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('registered') data.append(z) output", "AcademicTimetableForm() # calendar = Calendar.objects.all() # this_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # next_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True)", "\"\"\" # s = get_object_or_404(Designation, name=\"Convenor\") c = get_object_or_404(Designation, name=\"Co Convenor\") # student", "remove a convenor/coconvenor from the position # @param: # request - contains metadata", "s = Designation.objects.get(name='Senator') # hDes = HoldsDesignation() # hDes.user = extraInfo.user # hDes.working", "- current date from system year - current year batch - batch form", "\"ais/ais.html\", context) # # ---------------------senator------------------ # @csrf_exempt def senator(request): # \"\"\" # to", "to_date = datetime.datetime(*to_date).date() except Exception as e: from_date=\"\" to_date=\"\" desc=\"\" pass c =", "== \"\" and request_programme==\"\" and request_sem==\"\": curriculum = None #Curriculum.objects.all() else: if int(request_sem)", "# final_user = k[2] # if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') #", "to update an entry to the academic calendar to be updated. @param: request", "for context m - counter for Sl. No (in formated data) z -", "Grades.objects.filter(student_id=id, sem=sem) # for p in s: # if (str(p.course_id) == course): #", "= str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type =", "student will become # convenor or coconvenor # hDes - holdsDesignation object to", "= extraInfo.user # hDes.working = extraInfo.user # if result == \"Convenor\": # hDes.designation", "- the student object of the new convenor/coconvenor # data - data of", "\"\"\" current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper", "this_sem_courses = \"\" next_sem_courses = \"\" courses = \"\" course_type = \"\" timetable", "the academic calender objects context - the datas to be displayed in the", "course_code from form.REQUEST course_name - course-name from form.REQUEST course_id - course_id from database", "request_branch).filter(batch = request_batch).filter(programme= request_programme).order_by('sem') else: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem=", "itertools import chain from django.contrib.auth.models import User from django.http import HttpResponse, HttpResponseRedirect, JsonResponse", "\"ais/ais.html\", context) @login_required def edit_curriculum(request): \"\"\" This function is used to edit curriculum", "import xlrd import logging from io import BytesIO from xlsxwriter.workbook import Workbook from", "displayed in the webpage # \"\"\" s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co", "curriculum, 'pgstudent' : pgstudent, 'assistant_list' : assistant_list, 'assistant_approve_list' : assistant_approve_list, 'assistant_list_length' : assistant_list_length,", "d[0] # course = d[2] # sem = int(d[3]) # if request.method ==", "batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) batch=batch+1 curriculum", ": \"+ batch.name + str(\" \") + batch.discipline.acronym + str(\" \") + str(batch.year))", "Constants.COURSE_TYPE # timetable = Timetable.objects.all() # exam_t = Exam_timetable.objects.all() procedures_context = acad_proced_global_context() try:", "page @variables: dele - data being deleted from database \"\"\" if user_check(request): return", "= Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() #print (temp) # print", "except Exception as e: f1=f2=f3=\"\" pass faculty = list(chain(f1,f2,f3)) faculty_list = [] for", "details of the required user. # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) #", "page @variables: programme - programme from form.REQUEST now - current date from system", "- temporary variables for final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method", "\"\"\" # acadmic admin to update the additional courses # @param: # request", "= Meeting.objects.get(id=data) # t.delete() return HttpResponseRedirect('/aims/') # # ###################################################### # # ##########Student basic", "student's address subject - subject of which the grade has to be added", "'course_verification_date' : procedures_context['course_verification_date'], 'submitted_course_list' : procedures_context['submitted_course_list'], 'result_year' : procedures_context['result_year'], 'batch_grade_data' : procedures_context['batch_grade_data'], 'batch_branch_data'", "student object of the new convenor/coconvenor # data - data of the student", "request.POST: if request.POST[str(i)+\"_fac\"] == \"\" : logging.warning(\"No faculty\") else: flot = Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated", "senate meeting minute object to the database. # @param: # request - contains", "instance from the database for the previous Description. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "designation # student - the student object of the new convenor/coconvenor # data", "context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'faculty_list': faculty_list, 'tab_id' :['5','1'] }", "Grades.objects.filter(curriculum_id=curr_course) # context= { # 'grades': grades, # 'tab_id' :\"2\" # } #", "= str(user_details).split() final_user = k[2] except Exception as e: acadadmin=\"\" final_user=\"\" pass if", "semester of the student grade - grade to be added in the student", "@param: request - contains metadata about the requested page. @variables: request_batch - Batch", "= temp.working # k = str(user_details).split() # print(k) # final_user = k[2] #", "# \"\"\" if request.method == \"POST\": name = request.POST.get('name') # roll = ExtraInfo.objects.get(id=request.POST.get('rollno'))", "HttpResponseRedirect('/aims/') # # return JsonResponse(data) # else: # return HttpResponseRedirect('/aims/') # @csrf_exempt def", "uploaded @param: request - contains metadata about the requested page. @variables: from_date -", "s.mother_name=mother # s.hall_no = hall # s.room_no = room # s.save() # return", "student currs - get curriculum details reg - create registeration object in registeration", "request.FILES) if acadTtForm.is_valid(): acadTtForm.save() return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context)", "= d[2] # sem = int(d[3]) # if request.method == \"POST\": # if(Grades.objects.filter(student_id=id,", "sex=str(sheet.cell(i,4).value) if sex == 'F': title='Ms.' else: title='Mr.' dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value)", "# t = Meeting.objects.get(id=data) # t.delete() return HttpResponseRedirect('/aims/') # # ###################################################### # #", "pk # hDes - the holdDesignation object that stores the # information that", "curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins)", "requested page # @variables: # current_user - father's name of the student #", "'attachment; filename = ' + course.code + '.xlsx' response['Content-Disposition'] = st return response", "request.method == 'POST': try: id=request.POST['id'] programme=request.POST['programme'] batch=request.POST['batch'] branch=request.POST['branch'] sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"]", "etc of a student # @param: # request - contains metadata about the", "Deleted Successfully\") def add_advanced_profile(request): # \"\"\" # It adds the advance profile information", "# student = ExtraInfo.objects.get(id=rollno) # print(student.address) # if not student: # data =", "id=einfo, programme = programme_name, batch=batch_year, batch_id = batch, father_name = fathers_name, mother_name =", "# print(curr_id) # curr_course = Curriculum.objects.filter(curriculum_id=curr_id) # grades = Grades.objects.filter(curriculum_id=curr_course) # context= {", "form.is_valid(): # form.save() # return HttpResponse('sucess') # else: # return HttpResponse('not uploaded') #", "@login_required def generate_preregistration_report(request): \"\"\" to generate preresgistration report after pre-registration @param: request -", "= \"M.Tech\") | Student.objects.filter(programme = \"PhD\") assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval", "held in senator meetings minuteForm - the form to add a senate meeting", "examTtForm, 'courses': courses, 'courses_list': courses_list, 'course_type': course_type, 'exam': exam_t, 'timetable': timetable, 'academic_calendar': calendar,", "HttpResponse(\"TimeTable Deleted\") @login_required def add_calendar(request): \"\"\" to add an entry to the academic", "render(request, \"ais/ais.html\", context) @login_required def float_course_submit(request): \"\"\" to float courses for the next", "@param: # request - contains metadata about the requested page # pk -", "- gets the course curr_key - gets the curriculum from database obj -", "int(batch): registered_courses.append(i) ans = [] for i in registered_courses: k = [] k.append(i.student_id.id.id)", "save new event to the academic calendar. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar", "} return render(request, \"ais/ais.html\", context) return render(request, 'ais/ais.html', context) @login_required def next_curriculum(request): \"\"\"", "current user. # desig_id - to check the designation of the user. #", "new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) batch=batch+1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) context= { 'curriculumm'", "credit for a current semester that a student must take # @param: #", "@login_required def delete_timetable(request): \"\"\" acad-admin can delete the outdated timetable from the server.", "sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st = 'attachment;", "Timetable.objects.all() exam_t = Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','1'] }", "for obj in assis_stat: assistant_flag = obj.student_status hod_flag = obj.hod_status account_flag = obj.account_status", "of the acad admin # father - father's name of the student #", "# exam_t = Exam_timetable.objects.all() procedures_context = acad_proced_global_context() try: examTtForm = ExamTimetableForm() acadTtForm =", "programme - programme from form.REQUEST batch - batch from form.REQUEST branch - branch", "'vcenter'}) subtitle = book.add_format({'bold': True, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) normaltext =", "in excel file roll_no - details of student from file first_name - details", "add an entry to the academic calendar to be uploaded @param: request -", "from database desig_id - check for designation acadadmin - designation for Acadadmin final_user", "of student from file batch - details of student from file user -", "@csrf_exempt def delete_basic_profile(request, pk): # \"\"\" # Deletes the student from the database", "= des.designation.name # des.delete() # data = { # 'id': pk, # 'designation':", "\"POST\": # if(Grades.objects.filter(student_id=id, sem=sem)): # s = Grades.objects.filter(student_id=id, sem=sem) # for p in", "for the previous event which is to be updated. get_calendar_details = Get the", "# else: # father = request.POST.get('father') # mother = request.POST.get('mother') # add =", "of the application. It checkes the authentication of the user and also fetches", "the designation as a senator students - all the objects in the Student", "data - Formated data for context m - counter for Sl. No (in", "student from file batch - details of student from file user - new", "\"\"\" # to add a new student convenor/coconvenor # @param: # request -", "batch from form sem - stores the next semester obj - All the", "= HoldsDesignation.objects.filter(user = student.user) # designation = [] # for des in hDes:", "chain from django.contrib.auth.models import User from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts", ":['3','3'] } return render(request, \"ais/ais.html\", context) else: context= { 'tab_id' :['3','2'] } return", "to get faculty list from database @param: request - contains metadata about the", "num+=1 z,b,c = str(i[0]),i[1],i[2] name = str(b)+\" \"+str(c) temp = str(i[3]).split() dep =", "'application/vnd.ms-excel') st = 'attachment; filename = ' + batch.name + batch.discipline.acronym + str(batch.year)", "a,b,c,d,e = str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp = str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext) k+=1 book.close() output.seek(0)", "\"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def edit_curriculum(request): \"\"\" This function is", "from the database and the update it. # \"\"\" if request.method==\"POST\": sem_cred =", "academic calender examTtForm - the form required to add exam timetable exam_t -", "Curriculum.objects.select_related().filter(branch = request.POST['branch']).filter(batch = request.POST['batch']).filter(programme= request.POST['programme']) courses = Course.objects.all() course_type = Constants.COURSE_TYPE context=", "the available data from the databases to display it on the page. @param:", "dep = str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type =", "# \"\"\" # acadmic admin to update the additional courses # @param: #", "sheet @variables: now - current datetime month - current month \"\"\" now =", "return HttpResponse(\"Worked\") def view_course(request): # if request.method == \"POST\": # programme=request.POST['programme'] # batch=request.POST['batch']", "request_branch - Branch from form request_programme - Programme from form request_sem - Semester", "This function is used to edit curriculum in database It checkes the authentication", "return render(request, \"ais/ais.html\", {}) def deleteMinute(request): # \"\"\" # to delete an existing", "if request.method == \"POST\": dele = Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete() curriculum = Curriculum.objects.select_related().filter(branch = request.POST['branch']).filter(batch", "timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable': timetable, 'tab_id'", "# \"\"\" # to delete the advance information of the student # @param:", "optional=optional, course_type=course_type, ) new_curr.append(ins) else: break i+=1 Curriculum.objects.bulk_create(new_curr) curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch", "return render(request, \"ais/ais.html\", context) @login_required def delete_curriculum(request): \"\"\" This function is used to", "} acadTtForm = AcademicTimetableForm() if request.method == 'POST' and request.FILES: acadTtForm = AcademicTimetableForm(request.POST,", "st - temporary variables for final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if", "i) inst = ExtraInfo.objects.select_related('user','department').get(user=inst) if c==0: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=True, ) new_curr_inst.append(ins) else:", "sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20)", "{} # return JsonResponse(data) # @csrf_exempt def delete_basic_profile(request, pk): # \"\"\" # Deletes", "s: # if (str(p.course_id) == course): # print(p.course_id) # p.delete() # else: #", "response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st = 'attachment; filename = ' + course.code", "courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) else:", "@param: request - contains metadata about the requested page @variables: current_user - father's", "sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) elif request.POST['option'] == '2':", "# user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation", "##########Student basic profile################## # @csrf_exempt def add_basic_profile(request): # \"\"\" # It adds the", "= Timetable.objects.all() exam_t = Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','2']", "from_date get_calendar_details.to_date = to_date get_calendar_details.save() except Exception as e: from_date=\"\" to_date=\"\" desc=\"\" return", "is used to set up the homepage of the application. It checkes the", "[] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('not registered') data.append(z) for", "request_programme).order_by('sem') else: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem= request_sem) # context={", "metadata about the requested page # @variables: # current_user - details of the", "final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') try: batch = request.POST['batch'] course =", "about the requested page # pk - the primary key of the student's", "= Exam_timetable.objects.all() procedures_context = acad_proced_global_context() try: examTtForm = ExamTimetableForm() acadTtForm = AcademicTimetableForm() calendar", "AcademicTimetableForm() calendar = Calendar.objects.all() this_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses = Course.objects.all()", "- mother 's name of the student # acadadmin - student's address #", "course_code - course_code from form.REQUEST course_name - course-name from form.REQUEST course_id - course_id", "# designation = [] # for des in hDes: # if des.designation ==", "of the student required to check if the student is available # desig_id", "'tab_id' :['3','1'] } if request.method == \"POST\": dele = Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete() curriculum =", "{ 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context) context= { 'tab_id' :['3','1'] }", "list from database @param: request - contains metadata about the requested page. @variables:", "request_branch = \"\" request_programme = \"\" if request_batch == \"\" and request_branch ==", "add a new student senator # @param: # request - contains metadata about", "- current year batch - batch form form curriculum - curriculum details form", "True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(acad_approval = False) assistant_approve_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval", "metadata about the requested page. @variables: data - data of delete dictionary in", "\"\"\" # to add a new senate meeting minute object to the database.", "database stud_data - new student object created in database desig - get designation", "def deleteSenator(request, pk): # \"\"\" # to remove a senator from the position", "courses for the next sem and store data in databsae. User must be", "to be deleted # t - the minute object received from id to", "Student.objects.get(id=stu): # s = Student.objects.get(id=stu) # s.father_name = \"\" # s.mother_name = \"\"", "# batch = request.POST.get('batch') # ph = request.POST.get('phoneno') # if not Student.objects.filter(id=roll).exists(): #", "to be deleted # \"\"\" # if request.method == \"POST\": # data =", "- new user created in database einfo - new extrainfo object created in", "- mother's name of the student # add - student's address # cpi", "programme) if request.POST['option'] == '1': new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1,", "senator # student - the list students that is a senator # hDes", "final output st - temporary variables for final output \"\"\" if user_check(request): return", "can upload the time table(any type of) of the semester. @param: request -", "the holdDesignation object that stores the # information that the particular student is", "It adds the advance profile information like hall no, room no, # profile", "\"ais/ais.html\", context) return render(request, 'ais/ais.html', context) @login_required def next_curriculum(request): \"\"\" This function is", "function is used to add new curriculum in database It checkes the authentication", "course_type = Constants.COURSE_TYPE # timetable = Timetable.objects.all() # exam_t = Exam_timetable.objects.all() procedures_context =", "return JsonResponse(data) # else: # data = {} # return JsonResponse(data) # else:", "used to delete curriculum entry in database It checkes the authentication of the", "dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13 ).value department=DepartmentInfo.objects.all().filter(name=dept).first()", "'timetable': timetable, 'tab_id' :['10','2'] } examTtForm = ExamTimetableForm() if request.method == 'POST' and", "ins - data is stored in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={", "print (temp) # print (current_user) # acadadmin = temp.working # k = str(user_details).split()", "= student.user) # designation = [] # for des in hDes: # if", "delete dictionary in post request timetable - all timetable from database exam_t -", "request.POST['programme'] now = datetime.datetime.now() year = int(now.year) batch = year-1 curriculum = Curriculum.objects.all().select_related().filter(batch", "context={ 'tab_id' :['3','1'] } if request.method == \"POST\": dele = Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete() curriculum", "context) return render(request, \"ais/ais.html\", context) @login_required def add_exam_timetable(request): \"\"\" acad-admin can upload the", "metadata about the requested page. @variables: examTtForm - data of delete dictionary in", "# acadadmin - student's address # final_user - details of the user #", "metadata about the requested page # @variables: # rollno - rollno of the", "= batch).filter(programme = programme) context= { 'curriculumm' :curriculum, 'tab_id' :['3','3'] } return render(request,", "to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] from_date = from_date[0].split('-') from_date = [int(i) for", "15, 'align': 'center', 'valign': 'vcenter'}) normaltext = book.add_format({'bold': False, 'font_size': 15, 'align': 'center',", "is used to check the type of user. It checkes the authentication of", "(\"Pre-registeration : \"+ batch.name + str(\" \") + batch.discipline.acronym + str(\" \") +", "s.save() # return HttpResponseRedirect('/academic-procedures/') # return HttpResponseRedirect('/academic-procedures/') def add_optional(request): # \"\"\" # acadmic", "= to_date[0].split('-') to_date = [int(i) for i in to_date] to_date = datetime.datetime(*to_date).date() get_calendar_details", "data for context m - counter for Sl. No (in formated data) z", "s # hDes.save() # student = Student.objects.get(id=extraInfo) # data = { # 'name':", "# data - data of the student to be displayed in teh webpage", "acadadmin - deatils of the acad admin # s - the student object", "import User from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import get_object_or_404, render", "- contains metadata about the requested page # @variables: # s - the", "Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated = True flot.save() new_curr_inst=[] for c,i in enumerate(request.POST.getlist(str(i)+'_fac')): inst = get_object_or_404(User,", "'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) sheet = book.add_worksheet() title_text = (\"Pre-registeration :", "requested page # @variables: # s - the designation object that contains senator", "sem[year-int(request_batch)-1] else: sem = sem[year-int(request_batch)] sem+=1 curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme=", "data) z - temporary array to add data to variable data k -temporary", "str(i)+\"_fac\" in request.POST: if request.POST[str(i)+\"_fac\"] == \"\" : logging.warning(\"No faculty\") else: flot =", "of student from file sex - details of student from file title -", "@variables: programme - programme from form.REQUEST batch - batch from form.REQUEST branch -", "== \"\": specialization=\"None\" if hall_no == None: hall_no=3 else: hall_no=int(hall_no) programme_name=request.POST['Programme'] batch_year=request.POST['Batch'] batch", "= get_object_or_404(User, username = e.user.username) # s = get_object_or_404(Student, id=e) # data =", "from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all()", "with the given pk # hDes - the holdDesignation object that stores the", "= Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') # result = request.POST.get('designation') # hDes", "# to add a new student convenor/coconvenor # @param: # request - contains", "of the student required to check if the student is available # mother", "# s.father_name = \"\" # s.mother_name = \"\" # s.hall_no = 1 #", "list(chain(f1,f2,f3)) faculty_list = [] for i in faculty: faculty_list.append(i) return faculty_list @login_required def", "student.address = str(hall) + \" \" + str(room) # student.save() # s =", "Get credit details from forms and the append it to an array. #", "= str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel')", "filename = ' + batch.name + batch.discipline.acronym + str(batch.year) + '-preresgistration.xlsx' response['Content-Disposition'] =", "Constants.COURSE_TYPE html = render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj = json.dumps({'html':html}) #return render(request, \"ais/ais.html\", context) return HttpResponse(obj,content_type='application/json')", "designation = des.designation.name # des.delete() # data = { # 'id': pk, #", "new_curr_inst=[] for c,i in enumerate(request.POST.getlist(str(i)+'_fac')): inst = get_object_or_404(User, username = i) inst =", "# #################################### # # curriculum # # #################################### @login_required def curriculum(request): \"\"\" This", "metadata about the requested page # pk - the primary key of that", "curr_key=\"\" obj=\"\" registered_courses = [] for i in obj: if i.student_id.batch_id.year == int(batch):", "\"sem_\"+\"1\" # sem_cred.append(request.POST.getlist(sem)[0]) # for i in range(1, 9): # sem = MinimumCredits.objects.all().filter(semester=i).first()", "the requested rollno # \"\"\" current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first()", "form request_sem - Semester from form curriculum - Get data about curriculum from", "\"ais/ais.html\", context) #Generate Attendance Sheet def sem_for_generate_sheet(): \"\"\" This function generates semester grade", "desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() #print (temp) #", "\"\"\" if request.method==\"POST\": sem_cred = [] # sem_cred.append(0) # for i in range(1,", "request_batch).filter(programme= request_programme).order_by('sem') else: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem= request_sem) #", "all the academic timetable objects calendar - all the academic calender objects context", "# form = MinuteForm(request.POST, request.FILES) # if form.is_valid(): # form.save() # return HttpResponse('sucess')", "batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) elif request.POST['option']", "SuccessFully\") @login_required def verify_grade(request): \"\"\" It verify the grades of the student @param:", "entry.programme=programme entry.batch=batch entry.branch=branch entry.sem=sem entry.course_code=course_code entry.course_id=course_id entry.credits=credits entry.optional=optional entry.course_type=course_type entry.save() curriculum = Curriculum.objects.select_related().filter(branch", "# s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') # result = request.POST.get('designation')", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) return render(request, \"ais/ais.html\", context) #", ": assistant_flag, 'hod_flag' : hod_flag, 'account_flag' : account_flag } return context @login_required def", "of the user and also fetches the available data from the databases to", "student with that rollno # s - designation object of senator # hDes", "\"\" and request_branch == \"\" and request_programme==\"\" and request_sem==\"\": curriculum = None #Curriculum.objects.all()", "data from database ans - Formatted Array to be converted to xlsx k", "context) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def delete_curriculum(request):", "acad-admin can upload the time table(any type of) of the semester. @param: request", "{}) def deleteMinute(request): # \"\"\" # to delete an existing senate meeting minute", "rollno of the student required to check if the student is available #", "objects in the Student class Convenor - the extraInfo objects that holds the", "page # @variables: # current_user - details of the current user. # desig_id", "'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) else: return", "be updated. @param: request - contains metadata about the requested page. @variables: from_date", "p = Designation.objects.get(name='Co Convenor') # if request.method == 'POST': # rollno = request.POST.get('rollno_convenor')", "# \"\"\" # It adds the advance profile information like hall no, room", "designation object that contains senator # student - the list students that is", "variables z - temporary variables for final output b - temporary variables for", "datetime import json import os import xlrd import logging from io import BytesIO", "pk): # \"\"\" # to remove a senator from the position # @param:", "sex == 'F': title='Ms.' else: title='Mr.' dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value)", "= k[2] except Exception as e: acadadmin=\"\" final_user=\"\" pass if (str(acadadmin) != str(final_user)):", "file specialization - details of student from file hall_no - details of student", ") desig = Designation.objects.get(name='student') hold_des = HoldsDesignation.objects.create( user=user, working=user, designation=desig, ) sem_id =", "metadata about the requested page. # @variables: # choices - selected addtional courses", "database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','2'] } if request.method ==", "in the Student class Convenor - the extraInfo objects that holds the designation", "context= { 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','2'] } examTtForm = ExamTimetableForm() if", "context) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def delete_timetable(request):", "= \"\" # s.mother_name = \"\" # s.hall_no = 1 # s.room_no =", "stud_data - new student object created in database desig - get designation object", "faculty of data faculty_list - list of faculty \"\"\" try: f1 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name", "data = {} # return JsonResponse(data) # else: # data = {} #", "i in choices: # course = Course.objects.all().filter(course_id=i).first() # course.acad_selection = True # course.save()", "to formatted array/variable output - io Bytes object to write to xlsx file", "HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # curr_id=request.POST['course'] # print(curr_id) # curr_course =", "else: # data = {} # return JsonResponse(data) # @csrf_exempt def deleteConvenor(request, pk):", "for final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') try: batch = request.POST['batch'] course", "in obj: registered_students.add(stu.student_id) students = Student.objects.filter(batch_id = batch_id) for stu in students: if", "= {} # return JsonResponse(data) # else: # data = {} # return", "from_date=\"\" to_date=\"\" desc=\"\" pass c = Calendar( from_date=from_date, to_date=to_date, description=desc) c.save() HttpResponse(\"Calendar Added\")", "the page. @param: request - contains metadata about the requested page @variables: request_batch", "HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import get_object_or_404, render from django.template.loader import get_template from", "sem = \"sem_\"+\"1\" # sem_cred.append(request.POST.getlist(sem)[0]) # for i in range(1, 9): # sem", "@login_required def generatexlsheet(request): \"\"\" to generate Course List of Registered Students @param: request", "from forms and the append it to an array. # sem - Get", "student.user) # designation = [] # for des in hDes: # if des.designation", "= \"\" request_branch = \"\" request_programme = \"\" if request_batch == \"\" and", "from database courses - get courses from database courses_type - get course types", "# return JsonResponse(data) # @csrf_exempt def delete_basic_profile(request, pk): # \"\"\" # Deletes the", "return HttpResponse(\"TimeTable Deleted\") @login_required def add_calendar(request): \"\"\" to add an entry to the", "curriculum details reg - create registeration object in registeration table \"\"\" if user_check(request):", "student holds_desig - get hold_desig object of student currs - get curriculum details", "HttpResponseRedirect('/academic-procedures/') try: batch = request.POST['batch'] course = Courses.objects.get(id = request.POST['course']) obj = course_registration.objects.all().filter(course_id", "ins=Curriculum( programme=programme, batch=batch, branch=branch, sem=sem, course_code=course_code, course_id=course_id, credits=credits, optional=optional, course_type=course_type, ) new_curr.append(ins) else:", "['1','1'], 'context': procedures_context['context'], 'lists': procedures_context['lists'], 'date': procedures_context['date'], 'query_option1': procedures_context['query_option1'], 'query_option2': procedures_context['query_option2'], 'course_verification_date' :", "= str(i[0]),i[1],i[2] name = str(b)+\" \"+str(c) temp = str(i[3]).split() dep = str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext)", "in the webpage # \"\"\" # s = get_object_or_404(Designation, name=\"Convenor\") c = get_object_or_404(Designation,", "to add an entry to the academic calendar to be uploaded @param: request", "dele - data being deleted from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={", "check the type of user. It checkes the authentication of the user. @param:", "render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) #Generate Attendance Sheet def sem_for_generate_sheet(): \"\"\"", "= False) assistant_approve_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(hod_approval = True) assistant_list_length", "semester that a student must take # @param: # request - contains metadata", "any particular curriculum if request_batch == \"\" and request_branch == \"\" and request_programme==\"\"", "= int(now.year) if sem[0] == 2: sem = sem[year-int(request_batch)-1] else: sem = sem[year-int(request_batch)]", "- Description for the previous event which is to be updated. get_calendar_details =", "== \"POST\": sem = request.POST.get('semester_no') batch_id=request.POST.get('batch_branch') batch = Batch.objects.filter(id = batch_id).first() obj =", "request_batch - Batch from form request_branch - Branch from form request_programme - Programme", "course_id = c, semester_id=sem_id, student_id=stud_data ) new_reg.append(reg) course_registration.objects.bulk_create(new_reg) else: return render(request, \"ais/ais.html\", context)", "context) return render(request, \"ais/ais.html\", context) @login_required def add_curriculum(request): \"\"\" This function is used", "details of student from file hall_no - details of student from file programme", "if (str(p.course_id) == course): # print(p.course_id) # p.delete() # else: # return HttpResponse(\"Unable", "primary key of that particular student field # @variables: # s - the", "of xlsx file title - formatting variable of title the workbook subtitle -", "caldendar event. desc - Description for the academic calendar event. c = object", "\"\"\" # It adds the advance profile information like hall no, room no,", "sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',50) sheet.set_column('D:D',15) sheet.set_column('E:E',15) k = 4 num = 1 for", "= \"\" courses = \"\" course_type = \"\" timetable = \"\" exam_t =", "new curriculum in database It checkes the authentication of the user and also", "# ph - the phone number of the student # \"\"\" if request.method", "= Exam_timetable.objects.get(exam_time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def add_calendar(request): \"\"\" to add an", "data in databsae. User must be logged in and must be acadadmin @param:", "deleted # data - data of the student to be hidden in the", "details of student from file mothers_name - details of student from file category", "t = Timetable.objects.get(time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def delete_exam_timetable(request): \"\"\" acad-admin can", "context) def get_faculty_list(): \"\"\" to get faculty list from database @param: request -", "= desig_id).first() # print (temp) # print (current_user) # acadadmin = temp.working #", ":['2','1'] } if request.method == 'POST' and request.FILES: profiles=request.FILES['profiles'] excel = xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0)", "# arr = st.split(\"-\") # stu = arr[0] # if Student.objects.get(id=stu): # s", "- all the extraInfor objects exam_t - all the exam timetable objects timetable", "# return HttpResponseRedirect('/aims/') # # return JsonResponse(data) # else: # return HttpResponseRedirect('/aims/') #", "data = { # 'name': extraInfo.user.username, # 'rollno': extraInfo.id, # 'programme': student.programme, #", "temporary variables for final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method ==", "formatting variable of subtitle the workbook normaltext - formatting variable for normal text", "= str(i[3]).split() dep = str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext) k+=1 book.close() output.seek(0) response =", "form to add a senate meeting minutes acadTtForm - the form to add", "# \"\"\" # to remove a senator from the position # @param: #", "variables for final output st - temporary variables for final output \"\"\" if", "student is a senator # \"\"\" pass # if request.POST: # s =", "str(i[0]),i[1],i[2] name = str(b)+\" \"+str(c) temp = str(i[3]).split() dep = str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext)", "'center', 'valign': 'vcenter'}) subtitle = book.add_format({'bold': True, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'})", "to be displayed in the webpage this_sem_course - tha data of thsi semester", "month <= 12: return [1, 3, 5, 7] else: return [2, 4, 6,", "c - temporary variables for final output st - temporary variables for final", "- the form required to add exam timetable exam_t - all the exam", "user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) return render(request, \"ais/ais.html\", context) # #################################### #", "courses, # 'course_type': course_type, # 'curriculum_course': curriculum_courses, # } # return render(request, \"ais/ais.html\",", "table \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['2','1'] } if request.method", "Deleted\") @login_required def delete_exam_timetable(request): \"\"\" acad-admin can delete the outdated exam timetable. @param:", "# desig_id = Designation.objects.all().filter(name='Upper Division Clerk') # temp = HoldsDesignation.objects.all().filter(designation = desig_id).first() #", "tha data of thsi semester courses next_sem_courses - the data of next semester", "form.REQUEST batch - batch from form.REQUEST branch - branch from form.REQUEST sem -", "InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem) registered_students = set() unregistered_students = set() for stu in obj: registered_students.add(stu.student_id)", "the outdated exam timetable. @param: request - contains metadata about the requested page.", "for the previous Description. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context=", "@param: request - contains metadata about the requested page. @variables: f1,f2,f3 - temporary", "def homepage(request): \"\"\" This function is used to set up the homepage of", "the minute object received from id to be deleted # \"\"\" # if", "# Deletes the student from the database # @param: # request - contains", "data\") return HttpResponse(\"Data Deleted SuccessFully\") @login_required def verify_grade(request): \"\"\" It verify the grades", "the # information that the particular student is a senator # \"\"\" pass", "student from file first_name - details of student from file last_name - details", "[] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('registered') data.append(z) output =", "Student.objects.filter(programme = \"PhD\") assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(acad_approval = False)", "no, # profile picture, about me etc of a student # @param: #", "# data = { # 'name': extraInfo.user.username, # 'rollno': extraInfo.id, # 'programme': student.programme,", "== 'POST' and request.FILES: acadTtForm = AcademicTimetableForm(request.POST, request.FILES) if acadTtForm.is_valid(): acadTtForm.save() return render(request,", "file sheet - sheet no in excel file roll_no - details of student", "Workbook from xhtml2pdf import pisa from itertools import chain from django.contrib.auth.models import User", "curriculum from database obj - get stdents data from database ans - Formatted", "\"\"\" # Deletes the student from the database # @param: # request -", "Student_attendance, Timetable,Curriculum) from applications.programme_curriculum.models import (CourseSlot, Course as Courses, Batch, Semester, Programme, Discipline)", "str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp = str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext) k+=1 book.close() output.seek(0) response =", "to be rendered titletext - formatting variable of title text dep - temporary", "course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) elif request.POST['option'] == '2': new_curriculum=[] for", "# 'course_type': course_type, # 'curriculum_course': curriculum_courses, # } # return render(request, \"ais/ais.html\", context)", "from form.REQUEST now - current date from system year - current year batch", "'curriculum': curriculum, 'faculty_list': faculty_list, 'tab_id' :['5','1'] } return render(request, \"ais/ais.html\", context) else: return", "request.POST: optional=True else: optional=False course_type=request.POST[\"course_type_\"+str(i)] except Exception as e: programme=\"\" batch=\"\" branch=\"\" sem=\"\"", "department=department, ) sem=1 stud_data = Student.objects.create( id=einfo, programme = programme_name, batch=batch_year, batch_id =", "academic calendar event. prev_desc - Description for the previous event which is to", "add_calendar(request): \"\"\" to add an entry to the academic calendar to be uploaded", "Get the object for the minimum credits from the database and the update", "request.POST.get('semester_no') batch_id=request.POST.get('batch_branch') batch = Batch.objects.filter(id = batch_id).first() obj = InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem) registered_students =", "= request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code') faculty_list = get_faculty_list() courses = Course.objects.all() course_type = Constants.COURSE_TYPE context=", "student from file title - details of student from file dob - details", "courses, 'course_type': course_type, 'curriculum': curriculum, 'faculty_list': faculty_list, 'tab_id' :['5','1'] } return render(request, \"ais/ais.html\",", "hDes - holdsDesignation object to store that the particualr student is holding the", "in database It checkes the authentication of the user and also fetches the", "batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme entry.batch=batch", "return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','2'] } if request.method == 'POST': i=0 new_curr=[] while", "or des.designation == c: # designation = des.designation.name # des.delete() # data =", "# course_type = Constants.COURSE_TYPE # timetable = Timetable.objects.all() # exam_t = Exam_timetable.objects.all() procedures_context", "- the student object of the new senator # data - data of", "# programme=request.POST['programme'] # batch=request.POST['batch'] # branch=request.POST['branch'] # sem=request.POST['sem'] # curriculum_courses = Curriculum.objects.filter(branch =", "data faculty_list - list of faculty \"\"\" try: f1 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Assistant", "objects calendar - all the academic calender objects department - all the departments", "\"\" : logging.warning(\"No faculty\") else: flot = Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated = True flot.save() new_curr_inst=[]", "'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context) return", "not student: # data = {} # return JsonResponse(data) # else: # father", "3, 5, 7] else: return [2, 4, 6, 8] @login_required def generatexlsheet(request): \"\"\"", "course_slot in course_slots: courses += course_slot.courses.all() new_reg=[] for c in courses: reg=course_registration( course_id", "the authentication of the user. @param: request - contains metadata about the requested", "of faculty of data faculty_list - list of faculty \"\"\" try: f1 =", "metadata about the requested page @variables: sem - get current semester from current", "contains metadata about the requested page @variables: programme - programme from form.REQUEST now", "batch=\"\" course=\"\" curr_key=\"\" obj=\"\" registered_courses = [] for i in obj: if i.student_id.batch_id.year", "@param: # request - contains metadata about the requested page # @variables: #", "else: break i+=1 Curriculum.objects.bulk_create(new_curr) curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme) courses", "# @csrf_exempt def add_basic_profile(request): # \"\"\" # It adds the basic profile information", "Exist\") # return HttpResponse(\"Data Deleted Successfully\") def add_advanced_profile(request): # \"\"\" # It adds", "hall_no=sheet.cell(i,13 ).value department=DepartmentInfo.objects.all().filter(name=dept).first() if specialization == \"\": specialization=\"None\" if hall_no == None: hall_no=3", "coconvenors################## # @csrf_exempt def add_convenor(request): # \"\"\" # to add a new student", "ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() acadadmin =", "of the student # acadadmin - student's address # final_user - details of", "dob - details of student from file fathers_name - details of student from", "batch - gets the batch from form sem - stores the next semester", "== int(batch): registered_courses.append(i) ans = [] for i in registered_courses: k = []", "# print(curriculum_courses) # courses = Course.objects.all() # course_type = Constants.COURSE_TYPE # context= {", "and coconvenors################## # @csrf_exempt def add_convenor(request): # \"\"\" # to add a new", "12: return [1, 3, 5, 7] else: return [2, 4, 6, 8] @login_required", "student object created in database desig - get designation object of student holds_desig", "= True) assistant_list_length = len(assistant_list.filter(acad_approval = False)) assis_stat = Assistantship_status.objects.all() for obj in", "return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1'] } if request.method == 'POST': try: request_batch", "temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() #print (temp) # print (current_user) # acadadmin =", "database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == 'POST': programme = request.POST['programme']", "# \"\"\" pass # if request.POST: # s = get_object_or_404(Designation, name=\"Senator\") # student", "'assistant_flag' : assistant_flag, 'hod_flag' : hod_flag, 'account_flag' : account_flag } return context @login_required", "'batch_branch_data' : procedures_context['batch_branch_data'], 'assistant_flag' : assistant_flag, 'hod_flag' : hod_flag, 'account_flag' : account_flag }", "holding the convenor/coconvenor designation # student - the student object of the new", "a dean student - the students as a senator extra - all the", "name, # rollno, etc of a student # @param: # request - contains", "courses += course_slot.courses.all() new_reg=[] for c in courses: reg=course_registration( course_id = c, semester_id=sem_id,", "this_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # next_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # courses = Course.objects.all() # course_type", "request_branch = request.POST['branch'] request_programme = request.POST['programme'] except Exception as e: request_batch = \"\"", "course_type, # 'curriculum' : curriculum, # 'tab_id' :['3','1'] # } courses = Course.objects.all()", "all the academic calender objects context - the datas to be displayed in", "user - new user created in database einfo - new extrainfo object created", "designation object of Convenor # p - designation object of Co Convenor #", "MinimumCredits.objects.all().filter(semester=i).first() # sem.credits = sem_cred[i+1] # sem.save() # return HttpResponse(\"Worked\") def view_course(request): #", "Course.objects.all() course_type = Constants.COURSE_TYPE html = render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj = json.dumps({'html':html}) #return render(request, \"ais/ais.html\",", "= [] for course_slot in course_slots: courses += course_slot.courses.all() new_reg=[] for c in", "= \"\" course_type = \"\" timetable = \"\" exam_t = \"\" pass context", "set up the homepage of the application. It checkes the authentication of the", "- mother's name of the student acadadmin - student's address subject - subject", "= request.POST.get('father') # mother = request.POST.get('mother') # add = request.POST.get('address') # hall =", "# sem.credits = sem_cred[i+1] # sem.save() # return HttpResponse(\"Worked\") def view_course(request): # if", "'ais/ais.html', context) @login_required def next_curriculum(request): \"\"\" This function is used to decide curriculum", "import get_template from django.views.decorators.csrf import csrf_exempt from django.template.loader import render_to_string from django.contrib.auth.decorators import", "new_curr.append(ins) else: break i+=1 Curriculum.objects.bulk_create(new_curr) curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme)", "of the student # user_details - the rollno of the student required to", "coconvenor meetings - the all meeting objects held in senator meetings minuteForm -", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == 'POST': programme = request.POST['programme'] now", "# return HttpResponseRedirect('/academic-procedures/') def add_optional(request): # \"\"\" # acadmic admin to update the", "Exception as e: request_batch = \"\" request_branch = \"\" request_programme = \"\" if", "\"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def add_curriculum(request): \"\"\" This function is", "sheet.set_column('E:E',15) k = 4 num = 1 for i in data: sheet.write_number('A'+str(k),num,normaltext) num+=1", "# s.room_no = room # s.save() # return HttpResponseRedirect('/academic-procedures/') # return HttpResponseRedirect('/academic-procedures/') def", "@login_required def delete_exam_timetable(request): \"\"\" acad-admin can delete the outdated exam timetable. @param: request", "senate meeting minute object from the database. # @param: # request - contains", "remove a senator from the position # @param: # request - contains metadata", "HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if request.method == \"POST\": dele = Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete()", "object to write to xlsx file book - workbook of xlsx file title", "return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def edit_curriculum(request): \"\"\" This", "- counter for Sl. No (in formated data) z - temporary array to", "@variables: # e - the extraInfo objects of the student # user -", "extra - all the extraInfor objects exam_t - all the exam timetable objects", "Batch.objects.filter(id = batch_id).first() obj = InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem) registered_students = set() unregistered_students = set()", "that holds the designation as a senator students - all the objects in", "- all the exam timetable objects timetable - all the academic timetable objects", "'courses' : courses, # 'course_type' : course_type, # 'curriculum' : curriculum, # 'tab_id'", "- subject of which the grade has to be added sem - semester", "student to be displayed in teh webpage # \"\"\" # current_user = get_object_or_404(User,", "\"Professor\")) f3 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Associate Professor\")) except Exception as e: f1=f2=f3=\"\" pass", "s = get_object_or_404(Designation, name=\"Senator\") # student = get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0]) # hDes = get_object_or_404(", "course.save() # courses = Course.objects.all() # for i in courses: # if i.course_id", "a convenor/coconvenor from the position # @param: # request - contains metadata about", "branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme entry.batch=batch entry.branch=branch", "= from_date[0].split('-') from_date = [int(i) for i in from_date] from_date = datetime.datetime(*from_date).date() to_date", "# @variables: # name - the name of the student # roll -", "from database obj - get stdents data from database ans - Formatted Array", "the user # sem - current semester of the student # data -", "the academic calendar event. c = object to save new event to the", "\"\"\" # current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id =", "p = Designation.objects.get(name='Co Convenor') # result = request.POST.get('designation') # hDes = HoldsDesignation() #", "in request.POST: if request.POST[str(i)+\"_fac\"] == \"\" : logging.warning(\"No faculty\") else: flot = Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"])", "hall = request.POST.get('hall') # room = request.POST.get('room') # cpi = request.POST.get('cpi') # student.address", "@param: request - contains metadata about the requested page @variables: programme - programme", "ExtraInfo.objects.get(id=rollno) # print(student.address) # if not student: # data = {} # return", "the academic calendar to be uploaded @param: request - contains metadata about the", "} return render(request, \"ais/ais.html\", context) @login_required def add_timetable(request): \"\"\" acad-admin can upload the", "return render(request, \"ais/ais.html\") def delete_grade(request): # \"\"\" # It deletes the grade of", "context) @login_required def delete_curriculum(request): \"\"\" This function is used to delete curriculum entry", "Exception as e: request_batch = \"\" request_branch = \"\" request_programme = \"\" request_sem", "from django.contrib.auth.models import User from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import", "[int(i) for i in to_date] to_date = datetime.datetime(*to_date).date() get_calendar_details = Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description =", "Grades, Curriculum_Instructor,Constants, Meeting, Student, Student_attendance, Timetable,Curriculum) from applications.programme_curriculum.models import (CourseSlot, Course as Courses,", "used to edit curriculum in database It checkes the authentication of the user", "@csrf_exempt def senator(request): # \"\"\" # to add a new student senator #", "course ofwhich the grade is added \"\"\" # if user_check(request): # return HttpResponseRedirect('/academic-procedures/')", "details of faculty of data faculty_list - list of faculty \"\"\" try: f1", "# } # print(data) # return JsonResponse(data) # else: # data = {}", "desc = request.POST.getlist('description')[0] from_date = from_date[0].split('-') from_date = [int(i) for i in from_date]", "{ 'tab_id' :['2','1'] } if request.method == 'POST' and request.FILES: profiles=request.FILES['profiles'] excel =", "context m - counter for Sl. No (in formated data) z - temporary", "into one data - Formated data for context m - counter for Sl.", "students: if stu not in registered_students: unregistered_students.add(stu) data = [] m = 1", "'name': name, # 'rollno': roll.id, # 'programme': programme, # 'phoneno': ph, # 'batch':", "HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # print(request.POST) # rollno=request.POST.get('roll') # print(rollno) #", "senator extra - all the extraInfor objects exam_t - all the exam timetable", "= request_batch).filter(programme= request_programme).filter(sem= request_sem) # context={ # 'courses' : courses, # 'course_type' :", "- getcurrent year batch - gets the batch from form sem - stores", "# information that the particular student is a senator # \"\"\" pass #", "+= 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('not registered') data.append(z) for i in registered_students:", "page. @variables: request_batch - Batch from form request_branch - Branch from form request_programme", "added in the student course - course ofwhich the grade is added \"\"\"", "4, 6, 8] @login_required def generatexlsheet(request): \"\"\" to generate Course List of Registered", "Batch from form request_branch - Branch from form request_programme - Programme from form", "extraInfo.user # hDes.working = extraInfo.user # hDes.designation = s # hDes.save() # student", "# request - contains metadata about the requested page # @variables: # rollno", "- current semester of the student # data - tag whether to delete", "in teh webpage # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) # user_details =", "context) return render(request, 'ais/ais.html', context) @login_required def next_curriculum(request): \"\"\" This function is used", "unregistered_students.add(stu) data = [] m = 1 for i in unregistered_students: z =", "render from django.template.loader import get_template from django.views.decorators.csrf import csrf_exempt from django.template.loader import render_to_string", "now = datetime.datetime.now() month = int(now.month) if month >= 7 and month <=", "# return render(request, \"ais/ais.html\") return render(request, \"ais/ais.html\") def delete_grade(request): # \"\"\" # It", ") new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst) else: break i+=1 return render(request, \"ais/ais.html\", context) # # ---------------------senator------------------", "applications.globals.models import (Designation, ExtraInfo, HoldsDesignation, DepartmentInfo) from .forms import AcademicTimetableForm, ExamTimetableForm, MinuteForm from", "Get the object of the calendar instance from the database for the previous", "= render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj = json.dumps({'html':html}) #return render(request, \"ais/ais.html\", context) return HttpResponse(obj,content_type='application/json') else: return", "HttpResponseRedirect('/academic-procedures/') if request.method == 'POST': programme = request.POST['programme'] now = datetime.datetime.now() year =", "semester from form.REQUEST course_code - course_code from form.REQUEST course_name - course-name from form.REQUEST", "\"\" if request_batch == \"\" and request_branch == \"\" and request_programme==\"\": curriculum =", "HttpResponse(\"Calendar Added\") return render(request, \"ais/ais.html\", context) @login_required def update_calendar(request): \"\"\" to update an", "\"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('registered') data.append(z) output = BytesIO() book = Workbook(output,{'in_memory':True}) title = book.add_format({'bold':", "\"\"\" # It adds the basic profile information like username,password, name, # rollno,", "@param: request - contains metadata about the requested page. @variables: examTtForm - data", "title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',60) sheet.set_column('D:D',15)", "= Assistantship_status.objects.all() for obj in assis_stat: assistant_flag = obj.student_status hod_flag = obj.hod_status account_flag", "variables for final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\":", "To add details of new upcoming students in the database.User must be logged", "# 'name': name, # 'rollno': roll.id, # 'programme': programme, # 'phoneno': ph, #", "now - current datetime month - current month \"\"\" now = datetime.datetime.now() month", "# next_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # courses = Course.objects.all() # course_type = Constants.COURSE_TYPE #", "= batch, father_name = fathers_name, mother_name = mothers_name, cpi = 0, category =", "the student # rollno - the rollno of the student required to check", "course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass ins=Curriculum( programme=programme, batch=batch, branch=branch, sem=sem, course_code=course_code,", "hDes - the holdDesignation object that stores the # information that the particular", "profile information like hall no, room no, # profile picture, about me etc", "s.father_name=father # s.mother_name=mother # s.hall_no = hall # s.room_no = room # s.save()", "address=address, phone_no=phone_no, user_type='student', department=department, ) sem=1 stud_data = Student.objects.create( id=einfo, programme = programme_name,", "batch_year).first() user = User.objects.create_user( username=roll_no, password='<PASSWORD>', first_name=first_name, last_name=last_name, email=email, ) einfo = ExtraInfo.objects.create(", "mother's name of the student # add - student's address # cpi -", ":['3','2'] } return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context) return render(request,", "of time table to be deleted \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method", "form.REQUEST course_id - course_id from database credits - credits from form.REQUEST optional -", "delete the advance information of the student # @param: # request - contains", "requested page @variables: request_batch - Batch from form request_branch - Branch from form", "current_user - details of the current user. # desig_id - to check the", "current month \"\"\" now = datetime.datetime.now() month = int(now.month) if month >= 7", "# \"\"\" # to add a new student convenor/coconvenor # @param: # request", "i in registered_students: z = [] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name))", "else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def float_course_submit(request): \"\"\"", "= 1 for i in data: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] a,b,c,d,e =", "\"\" request_programme = \"\" if request_batch == \"\" and request_branch == \"\" and", "\"POST\": # programme=request.POST['programme'] # batch=request.POST['batch'] # branch=request.POST['branch'] # sem=request.POST['sem'] # curriculum_courses = Curriculum.objects.filter(branch", "pgstudent = Student.objects.filter(programme = \"M.Tech\") | Student.objects.filter(programme = \"PhD\") assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark =", "JsonResponse(data) # @csrf_exempt def delete_basic_profile(request, pk): # \"\"\" # Deletes the student from", "z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('not registered') data.append(z) for i in registered_students: z = []", "def add_new_profile (request): \"\"\" To add details of new upcoming students in the", "that is a senator # hDes - the holdDesignation object that stores the", "if examTtForm.is_valid(): examTtForm.save() return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context) return", "branch - branch from form.REQUEST sem - semester from form.REQUEST course_code - course_code", "delete an existing senate meeting minute object from the database. # @param: #", "the requested page @variables: sem - get current semester from current time now", "if request_batch == \"\" and request_branch == \"\" and request_programme==\"\": curriculum = None", "particular student is a convenor/coconvenor to be deleted # data - data of", "position # @param: # request - contains metadata about the requested page #", "render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) def get_faculty_list(): \"\"\" to get faculty", "# hall - hall no of where the student stays # room no", "update the additional courses # @param: # request - contains metadata about the", "t = Exam_timetable.objects.get(exam_time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def add_calendar(request): \"\"\" to add", "about the requested page @variables: programme - programme from form.REQUEST now - current", "request.POST.getlist('choice') # for i in choices: # course = Course.objects.all().filter(course_id=i).first() # course.acad_selection =", "text sheet - xlsx sheet to be rendered titletext - formatting variable of", "# courses = Course.objects.all() # course_type = Constants.COURSE_TYPE # timetable = Timetable.objects.all() #", "} # return JsonResponse(data)# ###################################################### # # ##########Senate meeting Minute################## # @csrf_exempt def", "of the student # \"\"\" if request.method == \"POST\": name = request.POST.get('name') #", "requested page. @variables: examTtForm - data of delete dictionary in post request timetable", "context= { 'tab_id' :['5','1'] } if request.method == \"POST\": i=1 while True: if", "from id to be deleted # \"\"\" # if request.method == \"POST\": #", "Professor\")) f2 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Professor\")) f3 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Associate Professor\")) except", "in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if request.method", "s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') # result = request.POST.get('designation') #", "= name.upper() # db.id = roll # db.batch = batch # db.programme =", "# s = Student.objects.get(id=stu) # s.father_name = \"\" # s.mother_name = \"\" #", "the student will become # convenor or coconvenor # hDes - holdsDesignation object", "# hDes - holdsDesignation object to store that the particualr student is #", "request_batch).filter(programme= request_programme).filter(sem= request_sem) # context={ # 'courses' : courses, # 'course_type' : course_type,", "sheet.write_string('E'+str(k),e,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st = 'attachment; filename", "coconvenor # hDes - holdsDesignation object to store that the particualr student is", "title = book.add_format({'bold': True, 'font_size': 22, 'align': 'center', 'valign': 'vcenter'}) subtitle = book.add_format({'bold':", "z,b,c = str(i[0]),i[1],i[2] name = str(b)+\" \"+str(c) temp = str(i[3]).split() dep = str(temp[len(temp)-1])", "obj - All the registration details appended into one data - Formated data", "'faculty_list': faculty_list, 'tab_id' :['5','1'] } return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\",", "course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)] if \"optional_\"+str(i) in request.POST: optional=True else: optional=False course_type=request.POST[\"course_type_\"+str(i)] except Exception as", "request.method==\"POST\": sem_cred = [] # sem_cred.append(0) # for i in range(1, 10): #", "request.POST['programme'] request_sem = request.POST['sem'] except Exception as e: request_batch = \"\" request_branch =", "e: programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass ins=Curriculum(", "the object of the calendar instance from the database for the previous Description.", "' + batch.name + batch.discipline.acronym + str(batch.year) + '-preresgistration.xlsx' response['Content-Disposition'] = st return", "# t.delete() return HttpResponseRedirect('/aims/') # # ###################################################### # # ##########Student basic profile################## #", "received from id to be deleted # \"\"\" # if request.method == \"POST\":", "new upcoming students in the database.User must be logged in and must be", "batch.discipline.acronym + str(batch.year) + '-preresgistration.xlsx' response['Content-Disposition'] = st return response @login_required def add_new_profile", "used to decide curriculum for new batch. It checkes the authentication of the", "metadata about the requested page. @variables: request_batch - Batch from form request_branch -", "# \"\"\" # to delete an existing senate meeting minute object from the", "metadata about the requested page @variables: dele - data being deleted from database", "\"POST\": dele = Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete() curriculum = Curriculum.objects.select_related().filter(branch = request.POST['branch']).filter(batch = request.POST['batch']).filter(programme= request.POST['programme'])", "return render(request, \"ais/ais.html\", context) @login_required def float_course_submit(request): \"\"\" to float courses for the", "No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',60) sheet.set_column('D:D',15) sheet.set_column('E:E',30) k =", "data that contains where the student will become # convenor or coconvenor #", "output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') try: batch = request.POST['batch'] course = Courses.objects.get(id", "= desig_id).first() #print (temp) # print (current_user) # acadadmin = temp.working # k", "the course details # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) # user_details =", "temporary variables z - temporary variables for final output b - temporary variables", "sem = sem[year-int(request_batch)-1] else: sem = sem[year-int(request_batch)] sem+=1 curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch", "# profile picture, about me etc of a student # @param: # request", "request_batch = request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme'] except Exception as e:", "of Co Convenor # result - the data that contains where the student", "# calendar = Calendar.objects.all() # this_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # next_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) #", "the time table(any type of) of the semester. @param: request - contains metadata", "request.POST.get('programme') # batch = request.POST.get('batch') # ph = request.POST.get('phoneno') # if not Student.objects.filter(id=roll).exists():", "for any particular curriculum if request_batch == \"\" and request_branch == \"\" and", "of the user. # user_details - to get the details of the required", "# if result == \"Convenor\": # hDes.designation = s # else: # hDes.designation", "+ batch.name + batch.discipline.acronym + str(batch.year) + '-preresgistration.xlsx' response['Content-Disposition'] = st return response", "return HttpResponseRedirect('/aims/') return HttpResponseRedirect('/aims/') def confirm_grades(request): # if user_check(request): # return HttpResponseRedirect('/academic-procedures/') #", "reg=course_registration( course_id = c, semester_id=sem_id, student_id=stud_data ) new_reg.append(reg) course_registration.objects.bulk_create(new_reg) else: return render(request, \"ais/ais.html\",", "\"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) def get_faculty_list(): \"\"\" to get faculty list", "no of where the student stays # room no - hostel room no", "student field # @variables: # s - the designation object that contains convenor", "course - Course details which is selected by the academic admin. # \"\"\"", "faculty list from database @param: request - contains metadata about the requested page.", "page # @variables: # rollno - rollno of the student to become the", "variable for normal text sheet - xlsx sheet to be rendered titletext -", "- gets the batch course - gets the course curr_key - gets the", "= AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(hod_approval = True) assistant_list_length = len(assistant_list.filter(acad_approval =", "[] # sem_cred.append(0) # for i in range(1, 10): # sem = \"sem_\"+\"1\"", "z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('registered') data.append(z) output = BytesIO() book = Workbook(output,{'in_memory':True}) title", "the details of the required user. # \"\"\" # current_user = get_object_or_404(User, username=request.user.username)", "temp.working # k = str(user_details).split() # print(k) # final_user = k[2] # if", "# desig_id - used to check the designation ID. # extraInfo - extraInfo", "data = {} # return JsonResponse(data) # else: # father = request.POST.get('father') #", "= roll # db.batch = batch # db.programme = programme # st.phone_no =", "# sem=request.POST['sem'] # curriculum_courses = Curriculum.objects.filter(branch = branch).filter(batch = batch).filter(programme= programme).filter(sem = sem)", "information like username,password, name, # rollno, etc of a student # @param: #", "batch # } # print(data) # return JsonResponse(data) # else: # data =", "it on the page. @param: request - contains metadata about the requested page", "workbook normaltext - formatting variable for normal text sheet - xlsx sheet to", "name = request.POST.get('name') # roll = ExtraInfo.objects.get(id=request.POST.get('rollno')) # programme = request.POST.get('programme') # batch", "- gets the data of current user. # user_details - gets the details", "student convenor/coconvenor # @param: # request - contains metadata about the requested page", "- Get the object for the minimum credits from the database and the", "# rollno, etc of a student # @param: # request - contains metadata", "room no - hostel room no # \"\"\" current_user = get_object_or_404(User, username=request.user.username) #", "information like hall no, room no, # profile picture, about me etc of", "for c in courses: reg=course_registration( course_id = c, semester_id=sem_id, student_id=stud_data ) new_reg.append(reg) course_registration.objects.bulk_create(new_reg)", "course_id from database credits - credits from form.REQUEST optional - optional from form.REQUEST", "is to be updated. get_calendar_details = Get the object of the calendar instance", "render(request, 'ais/ais.html', context) @login_required def next_curriculum(request): \"\"\" This function is used to decide", "des in hDes: # if des.designation == s or des.designation == c: #", "= Designation.objects.get(name='Senator') # hDes = HoldsDesignation() # hDes.user = extraInfo.user # hDes.working =", "primary key of the student's record in the database table # @variables: #", "in databsae. User must be logged in and must be acadadmin @param: request", "in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','2'] } if request.method", "return HttpResponse('sucess') # else: # return HttpResponse('not uploaded') # return render(request, \"ais/ais.html\", {})", "- Branch from form request_programme - Programme from form request_sem - Semester from", "'tab_id' :['5','1'] } return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context) return", "webpage # \"\"\" # s = get_object_or_404(Designation, name=\"Convenor\") c = get_object_or_404(Designation, name=\"Co Convenor\")", "get the details of the required user. # \"\"\" # current_user = get_object_or_404(User,", "desig_id - checking the designation of the current user # acadadmin - deatils", "and month <= 12: return [1, 3, 5, 7] else: return [2, 4,", "return render(request, \"ais/ais.html\", context) @login_required def update_calendar(request): \"\"\" to update an entry to", "gets basic gata from database to send to template @param: request - contains", "- curriculum details form database ins - Inster data in database \"\"\" if", "course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) batch=batch+1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) context=", "str(user_details).split() # print(k) # final_user = k[2] # if (str(acadadmin) != str(final_user)): #", "add new curriculum in database It checkes the authentication of the user and", "the User object of the student # s - the student object of", "desc=\"\" pass c = Calendar( from_date=from_date, to_date=to_date, description=desc) c.save() HttpResponse(\"Calendar Added\") return render(request,", "Does Not Exist\") # return HttpResponse(\"Data Deleted Successfully\") def add_advanced_profile(request): # \"\"\" #", "= arr[0] # if Student.objects.get(id=stu): # s = Student.objects.get(id=stu) # s.father_name = \"\"", "databases to display it on the page. @param: request - contains metadata about", "the form required to add exam timetable Dean - the extraInfo objects that", "student # batch - the current batch of the student # programme -", "except Exception as e: batch=\"\" course=\"\" curr_key=\"\" obj=\"\" registered_courses = [] for i", "the requested page @variables: current_user - father's name of the student user_details -", "next_sem_courses - the data of next semester courses courses - all the courses", "Sheet def sem_for_generate_sheet(): \"\"\" This function generates semester grade sheet @variables: now -", "calendar = Calendar.objects.all() # this_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # next_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # courses", "- All the registration details appended into one data - Formated data for", "= \"PhD\") assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(acad_approval = False) assistant_approve_list", "courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) return", "\"ais/ais.html\", context) @login_required def delete_timetable(request): \"\"\" acad-admin can delete the outdated timetable from", "extraInfo.user # hDes.designation = s # hDes.save() # student = Student.objects.get(id=extraInfo) # data", "semester. @param: request - contains metadata about the requested page. @variables: acadTtForm -", "= course) except Exception as e: batch=\"\" course=\"\" curr_key=\"\" obj=\"\" registered_courses = []", "(str(p.course_id) == course): # print(p.course_id) # p.delete() # else: # return HttpResponse(\"Unable to", "procedures_context['context'], 'lists': procedures_context['lists'], 'date': procedures_context['date'], 'query_option1': procedures_context['query_option1'], 'query_option2': procedures_context['query_option2'], 'course_verification_date' : procedures_context['course_verification_date'], 'submitted_course_list'", "sem = sem_for_generate_sheet() now = datetime.datetime.now() year = int(now.year) if sem[0] == 2:", "course_type = Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'faculty_list': faculty_list,", "s = Student.objects.get(id=student) # s.father_name=father # s.mother_name=mother # s.hall_no = hall # s.room_no", "= ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Senator') # hDes = HoldsDesignation() # hDes.user =", "database table # @variables: # e - the extraInfo objects of the student", "in courses: reg=course_registration( course_id = c, semester_id=sem_id, student_id=stud_data ) new_reg.append(reg) course_registration.objects.bulk_create(new_reg) else: return", "metadata about the requested page # @variables: # s - the designation object", "flot.floated = True flot.save() new_curr_inst=[] for c,i in enumerate(request.POST.getlist(str(i)+'_fac')): inst = get_object_or_404(User, username", "= request.POST.get('rollno_convenor') # extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Convenor') # p =", "database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) context['tab_id'][0]='6' if request.method ==", "that contains where the student will become # convenor or coconvenor # hDes", "- contains metadata about the requested page # @variables: # current_user - gets", "context= { 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','1'] } acadTtForm = AcademicTimetableForm() if", "m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('registered') data.append(z) output = BytesIO() book", "credits=request.POST[\"credits\"] if request.POST['optional'] == \"on\": optional=True else: optional=False course_type=request.POST[\"course_type\"] except Exception as e:", "stu in obj: registered_students.add(stu.student_id) students = Student.objects.filter(batch_id = batch_id) for stu in students:", "course_type=request.POST[\"course_type_\"+str(i)] except Exception as e: programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\"", "to_date=\"\" desc=\"\" pass c = Calendar( from_date=from_date, to_date=to_date, description=desc) c.save() HttpResponse(\"Calendar Added\") return", "hDes.save() # student = Student.objects.get(id=extraInfo) # data = { # 'name': extraInfo.user.username, #", "def delete_exam_timetable(request): \"\"\" acad-admin can delete the outdated exam timetable. @param: request -", "HttpResponse(\"Worked\") def view_course(request): # if request.method == \"POST\": # programme=request.POST['programme'] # batch=request.POST['batch'] #", "contains metadata about the requested page. @variables: examTtForm - data of delete dictionary", "in courses: # if i.course_id not in choices: # i.acad_selection = False #", "the academic calender objects department - all the departments in the college attendance", "the type of courses \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') course_list = sem_for_generate_sheet() if(course_list[0]==1):", "Course, Exam_timetable, Grades, Curriculum_Instructor,Constants, Meeting, Student, Student_attendance, Timetable,Curriculum) from applications.programme_curriculum.models import (CourseSlot, Course", "timetable. @param: request - contains metadata about the requested page. @variables: data -", "!= str(final_user)): return True else: return False def get_context(request): \"\"\" This function gets", "= HoldsDesignation.objects.create( user=user, working=user, designation=desig, ) sem_id = Semester.objects.get(curriculum = batch.curriculum, semester_no =", "= batch).filter(programme= programme).filter(sem = sem) # print(curriculum_courses) # courses = Course.objects.all() # course_type", "else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def edit_curriculum(request): \"\"\"", "c = object to save new event to the academic calendar. \"\"\" if", "course - course ofwhich the grade is added \"\"\" # if user_check(request): #", "details of the user # sem - current semester of the student #", "request.POST['delete'] t = Exam_timetable.objects.get(exam_time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def add_calendar(request): \"\"\" to", "HoldsDesignation() # hDes.user = extraInfo.user # hDes.working = extraInfo.user # hDes.designation = s", ":\"2\" # } # return render(request,\"ais/ais.html\", context) # else: # return HttpResponseRedirect('/aims/') return", "= batch.curriculum, semester_no = sem) course_slots = CourseSlot.objects.all().filter(semester = sem_id) courses = []", "AcademicTimetableForm(request.POST, request.FILES) if acadTtForm.is_valid(): acadTtForm.save() return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\",", "import render_to_string from django.contrib.auth.decorators import login_required from applications.academic_procedures.models import MinimumCredits, Register, InitialRegistration, course_registration,", "courses - get courses from database courses_type - get course types from database", "information that the particular student is a convenor/coconvenor to be deleted # data", "not Student.objects.filter(id=roll).exists(): # db = Student() # st = ExtraInfo.objects.get(id=roll.id) # db.name =", "database credits - credits from form.REQUEST optional - optional from form.REQUEST course_type -", "requested page. # @variables: # choices - selected addtional courses by the academic", "- stores the next semester obj - All the registration details appended into", "float_course(request): \"\"\" to float courses for the next sem and store data in", "excel file sheet - sheet no in excel file roll_no - details of", "request_programme).filter(sem= request_sem) # context={ # 'courses' : courses, # 'course_type' : course_type, #", "academic calendar. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context= { 'academic_calendar'", "= HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st = 'attachment; filename = ' + batch.name +", "if i.course_id not in choices: # i.acad_selection = False # i.save() # return", "student required to check if the student is available # mother - mother's", "holding the senator designation # student - the student object of the new", "HttpResponseRedirect('/academic-procedures/') context = get_context(request) context['tab_id'][0]='6' if request.method == 'POST': try: request_batch = request.POST['batch']", "- details of student from file email - details of student from file", "user # acadadmin - deatils of the acad admin # s - the", "request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme'] except Exception as e: request_batch =", "contains metadata about the requested page @variables: dele - data being deleted from", "category - details of student from file phone_no - details of student from", "\"POST\": sem = request.POST.get('semester_no') batch_id=request.POST.get('batch_branch') batch = Batch.objects.filter(id = batch_id).first() obj = InitialRegistration.objects.filter(student_id__batch_id=batch_id,", "- temporary array to add data to variable data k -temporary array to", "sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',60) sheet.set_column('D:D',15) sheet.set_column('E:E',30) k = 4 num = 1 for", "data to formatted array/variable output - io Bytes object to write to xlsx", "student.programme, # 'branch': extraInfo.department.name # } # return HttpResponseRedirect('/aims/') # # return JsonResponse(data)", "# des.delete() # data = { # 'id': pk, # 'designation': designation, #", "== 2: sem = sem[year-int(request_batch)-1] else: sem = sem[year-int(request_batch)] sem+=1 curriculum = Curriculum.objects.select_related().filter(branch", "from_date - The starting date for the academic calendar event. to_date - The", "k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st = 'attachment; filename =", "if str(i)+\"_ccode\" in request.POST: if str(i)+\"_fac\" in request.POST: if request.POST[str(i)+\"_fac\"] == \"\" :", "address # cpi - student's cpi # hall - hall no of where", "def curriculum(request): # ''' def delete_advanced_profile(request): # \"\"\" # to delete the advance", "- designation object of senator # hDes - holdsDesignation object to store that", "= Curriculum.objects.select_related().filter(branch = request.POST['branch']).filter(batch = request.POST['batch']).filter(programme= request.POST['programme']) courses = Course.objects.all() course_type = Constants.COURSE_TYPE", "This function gets basic gata from database to send to template @param: request", "+ str(room) # student.save() # s = Student.objects.get(id=student) # s.father_name=father # s.mother_name=mother #", "= ExamTimetableForm() # acadTtForm = AcademicTimetableForm() # calendar = Calendar.objects.all() # this_sem_courses =", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if request.method == \"POST\": dele", "= Student.objects.get(id=stu) # s.father_name = \"\" # s.mother_name = \"\" # s.hall_no =", "'name': extraInfo.user.username, # 'rollno': extraInfo.id, # 'programme': student.programme, # 'branch': extraInfo.department.name # }", "# student - the student object with the given pk # hDes -", "append it to an array. # sem - Get the object for the", "the designation object that contains senator # student - the list students that", "database. # @param: # request - contains metadata about the requested page #", "'align': 'center', 'valign': 'vcenter'}) normaltext = book.add_format({'bold': False, 'font_size': 15, 'align': 'center', 'valign':", "Exception as e: examTtForm = \"\" acadTtForm = \"\" calendar = \"\" this_sem_courses", "sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',60) sheet.set_column('D:D',15) sheet.set_column('E:E',30) k = 4", "it or not # course - get the course details # \"\"\" #", "specialization=\"None\" if hall_no == None: hall_no=3 else: hall_no=int(hall_no) programme_name=request.POST['Programme'] batch_year=request.POST['Batch'] batch = Batch.objects.all().filter(name", "request.POST.get('hall') # room = request.POST.get('room') # cpi = request.POST.get('cpi') # student.address = str(hall)", "HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context= { 'academic_calendar' :calendar, 'tab_id' :['4','1'] } if request.method", "object from the database. # @param: # request - contains metadata about the", "batch=batch, branch=branch, sem=sem, course_code=course_code, course_id=course_id, credits=credits, optional=optional, course_type=course_type, ) new_curr.append(ins) else: break i+=1", "pass c = Calendar( from_date=from_date, to_date=to_date, description=desc) c.save() HttpResponse(\"Calendar Added\") return render(request, \"ais/ais.html\",", "father's name of the student # rollno - the rollno of the student", "- details of student from file first_name - details of student from file", "response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st = 'attachment; filename = ' + batch.name", "programme - the programme the student is enrolled in # ph - the", "user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1'] } if request.method == 'POST': try:", ":curriculum, 'tab_id' :['3','3'] } return render(request, \"ais/ais.html\", context) else: context= { 'tab_id' :['3','2']", "False # i.save() # return HttpResponseRedirect('/academic-procedures/') def min_cred(request): # \"\"\" # to set", "form.REQUEST optional - optional from form.REQUEST course_type - course_type from form.REQUEST ins -", "= HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Professor\")) f3 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Associate Professor\")) except Exception as", "else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def delete_curriculum(request): \"\"\"", "request.POST[str(i)+\"_fac\"] == \"\" : logging.warning(\"No faculty\") else: flot = Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated = True", "academic timetable objects calendar - all the academic calender objects context - the", "des.delete() # data = { # 'id': pk, # 'designation': designation, # }", "# sem_cred.append(0) # for i in range(1, 10): # sem = \"sem_\"+\"1\" #", "contains metadata about the requested page @variables: senates - the extraInfo objects that", "examTtForm = ExamTimetableForm() if request.method == 'POST' and request.FILES: examTtForm = ExamTimetableForm(request.POST, request.FILES)", "in request.POST: optional=True else: optional=False course_type=request.POST[\"course_type_\"+str(i)] except Exception as e: programme=\"\" batch=\"\" branch=\"\"", ": procedures_context['result_year'], 'batch_grade_data' : procedures_context['batch_grade_data'], 'batch_branch_data' : procedures_context['batch_branch_data'], 'assistant_flag' : assistant_flag, 'hod_flag' :", "designation of the current user # acadadmin - deatils of the acad admin", "c = Calendar( from_date=from_date, to_date=to_date, description=desc) c.save() HttpResponse(\"Calendar Added\") return render(request, \"ais/ais.html\", context)", "= Exam_timetable.objects.all() pgstudent = Student.objects.filter(programme = \"M.Tech\") | Student.objects.filter(programme = \"PhD\") assistant_list =", "= { # 'name': extraInfo.user.username, # 'rollno': extraInfo.id, # 'programme': student.programme, # 'branch':", "rollno = request.POST.getlist('Roll Number')[0] # # print(request.POST.get('rollno')) # extraInfo = ExtraInfo.objects.get(id=rollno) # s", "HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st = 'attachment; filename = ' + course.code + '.xlsx'", "= request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] prev_desc = request.POST.getlist('prev_desc')[0] from_date = from_date[0].split('-') from_date =", "desig_id - mother 's name of the student # acadadmin - student's address", "- the minute object received from id to be deleted # \"\"\" #", "xlsx sheet to be rendered titletext - formatting variable of title text dep", "from file department - details of student from file specialization - details of", "False)) assis_stat = Assistantship_status.objects.all() for obj in assis_stat: assistant_flag = obj.student_status hod_flag =", "# to add a new student senator # @param: # request - contains", "# else: # return HttpResponse(\"Data Does Not Exist\") # return HttpResponse(\"Data Deleted Successfully\")", "# s = Designation.objects.get(name='Senator') # hDes = HoldsDesignation() # hDes.user = extraInfo.user #", "extraInfo.id, # 'designation': hDes.designation.name, # } # return JsonResponse(data) # else: # data", "procedures_context['date'], 'query_option1': procedures_context['query_option1'], 'query_option2': procedures_context['query_option2'], 'course_verification_date' : procedures_context['course_verification_date'], 'submitted_course_list' : procedures_context['submitted_course_list'], 'result_year' :", "student's record in the database table # @variables: # e - the extraInfo", "Exam_timetable.objects.all() procedures_context = acad_proced_global_context() try: examTtForm = ExamTimetableForm() acadTtForm = AcademicTimetableForm() calendar =", "- semester from form.REQUEST course_code - course_code from form.REQUEST course_name - course-name from", "curr_semester_no=sem, ) desig = Designation.objects.get(name='student') hold_des = HoldsDesignation.objects.create( user=user, working=user, designation=desig, ) sem_id", "# \"\"\" s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') # if request.method", "a new student senator # @param: # request - contains metadata about the", "d[2] # sem = int(d[3]) # if request.method == \"POST\": # if(Grades.objects.filter(student_id=id, sem=sem)):", "the rollno of the student # batch - the current batch of the", ": procedures_context['batch_grade_data'], 'batch_branch_data' : procedures_context['batch_branch_data'], 'assistant_flag' : assistant_flag, 'hod_flag' : hod_flag, 'account_flag' :", "print (current_user) # acadadmin = temp.working # k = str(user_details).split() # print(k) #", "\"ais/ais.html\", context) @login_required def add_timetable(request): \"\"\" acad-admin can upload the time table(any type", "'center', 'valign': 'vcenter'}) normaltext = book.add_format({'bold': False, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'})", "# ###################################################### # # ##########Student basic profile################## # @csrf_exempt def add_basic_profile(request): # \"\"\"", "# current_user - father's name of the student # user_details - the rollno", "try: id=request.POST['id'] programme=request.POST['programme'] batch=request.POST['batch'] branch=request.POST['branch'] sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"] if request.POST['optional'] ==", "while True: if str(i)+\"_ccode\" in request.POST: if str(i)+\"_fac\" in request.POST: if request.POST[str(i)+\"_fac\"] ==", "context - the datas to be displayed in the webpage this_sem_course - tha", "grade - grade to be added in the student course - course ofwhich", "p in s: # if (str(p.course_id) == course): # print(p.course_id) # p.delete() #", "room # s.save() # return HttpResponseRedirect('/academic-procedures/') # return HttpResponseRedirect('/academic-procedures/') def add_optional(request): # \"\"\"", "courses: # if i.course_id not in choices: # i.acad_selection = False # i.save()", "generate Course List of Registered Students @param: request - contains metadata about the", "# \"\"\" # to add a new student senator # @param: # request", "return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # curr_id=request.POST['course'] # print(curr_id) # curr_course", "department=DepartmentInfo.objects.all().filter(name=dept).first() if specialization == \"\": specialization=\"None\" if hall_no == None: hall_no=3 else: hall_no=int(hall_no)", "ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') # result =", "1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('not registered') data.append(z) for i in registered_students: z", "form.save() # return HttpResponse('sucess') # else: # return HttpResponse('not uploaded') # return render(request,", "return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['2','1'] } if request.method == 'POST' and request.FILES:", "form.REQUEST now - current date from system year - current year batch -", "the user has searched for any particular curriculum if request_batch == \"\" and", "ExtraInfo, HoldsDesignation, DepartmentInfo) from .forms import AcademicTimetableForm, ExamTimetableForm, MinuteForm from .models import (Calendar,", "to template @param: request - contains metadata about the requested page @variables: acadTtForm", "request.POST['programme'] except Exception as e: request_batch = \"\" request_branch = \"\" request_programme =", "\"\"\" pass # if request.POST: # s = get_object_or_404(Designation, name=\"Senator\") # student =", "= HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st = 'attachment; filename = ' + course.code +", "(str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # st", "@variables: current_user - get user from request user_details - extract details of user", "in the webpage \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) return render(request,", "'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) return render(request,", "hDes = get_object_or_404( HoldsDesignation, user = student.user) # hDes.delete() # return HttpResponseRedirect('/aims/') #", "minute object to the database. # @param: # request - contains metadata about", "the data that contains where the student will become # convenor or coconvenor", "hod_flag = obj.hod_status account_flag = obj.account_status except Exception as e: examTtForm = \"\"", "{ # 'grades': grades, # 'tab_id' :\"2\" # } # return render(request,\"ais/ais.html\", context)", "designation object that contains convenor # c - the designation object that contains", "the primary key of the student's record in the database table # @variables:", "acadTtForm = AcademicTimetableForm() calendar = Calendar.objects.all() this_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses", "'assistant_list' : assistant_list, 'assistant_approve_list' : assistant_approve_list, 'assistant_list_length' : assistant_list_length, 'tab_id': ['1','1'], 'context': procedures_context['context'],", "i.course_id not in choices: # i.acad_selection = False # i.save() # return HttpResponseRedirect('/academic-procedures/')", "request.method == 'POST': try: request_batch = request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme']", "(Designation, ExtraInfo, HoldsDesignation, DepartmentInfo) from .forms import AcademicTimetableForm, ExamTimetableForm, MinuteForm from .models import", "branch=request.POST['branch'] # sem=request.POST['sem'] # curriculum_courses = Curriculum.objects.filter(branch = branch).filter(batch = batch).filter(programme= programme).filter(sem =", "Student class Convenor - the extraInfo objects that holds the designation as a", "as a senator extra - all the extraInfor objects exam_t - all the", "\"Convenor\": # hDes.designation = s # else: # hDes.designation = p # hDes.save()", "sem_id) courses = [] for course_slot in course_slots: courses += course_slot.courses.all() new_reg=[] for", "entry to the academic calendar to be uploaded @param: request - contains metadata", "pass faculty = list(chain(f1,f2,f3)) faculty_list = [] for i in faculty: faculty_list.append(i) return", "server. @param: request - contains metadata about the requested page. @variables: data -", "# # ###################################################### # # ##########Student basic profile################## # @csrf_exempt def add_basic_profile(request): #", "user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['2','1'] } if request.method == 'POST' and", "acad admin # father - father's name of the student # rollno -", "from django.contrib.auth.decorators import login_required from applications.academic_procedures.models import MinimumCredits, Register, InitialRegistration, course_registration, AssistantshipClaim,Assistantship_status from", "} # print(data) # return JsonResponse(data) # else: # data = {} #", "# # ##########Senate meeting Minute################## # @csrf_exempt def addMinute(request): # \"\"\" # to", "post request timetable - all timetable from database exam_t - all exam timetable", "as e: request_batch = \"\" request_branch = \"\" request_programme = \"\" request_sem =", "the student object of the new senator # data - data of the", "and request_programme==\"\" and request_sem==\"\": curriculum = None #Curriculum.objects.all() else: if int(request_sem) == 0:", "to the database. # @param: # request - contains metadata about the requested", "about the requested page @variables: senates - the extraInfo objects that holds the", "# course = Course.objects.all().filter(course_id=i).first() # course.acad_selection = True # course.save() # courses =", "- details of student from file programme - details of student from file", "a convenor/coconvenor to be deleted # data - data of the student to", "details of student from file sex - details of student from file title", "choices: # course = Course.objects.all().filter(course_id=i).first() # course.acad_selection = True # course.save() # courses", "HttpResponse(\"Data Deleted SuccessFully\") @login_required def verify_grade(request): \"\"\" It verify the grades of the", "dean student - the students as a senator extra - all the extraInfor", "- the data of next semester courses courses - all the courses in", "= sem_id) courses = [] for course_slot in course_slots: courses += course_slot.courses.all() new_reg=[]", "# @variables: # data - the id of the minute object to be", "object that contains senator # student - the list students that is a", "normal text sheet - xlsx sheet to be rendered titletext - formatting variable", "to_date] to_date = datetime.datetime(*to_date).date() except Exception as e: from_date=\"\" to_date=\"\" desc=\"\" pass c", "# if request.method == \"POST\": # data = request.POST['delete'] # t = Meeting.objects.get(id=data)", "return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": sem = request.POST.get('semester_no') batch_id=request.POST.get('batch_branch') batch = Batch.objects.filter(id", "' + course.code + '.xlsx' response['Content-Disposition'] = st return response @login_required def generate_preregistration_report(request):", "sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) batch=batch+1 curriculum = Curriculum.objects.all().select_related().filter(batch", "Constants.COURSE_TYPE # context= { # 'courses': courses, # 'course_type': course_type, # 'curriculum_course': curriculum_courses,", "HttpResponseRedirect('/aims/') # @csrf_exempt def deleteSenator(request, pk): # \"\"\" # to remove a senator", "# @param: # request - contains metadata about the requested page. # @variables:", "\"ais/ais.html\", context) @login_required def update_calendar(request): \"\"\" to update an entry to the academic", "the all meeting objects held in senator meetings minuteForm - the form to", "request.POST['batch'] course = Courses.objects.get(id = request.POST['course']) obj = course_registration.objects.all().filter(course_id = course) except Exception", "def curriculum(request): \"\"\" This function is used to see curriculum and edit entries", "[] for i in faculty: faculty_list.append(i) return faculty_list @login_required def float_course(request): \"\"\" to", "Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'faculty_list': faculty_list, 'tab_id' :['5','1']", "to generate preresgistration report after pre-registration @param: request - contains metadata about the", "# } courses = Course.objects.all() course_type = Constants.COURSE_TYPE html = render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj =", "faculty_list = get_faculty_list() courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses': courses,", "sheet no in excel file roll_no - details of student from file first_name", "m - counter for Sl. No (in formated data) z - temporary array", "request - contains metadata about the requested page @variables: batch - gets the", "final_user - final designation of request user \"\"\" try: current_user = get_object_or_404(User, username=request.user.username)", "batch_id) for stu in students: if stu not in registered_students: unregistered_students.add(stu) data =", "@login_required def float_course_submit(request): \"\"\" to float courses for the next sem and store", "holdsDesignation object to store that the particualr student is holding the senator designation", "'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) return render(request, 'ais/ais.html', context) @login_required def", "= programme_name, batch=batch_year, batch_id = batch, father_name = fathers_name, mother_name = mothers_name, cpi", "# current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper", "\"\" # s.mother_name = \"\" # s.hall_no = 1 # s.room_no = \"\"", "render(request, \"ais/ais.html\", context) @login_required def add_timetable(request): \"\"\" acad-admin can upload the time table(any", "- Description for the academic calendar event. prev_desc - Description for the previous", "must be acadadmin @param: request - contains metadata about the requested page. @variables:", "the requested page. @variables: from_date - The starting date for the academic calendar", "# data = request.POST['delete'] # t = Meeting.objects.get(id=data) # t.delete() return HttpResponseRedirect('/aims/') #", "import pisa from itertools import chain from django.contrib.auth.models import User from django.http import", "render(request, \"ais/ais.html\", {}) def deleteMinute(request): # \"\"\" # to delete an existing senate", "# 'name': extraInfo.user.username, # 'rollno': extraInfo.id, # 'programme': student.programme, # 'branch': extraInfo.department.name #", "profiles - gets the excel file having data excel - excel file sheet", "if str(i)+\"_fac\" in request.POST: if request.POST[str(i)+\"_fac\"] == \"\" : logging.warning(\"No faculty\") else: flot", "request.FILES: profiles=request.FILES['profiles'] excel = xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) for i in range(sheet.nrows): roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value)", "{ # 'name': extraInfo.user.username, # 'rollno_convenor': extraInfo.id, # 'designation': hDes.designation.name, # } #", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == 'POST': programme = request.POST['programme'] now =", "titletext - formatting variable of title text dep - temporary variables z -", "= datetime.datetime(*from_date).date() to_date = to_date[0].split('-') to_date = [int(i) for i in to_date] to_date", "the programme the student is enrolled in # ph - the phone number", "str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # st = request.POST['delete']", "advance information of the student # @param: # request - contains metadata about", "all timetable from database exam_t - all exam timetable from database \"\"\" if", "= AcademicTimetableForm(request.POST, request.FILES) if acadTtForm.is_valid(): acadTtForm.save() return render(request, \"ais/ais.html\", context) else: return render(request,", "context) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def edit_curriculum(request):", "num = 1 for i in ans: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] name", "= [int(i) for i in to_date] to_date = datetime.datetime(*to_date).date() get_calendar_details = Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description", "- create registeration object in registeration table \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context=", "timetable objects timetable - all the academic timetable objects calendar - all the", "user_check(request): \"\"\" This function is used to check the type of user. It", "in database einfo - new extrainfo object created in database stud_data - new", "list students that is a senator # hDes - the holdDesignation object that", "HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST' and request.FILES: # form = MinuteForm(request.POST, request.FILES)", "pass if (str(acadadmin) != str(final_user)): return True else: return False def get_context(request): \"\"\"", "Student.objects.filter(programme = \"M.Tech\") | Student.objects.filter(programme = \"PhD\") assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark =", "# hDes = get_object_or_404( HoldsDesignation, user = student.user) # hDes.delete() # return HttpResponseRedirect('/aims/')", "import login_required from applications.academic_procedures.models import MinimumCredits, Register, InitialRegistration, course_registration, AssistantshipClaim,Assistantship_status from applications.globals.models import", "desig_id - check for designation acadadmin - designation for Acadadmin final_user - final", "\"ais/ais.html\", context) def get_faculty_list(): \"\"\" to get faculty list from database @param: request", "\"ais/ais.html\") return render(request, \"ais/ais.html\") def delete_grade(request): # \"\"\" # It deletes the grade", "not in choices: # i.acad_selection = False # i.save() # return HttpResponseRedirect('/academic-procedures/') def", "request.method == 'POST' and request.FILES: examTtForm = ExamTimetableForm(request.POST, request.FILES) if examTtForm.is_valid(): examTtForm.save() return", "system year - current year batch - batch form form curriculum - curriculum", "# print(request.POST) # rollno=request.POST.get('roll') # print(rollno) # student = ExtraInfo.objects.get(id=rollno) # print(student.address) #", "the requested page @variables: current_user - get user from request user_details - extract", "entry in database It checkes the authentication of the user and also fetches", "request_sem - Semester from form curriculum - Get data about curriculum from database", "page @variables: request_batch - Batch from form request_branch - Branch from form request_programme", "import Workbook from xhtml2pdf import pisa from itertools import chain from django.contrib.auth.models import", "@param: request - contains metadata about the requested page @variables: current_user - get", "- contains metadata about the requested page @variables: request_batch - Batch from form", "of the students context - the datas to be displayed in the webpage", "details of student from file first_name - details of student from file last_name", "else: # data = {} # return JsonResponse(data) # else: # data =", "- the datas to be displayed in the webpage \"\"\" if user_check(request): return", "HttpResponse('sucess') # else: # return HttpResponse('not uploaded') # return render(request, \"ais/ais.html\", {}) def", "request t - Object of time table to be deleted \"\"\" if user_check(request):", "It checkes the authentication of the user and also fetches the available data", "page @variables: acadTtForm - the form to add academic calender examTtForm - the", "student from file fathers_name - details of student from file mothers_name - details", "objects timetable - all the academic timetable objects calendar - all the academic", "if request.method == \"POST\": # curr_id=request.POST['course'] # print(curr_id) # curr_course = Curriculum.objects.filter(curriculum_id=curr_id) #", "- gets the details of the required user. # desig_id - used to", "delete curriculum entry in database It checkes the authentication of the user and", "sem.credits = sem_cred[i+1] # sem.save() # return HttpResponse(\"Worked\") def view_course(request): # if request.method", "request_branch == \"\" and request_programme==\"\": curriculum = None #Curriculum.objects.all() else: sem = sem_for_generate_sheet()", "- hall no of where the student stays # room no - hostel", "the append it to an array. # sem - Get the object for", "request_batch = \"\" request_branch = \"\" request_programme = \"\" request_sem = \"\" #for", "course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"] if request.POST['optional'] == \"on\": optional=True else: optional=False course_type=request.POST[\"course_type\"] except Exception", "return HttpResponse(\"Unable to delete data\") return HttpResponse(\"Data Deleted SuccessFully\") @login_required def verify_grade(request): \"\"\"", "sem - Get the object for the minimum credits from the database and", "All the registration details appended into one data - Formated data for context", "[2, 4, 6, 8] @login_required def generatexlsheet(request): \"\"\" to generate Course List of", "= Semester.objects.get(curriculum = batch.curriculum, semester_no = sem) course_slots = CourseSlot.objects.all().filter(semester = sem_id) courses", "for i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional,", "response['Content-Disposition'] = st return response @login_required def generate_preregistration_report(request): \"\"\" to generate preresgistration report", "if request.method == 'POST' and request.FILES: examTtForm = ExamTimetableForm(request.POST, request.FILES) if examTtForm.is_valid(): examTtForm.save()", "hold_desig object of student currs - get curriculum details reg - create registeration", "the grades of the student @param: request - contains metadata about the requested", "stu = arr[0] # if Student.objects.get(id=stu): # s = Student.objects.get(id=stu) # s.father_name =", "csrf_exempt from django.template.loader import render_to_string from django.contrib.auth.decorators import login_required from applications.academic_procedures.models import MinimumCredits,", "HoldsDesignation, user = student.user) # hDes.delete() # return HttpResponseRedirect('/aims/') # else: # return", "account_flag = obj.account_status except Exception as e: examTtForm = \"\" acadTtForm = \"\"", "branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)] if \"optional_\"+str(i) in request.POST: optional=True else: optional=False", "get_object_or_404(Student, id=e) # data = { # 'rollno': pk, # } # s.delete()", "phone_no - details of student from file address - details of student from", "# print(data) # return JsonResponse(data) # else: # data = {} # return", "details of student from file email - details of student from file sex", "check if the student is available # mother - mother's name of the", "1 for i in ans: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] name = str(b)+\"", "datetime.datetime(*from_date).date() to_date = to_date[0].split('-') to_date = [int(i) for i in to_date] to_date =", "available # mother - mother's name of the student # add - student's", "sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',60) sheet.set_column('D:D',15) sheet.set_column('E:E',30) k", "= Course.objects.all() # for i in courses: # if i.course_id not in choices:", "acadadmin - student's address # final_user - details of the user # sem", "all the objects in the Student class Convenor - the extraInfo objects that", "# s - the designation object that contains convenor # c - the", "object that contains co convenor # student - the student object with the", "try: batch = request.POST['batch'] course = Courses.objects.get(id = request.POST['course']) obj = course_registration.objects.all().filter(course_id =", "from form request_branch - Branch from form request_programme - Programme from form request_sem", "formatting variable of title text dep - temporary variables z - temporary variables", "s - designation object of senator # hDes - holdsDesignation object to store", "new_curr_inst.append(ins) else: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=False, ) new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst) else: break i+=1 return", "- designation object of Convenor # p - designation object of Co Convenor", "user # user_details - the details of the current user # desig_id -", "meeting minute object from the database. # @param: # request - contains metadata", "import BytesIO from xlsxwriter.workbook import Workbook from xhtml2pdf import pisa from itertools import", "@param: request - contains metadata about the requested page @variables: senates - the", "available data from the databases to display it on the page. @param: request", "course = Course.objects.all().filter(course_id=i).first() # course.acad_selection = True # course.save() # courses = Course.objects.all()", "= [] # for des in hDes: # if des.designation == s or", "the registration details appended into one data - Formated data for context m", "about the requested page # @variables: # current_user - the username of the", "extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Senator') # hDes = HoldsDesignation() # hDes.user", "a coconvenor meetings - the all meeting objects held in senator meetings minuteForm", "specialization - details of student from file hall_no - details of student from", "m = 1 for i in unregistered_students: z = [] z.append(m) m +=", "to add a senate meeting minutes acadTtForm - the form to add academic", "= Calendar.objects.all() this_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses = Course.objects.all() courses_list =", "title='Mr.' dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13 ).value", "if specialization == \"\": specialization=\"None\" if hall_no == None: hall_no=3 else: hall_no=int(hall_no) programme_name=request.POST['Programme']", ": account_flag } return context @login_required def homepage(request): \"\"\" This function is used", "# @csrf_exempt def addMinute(request): # \"\"\" # to add a new senate meeting", "request_sem - Semester from form \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id'", "request.method == \"POST\": # programme=request.POST['programme'] # batch=request.POST['batch'] # branch=request.POST['branch'] # sem=request.POST['sem'] # curriculum_courses", "# s.save() # return HttpResponseRedirect('/academic-procedures/') # return HttpResponseRedirect('/academic-procedures/') def add_optional(request): # \"\"\" #", "metadata about the requested page @variables: current_user - get user from request user_details", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if request.method == 'POST': try:", "e: examTtForm = \"\" acadTtForm = \"\" calendar = \"\" this_sem_courses = \"\"", "batch.name + batch.discipline.acronym + str(batch.year) + '-preresgistration.xlsx' response['Content-Disposition'] = st return response @login_required", "the additional courses # @param: # request - contains metadata about the requested", "form curriculum - Get data about curriculum from database courses - get courses", "Meeting.objects.get(id=data) # t.delete() return HttpResponseRedirect('/aims/') # # ###################################################### # # ##########Student basic profile##################", "# student.save() # s = Student.objects.get(id=student) # s.father_name=father # s.mother_name=mother # s.hall_no =", "the position # @param: # request - contains metadata about the requested page", "student # s - the student object of the student # \"\"\" e", "designation for Acadadmin final_user - final designation of request user \"\"\" try: current_user", "except Exception as e: acadadmin=\"\" final_user=\"\" pass if (str(acadadmin) != str(final_user)): return True", "pass # print(request.POST) # choices = request.POST.getlist('choice') # for i in choices: #", "== \"POST\": # st = request.POST['delete'] # arr = st.split(\"-\") # stu =", "k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department) ans.append(k) ans.sort() output = BytesIO() book = Workbook(output,{'in_memory':True}) title", "object that stores the # information that the particular student is a senator", "- sheet no in excel file roll_no - details of student from file", "HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Assistant Professor\")) f2 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Professor\")) f3 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name =", "# user_details - to get the details of the required user. # \"\"\"", "student # @param: # request - contains metadata about the requested page #", "range(sheet.nrows): roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value) if sex == 'F': title='Ms.' else: title='Mr.'", "Exam_timetable.objects.get(exam_time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def add_calendar(request): \"\"\" to add an entry", "# It adds the basic profile information like username,password, name, # rollno, etc", "@login_required def user_check(request): \"\"\" This function is used to check the type of", "user_details - the details of the current user # desig_id - checking the", "return HttpResponse(\"Data Does Not Exist\") # return HttpResponse(\"Data Deleted Successfully\") def add_advanced_profile(request): #", "Batch.objects.all().filter(name = programme_name, discipline__acronym = dept, year = batch_year).first() user = User.objects.create_user( username=roll_no,", "- get stdents data from database ans - Formatted Array to be converted", "get designation object of student holds_desig - get hold_desig object of student currs", "data from the databases to display it on the page. @param: request -", "if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": #", "# 'tab_id' :['3','1'] # } courses = Course.objects.all() course_type = Constants.COURSE_TYPE html =", "in registered_students: z = [] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name)", "i+=1 return render(request, \"ais/ais.html\", context) # # ---------------------senator------------------ # @csrf_exempt def senator(request): #", "add_advanced_profile(request): # \"\"\" # It adds the advance profile information like hall no,", "user. # user_details - gets the details of the required user. # desig_id", "#################################### # # curriculum # # #################################### @login_required def curriculum(request): \"\"\" This function", "delete data\") return HttpResponse(\"Data Deleted SuccessFully\") @login_required def verify_grade(request): \"\"\" It verify the", "the advance profile information like hall no, room no, # profile picture, about", "courses_type - get course types from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context", "metadata about the requested page # @variables: # current_user - gets the data", "- branch from form.REQUEST sem - semester from form.REQUEST course_code - course_code from", "the grade of the student # @param: # request - contains metadata about", "# add - student's address # cpi - student's cpi # hall -", ":['3','1'] } return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context) return render(request,", "grades = Grades.objects.filter(curriculum_id=curr_course) # context= { # 'grades': grades, # 'tab_id' :\"2\" #", "account_flag } return context @login_required def homepage(request): \"\"\" This function is used to", "deatils of the acad admin # s - the student object from the", "of student from file hall_no - details of student from file programme -", "=True).filter(hod_approval = True) assistant_list_length = len(assistant_list.filter(acad_approval = False)) assis_stat = Assistantship_status.objects.all() for obj", "the student to become the convenor/coconvenor # extraInfo - extraInfo object of the", "the previous event which is to be updated. get_calendar_details = Get the object", "- contains metadata about the requested page @variables: dele - data being deleted", "\"\"\" This function is used to see curriculum and edit entries in a", "c==0: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=True, ) new_curr_inst.append(ins) else: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=False, )", "table to be deleted \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\":", "- list of faculty \"\"\" try: f1 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Assistant Professor\")) f2", "i+=1 Curriculum.objects.bulk_create(new_curr) curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme) courses = Course.objects.all()", "to be added in the student course - course ofwhich the grade is", "desc - Description for the academic calendar event. prev_desc - Description for the", "- the extraInfo objects that holds the designation as a convenor CoConvenor -", "# s.father_name=father # s.mother_name=mother # s.hall_no = hall # s.room_no = room #", "verify_grade(request): \"\"\" It verify the grades of the student @param: request - contains", "student from file email - details of student from file sex - details", "get hold_desig object of student currs - get curriculum details reg - create", "# user - the User object of the student # s - the", "metadata about the requested page # @variables: # current_user - the username of", "designation = [] # for des in hDes: # if des.designation == s", "pk - the primary key of that particular student field # @variables: #", "with that rollno # s - designation object of senator # hDes -", "- extraInfo object of the student with that rollno # s - designation", "# acadTtForm = AcademicTimetableForm() # calendar = Calendar.objects.all() # this_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) #", "# extraInfo - extraInfo object of the student with that rollno # s", "return faculty_list @login_required def float_course(request): \"\"\" to float courses for the next sem", "try: from_date = request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] from_date = from_date[0].split('-')", "course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme entry.batch=batch entry.branch=branch entry.sem=sem entry.course_code=course_code", "'course_type': course_type, # 'curriculum_course': curriculum_courses, # } # return render(request, \"ais/ais.html\", context) #", "'timetable': timetable, 'academic_calendar': calendar, 'next_sem_course': next_sem_courses, 'this_sem_course': this_sem_courses, 'curriculum': curriculum, 'pgstudent' : pgstudent,", "like username,password, name, # rollno, etc of a student # @param: # request", "not # course - get the course details # \"\"\" # current_user =", "'curriculum': curriculum, 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) return render(request, 'ais/ais.html', context)", "user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": sem = request.POST.get('semester_no') batch_id=request.POST.get('batch_branch') batch =", "# i.acad_selection = False # i.save() # return HttpResponseRedirect('/academic-procedures/') def min_cred(request): # \"\"\"", "as a coconvenor meetings - the all meeting objects held in senator meetings", "delete dictionary in post request t - Object of time table to be", "curriculum = Curriculum.objects.select_related().filter(branch = request.POST['branch']).filter(batch = request.POST['batch']).filter(programme= request.POST['programme']) courses = Course.objects.all() course_type =", "\"\" this_sem_courses = \"\" next_sem_courses = \"\" courses = \"\" course_type = \"\"", "login_required from applications.academic_procedures.models import MinimumCredits, Register, InitialRegistration, course_registration, AssistantshipClaim,Assistantship_status from applications.globals.models import (Designation,", "formatting variable of title the workbook subtitle - formatting variable of subtitle the", "get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp", "# @csrf_exempt def deleteConvenor(request, pk): # \"\"\" # to remove a convenor/coconvenor from", "page # @variables: # s - the designation object that contains senator #", "'application/vnd.ms-excel') st = 'attachment; filename = ' + course.code + '.xlsx' response['Content-Disposition'] =", "year = int(now.year) batch = year-1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme)", "store that the particualr student is # holding the convenor/coconvenor designation # student", "'courses': courses, # 'course_type': course_type, # 'curriculum_course': curriculum_courses, # } # return render(request,", "def deleteMinute(request): # \"\"\" # to delete an existing senate meeting minute object", "forms and the append it to an array. # sem - Get the", "course_name - course-name from form.REQUEST course_id - course_id from database credits - credits", "# desig_id - to check the designation of the user. # user_details -", "s.delete() # e.delete() # u.delete() # return JsonResponse(data)# ######################################################### # ''' # #", "# data - tag whether to delete it or not # course -", "to check the type of user. It checkes the authentication of the user.", "{ 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','1'] } acadTtForm = AcademicTimetableForm() if request.method", "be displayed in the webpage # \"\"\" s = Designation.objects.get(name='Convenor') # p =", "metadata about the requested page. @variables: acadTtForm - data of delete dictionary in", "enrolled in # ph - the phone number of the student # \"\"\"", "BytesIO() book = Workbook(output,{'in_memory':True}) title = book.add_format({'bold': True, 'font_size': 22, 'align': 'center', 'valign':", "= \"\" pass context = { 'acadTtForm': acadTtForm, 'examTtForm': examTtForm, 'courses': courses, 'courses_list':", "unregistered_students = set() for stu in obj: registered_students.add(stu.student_id) students = Student.objects.filter(batch_id = batch_id)", "generate preresgistration report after pre-registration @param: request - contains metadata about the requested", "user = student.user) # hDes.delete() # return HttpResponseRedirect('/aims/') # else: # return HttpResponseRedirect('/aims/')#", "= batch_id) for stu in students: if stu not in registered_students: unregistered_students.add(stu) data", "sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',60) sheet.set_column('D:D',15) sheet.set_column('E:E',30) k = 4 num = 1 for i", "= ExamTimetableForm() acadTtForm = AcademicTimetableForm() calendar = Calendar.objects.all() this_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses =", "request.method == \"POST\": name = request.POST.get('name') # roll = ExtraInfo.objects.get(id=request.POST.get('rollno')) # programme =", "\"\"\" This function is used to set up the homepage of the application.", "request.method == 'POST': programme = request.POST['programme'] now = datetime.datetime.now() year = int(now.year) batch", "return response @login_required def add_new_profile (request): \"\"\" To add details of new upcoming", "of the student # programme - the programme the student is enrolled in", "sem_cred.append(0) # for i in range(1, 10): # sem = \"sem_\"+\"1\" # sem_cred.append(request.POST.getlist(sem)[0])", "the form to add academic calender examTtForm - the form required to add", "year batch - batch form form curriculum - curriculum details form database ins", "# return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST' and request.FILES: # form =", "= get_object_or_404(Designation, name=\"Convenor\") c = get_object_or_404(Designation, name=\"Co Convenor\") # student = get_object_or_404(ExtraInfo, id=pk)", "student # add - student's address # cpi - student's cpi # hall", "\"\"\" To add details of new upcoming students in the database.User must be", "''' # # view to add attendance data to database # def curriculum(request):", "additional courses # @param: # request - contains metadata about the requested page.", "sheet.set_column('B:B',20) sheet.set_column('C:C',60) sheet.set_column('D:D',15) sheet.set_column('E:E',30) k = 4 num = 1 for i in", "No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',60) sheet.set_column('D:D',15) sheet.set_column('E:E',30) k = 4 num", "= True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(acad_approval = False) assistant_approve_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark =", "name.upper() # db.id = roll # db.batch = batch # db.programme = programme", "[1, 3, 5, 7] else: return [2, 4, 6, 8] @login_required def generatexlsheet(request):", "data - data of the student to be hidden in the webpage #", "to variable data k -temporary array to add data to formatted array/variable output", "= Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # courses = Course.objects.all() # course_type = Constants.COURSE_TYPE # timetable =", "if request.method == 'POST': i=0 new_curr=[] while True: if \"semester_\"+str(i) in request.POST: try:", "# # ##########Student basic profile################## # @csrf_exempt def add_basic_profile(request): # \"\"\" # It", "\"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) #Generate Attendance Sheet def sem_for_generate_sheet(): \"\"\" This", "\"POST\": data = request.POST['delete'] t = Exam_timetable.objects.get(exam_time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def", "curriculum, 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context)", "from_date = [int(i) for i in from_date] from_date = datetime.datetime(*from_date).date() to_date = to_date[0].split('-')", "contains metadata about the requested page. @variables: f1,f2,f3 - temporary varibles faculty -", "calender examTtForm - the form required to add exam timetable Dean - the", "HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": data = request.POST['delete'] t = Timetable.objects.get(time_table=data) t.delete() return", "course_type = Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','2']", "user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == 'POST': programme = request.POST['programme'] now = datetime.datetime.now()", "students = Student.objects.filter(batch_id = batch_id) for stu in students: if stu not in", "str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST' and request.FILES: # form", "final_user = k[2] # if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # print(request.POST['delete'])", "in registered_students: unregistered_students.add(stu) data = [] m = 1 for i in unregistered_students:", "extrainfo object created in database stud_data - new student object created in database", "student required to check if the student is available desig_id - mother's name", "\"\" timetable = \"\" exam_t = \"\" pass context = { 'acadTtForm': acadTtForm,", "request - contains metadata about the requested page # pk - the primary", "contains co convenor # student - the student object with the given pk", "'tab_id' :['3','1'] } if request.method == 'POST': try: id=request.POST['id'] programme=request.POST['programme'] batch=request.POST['batch'] branch=request.POST['branch'] sem=request.POST[\"sem\"]", "user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if request.method == 'POST': try: id=request.POST['id']", "- contains metadata about the requested page # @variables: # name - the", "sem = sem[year-int(request_batch)] sem+=1 curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code') faculty_list", "HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if request.method == 'POST': try: id=request.POST['id'] programme=request.POST['programme'] batch=request.POST['batch']", "# return HttpResponseRedirect('/aims/') # @csrf_exempt def deleteSenator(request, pk): # \"\"\" # to remove", "pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme entry.batch=batch entry.branch=branch entry.sem=sem entry.course_code=course_code entry.course_id=course_id entry.credits=credits entry.optional=optional entry.course_type=course_type entry.save() curriculum", "object of the new convenor/coconvenor # data - data of the student to", "credits from the database and the update it. # \"\"\" if request.method==\"POST\": sem_cred", "[int(i) for i in from_date] from_date = datetime.datetime(*from_date).date() to_date = to_date[0].split('-') to_date =", "= Designation.objects.all().filter(name='Upper Division Clerk') # temp = HoldsDesignation.objects.all().filter(designation = desig_id).first() # print (temp)", "of user from database desig_id - check for designation acadadmin - designation for", "the primary key of that particular student field # @variables: # s -", "== s or des.designation == c: # designation = des.designation.name # des.delete() #", "try: programme=request.POST['AddProgramme'] batch=request.POST['AddBatch'] branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)] if \"optional_\"+str(i) in request.POST:", "the convenor/coconvenor # extraInfo - extraInfo object of the student with that rollno", "designation acadadmin - designation for Acadadmin final_user - final designation of request user", "- father's name of the student user_details - the rollno of the student", "request_programme = request.POST['programme'] request_sem = request.POST['sem'] except Exception as e: request_batch = \"\"", "new batch. It checkes the authentication of the user and also fetches the", "course_slots: courses += course_slot.courses.all() new_reg=[] for c in courses: reg=course_registration( course_id = c,", "@variables: # s - the designation object that contains senator # student -", ":['3','1'] } if request.method == 'POST': try: id=request.POST['id'] programme=request.POST['programme'] batch=request.POST['batch'] branch=request.POST['branch'] sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"]", "data to variable data k -temporary array to add data to formatted array/variable", "month = int(now.month) if month >= 7 and month <= 12: return [1,", "print(request.POST['delete']) # data = request.POST['delete'] # d = data.split(\"-\") # id = d[0]", "s = Student.objects.get(id=stu) # s.father_name = \"\" # s.mother_name = \"\" # s.hall_no", "key of the student's record in the database table # @variables: # e", "file hall_no - details of student from file programme - details of student", "logged in and must be acadadmin @param: request - contains metadata about the", "acadadmin - deatils of the acad admin # father - father's name of", "if(course_list[0]==1): course_list_2 = [2, 4, 6, 8] else: course_list_2 = [1, 3, 5,", "Courses.objects.all() course_type = Constants.COURSE_TYPE timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() pgstudent = Student.objects.filter(programme", "details which is selected by the academic admin. # \"\"\" if request.method ==", "calendar to be uploaded @param: request - contains metadata about the requested page.", "details of new upcoming students in the database.User must be logged in and", "update_calendar(request): \"\"\" to update an entry to the academic calendar to be updated.", "get current semester from current time now - get current time year -", "calendar - all the academic calender objects context - the datas to be", "= 1 for i in ans: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] name =", "= s # else: # hDes.designation = p # hDes.save() # data =", "# 'rollno': roll.id, # 'programme': programme, # 'phoneno': ph, # 'batch': batch #", "# batch=request.POST['batch'] # branch=request.POST['branch'] # sem=request.POST['sem'] # curriculum_courses = Curriculum.objects.filter(branch = branch).filter(batch =", "'id': pk, # 'designation': designation, # } # return JsonResponse(data)# ###################################################### # #", "{ 'academic_calendar' :calendar, 'tab_id' :['4','1'] } if request.method == \"POST\": try: from_date =", "a senate meeting minutes acadTtForm - the form to add academic calender examTtForm", "# current_user - details of the current user. # desig_id - to check", "profile information like username,password, name, # rollno, etc of a student # @param:", "of the student with that rollno # s - designation object of Convenor", "book.add_worksheet() title_text = ((str(course.name)+\" : \"+str(str(batch)))) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll", "# s - the designation object that contains senator # student - the", "# if i.course_id not in choices: # i.acad_selection = False # i.save() #", "rollno = request.POST.get('rollno_convenor') # extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Convenor') # p", "requested page. @variables: data - data of delete dictionary in post request t", "# return render(request,\"ais/ais.html\", context) # else: # return HttpResponseRedirect('/aims/') return HttpResponseRedirect('/aims/') def confirm_grades(request):", "= request.POST.get('semester_no') batch_id=request.POST.get('batch_branch') batch = Batch.objects.filter(id = batch_id).first() obj = InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem) registered_students", "\"\" calendar = \"\" this_sem_courses = \"\" next_sem_courses = \"\" courses = \"\"", "= {} # return JsonResponse(data) # @csrf_exempt def deleteConvenor(request, pk): # \"\"\" #", "# user = get_object_or_404(User, username = e.user.username) # s = get_object_or_404(Student, id=e) #", "function is used to decide curriculum for new batch. It checkes the authentication", "ExtraInfo.objects.create( id=roll_no, user=user, title=title, sex=sex, date_of_birth=dob, address=address, phone_no=phone_no, user_type='student', department=department, ) sem=1 stud_data", "user_check(request): return HttpResponseRedirect('/academic-procedures/') try: batch = request.POST['batch'] course = Courses.objects.get(id = request.POST['course']) obj", "e: from_date=\"\" to_date=\"\" desc=\"\" return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) #Generate", "HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1'] } if request.method == \"POST\": i=1 while True:", "import (Calendar, Course, Exam_timetable, Grades, Curriculum_Instructor,Constants, Meeting, Student, Student_attendance, Timetable,Curriculum) from applications.programme_curriculum.models import", "get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0]) # hDes = get_object_or_404( HoldsDesignation, user = student.user) # hDes.delete() #", "# for i in range(1, 10): # sem = \"sem_\"+\"1\" # sem_cred.append(request.POST.getlist(sem)[0]) #", "\") + str(batch.year)) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle)", "to store that the particualr student is # holding the convenor/coconvenor designation #", "#Curriculum.objects.all() else: sem = sem_for_generate_sheet() now = datetime.datetime.now() year = int(now.year) if sem[0]", "from django.shortcuts import get_object_or_404, render from django.template.loader import get_template from django.views.decorators.csrf import csrf_exempt", "- Inster data in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method ==", "Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() #print (temp) # print (current_user) # acadadmin", "= request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme'] request_sem = request.POST['sem'] except Exception", "exam_t, 'timetable': timetable, 'academic_calendar': calendar, 'next_sem_course': next_sem_courses, 'this_sem_course': this_sem_courses, 'curriculum': curriculum, 'pgstudent' :", "= request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme'] except Exception as e: request_batch", "return HttpResponseRedirect('/academic-procedures/') course_list = sem_for_generate_sheet() if(course_list[0]==1): course_list_2 = [2, 4, 6, 8] else:", "} if request.method == 'POST': i=0 new_curr=[] while True: if \"semester_\"+str(i) in request.POST:", "ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() #", "about the requested page @variables: sem - get current semester from current time", "curriculum entry in database It checkes the authentication of the user and also", "Deleted SuccessFully\") @login_required def verify_grade(request): \"\"\" It verify the grades of the student", "required to add exam timetable Dean - the extraInfo objects that holds the", "to_date[0].split('-') to_date = [int(i) for i in to_date] to_date = datetime.datetime(*to_date).date() except Exception", "HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['2','1'] } if request.method == 'POST' and request.FILES: profiles=request.FILES['profiles']", "import HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import get_object_or_404, render from django.template.loader import get_template", "title_text = (\"Pre-registeration : \"+ batch.name + str(\" \") + batch.discipline.acronym + str(\"", "- contains metadata about the requested page @variables: batch - gets the batch", "an entry to the academic calendar to be updated. @param: request - contains", "programme from form.REQUEST now - current date from system year - current year", "student - the list students that is a senator # hDes - the", "student from file category - details of student from file phone_no - details", "course_type - list the type of courses \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') course_list", "field # @variables: # s - the designation object that contains convenor #", "registeration table \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['2','1'] } if", "= set() for stu in obj: registered_students.add(stu.student_id) students = Student.objects.filter(batch_id = batch_id) for", "Calendar( from_date=from_date, to_date=to_date, description=desc) c.save() HttpResponse(\"Calendar Added\") return render(request, \"ais/ais.html\", context) @login_required def", "course_registration, AssistantshipClaim,Assistantship_status from applications.globals.models import (Designation, ExtraInfo, HoldsDesignation, DepartmentInfo) from .forms import AcademicTimetableForm,", "\"M.Tech\") | Student.objects.filter(programme = \"PhD\") assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(acad_approval", "request_sem = request.POST['sem'] except Exception as e: request_batch = \"\" request_branch = \"\"", "of the student to become the convenor/coconvenor # extraInfo - extraInfo object of", "all the academic timetable objects calendar - all the academic calender objects department", "= Timetable.objects.all() exam_t = Exam_timetable.objects.all() pgstudent = Student.objects.filter(programme = \"M.Tech\") | Student.objects.filter(programme =", "\"\"\" to float courses for the next sem and store data in databsae.", "id of the minute object to be deleted # t - the minute", "try: f1 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Assistant Professor\")) f2 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Professor\")) f3", "inst = ExtraInfo.objects.select_related('user','department').get(user=inst) if c==0: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=True, ) new_curr_inst.append(ins) else: ins=Curriculum_Instructor(", "an array. # sem - Get the object for the minimum credits from", ": hod_flag, 'account_flag' : account_flag } return context @login_required def homepage(request): \"\"\" This", "- course_code from form.REQUEST course_name - course-name from form.REQUEST course_id - course_id from", "# s - designation object of senator # hDes - holdsDesignation object to", "contains senator # student - the list students that is a senator #", "database courses_type - get course types from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "Convenor\") # student = get_object_or_404(ExtraInfo, id=pk) # hDes = HoldsDesignation.objects.filter(user = student.user) #", "get_context(request): \"\"\" This function gets basic gata from database to send to template", "the list students that is a senator # hDes - the holdDesignation object", "faculty_list, 'tab_id' :['5','1'] } return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context)", "# db.name = name.upper() # db.id = roll # db.batch = batch #", "and request.FILES: profiles=request.FILES['profiles'] excel = xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) for i in range(sheet.nrows): roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value)", "current user # desig_id - checking the designation of the current user #", "'-preresgistration.xlsx' response['Content-Disposition'] = st return response @login_required def add_new_profile (request): \"\"\" To add", "user_details - the rollno of the student required to check if the student", "# course.acad_selection = True # course.save() # courses = Course.objects.all() # for i", "list of faculty \"\"\" try: f1 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Assistant Professor\")) f2 =", "= sem_cred[i+1] # sem.save() # return HttpResponse(\"Worked\") def view_course(request): # if request.method ==", "that holds the designation as a coconvenor meetings - the all meeting objects", "if request.method==\"POST\": sem_cred = [] # sem_cred.append(0) # for i in range(1, 10):", "course_registration.objects.bulk_create(new_reg) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) def get_faculty_list(): \"\"\"", "sem=1 stud_data = Student.objects.create( id=einfo, programme = programme_name, batch=batch_year, batch_id = batch, father_name", "try: from_date = request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] prev_desc = request.POST.getlist('prev_desc')[0]", "page @variables: current_user - father's name of the student user_details - the rollno", "datas to be displayed in the webpage \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context", "\"\" exam_t = \"\" pass context = { 'acadTtForm': acadTtForm, 'examTtForm': examTtForm, 'courses':", "# context={ # 'courses' : courses, # 'course_type' : course_type, # 'curriculum' :", "batch_year=request.POST['Batch'] batch = Batch.objects.all().filter(name = programme_name, discipline__acronym = dept, year = batch_year).first() user", "= { # 'rollno': pk, # } # s.delete() # e.delete() # u.delete()", "requested rollno # \"\"\" current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() #", "Bytes object to write to xlsx file book - workbook of xlsx file", "\"\"\" if request.method == \"POST\": name = request.POST.get('name') # roll = ExtraInfo.objects.get(id=request.POST.get('rollno')) #", "== '1': new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code,", "send to template @param: request - contains metadata about the requested page @variables:", "new event to the academic calendar. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar =", "# 'grades': grades, # 'tab_id' :\"2\" # } # return render(request,\"ais/ais.html\", context) #", "- list the type of courses \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') course_list =", "@variables: examTtForm - data of delete dictionary in post request timetable - all", "= Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem= request_sem) # context={ # 'courses' :", "to add a new student convenor/coconvenor # @param: # request - contains metadata", "courses, 'courses_list': courses_list, 'course_type': course_type, 'exam': exam_t, 'timetable': timetable, 'academic_calendar': calendar, 'next_sem_course': next_sem_courses,", "database courses - get courses from database courses_type - get course types from", "form sem - stores the next semester obj - All the registration details", "# curr_id=request.POST['course'] # print(curr_id) # curr_course = Curriculum.objects.filter(curriculum_id=curr_id) # grades = Grades.objects.filter(curriculum_id=curr_course) #", "metadata about the requested page @variables: acadTtForm - the form to add academic", "if acadTtForm.is_valid(): acadTtForm.save() return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context) return", "context['tab_id'][0]='6' if request.method == 'POST': try: request_batch = request.POST['batch'] request_branch = request.POST['branch'] request_programme", "for final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": sem", "data of the student to be displayed in teh webpage # \"\"\" #", "[] m = 1 for i in unregistered_students: z = [] z.append(m) m", "- data is stored in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id'", "request_batch = \"\" request_branch = \"\" request_programme = \"\" if request_batch == \"\"", "request user \"\"\" try: current_user = get_object_or_404(User, username=request.user.username) user_details = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id =", "# this_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # next_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # courses = Course.objects.all() #", "= 0, category = category, hall_no = hall_no, specialization = specialization, curr_semester_no=sem, )", "json import os import xlrd import logging from io import BytesIO from xlsxwriter.workbook", "hall no of where the student stays # room no - hostel room", "# student - the student object of the new convenor/coconvenor # data -", "request.method == \"POST\": # print(request.POST) # rollno=request.POST.get('roll') # print(rollno) # student = ExtraInfo.objects.get(id=rollno)", "request.method == \"POST\": # data = request.POST['delete'] # t = Meeting.objects.get(id=data) # t.delete()", "database It checkes the authentication of the user and also fetches the available", "about the requested page. @variables: examTtForm - data of delete dictionary in post", "if request.method == \"POST\": pass # print(request.POST) # choices = request.POST.getlist('choice') # for", "Object of time table to be deleted \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if", "table # @variables: # e - the extraInfo objects of the student #", "i.acad_selection = False # i.save() # return HttpResponseRedirect('/academic-procedures/') def min_cred(request): # \"\"\" #", "entry.optional=optional entry.course_type=course_type entry.save() curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme) courses =", "8] @login_required def generatexlsheet(request): \"\"\" to generate Course List of Registered Students @param:", "else: # return HttpResponse('not uploaded') # return render(request, \"ais/ais.html\", {}) def deleteMinute(request): #", "be rendered titletext - formatting variable of title text dep - temporary variables", "page @variables: batch - gets the batch course - gets the course curr_key", "hDes.designation.name, # } # return JsonResponse(data) # else: # data = {} #", "sheet.set_column('C:C',60) sheet.set_column('D:D',15) sheet.set_column('E:E',30) k = 4 num = 1 for i in ans:", "departments in the college attendance - all the attendance objects of the students", "contains metadata about the requested page # @variables: # name - the name", "request.method == 'POST' and request.FILES: profiles=request.FILES['profiles'] excel = xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) for i in", "+ batch.discipline.acronym + str(batch.year) + '-preresgistration.xlsx' response['Content-Disposition'] = st return response @login_required def", "datas to be displayed in the webpage this_sem_course - tha data of thsi", "c,i in enumerate(request.POST.getlist(str(i)+'_fac')): inst = get_object_or_404(User, username = i) inst = ExtraInfo.objects.select_related('user','department').get(user=inst) if", "created in database desig - get designation object of student holds_desig - get", "course = Courses.objects.get(id = request.POST['course']) obj = course_registration.objects.all().filter(course_id = course) except Exception as", "sem - semester from form.REQUEST course_code - course_code from form.REQUEST course_name - course-name", "the requested page # pk - the primary key of the student's record", "from file last_name - details of student from file email - details of", "in obj: if i.student_id.batch_id.year == int(batch): registered_courses.append(i) ans = [] for i in", "semester courses courses - all the courses in curriculum course_type - list the", "to add exam timetable Dean - the extraInfo objects that holds the designation", "description=desc) c.save() HttpResponse(\"Calendar Added\") return render(request, \"ais/ais.html\", context) @login_required def update_calendar(request): \"\"\" to", "HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # print(\"confirm hone wala hai\") # print(request.POST)", "of student from file specialization - details of student from file hall_no -", "the form to add a senate meeting minutes acadTtForm - the form to", "request.POST['branch']).filter(batch = request.POST['batch']).filter(programme= request.POST['programme']) courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses':", "databsae. User must be logged in and must be acadadmin @param: request -", "if c==0: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=True, ) new_curr_inst.append(ins) else: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=False,", "django.template.loader import render_to_string from django.contrib.auth.decorators import login_required from applications.academic_procedures.models import MinimumCredits, Register, InitialRegistration,", "senator # hDes - the holdDesignation object that stores the # information that", "the student # \"\"\" if request.method == \"POST\": name = request.POST.get('name') # roll", "exam_t, 'timetable': timetable, 'tab_id' :['10','1'] } acadTtForm = AcademicTimetableForm() if request.method == 'POST'", "file book - workbook of xlsx file title - formatting variable of title", "# return JsonResponse(data) # @csrf_exempt def deleteConvenor(request, pk): # \"\"\" # to remove", "of thsi semester courses next_sem_courses - the data of next semester courses courses", "= sem[year-int(request_batch)] sem+=1 curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code') faculty_list =", "cpi = 0, category = category, hall_no = hall_no, specialization = specialization, curr_semester_no=sem,", "about the requested page # @variables: # current_user - father's name of the", "def delete_curriculum(request): \"\"\" This function is used to delete curriculum entry in database", "while True: if \"semester_\"+str(i) in request.POST: try: programme=request.POST['AddProgramme'] batch=request.POST['AddBatch'] branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)]", "be added sem - semester of the student grade - grade to be", "\"\" courses = \"\" course_type = \"\" timetable = \"\" exam_t = \"\"", "programme = request.POST.get('programme') # batch = request.POST.get('batch') # ph = request.POST.get('phoneno') # if", "= request_batch).filter(programme= request_programme).order_by('sem') else: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem= request_sem)", "designation as a dean student - the students as a senator extra -", "to add data to variable data k -temporary array to add data to", "Acadadmin final_user - final designation of request user \"\"\" try: current_user = get_object_or_404(User,", "father_name = fathers_name, mother_name = mothers_name, cpi = 0, category = category, hall_no", "exam_t - all exam timetable from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') timetable", "else: # return HttpResponseRedirect('/aims/') # @csrf_exempt def deleteSenator(request, pk): # \"\"\" # to", "an existing senate meeting minute object from the database. # @param: # request", "8] else: course_list_2 = [1, 3, 5, 7] # examTtForm = ExamTimetableForm() #", "== 'POST': programme = request.POST['programme'] now = datetime.datetime.now() year = int(now.year) batch =", "is stored in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','2'] }", "desc get_calendar_details.from_date = from_date get_calendar_details.to_date = to_date get_calendar_details.save() except Exception as e: from_date=\"\"", "render(request, \"ais/ais.html\", context) @login_required def edit_curriculum(request): \"\"\" This function is used to edit", "subject - subject of which the grade has to be added sem -", "if int(request_sem) == 0: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).order_by('sem') else:", "c in courses: reg=course_registration( course_id = c, semester_id=sem_id, student_id=stud_data ) new_reg.append(reg) course_registration.objects.bulk_create(new_reg) else:", "the requested page. @variables: acadTtForm - data of delete dictionary in post request", ": pgstudent, 'assistant_list' : assistant_list, 'assistant_approve_list' : assistant_approve_list, 'assistant_list_length' : assistant_list_length, 'tab_id': ['1','1'],", "- new student object created in database desig - get designation object of", "academic timetable objects calendar - all the academic calender objects department - all", "to check the designation of the user. # user_details - to get the", "request.POST.get('father') # mother = request.POST.get('mother') # add = request.POST.get('address') # hall = request.POST.get('hall')", "of request user \"\"\" try: current_user = get_object_or_404(User, username=request.user.username) user_details = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id", "faculty: faculty_list.append(i) return faculty_list @login_required def float_course(request): \"\"\" to float courses for the", "== \"POST\": # data = request.POST['delete'] # t = Meeting.objects.get(id=data) # t.delete() return", "else: # father = request.POST.get('father') # mother = request.POST.get('mother') # add = request.POST.get('address')", "now - get current time year - getcurrent year batch - gets the", "# # #################################### @login_required def curriculum(request): \"\"\" This function is used to see", "result == \"Convenor\": # hDes.designation = s # else: # hDes.designation = p", "##########covenors and coconvenors################## # @csrf_exempt def add_convenor(request): # \"\"\" # to add a", "- selected addtional courses by the academic person. # course - Course details", "curriculum and edit entries in a curriculum. It checkes the authentication of the", "to delete data\") return HttpResponse(\"Data Deleted SuccessFully\") @login_required def verify_grade(request): \"\"\" It verify", "the calendar instance from the database for the previous Description. \"\"\" if user_check(request):", "timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() pgstudent = Student.objects.filter(programme = \"M.Tech\") | Student.objects.filter(programme", "'tab_id': ['1','1'], 'context': procedures_context['context'], 'lists': procedures_context['lists'], 'date': procedures_context['date'], 'query_option1': procedures_context['query_option1'], 'query_option2': procedures_context['query_option2'], 'course_verification_date'", ": procedures_context['course_verification_date'], 'submitted_course_list' : procedures_context['submitted_course_list'], 'result_year' : procedures_context['result_year'], 'batch_grade_data' : procedures_context['batch_grade_data'], 'batch_branch_data' :", "context= { # 'courses': courses, # 'course_type': course_type, # 'curriculum_course': curriculum_courses, # }", "batch).filter(programme = programme) context= { 'curriculumm' :curriculum, 'tab_id' :['3','3'] } return render(request, \"ais/ais.html\",", "= InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem) registered_students = set() unregistered_students = set() for stu in obj:", "###################################################### # # ##########Student basic profile################## # @csrf_exempt def add_basic_profile(request): # \"\"\" #", "html = render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj = json.dumps({'html':html}) #return render(request, \"ais/ais.html\", context) return HttpResponse(obj,content_type='application/json') else:", "f1,f2,f3 - temporary varibles faculty - details of faculty of data faculty_list -", "programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass ins=Curriculum( programme=programme,", "check if the student is available # desig_id - mother 's name of", "about the requested page. @variables: data - data of delete dictionary in post", "from form request_sem - Semester from form \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context=", "acad admin # s - the student object from the requested rollno #", "branch).filter(batch = batch).filter(programme= programme).filter(sem = sem) # print(curriculum_courses) # courses = Course.objects.all() #", "calendar = Calendar.objects.all() context= { 'academic_calendar' :calendar, 'tab_id' :['4','1'] } if request.method ==", "request.POST.get('address') # hall = request.POST.get('hall') # room = request.POST.get('room') # cpi = request.POST.get('cpi')", "HoldsDesignation.objects.all().filter(designation = desig_id).first() # print (temp) # print (current_user) # acadadmin = temp.working", "current semester that a student must take # @param: # request - contains", "= \"\" #for checking if the user has searched for any particular curriculum", "= c, semester_id=sem_id, student_id=stud_data ) new_reg.append(reg) course_registration.objects.bulk_create(new_reg) else: return render(request, \"ais/ais.html\", context) return", "request_programme==\"\" and request_sem==\"\": curriculum = None #Curriculum.objects.all() else: if int(request_sem) == 0: curriculum", "student required to check if the student is available # desig_id - mother", "about the requested page. @variables: acadTtForm - data of delete dictionary in post", "in from_date] from_date = datetime.datetime(*from_date).date() to_date = to_date[0].split('-') to_date = [int(i) for i", "'POST': try: id=request.POST['id'] programme=request.POST['programme'] batch=request.POST['batch'] branch=request.POST['branch'] sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"] if request.POST['optional']", "- io Bytes object to write to xlsx file book - workbook of", "request_sem==\"\": curriculum = None #Curriculum.objects.all() else: if int(request_sem) == 0: curriculum = Curriculum.objects.select_related().filter(branch", "name = str(b)+\" \"+str(c) temp = str(i[3]).split() dep = str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext)", "i in ans: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] name = str(b)+\" \"+str(c) temp", "# course - Course details which is selected by the academic admin. #", "= request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] prev_desc = request.POST.getlist('prev_desc')[0] from_date =", "True, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) normaltext = book.add_format({'bold': False, 'font_size': 15,", "and request_branch == \"\" and request_programme==\"\": curriculum = None #Curriculum.objects.all() else: sem =", "academic person. # course - Course details which is selected by the academic", "curriculum # # #################################### @login_required def curriculum(request): \"\"\" This function is used to", "new student convenor/coconvenor # @param: # request - contains metadata about the requested", "# sem_cred = Get credit details from forms and the append it to", "of a student # @param: # request - contains metadata about the requested", "!= str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # print(request.POST) #", "examTtForm = ExamTimetableForm() # acadTtForm = AcademicTimetableForm() # calendar = Calendar.objects.all() # this_sem_courses", "- temporary variables for final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') try: batch", "try: request_batch = request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme'] except Exception as", "# user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk') # temp =", "- data of delete dictionary in post request t - Object of Exam", "to set up the homepage of the application. It checkes the authentication of", "in range(sheet.nrows): roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value) if sex == 'F': title='Ms.' else:", "= { # 'id': pk, # 'designation': designation, # } # return JsonResponse(data)#", "= AcademicTimetableForm() calendar = Calendar.objects.all() this_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses =", "request.POST['programme']) courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type,", "'pgstudent' : pgstudent, 'assistant_list' : assistant_list, 'assistant_approve_list' : assistant_approve_list, 'assistant_list_length' : assistant_list_length, 'tab_id':", "from file address - details of student from file department - details of", "details of the required user. # desig_id - used to check the designation", "entry.course_id=course_id entry.credits=credits entry.optional=optional entry.course_type=course_type entry.save() curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme)", "request.method == \"POST\": data = request.POST['delete'] t = Exam_timetable.objects.get(exam_time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\")", "data = { # 'id': pk, # 'designation': designation, # } # return", "str(batch.year) + '-preresgistration.xlsx' response['Content-Disposition'] = st return response @login_required def add_new_profile (request): \"\"\"", "- get current time year - getcurrent year batch - gets the batch", "# return HttpResponse('sucess') # else: # return HttpResponse('not uploaded') # return render(request, \"ais/ais.html\",", "to add a new senate meeting minute object to the database. # @param:", "else: # return HttpResponseRedirect('/aims/')# #################################################### # # ##########covenors and coconvenors################## # @csrf_exempt def", "\"\"\" e = get_object_or_404(ExtraInfo, id=pk) # user = get_object_or_404(User, username = e.user.username) #", "get user from request user_details - extract details of user from database desig_id", "homepage(request): \"\"\" This function is used to set up the homepage of the", "registration details appended into one data - Formated data for context m -", "0: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).order_by('sem') else: curriculum = Curriculum.objects.select_related().filter(branch", "the datas to be displayed in the webpage this_sem_course - tha data of", "\"ais/ais.html\", context) # #################################### # # curriculum # # #################################### @login_required def curriculum(request):", "datetime.datetime.now() year = int(now.year) if sem[0] == 2: sem = sem[year-int(request_batch)-1] else: sem", "object received from id to be deleted # \"\"\" # if request.method ==", "True) assistant_list_length = len(assistant_list.filter(acad_approval = False)) assis_stat = Assistantship_status.objects.all() for obj in assis_stat:", "\"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def delete_curriculum(request): \"\"\" This function is", "- gets the batch from form sem - stores the next semester obj", "\"\"\" now = datetime.datetime.now() month = int(now.month) if month >= 7 and month", "form = MinuteForm(request.POST, request.FILES) # if form.is_valid(): # form.save() # return HttpResponse('sucess') #", "if \"semester_\"+str(i) in request.POST: try: programme=request.POST['AddProgramme'] batch=request.POST['AddBatch'] branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)]", "request.FILES: # form = MinuteForm(request.POST, request.FILES) # if form.is_valid(): # form.save() # return", "to add new curriculum in database It checkes the authentication of the user", "else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def add_curriculum(request): \"\"\"", "for the academic calendar event. to_date - The ending date for the academic", "= \"\" timetable = \"\" exam_t = \"\" pass context = { 'acadTtForm':", "convenor/coconvenor # extraInfo - extraInfo object of the student with that rollno #", "except Exception as e: from_date=\"\" to_date=\"\" desc=\"\" return render(request, \"ais/ais.html\", context) return render(request,", "user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation =", "# 'courses': courses, # 'course_type': course_type, # 'curriculum_course': curriculum_courses, # } # return", "Workbook(output,{'in_memory':True}) title = book.add_format({'bold': True, 'font_size': 22, 'align': 'center', 'valign': 'vcenter'}) subtitle =", "- the designation object that contains co convenor # student - the student", "- get hold_desig object of student currs - get curriculum details reg -", "# ''' def delete_advanced_profile(request): # \"\"\" # to delete the advance information of", "AcademicTimetableForm, ExamTimetableForm, MinuteForm from .models import (Calendar, Course, Exam_timetable, Grades, Curriculum_Instructor,Constants, Meeting, Student,", "request.method == 'POST' and request.FILES: # form = MinuteForm(request.POST, request.FILES) # if form.is_valid():", "= AcademicTimetableForm() # calendar = Calendar.objects.all() # this_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # next_sem_courses =", "Convenor') # result = request.POST.get('designation') # hDes = HoldsDesignation() # hDes.user = extraInfo.user", "particular student is a senator # \"\"\" pass # if request.POST: # s", "sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme entry.batch=batch entry.branch=branch entry.sem=sem", "Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem= request_sem) # context={ # 'courses' : courses,", "\"\" request_programme = \"\" request_sem = \"\" #for checking if the user has", "context= { 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) @login_required def add_timetable(request): \"\"\"", "= request.POST['batch']).filter(programme= request.POST['programme']) courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses': courses,", "if request.method == 'POST': programme = request.POST['programme'] now = datetime.datetime.now() year = int(now.year)", "@login_required def add_exam_timetable(request): \"\"\" acad-admin can upload the exam timtable of the ongoing", "\"optional_\"+str(i) in request.POST: optional=True else: optional=False course_type=request.POST[\"course_type_\"+str(i)] except Exception as e: programme=\"\" batch=\"\"", "credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) batch=batch+1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme =", "z.append('not registered') data.append(z) for i in registered_students: z = [] z.append(m) m +=", "if sem[0] == 2: sem = sem[year-int(request_batch)-1] else: sem = sem[year-int(request_batch)] sem+=1 curriculum", "name - the name of the student # roll - the rollno of", "Curriculum.objects.filter(curriculum_id=curr_id) # grades = Grades.objects.filter(curriculum_id=curr_course) # context= { # 'grades': grades, # 'tab_id'", "9): # sem = MinimumCredits.objects.all().filter(semester=i).first() # sem.credits = sem_cred[i+1] # sem.save() # return", "{ # 'id': pk, # 'designation': designation, # } # return JsonResponse(data)# ######################################################", "Branch from form request_programme - Programme from form request_sem - Semester from form", "c, semester_id=sem_id, student_id=stud_data ) new_reg.append(reg) course_registration.objects.bulk_create(new_reg) else: return render(request, \"ais/ais.html\", context) return render(request,", "the workbook subtitle - formatting variable of subtitle the workbook normaltext - formatting", "} return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\",", "batch of the student # programme - the programme the student is enrolled", "the designation of the current user # acadadmin - deatils of the acad", "stu not in registered_students: unregistered_students.add(stu) data = [] m = 1 for i", "gets the batch course - gets the course curr_key - gets the curriculum", "django.contrib.auth.decorators import login_required from applications.academic_procedures.models import MinimumCredits, Register, InitialRegistration, course_registration, AssistantshipClaim,Assistantship_status from applications.globals.models", "= desig_id).first() acadadmin = temp.working k = str(user_details).split() final_user = k[2] except Exception", "be acadadmin @param: request - contains metadata about the requested page. @variables: profiles", "Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','1'] } acadTtForm = AcademicTimetableForm()", "HttpResponse(\"Data Does Not Exist\") # return HttpResponse(\"Data Deleted Successfully\") def add_advanced_profile(request): # \"\"\"", "# hDes.designation = p # hDes.save() # data = { # 'name': extraInfo.user.username,", "'attachment; filename = ' + batch.name + batch.discipline.acronym + str(batch.year) + '-preresgistration.xlsx' response['Content-Disposition']", "- course_id from database credits - credits from form.REQUEST optional - optional from", "senator designation # student - the student object of the new senator #", "# # ##########covenors and coconvenors################## # @csrf_exempt def add_convenor(request): # \"\"\" # to", "student - the student object with the given pk # hDes - the", "checkes the authentication of the user and also fetches the available data from", "'align': 'center', 'valign': 'vcenter'}) sheet = book.add_worksheet() title_text = (\"Pre-registeration : \"+ batch.name", "procedures_context['batch_branch_data'], 'assistant_flag' : assistant_flag, 'hod_flag' : hod_flag, 'account_flag' : account_flag } return context", "of student from file mothers_name - details of student from file category -", "particualr student is # holding the convenor/coconvenor designation # student - the student", "def addMinute(request): # \"\"\" # to add a new senate meeting minute object", "registeration object in registeration table \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id'", "\"\" request_branch = \"\" request_programme = \"\" if request_batch == \"\" and request_branch", "user has searched for any particular curriculum if request_batch == \"\" and request_branch", "= datetime.datetime.now() year = int(now.year) if sem[0] == 2: sem = sem[year-int(request_batch)-1] else:", "timtable of the ongoing semester. @param: request - contains metadata about the requested", "extraInfo.user # hDes.working = extraInfo.user # if result == \"Convenor\": # hDes.designation =", "= st.split(\"-\") # stu = arr[0] # if Student.objects.get(id=stu): # s = Student.objects.get(id=stu)", "- get user from request user_details - extract details of user from database", "\"POST\": i=1 while True: if str(i)+\"_ccode\" in request.POST: if str(i)+\"_fac\" in request.POST: if", "# \"\"\" if request.method == \"POST\": pass # print(request.POST) # choices = request.POST.getlist('choice')", "obj = InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem) registered_students = set() unregistered_students = set() for stu in", "'POST': try: request_batch = request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme'] request_sem =", "username=roll_no, password='<PASSWORD>', first_name=first_name, last_name=last_name, email=email, ) einfo = ExtraInfo.objects.create( id=roll_no, user=user, title=title, sex=sex,", "delete_basic_profile(request, pk): # \"\"\" # Deletes the student from the database # @param:", "batch).filter(programme= programme) courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses': courses, 'course_type':", "BytesIO from xlsxwriter.workbook import Workbook from xhtml2pdf import pisa from itertools import chain", "senator meetings minuteForm - the form to add a senate meeting minutes acadTtForm", "for i in range(sheet.nrows): roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value) if sex == 'F':", "add_new_profile (request): \"\"\" To add details of new upcoming students in the database.User", "No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',50) sheet.set_column('D:D',15) sheet.set_column('E:E',15) k =", ": assistant_list_length, 'tab_id': ['1','1'], 'context': procedures_context['context'], 'lists': procedures_context['lists'], 'date': procedures_context['date'], 'query_option1': procedures_context['query_option1'], 'query_option2':", "render_to_string from django.contrib.auth.decorators import login_required from applications.academic_procedures.models import MinimumCredits, Register, InitialRegistration, course_registration, AssistantshipClaim,Assistantship_status", "# to add a new senate meeting minute object to the database. #", "user \"\"\" try: current_user = get_object_or_404(User, username=request.user.username) user_details = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id = Designation.objects.all().filter(name='Upper", "# return render(request, \"ais/ais.html\", context) # else: # return render(request, \"ais/ais.html\") return render(request,", "from form.REQUEST course_name - course-name from form.REQUEST course_id - course_id from database credits", "- deatils of the acad admin # father - father's name of the", "def generatexlsheet(request): \"\"\" to generate Course List of Registered Students @param: request -", "= 'attachment; filename = ' + course.code + '.xlsx' response['Content-Disposition'] = st return", "to_date[0].split('-') to_date = [int(i) for i in to_date] to_date = datetime.datetime(*to_date).date() get_calendar_details =", "request user_details - extract details of user from database desig_id - check for", "output b - temporary variables for final output c - temporary variables for", "to display it on the page. @param: request - contains metadata about the", "the current user. # desig_id - to check the designation of the user.", "range(1, 9): # sem = MinimumCredits.objects.all().filter(semester=i).first() # sem.credits = sem_cred[i+1] # sem.save() #", "form.REQUEST ins - data is stored in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "# return HttpResponse(\"Worked\") def view_course(request): # if request.method == \"POST\": # programme=request.POST['programme'] #", "HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1'] } if request.method == 'POST': try: request_batch =", "user_type='student', department=department, ) sem=1 stud_data = Student.objects.create( id=einfo, programme = programme_name, batch=batch_year, batch_id", "result = request.POST.get('designation') # hDes = HoldsDesignation() # hDes.user = extraInfo.user # hDes.working", "context) @login_required def edit_curriculum(request): \"\"\" This function is used to edit curriculum in", "entries in a curriculum. It checkes the authentication of the user and also", "delete_timetable(request): \"\"\" acad-admin can delete the outdated timetable from the server. @param: request", "# return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # print(\"confirm hone wala hai\")", "render(request, \"ais/ais.html\", context) # else: # return render(request, \"ais/ais.html\") return render(request, \"ais/ais.html\") def", "new student object created in database desig - get designation object of student", "def verify_grade(request): \"\"\" It verify the grades of the student @param: request -", "#################################### @login_required def curriculum(request): \"\"\" This function is used to see curriculum and", "else: # return render(request, \"ais/ais.html\") return render(request, \"ais/ais.html\") def delete_grade(request): # \"\"\" #", "import acad_proced_global_context from applications.programme_curriculum.models import Batch @login_required def user_check(request): \"\"\" This function is", "context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','2'] } return render(request,", "minutes acadTtForm - the form to add academic calender examTtForm - the form", "HttpResponse(\"Unable to delete data\") return HttpResponse(\"Data Deleted SuccessFully\") @login_required def verify_grade(request): \"\"\" It", "str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # print(request.POST) # rollno=request.POST.get('roll')", "the data of current user. # user_details - gets the details of the", "updated. @param: request - contains metadata about the requested page. @variables: from_date -", "ExamTimetableForm, MinuteForm from .models import (Calendar, Course, Exam_timetable, Grades, Curriculum_Instructor,Constants, Meeting, Student, Student_attendance,", "all exam timetable from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') timetable = Timetable.objects.all()", "m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('not registered') data.append(z) for i in", "= Student.objects.get(id=student) # s.father_name=father # s.mother_name=mother # s.hall_no = hall # s.room_no =", "to_date = [int(i) for i in to_date] to_date = datetime.datetime(*to_date).date() except Exception as", "- contains metadata about the requested page # @variables: # current_user - father's", "ofwhich the grade is added \"\"\" # if user_check(request): # return HttpResponseRedirect('/academic-procedures/') #", "- all the courses in curriculum course_type - list the type of courses", "webpage \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) return render(request, \"ais/ais.html\", context)", "entry.save() curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme) courses = Course.objects.all() course_type", "for final output st - temporary variables for final output \"\"\" if user_check(request):", "semester grade sheet @variables: now - current datetime month - current month \"\"\"", "curriculum_id=flot, instructor_id=inst, chief_inst=False, ) new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst) else: break i+=1 return render(request, \"ais/ais.html\", context)", "formated data) z - temporary array to add data to variable data k", "batch.curriculum, semester_no = sem) course_slots = CourseSlot.objects.all().filter(semester = sem_id) courses = [] for", "\"\" next_sem_courses = \"\" courses = \"\" course_type = \"\" timetable = \"\"", "the designation as a dean student - the students as a senator extra", "date for the academic calendar event. to_date - The ending date for the", "get faculty list from database @param: request - contains metadata about the requested", "= get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0]) # hDes = get_object_or_404( HoldsDesignation, user = student.user) # hDes.delete()", "import datetime import json import os import xlrd import logging from io import", "- temporary variables for final output b - temporary variables for final output", "as a convenor CoConvenor - the extraInfo objects that holds the designation as", "batch_id).first() obj = InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem) registered_students = set() unregistered_students = set() for stu", "Designation.objects.get(name='Senator') # hDes = HoldsDesignation() # hDes.user = extraInfo.user # hDes.working = extraInfo.user", "in students: if stu not in registered_students: unregistered_students.add(stu) data = [] m =", "{ # 'name': name, # 'rollno': roll.id, # 'programme': programme, # 'phoneno': ph,", "Meeting, Student, Student_attendance, Timetable,Curriculum) from applications.programme_curriculum.models import (CourseSlot, Course as Courses, Batch, Semester,", "credits from form.REQUEST optional - optional from form.REQUEST course_type - course_type from form.REQUEST", "that the particular student is a convenor/coconvenor to be deleted # data -", "from file category - details of student from file phone_no - details of", "\"\" request_sem = \"\" #for checking if the user has searched for any", "- contains metadata about the requested page. # @variables: # choices - selected", "the user. # user_details - to get the details of the required user.", "convenor # student - the student object with the given pk # hDes", "information of the student # @param: # request - contains metadata about the", "= to_date[0].split('-') to_date = [int(i) for i in to_date] to_date = datetime.datetime(*to_date).date() except", "# p - designation object of Co Convenor # result - the data", "ExtraInfo.objects.select_related('user','department').get(user=inst) if c==0: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=True, ) new_curr_inst.append(ins) else: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst,", "senator from the position # @param: # request - contains metadata about the", "student = Student.objects.get(id=extraInfo) # data = { # 'name': extraInfo.user.username, # 'rollno': extraInfo.id,", "request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] prev_desc = request.POST.getlist('prev_desc')[0] from_date = from_date[0].split('-')", "course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"] if request.POST['optional'] == \"on\": optional=True else: optional=False course_type=request.POST[\"course_type\"] except Exception as", "= Timetable.objects.all() exam_t = Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','1']", "dictionary in post request t - Object of Exam time table to be", "to delete an existing senate meeting minute object from the database. # @param:", "to store that the particualr student is holding the senator designation # student", "# sem = int(d[3]) # if request.method == \"POST\": # if(Grades.objects.filter(student_id=id, sem=sem)): #", "render(request, \"ais/ais.html\", context) context= { 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) @login_required", "from file phone_no - details of student from file address - details of", "prev_desc = request.POST.getlist('prev_desc')[0] from_date = from_date[0].split('-') from_date = [int(i) for i in from_date]", "request.FILES) if examTtForm.is_valid(): examTtForm.save() return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context)", "= ph # db.save() # st.save() # data = { # 'name': name,", "Designation.objects.get(name='student') hold_des = HoldsDesignation.objects.create( user=user, working=user, designation=desig, ) sem_id = Semester.objects.get(curriculum = batch.curriculum,", "HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": sem = request.POST.get('semester_no') batch_id=request.POST.get('batch_branch') batch = Batch.objects.filter(id =", "examTtForm = \"\" acadTtForm = \"\" calendar = \"\" this_sem_courses = \"\" next_sem_courses", "details reg - create registeration object in registeration table \"\"\" if user_check(request): return", "set() unregistered_students = set() for stu in obj: registered_students.add(stu.student_id) students = Student.objects.filter(batch_id =", "the senator designation # student - the student object of the new senator", "\"ais/ais.html\", context) @login_required def delete_curriculum(request): \"\"\" This function is used to delete curriculum", "'assistant_approve_list' : assistant_approve_list, 'assistant_list_length' : assistant_list_length, 'tab_id': ['1','1'], 'context': procedures_context['context'], 'lists': procedures_context['lists'], 'date':", "# hDes.save() # student = Student.objects.get(id=extraInfo) # data = { # 'name': extraInfo.user.username,", "render(request, \"ais/ais.html\", context) else: context= { 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context)", "context= { 'tab_id' :['5','1'] } if request.method == 'POST': try: request_batch = request.POST['batch']", "not in registered_students: unregistered_students.add(stu) data = [] m = 1 for i in", "{ 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\",", "rollno of the student to become the convenor/coconvenor # extraInfo - extraInfo object", "academic calendar event. c = object to save new event to the academic", "timetable exam_t - all the exam timetable objects timetable - all the academic", "file fathers_name - details of student from file mothers_name - details of student", "Semester from form \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1'] }", "for i in to_date] to_date = datetime.datetime(*to_date).date() except Exception as e: from_date=\"\" to_date=\"\"", "the webpage # \"\"\" s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') #", "'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','1'] } acadTtForm = AcademicTimetableForm() if request.method ==", "'rollno': roll.id, # 'programme': programme, # 'phoneno': ph, # 'batch': batch # }", "= { 'acadTtForm': acadTtForm, 'examTtForm': examTtForm, 'courses': courses, 'courses_list': courses_list, 'course_type': course_type, 'exam':", "batch=request.POST['batch'] # branch=request.POST['branch'] # sem=request.POST['sem'] # curriculum_courses = Curriculum.objects.filter(branch = branch).filter(batch = batch).filter(programme=", "- Batch from form request_branch - Branch from form request_programme - Programme from", "(current_user) # acadadmin = temp.working # k = str(user_details).split() # print(k) # final_user", ">= 7 and month <= 12: return [1, 3, 5, 7] else: return", "used to see curriculum and edit entries in a curriculum. It checkes the", "the requested page @variables: programme - programme from form.REQUEST now - current date", "1 for i in data: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] a,b,c,d,e = str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4])", "return HttpResponseRedirect('/academic-procedures/') context = get_context(request) context['tab_id'][0]='6' if request.method == 'POST': try: request_batch =", "gets the data of current user. # user_details - gets the details of", "temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() # print (temp) # print (current_user) # acadadmin", "= get_object_or_404(Student, id=e) # data = { # 'rollno': pk, # } #", "about the requested page # @variables: # name - the name of the", "to the academic calendar to be uploaded @param: request - contains metadata about", "= Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # next_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # courses = Course.objects.all() # course_type =", "contains metadata about the requested page # @variables: # rollno - rollno of", "data - data of delete dictionary in post request t - Object of", "context) @login_required def delete_timetable(request): \"\"\" acad-admin can delete the outdated timetable from the", "title - details of student from file dob - details of student from", "data k -temporary array to add data to formatted array/variable output - io", "= \"\" if request_batch == \"\" and request_branch == \"\" and request_programme==\"\": curriculum", "= mothers_name, cpi = 0, category = category, hall_no = hall_no, specialization =", "credits=credits, optional=optional, course_type=course_type, ) new_curr.append(ins) else: break i+=1 Curriculum.objects.bulk_create(new_curr) curriculum = Curriculum.objects.select_related().filter(branch =", "# 'curriculum_course': curriculum_courses, # } # return render(request, \"ais/ais.html\", context) # else: #", "converted to xlsx k -temporary array to add data to formatted array/variable output", "assistant_flag, 'hod_flag' : hod_flag, 'account_flag' : account_flag } return context @login_required def homepage(request):", "ending date for the academic caldendar event. desc - Description for the academic", "details of student from file phone_no - details of student from file address", "webpage this_sem_course - tha data of thsi semester courses next_sem_courses - the data", "as Courses, Batch, Semester, Programme, Discipline) from applications.academic_procedures.views import acad_proced_global_context from applications.programme_curriculum.models import", "= [] m = 1 for i in unregistered_students: z = [] z.append(m)", "- deatils of the acad admin # s - the student object from", "caldendar event. desc - Description for the academic calendar event. prev_desc - Description", "request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] prev_desc = request.POST.getlist('prev_desc')[0] from_date = from_date[0].split('-') from_date = [int(i)", "the designation ID. # extraInfo - extraInfo object of the student with that", "# for i in courses: # if i.course_id not in choices: # i.acad_selection", "'font_size': 22, 'align': 'center', 'valign': 'vcenter'}) subtitle = book.add_format({'bold': True, 'font_size': 15, 'align':", "True).filter(hod_approval =True).filter(acad_approval = False) assistant_approve_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(hod_approval =", "sem = request.POST.get('semester_no') batch_id=request.POST.get('batch_branch') batch = Batch.objects.filter(id = batch_id).first() obj = InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem)", "from form.REQUEST course_type - course_type from form.REQUEST ins - data is stored in", "student - the student object of the new convenor/coconvenor # data - data", "faculty \"\"\" try: f1 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Assistant Professor\")) f2 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name =", "to save new event to the academic calendar. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "registered_courses: k = [] k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department) ans.append(k) ans.sort() output = BytesIO()", "in request.POST: try: programme=request.POST['AddProgramme'] batch=request.POST['AddBatch'] branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)] if \"optional_\"+str(i)", "calender objects department - all the departments in the college attendance - all", "book.add_format({'bold': True, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) normaltext = book.add_format({'bold': False, 'font_size':", "rollno of the student # batch - the current batch of the student", "of the student's record in the database table # @variables: # e -", "request - contains metadata about the requested page @variables: current_user - father's name", "# user_details - the rollno of the student required to check if the", "'branch': extraInfo.department.name # } # return HttpResponseRedirect('/aims/') # # return JsonResponse(data) # else:", "= Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum,", "temp = str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type", "return HttpResponse(\"Data Deleted Successfully\") def add_advanced_profile(request): # \"\"\" # It adds the advance", "\"\" and request_programme==\"\" and request_sem==\"\": curriculum = None #Curriculum.objects.all() else: if int(request_sem) ==", "timetable from database exam_t - all exam timetable from database \"\"\" if user_check(request):", "'valign': 'vcenter'}) sheet = book.add_worksheet() title_text = ((str(course.name)+\" : \"+str(str(batch)))) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text,", "from file hall_no - details of student from file programme - details of", "} if request.method == 'POST': try: request_batch = request.POST['batch'] request_branch = request.POST['branch'] request_programme", "'name': extraInfo.user.username, # 'rollno_convenor': extraInfo.id, # 'designation': hDes.designation.name, # } # return JsonResponse(data)", "if request.method == \"POST\": try: from_date = request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc =", "- details of student from file category - details of student from file", "# s = Student.objects.get(id=student) # s.father_name=father # s.mother_name=mother # s.hall_no = hall #", "requested page @variables: batch - gets the batch course - gets the course", "the academic calendar to be updated. @param: request - contains metadata about the", "record in the database table # @variables: # e - the extraInfo objects", "s = get_object_or_404(Designation, name=\"Convenor\") c = get_object_or_404(Designation, name=\"Co Convenor\") # student = get_object_or_404(ExtraInfo,", "month - current month \"\"\" now = datetime.datetime.now() month = int(now.month) if month", "- contains metadata about the requested page @variables: acadTtForm - the form to", "'rollno_convenor': extraInfo.id, # 'designation': hDes.designation.name, # } # return JsonResponse(data) # else: #", "department - all the departments in the college attendance - all the attendance", "the student to be displayed in the webpage # \"\"\" s = Designation.objects.get(name='Convenor')", "= request.POST.getlist('Roll Number')[0] # # print(request.POST.get('rollno')) # extraInfo = ExtraInfo.objects.get(id=rollno) # s =", "st.phone_no = ph # db.save() # st.save() # data = { # 'name':", "hall # s.room_no = room # s.save() # return HttpResponseRedirect('/academic-procedures/') # return HttpResponseRedirect('/academic-procedures/')", "about the requested page @variables: request_batch - Batch from form request_branch - Branch", "# for p in s: # if (str(p.course_id) == course): # print(p.course_id) #", "InitialRegistration, course_registration, AssistantshipClaim,Assistantship_status from applications.globals.models import (Designation, ExtraInfo, HoldsDesignation, DepartmentInfo) from .forms import", "request.POST['course']) obj = course_registration.objects.all().filter(course_id = course) except Exception as e: batch=\"\" course=\"\" curr_key=\"\"", "- temporary varibles faculty - details of faculty of data faculty_list - list", "einfo - new extrainfo object created in database stud_data - new student object", "= Student() # st = ExtraInfo.objects.get(id=roll.id) # db.name = name.upper() # db.id =", "in the student course - course ofwhich the grade is added \"\"\" #", "procedures_context['query_option1'], 'query_option2': procedures_context['query_option2'], 'course_verification_date' : procedures_context['course_verification_date'], 'submitted_course_list' : procedures_context['submitted_course_list'], 'result_year' : procedures_context['result_year'], 'batch_grade_data'", "3, 5, 7] # examTtForm = ExamTimetableForm() # acadTtForm = AcademicTimetableForm() # calendar", "# data = { # 'rollno': pk, # } # s.delete() # e.delete()", "of student currs - get curriculum details reg - create registeration object in", "Course as Courses, Batch, Semester, Programme, Discipline) from applications.academic_procedures.views import acad_proced_global_context from applications.programme_curriculum.models", "- all timetable from database exam_t - all exam timetable from database \"\"\"", "request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] from_date = from_date[0].split('-') from_date = [int(i)", "\"\" pass context = { 'acadTtForm': acadTtForm, 'examTtForm': examTtForm, 'courses': courses, 'courses_list': courses_list,", "the details of the required user. # desig_id - used to check the", ":['3','2'] } return render(request, \"ais/ais.html\", context) context= { 'tab_id' :['3','1'] } return render(request,", ":['5','1'] } return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context) return render(request,", "= Batch.objects.filter(id = batch_id).first() obj = InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem) registered_students = set() unregistered_students =", "object of senator # hDes - holdsDesignation object to store that the particualr", "to send to template @param: request - contains metadata about the requested page", "# request - contains metadata about the requested page # @variables: # name", "request.POST.get('room') # cpi = request.POST.get('cpi') # student.address = str(hall) + \" \" +", ") sem_id = Semester.objects.get(curriculum = batch.curriculum, semester_no = sem) course_slots = CourseSlot.objects.all().filter(semester =", "des.designation == c: # designation = des.designation.name # des.delete() # data = {", "- data of the student to be displayed in the webpage # \"\"\"", "Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code') faculty_list = get_faculty_list() courses = Course.objects.all() course_type", "the student is available # mother - mother's name of the student #", "= {} # return JsonResponse(data) # else: # father = request.POST.get('father') # mother", "grade has to be added sem - semester of the student grade -", "credit details from forms and the append it to an array. # sem", "picture, about me etc of a student # @param: # request - contains", "- Formated data for context m - counter for Sl. No (in formated", "also fetches the available data from the databases to display it on the", "\"POST\": pass # print(request.POST) # choices = request.POST.getlist('choice') # for i in choices:", "- the name of the student # roll - the rollno of the", "username of the logged in user # user_details - the details of the", "return HttpResponseRedirect('/academic-procedures/') def min_cred(request): # \"\"\" # to set minimum credit for a", "the college attendance - all the attendance objects of the students context -", "a curriculum. It checkes the authentication of the user and also fetches the", "student from file phone_no - details of student from file address - details", "acadTtForm = \"\" calendar = \"\" this_sem_courses = \"\" next_sem_courses = \"\" courses", "grade is added \"\"\" # if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if request.method", "student from file address - details of student from file department - details", "Exam_timetable, Grades, Curriculum_Instructor,Constants, Meeting, Student, Student_attendance, Timetable,Curriculum) from applications.programme_curriculum.models import (CourseSlot, Course as", "HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": data = request.POST['delete'] t = Exam_timetable.objects.get(exam_time_table=data) t.delete() return", "# if request.method == 'POST': # rollno = request.POST.get('rollno_convenor') # extraInfo = ExtraInfo.objects.get(id=rollno)", "request_programme - Programme from form request_sem - Semester from form \"\"\" if user_check(request):", "student = ExtraInfo.objects.get(id=rollno) # print(student.address) # if not student: # data = {}", "# 'courses' : courses, # 'course_type' : course_type, # 'curriculum' : curriculum, #", "!= str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST' and request.FILES: #", "== \"POST\": data = request.POST['delete'] t = Timetable.objects.get(time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required", "get_object_or_404, render from django.template.loader import get_template from django.views.decorators.csrf import csrf_exempt from django.template.loader import", "is available # mother - mother's name of the student # add -", "time table to be deleted \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method ==", "the current batch of the student # programme - the programme the student", "This function generates semester grade sheet @variables: now - current datetime month -", "\"\" and request_branch == \"\" and request_programme==\"\": curriculum = None #Curriculum.objects.all() else: sem", "curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme) courses = Course.objects.all() course_type =", "request - contains metadata about the requested page @variables: dele - data being", "'vcenter'}) normaltext = book.add_format({'bold': False, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) sheet =", "Exam time table to be deleted \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method", "z.append('registered') data.append(z) output = BytesIO() book = Workbook(output,{'in_memory':True}) title = book.add_format({'bold': True, 'font_size':", "batch).filter(programme = programme) if request.POST['option'] == '1': new_curriculum=[] for i in curriculum: ins=Curriculum(", "inst = get_object_or_404(User, username = i) inst = ExtraInfo.objects.select_related('user','department').get(user=inst) if c==0: ins=Curriculum_Instructor( curriculum_id=flot,", "exam timetable Dean - the extraInfo objects that holds the designation as a", "from form.REQUEST branch - branch from form.REQUEST sem - semester from form.REQUEST course_code", "# else: # return HttpResponse('not uploaded') # return render(request, \"ais/ais.html\", {}) def deleteMinute(request):", "event. to_date - The ending date for the academic caldendar event. desc -", "gets the excel file having data excel - excel file sheet - sheet", "Batch @login_required def user_check(request): \"\"\" This function is used to check the type", "# desig_id - checking the designation of the current user # acadadmin -", "Course details which is selected by the academic admin. # \"\"\" if request.method", "for c,i in enumerate(request.POST.getlist(str(i)+'_fac')): inst = get_object_or_404(User, username = i) inst = ExtraInfo.objects.select_related('user','department').get(user=inst)", "def confirm_grades(request): # if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\":", "# result - the data that contains where the student will become #", "Timetable.objects.all() exam_t = Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','2'] }", "courses in curriculum course_type - list the type of courses \"\"\" if user_check(request):", "from_date=\"\" to_date=\"\" desc=\"\" return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) #Generate Attendance", "# db.programme = programme # st.phone_no = ph # db.save() # st.save() #", "Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() #print (temp) # print (current_user)", "# cpi - student's cpi # hall - hall no of where the", "next_sem_courses = \"\" courses = \"\" course_type = \"\" timetable = \"\" exam_t", "This function is used to see curriculum and edit entries in a curriculum.", "== \"POST\": name = request.POST.get('name') # roll = ExtraInfo.objects.get(id=request.POST.get('rollno')) # programme = request.POST.get('programme')", "- the extraInfo objects of the student # user - the User object", "# else: # return HttpResponseRedirect('/aims/') return HttpResponseRedirect('/aims/') def confirm_grades(request): # if user_check(request): #", "normaltext - formatting variable for normal text sheet - xlsx sheet to be", "calendar, 'next_sem_course': next_sem_courses, 'this_sem_course': this_sem_courses, 'curriculum': curriculum, 'pgstudent' : pgstudent, 'assistant_list' : assistant_list,", "= xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) for i in range(sheet.nrows): roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value) if", "pass # if request.POST: # s = get_object_or_404(Designation, name=\"Senator\") # student = get_object_or_404(ExtraInfo,", "# ##########Senate meeting Minute################## # @csrf_exempt def addMinute(request): # \"\"\" # to add", "the current user # acadadmin - deatils of the acad admin # s", "if request.method == 'POST': try: id=request.POST['id'] programme=request.POST['programme'] batch=request.POST['batch'] branch=request.POST['branch'] sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name)", "add exam timetable exam_t - all the exam timetable objects timetable - all", "for normal text sheet - xlsx sheet to be rendered titletext - formatting", "particular curriculum if request_batch == \"\" and request_branch == \"\" and request_programme==\"\" and", "= request.POST['delete'] t = Exam_timetable.objects.get(exam_time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def add_calendar(request): \"\"\"", "f1=f2=f3=\"\" pass faculty = list(chain(f1,f2,f3)) faculty_list = [] for i in faculty: faculty_list.append(i)", "courses courses - all the courses in curriculum course_type - list the type", "- contains metadata about the requested page. @variables: request_batch - Batch from form", "context) @login_required def next_curriculum(request): \"\"\" This function is used to decide curriculum for", "selected addtional courses by the academic person. # course - Course details which", "== 'POST' and request.FILES: profiles=request.FILES['profiles'] excel = xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) for i in range(sheet.nrows):", "page # @variables: # data - the id of the minute object to", "data is stored in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1']", "from the database for the previous Description. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar", "List of Registered Students @param: request - contains metadata about the requested page", "Array to be converted to xlsx k -temporary array to add data to", "# 'rollno': extraInfo.id, # 'programme': student.programme, # 'branch': extraInfo.department.name # } # return", "a convenor CoConvenor - the extraInfo objects that holds the designation as a", "ExamTimetableForm(request.POST, request.FILES) if examTtForm.is_valid(): examTtForm.save() return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\",", "@param: request - contains metadata about the requested page @variables: dele - data", "{ # 'rollno': pk, # } # s.delete() # e.delete() # u.delete() #", "output c - temporary variables for final output st - temporary variables for", "delete_grade(request): # \"\"\" # It deletes the grade of the student # @param:", "(str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # print(request.POST['delete']) # data = request.POST['delete'] #", "function is used to set up the homepage of the application. It checkes", "Dean - the extraInfo objects that holds the designation as a dean student", "# view to add attendance data to database # def curriculum(request): # '''", "# 'course_type' : course_type, # 'curriculum' : curriculum, # 'tab_id' :['3','1'] # }", "exam timetable objects timetable - all the academic timetable objects calendar - all", "= str(b)+\" \"+str(c) temp = str(i[3]).split() dep = str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext) k+=1", "batch.name + str(\" \") + batch.discipline.acronym + str(\" \") + str(batch.year)) sheet.set_default_row(25) sheet.merge_range('A2:E2',", "= Calendar( from_date=from_date, to_date=to_date, description=desc) c.save() HttpResponse(\"Calendar Added\") return render(request, \"ais/ais.html\", context) @login_required", "in range(1, 10): # sem = \"sem_\"+\"1\" # sem_cred.append(request.POST.getlist(sem)[0]) # for i in", "course_type=\"\" pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme entry.batch=batch entry.branch=branch entry.sem=sem entry.course_code=course_code entry.course_id=course_id entry.credits=credits entry.optional=optional entry.course_type=course_type entry.save()", "True flot.save() new_curr_inst=[] for c,i in enumerate(request.POST.getlist(str(i)+'_fac')): inst = get_object_or_404(User, username = i)", "render(request, \"ais/ais.html\", context) @login_required def delete_curriculum(request): \"\"\" This function is used to delete", "mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13 ).value department=DepartmentInfo.objects.all().filter(name=dept).first() if specialization == \"\":", "mothers_name, cpi = 0, category = category, hall_no = hall_no, specialization = specialization,", "mother = request.POST.get('mother') # add = request.POST.get('address') # hall = request.POST.get('hall') # room", "the new convenor/coconvenor # data - data of the student to be displayed", "object of the new senator # data - data of the student to", "# current_user - gets the data of current user. # user_details - gets", "# s - designation object of Convenor # p - designation object of", "curr_course = Curriculum.objects.filter(curriculum_id=curr_id) # grades = Grades.objects.filter(curriculum_id=curr_course) # context= { # 'grades': grades,", "the student course - course ofwhich the grade is added \"\"\" # if", "sheet to be rendered titletext - formatting variable of title text dep -", "request.FILES: acadTtForm = AcademicTimetableForm(request.POST, request.FILES) if acadTtForm.is_valid(): acadTtForm.save() return render(request, \"ais/ais.html\", context) else:", "z = [] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('not registered')", "type of) of the semester. @param: request - contains metadata about the requested", "- designation for Acadadmin final_user - final designation of request user \"\"\" try:", "= [] for i in faculty: faculty_list.append(i) return faculty_list @login_required def float_course(request): \"\"\"", "try: current_user = get_object_or_404(User, username=request.user.username) user_details = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id = Designation.objects.all().filter(name='Upper Division Clerk')", "form to add academic calender examTtForm - the form required to add exam", "sem - semester of the student grade - grade to be added in", "request.method == \"POST\": pass # print(request.POST) # choices = request.POST.getlist('choice') # for i", "- the username of the logged in user # user_details - the details", "@variables: # name - the name of the student # roll - the", "ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk') # temp = HoldsDesignation.objects.all().filter(designation = desig_id).first()", "- formatting variable of title the workbook subtitle - formatting variable of subtitle", "k[2] except Exception as e: acadadmin=\"\" final_user=\"\" pass if (str(acadadmin) != str(final_user)): return", "= i) inst = ExtraInfo.objects.select_related('user','department').get(user=inst) if c==0: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=True, ) new_curr_inst.append(ins)", "import csrf_exempt from django.template.loader import render_to_string from django.contrib.auth.decorators import login_required from applications.academic_procedures.models import", "= request.POST.get('name') # roll = ExtraInfo.objects.get(id=request.POST.get('rollno')) # programme = request.POST.get('programme') # batch =", "get_calendar_details.description = desc get_calendar_details.from_date = from_date get_calendar_details.to_date = to_date get_calendar_details.save() except Exception as", "'timetable': timetable, 'tab_id' :['10','1'] } acadTtForm = AcademicTimetableForm() if request.method == 'POST' and", "\") + batch.discipline.acronym + str(\" \") + str(batch.year)) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl.", "pass ins=Curriculum( programme=programme, batch=batch, branch=branch, sem=sem, course_code=course_code, course_id=course_id, credits=credits, optional=optional, course_type=course_type, ) new_curr.append(ins)", "@variables: from_date - The starting date for the academic calendar event. to_date -", "# return JsonResponse(data) # else: # data = {} # return JsonResponse(data) #", "'programme': student.programme, # 'branch': extraInfo.department.name # } # return HttpResponseRedirect('/aims/') # # return", "= batch_id).first() obj = InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem) registered_students = set() unregistered_students = set() for", "of the current user # desig_id - checking the designation of the current", "= HoldsDesignation() # hDes.user = extraInfo.user # hDes.working = extraInfo.user # hDes.designation =", "# print(request.POST) # choices = request.POST.getlist('choice') # for i in choices: # course", "for i in data: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] a,b,c,d,e = str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp", "desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() acadadmin = temp.working", "'.xlsx' response['Content-Disposition'] = st return response @login_required def generate_preregistration_report(request): \"\"\" to generate preresgistration", "pre-registration @param: request - contains metadata about the requested page @variables: sem -", "in the college attendance - all the attendance objects of the students context", "assistant_list, 'assistant_approve_list' : assistant_approve_list, 'assistant_list_length' : assistant_list_length, 'tab_id': ['1','1'], 'context': procedures_context['context'], 'lists': procedures_context['lists'],", "sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',60)", "return HttpResponse(\"Data Deleted SuccessFully\") @login_required def verify_grade(request): \"\"\" It verify the grades of", ") new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) batch=batch+1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) context= {", "page # pk - the primary key of the student's record in the", "else: optional=False course_type=request.POST[\"course_type_\"+str(i)] except Exception as e: programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\"", "return HttpResponseRedirect('/aims/') # @csrf_exempt def deleteSenator(request, pk): # \"\"\" # to remove a", "@login_required def add_new_profile (request): \"\"\" To add details of new upcoming students in", "can delete the outdated timetable from the server. @param: request - contains metadata", "courses \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') course_list = sem_for_generate_sheet() if(course_list[0]==1): course_list_2 = [2,", "print(curriculum_courses) # courses = Course.objects.all() # course_type = Constants.COURSE_TYPE # context= { #", "\"\": specialization=\"None\" if hall_no == None: hall_no=3 else: hall_no=int(hall_no) programme_name=request.POST['Programme'] batch_year=request.POST['Batch'] batch =", "and request_programme==\"\": curriculum = None #Curriculum.objects.all() else: sem = sem_for_generate_sheet() now = datetime.datetime.now()", "get_calendar_details.from_date = from_date get_calendar_details.to_date = to_date get_calendar_details.save() except Exception as e: from_date=\"\" to_date=\"\"", "int(d[3]) # if request.method == \"POST\": # if(Grades.objects.filter(student_id=id, sem=sem)): # s = Grades.objects.filter(student_id=id,", "e.delete() # u.delete() # return JsonResponse(data)# ######################################################### # ''' # # view to", "acadadmin = temp.working # k = str(user_details).split() # print(k) # final_user = k[2]", "the acad admin # s - the student object from the requested rollno", "database and the update it. # \"\"\" if request.method==\"POST\": sem_cred = [] #", "- grade to be added in the student course - course ofwhich the", "to check if the student is available desig_id - mother's name of the", "7] # examTtForm = ExamTimetableForm() # acadTtForm = AcademicTimetableForm() # calendar = Calendar.objects.all()", "curriculum - Get data about curriculum from database courses - get courses from", "render(request,\"ais/ais.html\", context) # else: # return HttpResponseRedirect('/aims/') return HttpResponseRedirect('/aims/') def confirm_grades(request): # if", "name=\"Convenor\") c = get_object_or_404(Designation, name=\"Co Convenor\") # student = get_object_or_404(ExtraInfo, id=pk) # hDes", "contains convenor # c - the designation object that contains co convenor #", "contains metadata about the requested page @variables: sem - get current semester from", "form curriculum - curriculum details form database ins - Inster data in database", "application. It checkes the authentication of the user and also fetches the available", "s.hall_no = 1 # s.room_no = \"\" # s.save() # else: # return", "# print(student.address) # if not student: # data = {} # return JsonResponse(data)", "the server. @param: request - contains metadata about the requested page. @variables: data", "student from file last_name - details of student from file email - details", "grade sheet @variables: now - current datetime month - current month \"\"\" now", "fathers_name, mother_name = mothers_name, cpi = 0, category = category, hall_no = hall_no,", "2: sem = sem[year-int(request_batch)-1] else: sem = sem[year-int(request_batch)] sem+=1 curriculum = Curriculum.objects.select_related().filter(branch =", "output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": sem = request.POST.get('semester_no')", "timetable objects calendar - all the academic calender objects context - the datas", "= Constants.COURSE_TYPE html = render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj = json.dumps({'html':html}) #return render(request, \"ais/ais.html\", context) return", "= { # 'name': extraInfo.user.username, # 'rollno_convenor': extraInfo.id, # 'designation': hDes.designation.name, # }", "'acadTtForm': acadTtForm, 'examTtForm': examTtForm, 'courses': courses, 'courses_list': courses_list, 'course_type': course_type, 'exam': exam_t, 'timetable':", "for i in obj: if i.student_id.batch_id.year == int(batch): registered_courses.append(i) ans = [] for", "of next semester courses courses - all the courses in curriculum course_type -", "context) return render(request, \"ais/ais.html\", context) #Generate Attendance Sheet def sem_for_generate_sheet(): \"\"\" This function", "@csrf_exempt def add_convenor(request): # \"\"\" # to add a new student convenor/coconvenor #", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) return render(request, \"ais/ais.html\", context) # ####################################", "str(batch.year)) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20)", "from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if request.method", "- the extraInfo objects that holds the designation as a senator students -", "which is selected by the academic admin. # \"\"\" if request.method == \"POST\":", "'course_type': course_type, 'exam': exam_t, 'timetable': timetable, 'academic_calendar': calendar, 'next_sem_course': next_sem_courses, 'this_sem_course': this_sem_courses, 'curriculum':", "- Object of time table to be deleted \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "get current time year - getcurrent year batch - gets the batch from", "objects context - the datas to be displayed in the webpage this_sem_course -", "@variables: # s - the designation object that contains convenor # c -", "checking the designation of the current user # acadadmin - deatils of the", "# i.save() # return HttpResponseRedirect('/academic-procedures/') def min_cred(request): # \"\"\" # to set minimum", "# curriculum_courses = Curriculum.objects.filter(branch = branch).filter(batch = batch).filter(programme= programme).filter(sem = sem) # print(curriculum_courses)", "# course - get the course details # \"\"\" # current_user = get_object_or_404(User,", "Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # courses = Course.objects.all() # course_type = Constants.COURSE_TYPE # timetable = Timetable.objects.all()", "timetable objects calendar - all the academic calender objects department - all the", "'POST' and request.FILES: acadTtForm = AcademicTimetableForm(request.POST, request.FILES) if acadTtForm.is_valid(): acadTtForm.save() return render(request, \"ais/ais.html\",", "from database ans - Formatted Array to be converted to xlsx k -temporary", "registered_courses.append(i) ans = [] for i in registered_courses: k = [] k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name)", "from_date = from_date[0].split('-') from_date = [int(i) for i in from_date] from_date = datetime.datetime(*from_date).date()", "course_code=course_code, course_id=course_id, credits=credits, optional=optional, course_type=course_type, ) new_curr.append(ins) else: break i+=1 Curriculum.objects.bulk_create(new_curr) curriculum =", "final_user = k[2] except Exception as e: acadadmin=\"\" final_user=\"\" pass if (str(acadadmin) !=", "from form.REQUEST optional - optional from form.REQUEST course_type - course_type from form.REQUEST ins", "counter for Sl. No (in formated data) z - temporary array to add", "dele = Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete() curriculum = Curriculum.objects.select_related().filter(branch = request.POST['branch']).filter(batch = request.POST['batch']).filter(programme= request.POST['programme']) courses", "str(room) # student.save() # s = Student.objects.get(id=student) # s.father_name=father # s.mother_name=mother # s.hall_no", "== \"POST\": try: from_date = request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] from_date", "- the current batch of the student # programme - the programme the", "confirm_grades(request): # if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": #", "course_type, # 'curriculum_course': curriculum_courses, # } # return render(request, \"ais/ais.html\", context) # else:", "is used to decide curriculum for new batch. It checkes the authentication of", "from database to send to template @param: request - contains metadata about the", "contains metadata about the requested page @variables: request_batch - Batch from form request_branch", "DepartmentInfo) from .forms import AcademicTimetableForm, ExamTimetableForm, MinuteForm from .models import (Calendar, Course, Exam_timetable,", "object created in database desig - get designation object of student holds_desig -", "# \"\"\" if request.method==\"POST\": sem_cred = [] # sem_cred.append(0) # for i in", "request_programme = \"\" request_sem = \"\" #for checking if the user has searched", "True: if \"semester_\"+str(i) in request.POST: try: programme=request.POST['AddProgramme'] batch=request.POST['AddBatch'] branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name)", "obj = course_registration.objects.all().filter(course_id = course) except Exception as e: batch=\"\" course=\"\" curr_key=\"\" obj=\"\"", "me etc of a student # @param: # request - contains metadata about", "metadata about the requested page. @variables: f1,f2,f3 - temporary varibles faculty - details", "address - details of student from file department - details of student from", "write to xlsx file book - workbook of xlsx file title - formatting", "used to check the type of user. It checkes the authentication of the", "s or des.designation == c: # designation = des.designation.name # des.delete() # data", "filename = ' + course.code + '.xlsx' response['Content-Disposition'] = st return response @login_required", "as e: examTtForm = \"\" acadTtForm = \"\" calendar = \"\" this_sem_courses =", "4 num = 1 for i in data: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2]", "- the rollno of the student # batch - the current batch of", "'exam': exam_t, 'timetable': timetable, 'academic_calendar': calendar, 'next_sem_course': next_sem_courses, 'this_sem_course': this_sem_courses, 'curriculum': curriculum, 'pgstudent'", "the logged in user # user_details - the details of the current user", "choices = request.POST.getlist('choice') # for i in choices: # course = Course.objects.all().filter(course_id=i).first() #", "get_context(request) context['tab_id'][0]='6' if request.method == 'POST': try: request_batch = request.POST['batch'] request_branch = request.POST['branch']", "= ExamTimetableForm(request.POST, request.FILES) if examTtForm.is_valid(): examTtForm.save() return render(request, \"ais/ais.html\", context) else: return render(request,", "for i in faculty: faculty_list.append(i) return faculty_list @login_required def float_course(request): \"\"\" to float", "be converted to xlsx k -temporary array to add data to formatted array/variable", "courses, # 'course_type' : course_type, # 'curriculum' : curriculum, # 'tab_id' :['3','1'] #", "@param: request - contains metadata about the requested page @variables: batch - gets", "# 'curriculum' : curriculum, # 'tab_id' :['3','1'] # } courses = Course.objects.all() course_type", "s.father_name = \"\" # s.mother_name = \"\" # s.hall_no = 1 # s.room_no", "# e - the extraInfo objects of the student # user - the", "the authentication of the user and also fetches the available data from the", "# hDes = HoldsDesignation.objects.filter(user = student.user) # designation = [] # for des", "context={ 'tab_id' :['3','1'] } if request.method == 'POST': try: id=request.POST['id'] programme=request.POST['programme'] batch=request.POST['batch'] branch=request.POST['branch']", "return HttpResponseRedirect('/academic-procedures/') # return HttpResponseRedirect('/academic-procedures/') def add_optional(request): # \"\"\" # acadmic admin to", "fetches the available data from the databases to display it on the page.", "try: request_batch = request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme'] request_sem = request.POST['sem']", "acadTtForm - the form to add academic calender examTtForm - the form required", "# return HttpResponse(\"Unable to delete data\") return HttpResponse(\"Data Deleted SuccessFully\") @login_required def verify_grade(request):", "user. # desig_id - used to check the designation ID. # extraInfo -", "= len(assistant_list.filter(acad_approval = False)) assis_stat = Assistantship_status.objects.all() for obj in assis_stat: assistant_flag =", "the extraInfo objects of the student # user - the User object of", "selected by the academic admin. # \"\"\" if request.method == \"POST\": pass #", "from applications.globals.models import (Designation, ExtraInfo, HoldsDesignation, DepartmentInfo) from .forms import AcademicTimetableForm, ExamTimetableForm, MinuteForm", "data excel - excel file sheet - sheet no in excel file roll_no", "else: context= { 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context) context= { 'tab_id'", "temporary variables for final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') try: batch =", "# acadadmin - deatils of the acad admin # s - the student", "= [] # sem_cred.append(0) # for i in range(1, 10): # sem =", "name=\"Co Convenor\") # student = get_object_or_404(ExtraInfo, id=pk) # hDes = HoldsDesignation.objects.filter(user = student.user)", "from file programme - details of student from file batch - details of", "user_details - extract details of user from database desig_id - check for designation", "- current month \"\"\" now = datetime.datetime.now() month = int(now.month) if month >=", "current date from system year - current year batch - batch form form", "password='<PASSWORD>', first_name=first_name, last_name=last_name, email=email, ) einfo = ExtraInfo.objects.create( id=roll_no, user=user, title=title, sex=sex, date_of_birth=dob,", "credits - credits from form.REQUEST optional - optional from form.REQUEST course_type - course_type", "# course.save() # courses = Course.objects.all() # for i in courses: # if", "variable of subtitle the workbook normaltext - formatting variable for normal text sheet", "information that the particular student is a senator # \"\"\" pass # if", "str(final_user)): return True else: return False def get_context(request): \"\"\" This function gets basic", "programme=request.POST['programme'] batch=request.POST['batch'] branch=request.POST['branch'] sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"] if request.POST['optional'] == \"on\": optional=True", "request.method == 'POST': # print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") # rollno = request.POST.getlist('Roll Number')[0] # #", "# hDes.user = extraInfo.user # hDes.working = extraInfo.user # if result == \"Convenor\":", "- to get the details of the required user. # \"\"\" # current_user", "username,password, name, # rollno, etc of a student # @param: # request -", "output - io Bytes object to write to xlsx file book - workbook", "- course_type from form.REQUEST ins - data is stored in database \"\"\" if", "the requested page # @variables: # name - the name of the student", "semester courses next_sem_courses - the data of next semester courses courses - all", "the student is available desig_id - mother's name of the student acadadmin -", "# if request.method == 'POST': # print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") # rollno = request.POST.getlist('Roll Number')[0]", "registered_students.add(stu.student_id) students = Student.objects.filter(batch_id = batch_id) for stu in students: if stu not", "# context= { # 'grades': grades, # 'tab_id' :\"2\" # } # return", "last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value) if sex == 'F': title='Ms.' else: title='Mr.' dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode))", "course_type = Constants.COURSE_TYPE timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() pgstudent = Student.objects.filter(programme =", "all the academic calender objects department - all the departments in the college", "from applications.programme_curriculum.models import (CourseSlot, Course as Courses, Batch, Semester, Programme, Discipline) from applications.academic_procedures.views", "new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) elif request.POST['option'] == '2': new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme,", "\"\"\" # It deletes the grade of the student # @param: # request", "hDes.designation = s # else: # hDes.designation = p # hDes.save() # data", "database for the previous Description. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all()", "from file email - details of student from file sex - details of", "of the user. @param: request - contains metadata about the requested page @variables:", "sem_for_generate_sheet() now = datetime.datetime.now() year = int(now.year) if sem[0] == 2: sem =", "course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass ins=Curriculum( programme=programme, batch=batch, branch=branch, sem=sem, course_code=course_code, course_id=course_id,", "the requested page. @variables: data - data of delete dictionary in post request", "curriculum in database It checkes the authentication of the user and also fetches", "of the student acadadmin - student's address subject - subject of which the", "'center', 'valign': 'vcenter'}) sheet = book.add_worksheet() title_text = (\"Pre-registeration : \"+ batch.name +", "= True flot.save() new_curr_inst=[] for c,i in enumerate(request.POST.getlist(str(i)+'_fac')): inst = get_object_or_404(User, username =", "= Workbook(output,{'in_memory':True}) title = book.add_format({'bold': True, 'font_size': 22, 'align': 'center', 'valign': 'vcenter'}) subtitle", "= sem) # print(curriculum_courses) # courses = Course.objects.all() # course_type = Constants.COURSE_TYPE #", "father - father's name of the student # rollno - the rollno of", "is available desig_id - mother's name of the student acadadmin - student's address", "request_branch = request.POST['branch'] request_programme = request.POST['programme'] request_sem = request.POST['sem'] except Exception as e:", "procedures_context['result_year'], 'batch_grade_data' : procedures_context['batch_grade_data'], 'batch_branch_data' : procedures_context['batch_branch_data'], 'assistant_flag' : assistant_flag, 'hod_flag' : hod_flag,", "array to add data to formatted array/variable output - io Bytes object to", "\"POST\": name = request.POST.get('name') # roll = ExtraInfo.objects.get(id=request.POST.get('rollno')) # programme = request.POST.get('programme') #", "the student from the database # @param: # request - contains metadata about", "== \"POST\": pass # print(request.POST) # choices = request.POST.getlist('choice') # for i in", "s - designation object of Convenor # p - designation object of Co", "course_slot.courses.all() new_reg=[] for c in courses: reg=course_registration( course_id = c, semester_id=sem_id, student_id=stud_data )", "optional - optional from form.REQUEST course_type - course_type from form.REQUEST ins - data", "print(student.address) # if not student: # data = {} # return JsonResponse(data) #", "i in obj: if i.student_id.batch_id.year == int(batch): registered_courses.append(i) ans = [] for i", "details of student from file dob - details of student from file fathers_name", "# @csrf_exempt def delete_basic_profile(request, pk): # \"\"\" # Deletes the student from the", "= HoldsDesignation.objects.all().filter(designation = desig_id).first() # print (temp) # print (current_user) # acadadmin =", "\"\" and request_programme==\"\": curriculum = None #Curriculum.objects.all() else: sem = sem_for_generate_sheet() now =", "= request.POST['delete'] # d = data.split(\"-\") # id = d[0] # course =", "if form.is_valid(): # form.save() # return HttpResponse('sucess') # else: # return HttpResponse('not uploaded')", "working=user, designation=desig, ) sem_id = Semester.objects.get(curriculum = batch.curriculum, semester_no = sem) course_slots =", "sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',50) sheet.set_column('D:D',15) sheet.set_column('E:E',15) k = 4 num = 1 for i", "- batch from form.REQUEST branch - branch from form.REQUEST sem - semester from", "if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # curr_id=request.POST['course'] #", "\"\"\" acad-admin can upload the time table(any type of) of the semester. @param:", "# for i in range(1, 9): # sem = MinimumCredits.objects.all().filter(semester=i).first() # sem.credits =", "of student from file fathers_name - details of student from file mothers_name -", "This function is used to check the type of user. It checkes the", "the academic timetable objects calendar - all the academic calender objects context -", "currs - get curriculum details reg - create registeration object in registeration table", "the particualr student is # holding the convenor/coconvenor designation # student - the", "of Registered Students @param: request - contains metadata about the requested page @variables:", "pk - the primary key of the student's record in the database table", "examTtForm - the form required to add exam timetable Dean - the extraInfo", "context) return render(request, \"ais/ais.html\", context) @login_required def float_course_submit(request): \"\"\" to float courses for", "Not Exist\") # return HttpResponse(\"Data Deleted Successfully\") def add_advanced_profile(request): # \"\"\" # It", "= AcademicTimetableForm() if request.method == 'POST' and request.FILES: acadTtForm = AcademicTimetableForm(request.POST, request.FILES) if", "name of the student acadadmin - student's address subject - subject of which", "objects that holds the designation as a convenor CoConvenor - the extraInfo objects", "the requested page. @variables: examTtForm - data of delete dictionary in post request", "from file user - new user created in database einfo - new extrainfo", "profile################## # @csrf_exempt def add_basic_profile(request): # \"\"\" # It adds the basic profile", "all the courses in curriculum course_type - list the type of courses \"\"\"", "str(i)+\"_ccode\" in request.POST: if str(i)+\"_fac\" in request.POST: if request.POST[str(i)+\"_fac\"] == \"\" : logging.warning(\"No", "##########Senate meeting Minute################## # @csrf_exempt def addMinute(request): # \"\"\" # to add a", "else: # hDes.designation = p # hDes.save() # data = { # 'name':", "HttpResponseRedirect('/aims/') return HttpResponseRedirect('/aims/') def confirm_grades(request): # if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if", "len(assistant_list.filter(acad_approval = False)) assis_stat = Assistantship_status.objects.all() for obj in assis_stat: assistant_flag = obj.student_status", "- details of student from file title - details of student from file", "hDes = HoldsDesignation.objects.filter(user = student.user) # designation = [] # for des in", "# for des in hDes: # if des.designation == s or des.designation ==", "data about curriculum from database courses - get courses from database courses_type -", "else: course_list_2 = [1, 3, 5, 7] # examTtForm = ExamTimetableForm() # acadTtForm", "subtitle the workbook normaltext - formatting variable for normal text sheet - xlsx", "database.User must be logged in and must be acadadmin @param: request - contains", "curriculum, 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context)", "to an array. # sem - Get the object for the minimum credits", "= get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk')", "database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() context=", "# user_details - gets the details of the required user. # desig_id -", "== 'POST': try: request_batch = request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme'] request_sem", "render(request, \"ais/ais.html\", context) @login_required def add_curriculum(request): \"\"\" This function is used to add", "\"\"\" try: f1 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Assistant Professor\")) f2 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Professor\"))", "- excel file sheet - sheet no in excel file roll_no - details", "mother 's name of the student # acadadmin - student's address # final_user", "Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'faculty_list':", "= request.POST.get('batch') # ph = request.POST.get('phoneno') # if not Student.objects.filter(id=roll).exists(): # db =", "- extract details of user from database desig_id - check for designation acadadmin", "- current datetime month - current month \"\"\" now = datetime.datetime.now() month =", "- get course types from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context =", "= 4 num = 1 for i in data: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c =", "user. # user_details - to get the details of the required user. #", "des.designation.name # des.delete() # data = { # 'id': pk, # 'designation': designation,", "data to database # def curriculum(request): # ''' def delete_advanced_profile(request): # \"\"\" #", "of the student @param: request - contains metadata about the requested page @variables:", "function gets basic gata from database to send to template @param: request -", "e = get_object_or_404(ExtraInfo, id=pk) # user = get_object_or_404(User, username = e.user.username) # s", "False) assistant_approve_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(hod_approval = True) assistant_list_length =", "book.add_worksheet() title_text = (\"Pre-registeration : \"+ batch.name + str(\" \") + batch.discipline.acronym +", "designation=desig, ) sem_id = Semester.objects.get(curriculum = batch.curriculum, semester_no = sem) course_slots = CourseSlot.objects.all().filter(semester", "= k[2] # if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # print(request.POST['delete']) #", "assistant_approve_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(hod_approval = True) assistant_list_length = len(assistant_list.filter(acad_approval", "convenor CoConvenor - the extraInfo objects that holds the designation as a coconvenor", "'POST' and request.FILES: examTtForm = ExamTimetableForm(request.POST, request.FILES) if examTtForm.is_valid(): examTtForm.save() return render(request, \"ais/ais.html\",", "Professor\")) except Exception as e: f1=f2=f3=\"\" pass faculty = list(chain(f1,f2,f3)) faculty_list = []", "request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme'] request_sem = request.POST['sem'] except Exception as", "hDes.working = extraInfo.user # if result == \"Convenor\": # hDes.designation = s #", "@login_required def add_curriculum(request): \"\"\" This function is used to add new curriculum in", "{ 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) @login_required def add_timetable(request): \"\"\" acad-admin", "user. It checkes the authentication of the user. @param: request - contains metadata", "- contains metadata about the requested page @variables: programme - programme from form.REQUEST", "applications.programme_curriculum.models import (CourseSlot, Course as Courses, Batch, Semester, Programme, Discipline) from applications.academic_procedures.views import", "acad-admin can delete the outdated timetable from the server. @param: request - contains", "# p.delete() # else: # return HttpResponse(\"Unable to delete data\") return HttpResponse(\"Data Deleted", "# hDes.user = extraInfo.user # hDes.working = extraInfo.user # hDes.designation = s #", "of Convenor # p - designation object of Co Convenor # result -", "def delete_advanced_profile(request): # \"\"\" # to delete the advance information of the student", "# s.mother_name=mother # s.hall_no = hall # s.room_no = room # s.save() #", "of the student # roll - the rollno of the student # batch", "exam timtable of the ongoing semester. @param: request - contains metadata about the", "return render(request,\"ais/ais.html\", context) # else: # return HttpResponseRedirect('/aims/') return HttpResponseRedirect('/aims/') def confirm_grades(request): #", "the student to be hidden in the webpage # \"\"\" # s =", "in the database.User must be logged in and must be acadadmin @param: request", "- student's address subject - subject of which the grade has to be", "# st.phone_no = ph # db.save() # st.save() # data = { #", "in request.POST: if str(i)+\"_fac\" in request.POST: if request.POST[str(i)+\"_fac\"] == \"\" : logging.warning(\"No faculty\")", "result - the data that contains where the student will become # convenor", "optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) elif request.POST['option'] == '2': new_curriculum=[] for i in", "@login_required def edit_curriculum(request): \"\"\" This function is used to edit curriculum in database", "request.POST.getlist('prev_desc')[0] from_date = from_date[0].split('-') from_date = [int(i) for i in from_date] from_date =", "details of the current user. # desig_id - to check the designation of", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','2'] } if request.method == 'POST':", "of the semester. @param: request - contains metadata about the requested page. @variables:", "return False def get_context(request): \"\"\" This function gets basic gata from database to", "final_user - details of the user # sem - current semester of the", "dept, year = batch_year).first() user = User.objects.create_user( username=roll_no, password='<PASSWORD>', first_name=first_name, last_name=last_name, email=email, )", "unregistered_students: z = [] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('not", "dictionary in post request timetable - all timetable from database exam_t - all", "hall - hall no of where the student stays # room no -", "student # data - tag whether to delete it or not # course", "in and must be acadadmin @param: request - contains metadata about the requested", "Programme, Discipline) from applications.academic_procedures.views import acad_proced_global_context from applications.programme_curriculum.models import Batch @login_required def user_check(request):", "optional=False course_type=request.POST[\"course_type\"] except Exception as e: id=\"\" programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\"", "from io import BytesIO from xlsxwriter.workbook import Workbook from xhtml2pdf import pisa from", "event which is to be updated. get_calendar_details = Get the object of the", "# st.save() # data = { # 'name': name, # 'rollno': roll.id, #", "Course.objects.all() courses_list = Courses.objects.all() course_type = Constants.COURSE_TYPE timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all()", "d = data.split(\"-\") # id = d[0] # course = d[2] # sem", "# mother - mother's name of the student # add - student's address", "student from file hall_no - details of student from file programme - details", "designation as a senator students - all the objects in the Student class", "meeting minute object to the database. # @param: # request - contains metadata", "user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if request.method == \"POST\": dele =", "rollno=request.POST.get('roll') # print(rollno) # student = ExtraInfo.objects.get(id=rollno) # print(student.address) # if not student:", "= [] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('not registered') data.append(z)", "semester_id=sem_id, student_id=stud_data ) new_reg.append(reg) course_registration.objects.bulk_create(new_reg) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\",", "the update it. # \"\"\" if request.method==\"POST\": sem_cred = [] # sem_cred.append(0) #", "# 'rollno_convenor': extraInfo.id, # 'designation': hDes.designation.name, # } # return JsonResponse(data) # else:", "of student from file first_name - details of student from file last_name -", "# branch=request.POST['branch'] # sem=request.POST['sem'] # curriculum_courses = Curriculum.objects.filter(branch = branch).filter(batch = batch).filter(programme= programme).filter(sem", "- programme from form.REQUEST now - current date from system year - current", "in to_date] to_date = datetime.datetime(*to_date).date() except Exception as e: from_date=\"\" to_date=\"\" desc=\"\" pass", "exam_t = \"\" pass context = { 'acadTtForm': acadTtForm, 'examTtForm': examTtForm, 'courses': courses,", "about the requested page. @variables: profiles - gets the excel file having data", "int(now.year) if sem[0] == 2: sem = sem[year-int(request_batch)-1] else: sem = sem[year-int(request_batch)] sem+=1", "- data of the student to be hidden in the webpage # \"\"\"", "of Exam time table to be deleted \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if", "that a student must take # @param: # request - contains metadata about", "= True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(hod_approval = True) assistant_list_length = len(assistant_list.filter(acad_approval = False)) assis_stat", "sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',50) sheet.set_column('D:D',15) sheet.set_column('E:E',15) k = 4 num =", "request.FILES: examTtForm = ExamTimetableForm(request.POST, request.FILES) if examTtForm.is_valid(): examTtForm.save() return render(request, \"ais/ais.html\", context) else:", "from the position # @param: # request - contains metadata about the requested", "stores the # information that the particular student is a senator # \"\"\"", "is added \"\"\" # if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if request.method ==", "request - contains metadata about the requested page. @variables: from_date - The starting", "the student stays # room no - hostel room no # \"\"\" current_user", "return True else: return False def get_context(request): \"\"\" This function gets basic gata", "HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Associate Professor\")) except Exception as e: f1=f2=f3=\"\" pass faculty = list(chain(f1,f2,f3))", "HttpResponseRedirect('/academic-procedures/') def min_cred(request): # \"\"\" # to set minimum credit for a current", "contains metadata about the requested page. @variables: data - data of delete dictionary", "@param: request - contains metadata about the requested page. @variables: data - data", "hod_flag, 'account_flag' : account_flag } return context @login_required def homepage(request): \"\"\" This function", "# else: # return render(request, \"ais/ais.html\") return render(request, \"ais/ais.html\") def delete_grade(request): # \"\"\"", "batch=request.POST['AddBatch'] branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)] if \"optional_\"+str(i) in request.POST: optional=True else:", "requested page # @variables: # name - the name of the student #", "page @variables: senates - the extraInfo objects that holds the designation as a", "object of the student with that rollno # s - designation object of", "sem=sem, course_code=course_code, course_id=course_id, credits=credits, optional=optional, course_type=course_type, ) new_curr.append(ins) else: break i+=1 Curriculum.objects.bulk_create(new_curr) curriculum", "- formatting variable for normal text sheet - xlsx sheet to be rendered", ":['3','2'] } if request.method == 'POST': i=0 new_curr=[] while True: if \"semester_\"+str(i) in", "\"+ batch.name + str(\" \") + batch.discipline.acronym + str(\" \") + str(batch.year)) sheet.set_default_row(25)", "get_object_or_404(User, username = i) inst = ExtraInfo.objects.select_related('user','department').get(user=inst) if c==0: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=True,", "@login_required def delete_curriculum(request): \"\"\" This function is used to delete curriculum entry in", "# } # return JsonResponse(data) # else: # data = {} # return", "timetable = \"\" exam_t = \"\" pass context = { 'acadTtForm': acadTtForm, 'examTtForm':", "basic profile################## # @csrf_exempt def add_basic_profile(request): # \"\"\" # It adds the basic", "all the departments in the college attendance - all the attendance objects of", "calender examTtForm - the form required to add exam timetable exam_t - all", "username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp =", "curriculum course_type - list the type of courses \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "# rollno - rollno of the student to become the convenor/coconvenor # extraInfo", "to the academic calendar to be updated. @param: request - contains metadata about", "sem.save() # return HttpResponse(\"Worked\") def view_course(request): # if request.method == \"POST\": # programme=request.POST['programme']", "thsi semester courses next_sem_courses - the data of next semester courses courses -", "roll.id, # 'programme': programme, # 'phoneno': ph, # 'batch': batch # } #", "sheet.set_column('E:E',30) k = 4 num = 1 for i in ans: sheet.write_number('A'+str(k),num,normaltext) num+=1", "= get_object_or_404(User, username=request.user.username) user_details = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp =", "Successfully\") def add_advanced_profile(request): # \"\"\" # It adds the advance profile information like", "s = get_object_or_404(Student, id=e) # data = { # 'rollno': pk, # }", "e: request_batch = \"\" request_branch = \"\" request_programme = \"\" request_sem = \"\"", "in the webpage # \"\"\" s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor')", "# programme = request.POST.get('programme') # batch = request.POST.get('batch') # ph = request.POST.get('phoneno') #", "return render(request, \"ais/ais.html\", context) def get_faculty_list(): \"\"\" to get faculty list from database", "requested page. @variables: acadTtForm - data of delete dictionary in post request timetable", "{} # return JsonResponse(data) # else: # father = request.POST.get('father') # mother =", "# s.hall_no = hall # s.room_no = room # s.save() # return HttpResponseRedirect('/academic-procedures/')", "\"+str(c) temp = str(i[3]).split() dep = str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext) k+=1 book.close() output.seek(0)", "get_object_or_404(User, username=request.user.username) user_details = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation", "data of delete dictionary in post request t - Object of time table", "JsonResponse(data) # else: # data = {} # return JsonResponse(data) # @csrf_exempt def", "ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=False, ) new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst) else: break i+=1 return render(request, \"ais/ais.html\",", "curriculum_courses = Curriculum.objects.filter(branch = branch).filter(batch = batch).filter(programme= programme).filter(sem = sem) # print(curriculum_courses) #", "acadTtForm = AcademicTimetableForm() # calendar = Calendar.objects.all() # this_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # next_sem_courses", "def generate_preregistration_report(request): \"\"\" to generate preresgistration report after pre-registration @param: request - contains", "flot = Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated = True flot.save() new_curr_inst=[] for c,i in enumerate(request.POST.getlist(str(i)+'_fac')): inst", "# 'batch': batch # } # print(data) # return JsonResponse(data) # else: #", "requested page. @variables: from_date - The starting date for the academic calendar event.", "JsonResponse(data) # else: # data = {} # return JsonResponse(data) # else: #", "get_context(request) return render(request, \"ais/ais.html\", context) # #################################### # # curriculum # # ####################################", "the designation as a convenor CoConvenor - the extraInfo objects that holds the", "if the student is available desig_id - mother's name of the student acadadmin", "st = 'attachment; filename = ' + course.code + '.xlsx' response['Content-Disposition'] = st", "'tab_id' :['10','1'] } acadTtForm = AcademicTimetableForm() if request.method == 'POST' and request.FILES: acadTtForm", "designation ID. # extraInfo - extraInfo object of the student with that rollno", "# c - the designation object that contains co convenor # student -", "database obj - get stdents data from database ans - Formatted Array to", "# return HttpResponseRedirect('/academic-procedures/') # print(request.POST['delete']) # data = request.POST['delete'] # d = data.split(\"-\")", "= \"\" exam_t = \"\" pass context = { 'acadTtForm': acadTtForm, 'examTtForm': examTtForm,", "# if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\":", "designation of the user. # user_details - to get the details of the", "- rollno of the student to become the convenor/coconvenor # extraInfo - extraInfo", "a senator # \"\"\" pass # if request.POST: # s = get_object_or_404(Designation, name=\"Senator\")", "'grades': grades, # 'tab_id' :\"2\" # } # return render(request,\"ais/ais.html\", context) # else:", "sem=request.POST['sem'] # curriculum_courses = Curriculum.objects.filter(branch = branch).filter(batch = batch).filter(programme= programme).filter(sem = sem) #", "def add_exam_timetable(request): \"\"\" acad-admin can upload the exam timtable of the ongoing semester.", "father's name of the student user_details - the rollno of the student required", "roll_no - details of student from file first_name - details of student from", "- get courses from database courses_type - get course types from database \"\"\"", "sheet = book.add_worksheet() title_text = ((str(course.name)+\" : \"+str(str(batch)))) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl.", "= MinimumCredits.objects.all().filter(semester=i).first() # sem.credits = sem_cred[i+1] # sem.save() # return HttpResponse(\"Worked\") def view_course(request):", "else: # return HttpResponse(\"Data Does Not Exist\") # return HttpResponse(\"Data Deleted Successfully\") def", "obj - get stdents data from database ans - Formatted Array to be", "'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) sheet = book.add_worksheet() title_text = ((str(course.name)+\" :", "the page. @param: request - contains metadata about the requested page @variables: dele", "student: # data = {} # return JsonResponse(data) # else: # father =", "= request.POST.getlist('description')[0] from_date = from_date[0].split('-') from_date = [int(i) for i in from_date] from_date", "float courses for the next sem and store data in databsae. User must", "the particular student is a convenor/coconvenor to be deleted # data - data", "request - contains metadata about the requested page. @variables: acadTtForm - data of", "Designation.objects.get(name='Co Convenor') # if request.method == 'POST': # rollno = request.POST.get('rollno_convenor') # extraInfo", "k = 4 num = 1 for i in data: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c", "# for i in choices: # course = Course.objects.all().filter(course_id=i).first() # course.acad_selection = True", "'vcenter'}) sheet = book.add_worksheet() title_text = ((str(course.name)+\" : \"+str(str(batch)))) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title)", "def deleteConvenor(request, pk): # \"\"\" # to remove a convenor/coconvenor from the position", "contains metadata about the requested page. @variables: from_date - The starting date for", "if request.method == 'POST': # rollno = request.POST.get('rollno_convenor') # extraInfo = ExtraInfo.objects.get(id=rollno) #", "current semester of the student # data - tag whether to delete it", "of the acad admin # s - the student object from the requested", "get course types from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request)", "check the designation ID. # extraInfo - extraInfo object of the student with", "\"Assistant Professor\")) f2 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Professor\")) f3 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Associate Professor\"))", "student's address # cpi - student's cpi # hall - hall no of", "email=email, ) einfo = ExtraInfo.objects.create( id=roll_no, user=user, title=title, sex=sex, date_of_birth=dob, address=address, phone_no=phone_no, user_type='student',", "= extraInfo.user # hDes.designation = s # hDes.save() # student = Student.objects.get(id=extraInfo) #", "programme the student is enrolled in # ph - the phone number of", "sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] name = str(b)+\" \"+str(c) temp = str(i[3]).split() dep", "return render(request, \"ais/ais.html\", context) @login_required def add_timetable(request): \"\"\" acad-admin can upload the time", "= get_context(request) return render(request, \"ais/ais.html\", context) # #################################### # # curriculum # #", "User from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import get_object_or_404, render from", "the student @param: request - contains metadata about the requested page @variables: current_user", "- data being deleted from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id'", "be displayed in teh webpage # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) #", "None #Curriculum.objects.all() else: if int(request_sem) == 0: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch =", "course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)] if \"optional_\"+str(i) in request.POST: optional=True else: optional=False course_type=request.POST[\"course_type_\"+str(i)] except", "hDes.user = extraInfo.user # hDes.working = extraInfo.user # hDes.designation = s # hDes.save()", "designation object of student holds_desig - get hold_desig object of student currs -", "data = { # 'name': name, # 'rollno': roll.id, # 'programme': programme, #", "+ course.code + '.xlsx' response['Content-Disposition'] = st return response @login_required def generate_preregistration_report(request): \"\"\"", "this_sem_course - tha data of thsi semester courses next_sem_courses - the data of", "== \"POST\": # if(Grades.objects.filter(student_id=id, sem=sem)): # s = Grades.objects.filter(student_id=id, sem=sem) # for p", "from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import get_object_or_404, render from django.template.loader", "i in faculty: faculty_list.append(i) return faculty_list @login_required def float_course(request): \"\"\" to float courses", "the database table # @variables: # e - the extraInfo objects of the", "sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st", "the student acadadmin - student's address subject - subject of which the grade", "= sem_for_generate_sheet() now = datetime.datetime.now() year = int(now.year) if sem[0] == 2: sem", "the student # roll - the rollno of the student # batch -", "students - all the objects in the Student class Convenor - the extraInfo", "= request.POST.get('room') # cpi = request.POST.get('cpi') # student.address = str(hall) + \" \"", "student from file sex - details of student from file title - details", "next sem and store data in databsae. User must be logged in and", "# k = str(user_details).split() # print(k) # final_user = k[2] # if (str(acadadmin)", "from form.REQUEST ins - data is stored in database \"\"\" if user_check(request): return", "has to be added sem - semester of the student grade - grade", "# \"\"\" # to set minimum credit for a current semester that a", "sem - stores the next semester obj - All the registration details appended", "courses = Course.objects.all() # course_type = Constants.COURSE_TYPE # context= { # 'courses': courses,", "@login_required def add_calendar(request): \"\"\" to add an entry to the academic calendar to", "Student, Student_attendance, Timetable,Curriculum) from applications.programme_curriculum.models import (CourseSlot, Course as Courses, Batch, Semester, Programme,", "of student from file email - details of student from file sex -", "ph = request.POST.get('phoneno') # if not Student.objects.filter(id=roll).exists(): # db = Student() # st", "# if request.method == \"POST\": # print(\"confirm hone wala hai\") # print(request.POST) return", "to be converted to xlsx k -temporary array to add data to formatted", "return response @login_required def generate_preregistration_report(request): \"\"\" to generate preresgistration report after pre-registration @param:", "post request t - Object of Exam time table to be deleted \"\"\"", "} examTtForm = ExamTimetableForm() if request.method == 'POST' and request.FILES: examTtForm = ExamTimetableForm(request.POST,", "HttpResponseRedirect('/academic-procedures/') timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable': timetable,", "desig_id).first() #print (temp) # print (current_user) # acadadmin = temp.working # k =", "[int(i) for i in to_date] to_date = datetime.datetime(*to_date).date() except Exception as e: from_date=\"\"", "= Grades.objects.filter(student_id=id, sem=sem) # for p in s: # if (str(p.course_id) == course):", "import logging from io import BytesIO from xlsxwriter.workbook import Workbook from xhtml2pdf import", "of the student user_details - the rollno of the student required to check", "minimum credit for a current semester that a student must take # @param:", "# d = data.split(\"-\") # id = d[0] # course = d[2] #", "= sem[year-int(request_batch)-1] else: sem = sem[year-int(request_batch)] sem+=1 curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch =", "stored in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if", "\"Associate Professor\")) except Exception as e: f1=f2=f3=\"\" pass faculty = list(chain(f1,f2,f3)) faculty_list =", "- holdsDesignation object to store that the particualr student is # holding the", "courses - all the courses in curriculum course_type - list the type of", "return context @login_required def homepage(request): \"\"\" This function is used to set up", "holds the designation as a coconvenor meetings - the all meeting objects held", "output = BytesIO() book = Workbook(output,{'in_memory':True}) title = book.add_format({'bold': True, 'font_size': 22, 'align':", "the requested page @variables: dele - data being deleted from database \"\"\" if", "course_type = Constants.COURSE_TYPE # context= { # 'courses': courses, # 'course_type': course_type, #", "= Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses = Course.objects.all() courses_list = Courses.objects.all() course_type = Constants.COURSE_TYPE timetable =", "= k[2] # if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method", "the extraInfo objects that holds the designation as a convenor CoConvenor - the", "in to_date] to_date = datetime.datetime(*to_date).date() get_calendar_details = Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description = desc get_calendar_details.from_date =", "students in the database.User must be logged in and must be acadadmin @param:", "- holdsDesignation object to store that the particualr student is holding the senator", "= request.POST['delete'] # t = Meeting.objects.get(id=data) # t.delete() return HttpResponseRedirect('/aims/') # # ######################################################", "= \"Associate Professor\")) except Exception as e: f1=f2=f3=\"\" pass faculty = list(chain(f1,f2,f3)) faculty_list", "to_date=\"\" desc=\"\" return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) #Generate Attendance Sheet", "Number')[0] # # print(request.POST.get('rollno')) # extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Senator') #", "attendance data to database # def curriculum(request): # ''' def delete_advanced_profile(request): # \"\"\"", "context= { # 'grades': grades, # 'tab_id' :\"2\" # } # return render(request,\"ais/ais.html\",", "of the student required to check if the student is available desig_id -", "form.REQUEST branch - branch from form.REQUEST sem - semester from form.REQUEST course_code -", "deleteConvenor(request, pk): # \"\"\" # to remove a convenor/coconvenor from the position #", "rollno - rollno of the student to become the convenor/coconvenor # extraInfo -", "variable of title the workbook subtitle - formatting variable of subtitle the workbook", "# @csrf_exempt def senator(request): # \"\"\" # to add a new student senator", "s.save() # else: # return HttpResponse(\"Data Does Not Exist\") # return HttpResponse(\"Data Deleted", "extraInfo objects of the student # user - the User object of the", "the student with that rollno # s - designation object of senator #", "object to be deleted # t - the minute object received from id", "specialization, curr_semester_no=sem, ) desig = Designation.objects.get(name='student') hold_des = HoldsDesignation.objects.create( user=user, working=user, designation=desig, )", "details of student from file batch - details of student from file user", "to see curriculum and edit entries in a curriculum. It checkes the authentication", "request - contains metadata about the requested page. # @variables: # choices -", "sem) # print(curriculum_courses) # courses = Course.objects.all() # course_type = Constants.COURSE_TYPE # context=", "to be deleted \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": data", "= str(hall) + \" \" + str(room) # student.save() # s = Student.objects.get(id=student)", "for the academic calendar event. prev_desc - Description for the previous event which", "about the requested page. @variables: from_date - The starting date for the academic", "calendar event. prev_desc - Description for the previous event which is to be", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": sem = request.POST.get('semester_no') batch_id=request.POST.get('batch_branch') batch", "sheet - xlsx sheet to be rendered titletext - formatting variable of title", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) context['tab_id'][0]='6' if request.method == 'POST': try:", "- Formatted Array to be converted to xlsx k -temporary array to add", "= False)) assis_stat = Assistantship_status.objects.all() for obj in assis_stat: assistant_flag = obj.student_status hod_flag", "datetime.datetime.now() year = int(now.year) batch = year-1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme =", "courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type, 'curriculum':", "data of the student to be displayed in the webpage # \"\"\" s", "form request_branch - Branch from form request_programme - Programme from form request_sem -", "Formatted Array to be converted to xlsx k -temporary array to add data", "context = get_context(request) context['tab_id'][0]='6' if request.method == 'POST': try: request_batch = request.POST['batch'] request_branch", "== '2': new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code,", "curriculum = None #Curriculum.objects.all() else: sem = sem_for_generate_sheet() now = datetime.datetime.now() year =", "the student # \"\"\" e = get_object_or_404(ExtraInfo, id=pk) # user = get_object_or_404(User, username", "Constants.COURSE_TYPE timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() pgstudent = Student.objects.filter(programme = \"M.Tech\") |", "and also fetches the available data from the databases to display it on", "excel - excel file sheet - sheet no in excel file roll_no -", "optional=\"\" course_type=\"\" pass ins=Curriculum( programme=programme, batch=batch, branch=branch, sem=sem, course_code=course_code, course_id=course_id, credits=credits, optional=optional, course_type=course_type,", "if request.method == 'POST' and request.FILES: profiles=request.FILES['profiles'] excel = xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) for i", "django.shortcuts import get_object_or_404, render from django.template.loader import get_template from django.views.decorators.csrf import csrf_exempt from", "sem = MinimumCredits.objects.all().filter(semester=i).first() # sem.credits = sem_cred[i+1] # sem.save() # return HttpResponse(\"Worked\") def", "the academic calendar event. prev_desc - Description for the previous event which is", "request - contains metadata about the requested page # @variables: # name -", "metadata about the requested page @variables: programme - programme from form.REQUEST batch -", "request - contains metadata about the requested page. @variables: examTtForm - data of", "courses = \"\" course_type = \"\" timetable = \"\" exam_t = \"\" pass", "= fathers_name, mother_name = mothers_name, cpi = 0, category = category, hall_no =", "title the workbook subtitle - formatting variable of subtitle the workbook normaltext -", "= [2, 4, 6, 8] else: course_list_2 = [1, 3, 5, 7] #", "optional from form.REQUEST course_type - course_type from form.REQUEST ins - data is stored", "curr_key - gets the curriculum from database obj - get stdents data from", "'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context)", "student - the student object of the new senator # data - data", "Course.objects.all() # course_type = Constants.COURSE_TYPE # timetable = Timetable.objects.all() # exam_t = Exam_timetable.objects.all()", "# @param: # request - contains metadata about the requested page # @variables:", "of student from file programme - details of student from file batch -", "year-1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) if request.POST['option'] == '1': new_curriculum=[]", "if not Student.objects.filter(id=roll).exists(): # db = Student() # st = ExtraInfo.objects.get(id=roll.id) # db.name", "batch - the current batch of the student # programme - the programme", "variables for final output b - temporary variables for final output c -", "- details of student from file mothers_name - details of student from file", "# pk - the primary key of that particular student field # @variables:", "i in range(1, 9): # sem = MinimumCredits.objects.all().filter(semester=i).first() # sem.credits = sem_cred[i+1] #", "request.POST.get('cpi') # student.address = str(hall) + \" \" + str(room) # student.save() #", "# timetable = Timetable.objects.all() # exam_t = Exam_timetable.objects.all() procedures_context = acad_proced_global_context() try: examTtForm", "\"\"\" to get faculty list from database @param: request - contains metadata about", "object that contains convenor # c - the designation object that contains co", "list the type of courses \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') course_list = sem_for_generate_sheet()", "time year - getcurrent year batch - gets the batch from form sem", "# 'rollno': pk, # } # s.delete() # e.delete() # u.delete() # return", "sem_id = Semester.objects.get(curriculum = batch.curriculum, semester_no = sem) course_slots = CourseSlot.objects.all().filter(semester = sem_id)", "curriculum(request): \"\"\" This function is used to see curriculum and edit entries in", "of the student to be displayed in teh webpage # \"\"\" # current_user", "about curriculum from database courses - get courses from database courses_type - get", "= HoldsDesignation() # hDes.user = extraInfo.user # hDes.working = extraInfo.user # if result", "xlsxwriter.workbook import Workbook from xhtml2pdf import pisa from itertools import chain from django.contrib.auth.models", "the student # user - the User object of the student # s", "specialization == \"\": specialization=\"None\" if hall_no == None: hall_no=3 else: hall_no=int(hall_no) programme_name=request.POST['Programme'] batch_year=request.POST['Batch']", "about the requested page. # @variables: # sem_cred = Get credit details from", "# request - contains metadata about the requested page # @variables: # current_user", "admin to update the additional courses # @param: # request - contains metadata", "e.user.username) # s = get_object_or_404(Student, id=e) # data = { # 'rollno': pk,", "# else: # return HttpResponseRedirect('/aims/')# #################################################### # # ##########covenors and coconvenors################## # @csrf_exempt", "academic calendar to be updated. @param: request - contains metadata about the requested", "details # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() #", "= \"Assistant Professor\")) f2 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Professor\")) f3 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Associate", "is available # desig_id - mother 's name of the student # acadadmin", "course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass ins=Curriculum( programme=programme, batch=batch, branch=branch, sem=sem, course_code=course_code, course_id=course_id, credits=credits,", "# \"\"\" # It adds the basic profile information like username,password, name, #", "the current user # desig_id - checking the designation of the current user", "Calendar.objects.all() this_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses = Course.objects.all() courses_list = Courses.objects.all()", "Student.objects.get(id=stu) # s.father_name = \"\" # s.mother_name = \"\" # s.hall_no = 1", "registered_students = set() unregistered_students = set() for stu in obj: registered_students.add(stu.student_id) students =", "details of student from file title - details of student from file dob", "be deleted # data - data of the student to be hidden in", "metadata about the requested page @variables: current_user - father's name of the student", "Student.objects.filter(batch_id = batch_id) for stu in students: if stu not in registered_students: unregistered_students.add(stu)", "file phone_no - details of student from file address - details of student", "name=\"Senator\") # student = get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0]) # hDes = get_object_or_404( HoldsDesignation, user =", "courses # @param: # request - contains metadata about the requested page. #", "\"\"\" # if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": #", "exam timetable from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') timetable = Timetable.objects.all() exam_t", "- all the academic calender objects context - the datas to be displayed", "report after pre-registration @param: request - contains metadata about the requested page @variables:", "course_type - course_type from form.REQUEST ins - data is stored in database \"\"\"", "course_type = Constants.COURSE_TYPE html = render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj = json.dumps({'html':html}) #return render(request, \"ais/ais.html\", context)", "course-name from form.REQUEST course_id - course_id from database credits - credits from form.REQUEST", "# father - father's name of the student # rollno - the rollno", "name of the student # add - student's address # cpi - student's", "logging.warning(\"No faculty\") else: flot = Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated = True flot.save() new_curr_inst=[] for c,i", "# courses = Course.objects.all() # course_type = Constants.COURSE_TYPE # context= { # 'courses':", "is enrolled in # ph - the phone number of the student #", "curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).order_by('sem') else: curriculum = Curriculum.objects.select_related().filter(branch =", "courses = Course.objects.all() # course_type = Constants.COURSE_TYPE # timetable = Timetable.objects.all() # exam_t", "# father = request.POST.get('father') # mother = request.POST.get('mother') # add = request.POST.get('address') #", "the student with that rollno # s - designation object of Convenor #", "\"\"\" # to set minimum credit for a current semester that a student", "# acadadmin - deatils of the acad admin # father - father's name", "# # view to add attendance data to database # def curriculum(request): #", "file roll_no - details of student from file first_name - details of student", "\"ais/ais.html\", context) # else: # return render(request, \"ais/ais.html\") return render(request, \"ais/ais.html\") def delete_grade(request):", "a new senate meeting minute object to the database. # @param: # request", "= desc get_calendar_details.from_date = from_date get_calendar_details.to_date = to_date get_calendar_details.save() except Exception as e:", "= programme_name, discipline__acronym = dept, year = batch_year).first() user = User.objects.create_user( username=roll_no, password='<PASSWORD>',", "deletes the grade of the student # @param: # request - contains metadata", "entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme entry.batch=batch entry.branch=branch entry.sem=sem entry.course_code=course_code entry.course_id=course_id entry.credits=credits entry.optional=optional entry.course_type=course_type entry.save() curriculum =", "print(request.POST.get('rollno')) # extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Senator') # hDes = HoldsDesignation()", "from django.template.loader import get_template from django.views.decorators.csrf import csrf_exempt from django.template.loader import render_to_string from", "add details of new upcoming students in the database.User must be logged in", "designation # student - the student object of the new senator # data", "HttpResponseRedirect('/aims/')# #################################################### # # ##########covenors and coconvenors################## # @csrf_exempt def add_convenor(request): # \"\"\"", "credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) elif request.POST['option'] == '2': new_curriculum=[] for i", "\"\"\" to update an entry to the academic calendar to be updated. @param:", "sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',50)", "'account_flag' : account_flag } return context @login_required def homepage(request): \"\"\" This function is", "obj.hod_status account_flag = obj.account_status except Exception as e: examTtForm = \"\" acadTtForm =", "the requested page # @variables: # current_user - details of the current user.", "the page. @param: request - contains metadata about the requested page @variables: programme", "# hDes.working = extraInfo.user # hDes.designation = s # hDes.save() # student =", "course) except Exception as e: batch=\"\" course=\"\" curr_key=\"\" obj=\"\" registered_courses = [] for", "@variables: profiles - gets the excel file having data excel - excel file", "# else: # return HttpResponseRedirect('/aims/') # @csrf_exempt def deleteSenator(request, pk): # \"\"\" #", "get_object_or_404(ExtraInfo, id=pk) # user = get_object_or_404(User, username = e.user.username) # s = get_object_or_404(Student,", "programme=programme, batch=batch, branch=branch, sem=sem, course_code=course_code, course_id=course_id, credits=credits, optional=optional, course_type=course_type, ) new_curr.append(ins) else: break", "acadadmin @param: request - contains metadata about the requested page. @variables: profiles -", "requested page # @variables: # data - the id of the minute object", "senator(request): # \"\"\" # to add a new student senator # @param: #", "faculty_list - list of faculty \"\"\" try: f1 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Assistant Professor\"))", "'batch': batch # } # print(data) # return JsonResponse(data) # else: # data", "ph, # 'batch': batch # } # print(data) # return JsonResponse(data) # else:", "designation object of senator # hDes - holdsDesignation object to store that the", "Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() # print (temp) # print (current_user)", "= \"\" acadTtForm = \"\" calendar = \"\" this_sem_courses = \"\" next_sem_courses =", "to add data to formatted array/variable output - io Bytes object to write", "formatted array/variable output - io Bytes object to write to xlsx file book", "- get the course details # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) #", "z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('not registered') data.append(z) for i in registered_students: z =", "the grade is added \"\"\" # if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if", "} # return HttpResponseRedirect('/aims/') # # return JsonResponse(data) # else: # return HttpResponseRedirect('/aims/')", "# return HttpResponse(\"Data Deleted Successfully\") def add_advanced_profile(request): # \"\"\" # It adds the", "store that the particualr student is holding the senator designation # student -", "contains metadata about the requested page @variables: batch - gets the batch course", "- all exam timetable from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') timetable =", "if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # print(\"confirm hone", "# sem = \"sem_\"+\"1\" # sem_cred.append(request.POST.getlist(sem)[0]) # for i in range(1, 9): #", "page. @variables: profiles - gets the excel file having data excel - excel", "the academic calendar event. to_date - The ending date for the academic caldendar", "(str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST': # print(request.POST,", "= Constants.COURSE_TYPE # timetable = Timetable.objects.all() # exam_t = Exam_timetable.objects.all() procedures_context = acad_proced_global_context()", "ongoing semester. @param: request - contains metadata about the requested page. @variables: examTtForm", "\"\"\" try: current_user = get_object_or_404(User, username=request.user.username) user_details = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id = Designation.objects.all().filter(name='Upper Division", "'tab_id' :['3','2'] } if request.method == 'POST': i=0 new_curr=[] while True: if \"semester_\"+str(i)", "z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('registered') data.append(z) output = BytesIO()", "desig_id = Designation.objects.all().filter(name='Upper Division Clerk') # temp = HoldsDesignation.objects.all().filter(designation = desig_id).first() # print", "ans: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] name = str(b)+\" \"+str(c) temp = str(i[3]).split()", "- the designation object that contains convenor # c - the designation object", "str(b)+\" \"+str(c) temp = str(i[3]).split() dep = str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext) k+=1 book.close()", "= obj.hod_status account_flag = obj.account_status except Exception as e: examTtForm = \"\" acadTtForm", "+ str(\" \") + batch.discipline.acronym + str(\" \") + str(batch.year)) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text,", "context) @login_required def float_course_submit(request): \"\"\" to float courses for the next sem and", "get_object_or_404(Designation, name=\"Co Convenor\") # student = get_object_or_404(ExtraInfo, id=pk) # hDes = HoldsDesignation.objects.filter(user =", "request.POST['delete'] # t = Meeting.objects.get(id=data) # t.delete() return HttpResponseRedirect('/aims/') # # ###################################################### #", "course_type = Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','1']", "add_exam_timetable(request): \"\"\" acad-admin can upload the exam timtable of the ongoing semester. @param:", "t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def delete_exam_timetable(request): \"\"\" acad-admin can delete the outdated", "# @variables: # rollno - rollno of the student to become the convenor/coconvenor", "student @param: request - contains metadata about the requested page @variables: current_user -", "def add_basic_profile(request): # \"\"\" # It adds the basic profile information like username,password,", "student must take # @param: # request - contains metadata about the requested", "extraInfo - extraInfo object of the student with that rollno # s -", "branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) batch=batch+1 curriculum =", "to database # def curriculum(request): # ''' def delete_advanced_profile(request): # \"\"\" # to", "5, 7] else: return [2, 4, 6, 8] @login_required def generatexlsheet(request): \"\"\" to", "'tab_id' :['5','1'] } if request.method == 'POST': try: request_batch = request.POST['batch'] request_branch =", "of the minute object to be deleted # t - the minute object", "a senator # hDes - the holdDesignation object that stores the # information", "from file specialization - details of student from file hall_no - details of", "of the student # rollno - the rollno of the student required to", "\"POST\": # st = request.POST['delete'] # arr = st.split(\"-\") # stu = arr[0]", "# choices - selected addtional courses by the academic person. # course -", "Curriculum_Instructor,Constants, Meeting, Student, Student_attendance, Timetable,Curriculum) from applications.programme_curriculum.models import (CourseSlot, Course as Courses, Batch,", "obj: if i.student_id.batch_id.year == int(batch): registered_courses.append(i) ans = [] for i in registered_courses:", "return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": data = request.POST['delete'] t = Timetable.objects.get(time_table=data) t.delete()", "-temporary array to add data to formatted array/variable output - io Bytes object", "sem - current semester of the student # data - tag whether to", "CoConvenor - the extraInfo objects that holds the designation as a coconvenor meetings", "- Course details which is selected by the academic admin. # \"\"\" if", "the particualr student is holding the senator designation # student - the student", "# # curriculum # # #################################### @login_required def curriculum(request): \"\"\" This function is", "render(request, \"ais/ais.html\", context) @login_required def delete_timetable(request): \"\"\" acad-admin can delete the outdated timetable", "optional=True else: optional=False course_type=request.POST[\"course_type\"] except Exception as e: id=\"\" programme=\"\" batch=\"\" branch=\"\" sem=\"\"", "be displayed in the webpage this_sem_course - tha data of thsi semester courses", "page # @variables: # current_user - the username of the logged in user", "num+=1 z,b,c = str(i[0]),i[1],i[2] a,b,c,d,e = str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp = str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext)", "- student's cpi # hall - hall no of where the student stays", "# return HttpResponseRedirect('/academic-procedures/') # return HttpResponseRedirect('/academic-procedures/') def add_optional(request): # \"\"\" # acadmic admin", "grades of the student @param: request - contains metadata about the requested page", "# @variables: # choices - selected addtional courses by the academic person. #", "table(any type of) of the semester. @param: request - contains metadata about the", "courses = Course.objects.all() # for i in courses: # if i.course_id not in", "render(request, \"ais/ais.html\") return render(request, \"ais/ais.html\") def delete_grade(request): # \"\"\" # It deletes the", "the Student class Convenor - the extraInfo objects that holds the designation as", "up the homepage of the application. It checkes the authentication of the user", "True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(hod_approval = True) assistant_list_length = len(assistant_list.filter(acad_approval = False)) assis_stat =", "15, 'align': 'center', 'valign': 'vcenter'}) sheet = book.add_worksheet() title_text = (\"Pre-registeration : \"+", "HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() #print (temp) # print (current_user) # acadadmin = temp.working #", "HttpResponseRedirect('/academic-procedures/') def add_optional(request): # \"\"\" # acadmic admin to update the additional courses", "context @login_required def homepage(request): \"\"\" This function is used to set up the", "the academic calendar. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context= {", ":['3','1'] } if request.method == \"POST\": dele = Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete() curriculum = Curriculum.objects.select_related().filter(branch", "if the student is available # mother - mother's name of the student", "senator students - all the objects in the Student class Convenor - the", "branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) elif request.POST['option'] ==", "else: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem= request_sem) # context={ #", "meeting minutes acadTtForm - the form to add academic calender examTtForm - the", "meetings - the all meeting objects held in senator meetings minuteForm - the", "in hDes: # if des.designation == s or des.designation == c: # designation", "= Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() # print (temp) #", "about the requested page # @variables: # current_user - gets the data of", "# add = request.POST.get('address') # hall = request.POST.get('hall') # room = request.POST.get('room') #", "# @variables: # s - the designation object that contains senator # student", "# 'programme': programme, # 'phoneno': ph, # 'batch': batch # } # print(data)", "if request.method == \"POST\": name = request.POST.get('name') # roll = ExtraInfo.objects.get(id=request.POST.get('rollno')) # programme", "convenor or coconvenor # hDes - holdsDesignation object to store that the particualr", "deleteMinute(request): # \"\"\" # to delete an existing senate meeting minute object from", "- contains metadata about the requested page # @variables: # rollno - rollno", "+ str(batch.year) + '-preresgistration.xlsx' response['Content-Disposition'] = st return response @login_required def add_new_profile (request):", "sheet.set_column('B:B',20) sheet.set_column('C:C',50) sheet.set_column('D:D',15) sheet.set_column('E:E',15) k = 4 num = 1 for i in", "new extrainfo object created in database stud_data - new student object created in", "acadTtForm = AcademicTimetableForm(request.POST, request.FILES) if acadTtForm.is_valid(): acadTtForm.save() return render(request, \"ais/ais.html\", context) else: return", "request.POST.getlist('Roll Number')[0] # # print(request.POST.get('rollno')) # extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Senator')", "get_calendar_details = Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description = desc get_calendar_details.from_date = from_date get_calendar_details.to_date = to_date get_calendar_details.save()", "objects exam_t - all the exam timetable objects timetable - all the academic", "to be displayed in teh webpage # \"\"\" # current_user = get_object_or_404(User, username=request.user.username)", "Convenor - the extraInfo objects that holds the designation as a convenor CoConvenor", "extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') #", "to delete the advance information of the student # @param: # request -", "z - temporary array to add data to variable data k -temporary array", "course = d[2] # sem = int(d[3]) # if request.method == \"POST\": #", "\"\"\" acad-admin can delete the outdated timetable from the server. @param: request -", "= request.POST['branch']).filter(batch = request.POST['batch']).filter(programme= request.POST['programme']) courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= {", "Division Clerk') # temp = HoldsDesignation.objects.all().filter(designation = desig_id).first() # print (temp) # print", "Programme from form request_sem - Semester from form curriculum - Get data about", "calender objects context - the datas to be displayed in the webpage this_sem_course", "[] k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department) ans.append(k) ans.sort() output = BytesIO() book = Workbook(output,{'in_memory':True})", "batch - gets the batch course - gets the course curr_key - gets", "sheet.set_column('C:C',50) sheet.set_column('D:D',15) sheet.set_column('E:E',15) k = 4 num = 1 for i in data:", "convenor # c - the designation object that contains co convenor # student", "minute object received from id to be deleted # \"\"\" # if request.method", "= ((str(course.name)+\" : \"+str(str(batch)))) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle)", "event. desc - Description for the academic calendar event. prev_desc - Description for", "metadata about the requested page # pk - the primary key of the", "'POST': try: request_batch = request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme'] except Exception", "'this_sem_course': this_sem_courses, 'curriculum': curriculum, 'pgstudent' : pgstudent, 'assistant_list' : assistant_list, 'assistant_approve_list' : assistant_approve_list,", "hall_no, specialization = specialization, curr_semester_no=sem, ) desig = Designation.objects.get(name='student') hold_des = HoldsDesignation.objects.create( user=user,", "\"\"\" # to remove a senator from the position # @param: # request", "\"\"\" if request.method == \"POST\": pass # print(request.POST) # choices = request.POST.getlist('choice') #", "= request.POST['delete'] # arr = st.split(\"-\") # stu = arr[0] # if Student.objects.get(id=stu):", "= request.POST['batch'] course = Courses.objects.get(id = request.POST['course']) obj = course_registration.objects.all().filter(course_id = course) except", "[] for course_slot in course_slots: courses += course_slot.courses.all() new_reg=[] for c in courses:", "ans - Formatted Array to be converted to xlsx k -temporary array to", "= request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem= request_sem) # context={ # 'courses' : courses, #", "object from the requested rollno # \"\"\" current_user = get_object_or_404(User, username=request.user.username) # user_details", "# s.mother_name = \"\" # s.hall_no = 1 # s.room_no = \"\" #", "meeting Minute################## # @csrf_exempt def addMinute(request): # \"\"\" # to add a new", "the student required to check if the student is available # mother -", "z.append(i.id.department.name) z.append('registered') data.append(z) output = BytesIO() book = Workbook(output,{'in_memory':True}) title = book.add_format({'bold': True,", "# if request.method == \"POST\": # curr_id=request.POST['course'] # print(curr_id) # curr_course = Curriculum.objects.filter(curriculum_id=curr_id)", "data of the student to be hidden in the webpage # \"\"\" #", "check for designation acadadmin - designation for Acadadmin final_user - final designation of", "the webpage \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) return render(request, \"ais/ais.html\",", "'curriculumm' :curriculum, 'tab_id' :['3','3'] } return render(request, \"ais/ais.html\", context) else: context= { 'tab_id'", "{ # 'courses': courses, # 'course_type': course_type, # 'curriculum_course': curriculum_courses, # } #", "k[2] # if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # print(request.POST['delete']) # data", "if request.POST: # s = get_object_or_404(Designation, name=\"Senator\") # student = get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0]) #", "@csrf_exempt def deleteSenator(request, pk): # \"\"\" # to remove a senator from the", "the exam timetable objects timetable - all the academic timetable objects calendar -", "# print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") # rollno = request.POST.getlist('Roll Number')[0] # # print(request.POST.get('rollno')) # extraInfo", "# #################################### @login_required def curriculum(request): \"\"\" This function is used to see curriculum", "id=pk) # user = get_object_or_404(User, username = e.user.username) # s = get_object_or_404(Student, id=e)", "flot.save() new_curr_inst=[] for c,i in enumerate(request.POST.getlist(str(i)+'_fac')): inst = get_object_or_404(User, username = i) inst", "None #Curriculum.objects.all() else: sem = sem_for_generate_sheet() now = datetime.datetime.now() year = int(now.year) if", "dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13 ).value department=DepartmentInfo.objects.all().filter(name=dept).first() if specialization == \"\": specialization=\"None\" if hall_no ==", "- all the academic timetable objects calendar - all the academic calender objects", "from the database # @param: # request - contains metadata about the requested", "address # final_user - details of the user # sem - current semester", "the requested page # @variables: # rollno - rollno of the student to", "the exam timtable of the ongoing semester. @param: request - contains metadata about", "# hDes - the holdDesignation object that stores the # information that the", "temporary variables for final output st - temporary variables for final output \"\"\"", "- details of student from file last_name - details of student from file", "file title - details of student from file dob - details of student", "if request.method == \"POST\": data = request.POST['delete'] t = Timetable.objects.get(time_table=data) t.delete() return HttpResponse(\"TimeTable", "course.code + '.xlsx' response['Content-Disposition'] = st return response @login_required def generate_preregistration_report(request): \"\"\" to", "- get curriculum details reg - create registeration object in registeration table \"\"\"", "batch = Batch.objects.filter(id = batch_id).first() obj = InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem) registered_students = set() unregistered_students", "be updated. get_calendar_details = Get the object of the calendar instance from the", "course_type, 'exam': exam_t, 'timetable': timetable, 'academic_calendar': calendar, 'next_sem_course': next_sem_courses, 'this_sem_course': this_sem_courses, 'curriculum': curriculum,", "== 'POST' and request.FILES: # form = MinuteForm(request.POST, request.FILES) # if form.is_valid(): #", "\"POST\": # data = request.POST['delete'] # t = Meeting.objects.get(id=data) # t.delete() return HttpResponseRedirect('/aims/')", "} courses = Course.objects.all() course_type = Constants.COURSE_TYPE html = render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj = json.dumps({'html':html})", "else: optional=False course_type=request.POST[\"course_type\"] except Exception as e: id=\"\" programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\"", "str(hall) + \" \" + str(room) # student.save() # s = Student.objects.get(id=student) #", "context= { 'tab_id' :['2','1'] } if request.method == 'POST' and request.FILES: profiles=request.FILES['profiles'] excel", "= request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] from_date = from_date[0].split('-') from_date = [int(i) for i", "# id = d[0] # course = d[2] # sem = int(d[3]) #", "# rollno - the rollno of the student required to check if the", "'POST': programme = request.POST['programme'] now = datetime.datetime.now() year = int(now.year) batch = year-1", "upload the time table(any type of) of the semester. @param: request - contains", "HttpResponseRedirect('/academic-procedures/') course_list = sem_for_generate_sheet() if(course_list[0]==1): course_list_2 = [2, 4, 6, 8] else: course_list_2", ":['3','1'] } return render(request, \"ais/ais.html\", context) @login_required def add_timetable(request): \"\"\" acad-admin can upload", "title - formatting variable of title the workbook subtitle - formatting variable of", "s - the student object of the student # \"\"\" e = get_object_or_404(ExtraInfo,", "convenor/coconvenor # @param: # request - contains metadata about the requested page #", "can delete the outdated exam timetable. @param: request - contains metadata about the", "- details of student from file address - details of student from file", "\"\"\" # if request.method == \"POST\": # data = request.POST['delete'] # t =", "add exam timetable Dean - the extraInfo objects that holds the designation as", "HttpResponseRedirect('/academic-procedures/') context = get_context(request) return render(request, \"ais/ais.html\", context) # #################################### # # curriculum", "@variables: current_user - father's name of the student user_details - the rollno of", "semester obj - All the registration details appended into one data - Formated", "# if request.method == \"POST\": # programme=request.POST['programme'] # batch=request.POST['batch'] # branch=request.POST['branch'] # sem=request.POST['sem']", "= Courses.objects.get(id = request.POST['course']) obj = course_registration.objects.all().filter(course_id = course) except Exception as e:", ":['5','1'] } if request.method == 'POST': try: request_batch = request.POST['batch'] request_branch = request.POST['branch']", "is holding the senator designation # student - the student object of the", "# if request.POST: # s = get_object_or_404(Designation, name=\"Senator\") # student = get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0])", "the minimum credits from the database and the update it. # \"\"\" if", "get_calendar_details = Get the object of the calendar instance from the database for", "the form required to add exam timetable exam_t - all the exam timetable", "desc = request.POST.getlist('description')[0] prev_desc = request.POST.getlist('prev_desc')[0] from_date = from_date[0].split('-') from_date = [int(i) for", "# st = request.POST['delete'] # arr = st.split(\"-\") # stu = arr[0] #", "It verify the grades of the student @param: request - contains metadata about", "- details of student from file batch - details of student from file", "def get_faculty_list(): \"\"\" to get faculty list from database @param: request - contains", "data - tag whether to delete it or not # course - get", "in choices: # i.acad_selection = False # i.save() # return HttpResponseRedirect('/academic-procedures/') def min_cred(request):", "the extraInfor objects exam_t - all the exam timetable objects timetable - all", "getcurrent year batch - gets the batch from form sem - stores the", "It adds the basic profile information like username,password, name, # rollno, etc of", "programme, # 'phoneno': ph, # 'batch': batch # } # print(data) # return", "the requested page @variables: request_batch - Batch from form request_branch - Branch from", "JsonResponse from django.shortcuts import get_object_or_404, render from django.template.loader import get_template from django.views.decorators.csrf import", "holds the designation as a convenor CoConvenor - the extraInfo objects that holds", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": data = request.POST['delete'] t", "'designation': hDes.designation.name, # } # return JsonResponse(data) # else: # data = {}", "Course.objects.all().filter(course_id=i).first() # course.acad_selection = True # course.save() # courses = Course.objects.all() # for", "instructor_id=inst, chief_inst=True, ) new_curr_inst.append(ins) else: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=False, ) new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst) else:", "display it on the page. @param: request - contains metadata about the requested", "of the student # add - student's address # cpi - student's cpi", "be uploaded @param: request - contains metadata about the requested page. @variables: from_date", "== \"\" and request_branch == \"\" and request_programme==\"\": curriculum = None #Curriculum.objects.all() else:", "} if request.method == \"POST\": i=1 while True: if str(i)+\"_ccode\" in request.POST: if", "Student.objects.get(id=extraInfo) # data = { # 'name': extraInfo.user.username, # 'rollno': extraInfo.id, # 'programme':", "of student from file phone_no - details of student from file address -", "academic calender objects context - the datas to be displayed in the webpage", "- student's address # cpi - student's cpi # hall - hall no", "ExtraInfo.objects.get(id=roll.id) # db.name = name.upper() # db.id = roll # db.batch = batch", "xlsx file title - formatting variable of title the workbook subtitle - formatting", "# data = request.POST['delete'] # d = data.split(\"-\") # id = d[0] #", "applications.academic_procedures.views import acad_proced_global_context from applications.programme_curriculum.models import Batch @login_required def user_check(request): \"\"\" This function", "return HttpResponseRedirect('/aims/') # # ###################################################### # # ##########Student basic profile################## # @csrf_exempt def", "== \"POST\": # print(request.POST) # rollno=request.POST.get('roll') # print(rollno) # student = ExtraInfo.objects.get(id=rollno) #", "'tab_id' :['10','2'] } examTtForm = ExamTimetableForm() if request.method == 'POST' and request.FILES: examTtForm", "# 'tab_id' :\"2\" # } # return render(request,\"ais/ais.html\", context) # else: # return", "15, 'align': 'center', 'valign': 'vcenter'}) sheet = book.add_worksheet() title_text = ((str(course.name)+\" : \"+str(str(batch))))", "student is available desig_id - mother's name of the student acadadmin - student's", "= branch).filter(batch = batch).filter(programme= programme).filter(sem = sem) # print(curriculum_courses) # courses = Course.objects.all()", "roll = ExtraInfo.objects.get(id=request.POST.get('rollno')) # programme = request.POST.get('programme') # batch = request.POST.get('batch') # ph", "'center', 'valign': 'vcenter'}) sheet = book.add_worksheet() title_text = ((str(course.name)+\" : \"+str(str(batch)))) sheet.set_default_row(25) sheet.merge_range('A2:E2',", "requested page @variables: current_user - father's name of the student user_details - the", "homepage of the application. It checkes the authentication of the user and also", "object with the given pk # hDes - the holdDesignation object that stores", "return render(request, \"ais/ais.html\") return render(request, \"ais/ais.html\") def delete_grade(request): # \"\"\" # It deletes", "return HttpResponseRedirect('/academic-procedures/') if request.method == 'POST': programme = request.POST['programme'] now = datetime.datetime.now() year", ").value department=DepartmentInfo.objects.all().filter(name=dept).first() if specialization == \"\": specialization=\"None\" if hall_no == None: hall_no=3 else:", "to_date = to_date[0].split('-') to_date = [int(i) for i in to_date] to_date = datetime.datetime(*to_date).date()", "programme - details of student from file batch - details of student from", "c.save() HttpResponse(\"Calendar Added\") return render(request, \"ais/ais.html\", context) @login_required def update_calendar(request): \"\"\" to update", "# 'id': pk, # 'designation': designation, # } # return JsonResponse(data)# ###################################################### #", "optional=True else: optional=False course_type=request.POST[\"course_type_\"+str(i)] except Exception as e: programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\"", "be deleted # t - the minute object received from id to be", "arr[0] # if Student.objects.get(id=stu): # s = Student.objects.get(id=stu) # s.father_name = \"\" #", "designation object of Co Convenor # result - the data that contains where", "AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(acad_approval = False) assistant_approve_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark", "displayed in the webpage \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) return", "- details of faculty of data faculty_list - list of faculty \"\"\" try:", "= Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).order_by('sem') else: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch", "= Get the object of the calendar instance from the database for the", "student from file specialization - details of student from file hall_no - details", "academic caldendar event. desc - Description for the academic calendar event. prev_desc -", "user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": data = request.POST['delete'] t = Exam_timetable.objects.get(exam_time_table=data)", "in # ph - the phone number of the student # \"\"\" if", "displayed in the webpage this_sem_course - tha data of thsi semester courses next_sem_courses", "current_user - the username of the logged in user # user_details - the", "from database exam_t - all exam timetable from database \"\"\" if user_check(request): return", "from the databases to display it on the page. @param: request - contains", "# \"\"\" # current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id", "authentication of the user and also fetches the available data from the databases", "form required to add exam timetable exam_t - all the exam timetable objects", "file user - new user created in database einfo - new extrainfo object", "to be uploaded @param: request - contains metadata about the requested page. @variables:", "context= { 'academic_calendar' :calendar, 'tab_id' :['4','1'] } if request.method == \"POST\": try: from_date", "HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST': # print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") # rollno = request.POST.getlist('Roll", "of student holds_desig - get hold_desig object of student currs - get curriculum", "user from request user_details - extract details of user from database desig_id -", "= course_registration.objects.all().filter(course_id = course) except Exception as e: batch=\"\" course=\"\" curr_key=\"\" obj=\"\" registered_courses", "of title text dep - temporary variables z - temporary variables for final", "hDes - holdsDesignation object to store that the particualr student is # holding", "Object of Exam time table to be deleted \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "i in registered_courses: k = [] k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department) ans.append(k) ans.sort() output", "# print(k) # final_user = k[2] # if (str(acadadmin) != str(final_user)): # return", "if request.method == \"POST\": sem = request.POST.get('semester_no') batch_id=request.POST.get('batch_branch') batch = Batch.objects.filter(id = batch_id).first()", "@param: request - contains metadata about the requested page @variables: sem - get", "(str(acadadmin) != str(final_user)): return True else: return False def get_context(request): \"\"\" This function", ":['3','1'] } return render(request, \"ais/ais.html\", context) return render(request, 'ais/ais.html', context) @login_required def next_curriculum(request):", "course.acad_selection = True # course.save() # courses = Course.objects.all() # for i in", "} # s.delete() # e.delete() # u.delete() # return JsonResponse(data)# ######################################################### # '''", "return HttpResponseRedirect('/aims/') # # return JsonResponse(data) # else: # return HttpResponseRedirect('/aims/') # @csrf_exempt", "- contains metadata about the requested page. # @variables: # sem_cred = Get", "request.FILES) # if form.is_valid(): # form.save() # return HttpResponse('sucess') # else: # return", "calendar event. to_date - The ending date for the academic caldendar event. desc", "array. # sem - Get the object for the minimum credits from the", "context={ # 'courses' : courses, # 'course_type' : course_type, # 'curriculum' : curriculum,", "} if request.method == \"POST\": try: from_date = request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc", "the student object of the student # \"\"\" e = get_object_or_404(ExtraInfo, id=pk) #", "# if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # print(\"confirm", "Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) context= { 'curriculumm' :curriculum, 'tab_id' :['3','3'] } return", "hDes = HoldsDesignation() # hDes.user = extraInfo.user # hDes.working = extraInfo.user # if", "extraInfo.user.username, # 'rollno': extraInfo.id, # 'programme': student.programme, # 'branch': extraInfo.department.name # } #", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') course_list = sem_for_generate_sheet() if(course_list[0]==1): course_list_2 = [2, 4,", "data = { # 'name': extraInfo.user.username, # 'rollno_convenor': extraInfo.id, # 'designation': hDes.designation.name, #", "str(\" \") + batch.discipline.acronym + str(\" \") + str(batch.year)) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title)", "programme_name=request.POST['Programme'] batch_year=request.POST['Batch'] batch = Batch.objects.all().filter(name = programme_name, discipline__acronym = dept, year = batch_year).first()", "print(request.POST) # choices = request.POST.getlist('choice') # for i in choices: # course =", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() context= {", "def add_calendar(request): \"\"\" to add an entry to the academic calendar to be", "for final output c - temporary variables for final output st - temporary", "k = [] k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department) ans.append(k) ans.sort() output = BytesIO() book", "if the student is available # desig_id - mother 's name of the", "e: request_batch = \"\" request_branch = \"\" request_programme = \"\" if request_batch ==", "# if request.method == \"POST\": # print(request.POST) # rollno=request.POST.get('roll') # print(rollno) # student", "programme = programme_name, batch=batch_year, batch_id = batch, father_name = fathers_name, mother_name = mothers_name,", "file department - details of student from file specialization - details of student", "# 'programme': student.programme, # 'branch': extraInfo.department.name # } # return HttpResponseRedirect('/aims/') # #", "\"\"\" # to delete an existing senate meeting minute object from the database.", "# } # return JsonResponse(data)# ###################################################### # # ##########Senate meeting Minute################## # @csrf_exempt", "- temporary variables for final output c - temporary variables for final output", "the user and also fetches the available data from the databases to display", "- gets the curriculum from database obj - get stdents data from database", "return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def delete_timetable(request): \"\"\" acad-admin", "to_date get_calendar_details.save() except Exception as e: from_date=\"\" to_date=\"\" desc=\"\" return render(request, \"ais/ais.html\", context)", "else: break i+=1 return render(request, \"ais/ais.html\", context) # # ---------------------senator------------------ # @csrf_exempt def", "procedures_context = acad_proced_global_context() try: examTtForm = ExamTimetableForm() acadTtForm = AcademicTimetableForm() calendar = Calendar.objects.all()", "roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value) if sex == 'F': title='Ms.' else: title='Mr.' dob_tmp=sheet.cell(i,5).value", "webpage # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() #", "curriculum from database courses - get courses from database courses_type - get course", "now = datetime.datetime.now() year = int(now.year) if sem[0] == 2: sem = sem[year-int(request_batch)-1]", "the student # @param: # request - contains metadata about the requested page", "else: # data = {} # return JsonResponse(data) # @csrf_exempt def delete_basic_profile(request, pk):", "final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": sem =", ":['10','2'] } examTtForm = ExamTimetableForm() if request.method == 'POST' and request.FILES: examTtForm =", "is a senator # hDes - the holdDesignation object that stores the #", "roll - the rollno of the student # batch - the current batch", "id=request.POST.getlist(\"senate_id\")[0]) # hDes = get_object_or_404( HoldsDesignation, user = student.user) # hDes.delete() # return", "# data = {} # return JsonResponse(data) # else: # data = {}", "sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20)", "return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST': # print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") # rollno =", "# student.address = str(hall) + \" \" + str(room) # student.save() # s", ".forms import AcademicTimetableForm, ExamTimetableForm, MinuteForm from .models import (Calendar, Course, Exam_timetable, Grades, Curriculum_Instructor,Constants,", "request.POST.get('mother') # add = request.POST.get('address') # hall = request.POST.get('hall') # room = request.POST.get('room')", "batch form form curriculum - curriculum details form database ins - Inster data", "objects that holds the designation as a dean student - the students as", "# data - data of the student to be hidden in the webpage", "return JsonResponse(data) # else: # father = request.POST.get('father') # mother = request.POST.get('mother') #", "request_programme==\"\": curriculum = None #Curriculum.objects.all() else: sem = sem_for_generate_sheet() now = datetime.datetime.now() year", "= specialization, curr_semester_no=sem, ) desig = Designation.objects.get(name='student') hold_des = HoldsDesignation.objects.create( user=user, working=user, designation=desig,", "previous Description. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context= { 'academic_calendar'", "if request.method == \"POST\": # st = request.POST['delete'] # arr = st.split(\"-\") #", "z - temporary variables for final output b - temporary variables for final", "whether to delete it or not # course - get the course details", "'courses': courses, 'courses_list': courses_list, 'course_type': course_type, 'exam': exam_t, 'timetable': timetable, 'academic_calendar': calendar, 'next_sem_course':", "as e: f1=f2=f3=\"\" pass faculty = list(chain(f1,f2,f3)) faculty_list = [] for i in", "# request - contains metadata about the requested page # pk - the", "Timetable.objects.get(time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def delete_exam_timetable(request): \"\"\" acad-admin can delete the", "- formatting variable of subtitle the workbook normaltext - formatting variable for normal", "else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def delete_timetable(request): \"\"\"", "else: hall_no=int(hall_no) programme_name=request.POST['Programme'] batch_year=request.POST['Batch'] batch = Batch.objects.all().filter(name = programme_name, discipline__acronym = dept, year", "used to add new curriculum in database It checkes the authentication of the", "id=\"\" programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first()", "= int(now.month) if month >= 7 and month <= 12: return [1, 3,", "stu in students: if stu not in registered_students: unregistered_students.add(stu) data = [] m", "the new senator # data - data of the student to be displayed", "@param: # request - contains metadata about the requested page. # @variables: #", "database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if request.method ==", "profiles=request.FILES['profiles'] excel = xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) for i in range(sheet.nrows): roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value)", "else: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=False, ) new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst) else: break i+=1 return render(request,", "holdsDesignation object to store that the particualr student is # holding the convenor/coconvenor", "@variables: f1,f2,f3 - temporary varibles faculty - details of faculty of data faculty_list", "the particular student is a senator # \"\"\" pass # if request.POST: #", "array to add data to variable data k -temporary array to add data", "@login_required def next_curriculum(request): \"\"\" This function is used to decide curriculum for new", "# to remove a senator from the position # @param: # request -", "render(request, \"ais/ais.html\", context) # #################################### # # curriculum # # #################################### @login_required def", "add academic calender examTtForm - the form required to add exam timetable exam_t", "- contains metadata about the requested page @variables: current_user - father's name of", "senator # data - data of the student to be displayed in teh", "admin # s - the student object from the requested rollno # \"\"\"", "else: sem = sem[year-int(request_batch)] sem+=1 curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code')", "context) # else: # return render(request, \"ais/ais.html\") return render(request, \"ais/ais.html\") def delete_grade(request): #", "batch = request.POST.get('batch') # ph = request.POST.get('phoneno') # if not Student.objects.filter(id=roll).exists(): # db", "student # user - the User object of the student # s -", "in the webpage this_sem_course - tha data of thsi semester courses next_sem_courses -", "- details of student from file dob - details of student from file", "exam_t = Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','1'] } acadTtForm", "== 'F': title='Ms.' else: title='Mr.' dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value)", "to add exam timetable exam_t - all the exam timetable objects timetable -", "<= 12: return [1, 3, 5, 7] else: return [2, 4, 6, 8]", "return HttpResponseRedirect('/academic-procedures/') timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable':", "= programme) if request.POST['option'] == '1': new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme,", "@variables: sem - get current semester from current time now - get current", "add - student's address # cpi - student's cpi # hall - hall", "registered_students: unregistered_students.add(stu) data = [] m = 1 for i in unregistered_students: z", "for Acadadmin final_user - final designation of request user \"\"\" try: current_user =", "if result == \"Convenor\": # hDes.designation = s # else: # hDes.designation =", "from form sem - stores the next semester obj - All the registration", "varibles faculty - details of faculty of data faculty_list - list of faculty", "AcademicTimetableForm() if request.method == 'POST' and request.FILES: acadTtForm = AcademicTimetableForm(request.POST, request.FILES) if acadTtForm.is_valid():", "function generates semester grade sheet @variables: now - current datetime month - current", "'courses_list': courses_list, 'course_type': course_type, 'exam': exam_t, 'timetable': timetable, 'academic_calendar': calendar, 'next_sem_course': next_sem_courses, 'this_sem_course':", "id=roll_no, user=user, title=title, sex=sex, date_of_birth=dob, address=address, phone_no=phone_no, user_type='student', department=department, ) sem=1 stud_data =", "- the all meeting objects held in senator meetings minuteForm - the form", "student = get_object_or_404(ExtraInfo, id=pk) # hDes = HoldsDesignation.objects.filter(user = student.user) # designation =", "sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] a,b,c,d,e = str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp = str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext)", "the phone number of the student # \"\"\" if request.method == \"POST\": name", "object of student holds_desig - get hold_desig object of student currs - get", "def delete_timetable(request): \"\"\" acad-admin can delete the outdated timetable from the server. @param:", "applications.programme_curriculum.models import Batch @login_required def user_check(request): \"\"\" This function is used to check", "or not # course - get the course details # \"\"\" # current_user", "course_type from form.REQUEST ins - data is stored in database \"\"\" if user_check(request):", "details of student from file department - details of student from file specialization", "# sem - Get the object for the minimum credits from the database", "batch, father_name = fathers_name, mother_name = mothers_name, cpi = 0, category = category,", "if des.designation == s or des.designation == c: # designation = des.designation.name #", "== \"POST\": # curr_id=request.POST['course'] # print(curr_id) # curr_course = Curriculum.objects.filter(curriculum_id=curr_id) # grades =", "to become the convenor/coconvenor # extraInfo - extraInfo object of the student with", "timetable, 'tab_id' :['10','1'] } acadTtForm = AcademicTimetableForm() if request.method == 'POST' and request.FILES:", "s - the student object from the requested rollno # \"\"\" current_user =", "course_type, 'curriculum': curriculum, 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) return render(request, 'ais/ais.html',", "render(request, \"ais/ais.html\", context) # # ---------------------senator------------------ # @csrf_exempt def senator(request): # \"\"\" #", "current_user = get_object_or_404(User, username=request.user.username) user_details = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp", "# if not Student.objects.filter(id=roll).exists(): # db = Student() # st = ExtraInfo.objects.get(id=roll.id) #", "user. # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() #", "assis_stat: assistant_flag = obj.student_status hod_flag = obj.hod_status account_flag = obj.account_status except Exception as", "} if request.method == 'POST' and request.FILES: profiles=request.FILES['profiles'] excel = xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) for", "# @csrf_exempt def add_convenor(request): # \"\"\" # to add a new student convenor/coconvenor", "context) @login_required def update_calendar(request): \"\"\" to update an entry to the academic calendar", "the student # acadadmin - student's address # final_user - details of the", "from xhtml2pdf import pisa from itertools import chain from django.contrib.auth.models import User from", "student # acadadmin - student's address # final_user - details of the user", "in ans: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] name = str(b)+\" \"+str(c) temp =", "file sex - details of student from file title - details of student", "starting date for the academic calendar event. to_date - The ending date for", "request - contains metadata about the requested page. @variables: data - data of", "# return HttpResponseRedirect('/aims/') # else: # return HttpResponseRedirect('/aims/')# #################################################### # # ##########covenors and", "return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def add_exam_timetable(request): \"\"\" acad-admin", "hDes.working = extraInfo.user # hDes.designation = s # hDes.save() # student = Student.objects.get(id=extraInfo)", "# data = { # 'name': extraInfo.user.username, # 'rollno_convenor': extraInfo.id, # 'designation': hDes.designation.name,", "= category, hall_no = hall_no, specialization = specialization, curr_semester_no=sem, ) desig = Designation.objects.get(name='student')", "page. # @variables: # choices - selected addtional courses by the academic person.", "= HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() #print (temp) # print (current_user) # acadadmin = temp.working", "is used to edit curriculum in database It checkes the authentication of the", "of user. It checkes the authentication of the user. @param: request - contains", "year - current year batch - batch form form curriculum - curriculum details", "# 'branch': extraInfo.department.name # } # return HttpResponseRedirect('/aims/') # # return JsonResponse(data) #", "@param: request - contains metadata about the requested page. @variables: acadTtForm - data", "the student # data - tag whether to delete it or not #", "examTtForm.save() return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\",", "student from file department - details of student from file specialization - details", "Calendar.objects.all() context= { 'academic_calendar' :calendar, 'tab_id' :['4','1'] } if request.method == \"POST\": try:", "ExamTimetableForm() acadTtForm = AcademicTimetableForm() calendar = Calendar.objects.all() this_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True)", "batch - batch form form curriculum - curriculum details form database ins -", "= \"\" request_programme = \"\" request_sem = \"\" #for checking if the user", "data of delete dictionary in post request t - Object of Exam time", "of delete dictionary in post request t - Object of Exam time table", "'tab_id' :\"2\" # } # return render(request,\"ais/ais.html\", context) # else: # return HttpResponseRedirect('/aims/')", "to xlsx k -temporary array to add data to formatted array/variable output -", "to add academic calender examTtForm - the form required to add exam timetable", "from file mothers_name - details of student from file category - details of", "database # def curriculum(request): # ''' def delete_advanced_profile(request): # \"\"\" # to delete", "desig_id - mother's name of the student acadadmin - student's address subject -", "desc - Description for the academic calendar event. c = object to save", "request - contains metadata about the requested page # @variables: # rollno -", "generate_preregistration_report(request): \"\"\" to generate preresgistration report after pre-registration @param: request - contains metadata", "= 4 num = 1 for i in ans: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c =", "- the extraInfo objects that holds the designation as a coconvenor meetings -", "the type of user. It checkes the authentication of the user. @param: request", "def senator(request): # \"\"\" # to add a new student senator # @param:", "return HttpResponseRedirect('/academic-procedures/') # print(request.POST['delete']) # data = request.POST['delete'] # d = data.split(\"-\") #", "= request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code') faculty_list = get_faculty_list() courses = Course.objects.all() course_type =", "{} # return JsonResponse(data) # @csrf_exempt def deleteConvenor(request, pk): # \"\"\" # to", "sheet - sheet no in excel file roll_no - details of student from", "programme).filter(sem = sem) # print(curriculum_courses) # courses = Course.objects.all() # course_type = Constants.COURSE_TYPE", "academic admin. # \"\"\" if request.method == \"POST\": pass # print(request.POST) # choices", "range(1, 10): # sem = \"sem_\"+\"1\" # sem_cred.append(request.POST.getlist(sem)[0]) # for i in range(1,", "e: from_date=\"\" to_date=\"\" desc=\"\" pass c = Calendar( from_date=from_date, to_date=to_date, description=desc) c.save() HttpResponse(\"Calendar", "batch_id=request.POST.get('batch_branch') batch = Batch.objects.filter(id = batch_id).first() obj = InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem) registered_students = set()", "# data = { # 'id': pk, # 'designation': designation, # } #", "student acadadmin - student's address subject - subject of which the grade has", "return HttpResponseRedirect('/academic-procedures/') try: batch = request.POST['batch'] course = Courses.objects.get(id = request.POST['course']) obj =", "particular student field # @variables: # s - the designation object that contains", "# return JsonResponse(data) # else: # father = request.POST.get('father') # mother = request.POST.get('mother')", "username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk') # temp", "contains metadata about the requested page # @variables: # current_user - details of", "Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description = desc get_calendar_details.from_date = from_date get_calendar_details.to_date = to_date get_calendar_details.save() except Exception", "address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13 ).value department=DepartmentInfo.objects.all().filter(name=dept).first() if specialization == \"\": specialization=\"None\" if hall_no", "available desig_id - mother's name of the student acadadmin - student's address subject", "curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem= request_sem) # context={ # 'courses'", "= int(d[3]) # if request.method == \"POST\": # if(Grades.objects.filter(student_id=id, sem=sem)): # s =", "data.append(z) output = BytesIO() book = Workbook(output,{'in_memory':True}) title = book.add_format({'bold': True, 'font_size': 22,", "context) return render(request, \"ais/ais.html\", context) @login_required def edit_curriculum(request): \"\"\" This function is used", "# @variables: # current_user - the username of the logged in user #", "# student = get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0]) # hDes = get_object_or_404( HoldsDesignation, user = student.user)", "'POST' and request.FILES: profiles=request.FILES['profiles'] excel = xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) for i in range(sheet.nrows): roll_no=int(sheet.cell(i,0).value)", "metadata about the requested page # @variables: # data - the id of", "create registeration object in registeration table \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= {", "in database stud_data - new student object created in database desig - get", "Programme from form request_sem - Semester from form \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "ph - the phone number of the student # \"\"\" if request.method ==", "# s.room_no = \"\" # s.save() # else: # return HttpResponse(\"Data Does Not", "or coconvenor # hDes - holdsDesignation object to store that the particualr student", "specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13 ).value department=DepartmentInfo.objects.all().filter(name=dept).first() if specialization == \"\": specialization=\"None\" if hall_no == None:", "acadTtForm, 'examTtForm': examTtForm, 'courses': courses, 'courses_list': courses_list, 'course_type': course_type, 'exam': exam_t, 'timetable': timetable,", "HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() # print (temp) # print (current_user) # acadadmin = temp.working", "the minute object to be deleted # t - the minute object received", "return render(request, \"ais/ais.html\", context) # else: # return render(request, \"ais/ais.html\") return render(request, \"ais/ais.html\")", "current_user - get user from request user_details - extract details of user from", "user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context= { 'academic_calendar' :calendar, 'tab_id' :['4','1'] }", "current_user - father's name of the student user_details - the rollno of the", "- the details of the current user # desig_id - checking the designation", "new_reg=[] for c in courses: reg=course_registration( course_id = c, semester_id=sem_id, student_id=stud_data ) new_reg.append(reg)", "is used to delete curriculum entry in database It checkes the authentication of", "= batch_year).first() user = User.objects.create_user( username=roll_no, password='<PASSWORD>', first_name=first_name, last_name=last_name, email=email, ) einfo =", "ID. # extraInfo - extraInfo object of the student with that rollno #", "from the requested rollno # \"\"\" current_user = get_object_or_404(User, username=request.user.username) # user_details =", "entry.course_type=course_type entry.save() curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme) courses = Course.objects.all()", "= Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'faculty_list': faculty_list, 'tab_id'", "- The ending date for the academic caldendar event. desc - Description for", "= request.POST['branch'] request_programme = request.POST['programme'] request_sem = request.POST['sem'] except Exception as e: request_batch", "the student # batch - the current batch of the student # programme", "event. desc - Description for the academic calendar event. c = object to", "sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass ins=Curriculum( programme=programme, batch=batch, branch=branch, sem=sem,", "render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def add_exam_timetable(request): \"\"\" acad-admin can", "Convenor # result - the data that contains where the student will become", "of the student to be hidden in the webpage # \"\"\" # s", "and request_sem==\"\": curriculum = None #Curriculum.objects.all() else: if int(request_sem) == 0: curriculum =", "generates semester grade sheet @variables: now - current datetime month - current month", "\"POST\": try: from_date = request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] prev_desc =", "str(user_details).split() final_user = k[2] except Exception as e: acadadmin=\"\" final_user=\"\" pass if (str(acadadmin)", "in curriculum course_type - list the type of courses \"\"\" if user_check(request): return", "in unregistered_students: z = [] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name)", "desig = Designation.objects.get(name='student') hold_des = HoldsDesignation.objects.create( user=user, working=user, designation=desig, ) sem_id = Semester.objects.get(curriculum", "final designation of request user \"\"\" try: current_user = get_object_or_404(User, username=request.user.username) user_details =", "dictionary in post request t - Object of time table to be deleted", "@variables: # current_user - father's name of the student # user_details - the", "of the new convenor/coconvenor # data - data of the student to be", "Convenor') # if request.method == 'POST': # rollno = request.POST.get('rollno_convenor') # extraInfo =", "db.save() # st.save() # data = { # 'name': name, # 'rollno': roll.id,", "#################################################### # # ##########covenors and coconvenors################## # @csrf_exempt def add_convenor(request): # \"\"\" #", "page @variables: current_user - get user from request user_details - extract details of", "hall_no - details of student from file programme - details of student from", "address subject - subject of which the grade has to be added sem", "prev_desc - Description for the previous event which is to be updated. get_calendar_details", "page # @variables: # name - the name of the student # roll", "to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] prev_desc = request.POST.getlist('prev_desc')[0] from_date = from_date[0].split('-') from_date", "delete it or not # course - get the course details # \"\"\"", "request.POST['sem'] except Exception as e: request_batch = \"\" request_branch = \"\" request_programme =", "'query_option2': procedures_context['query_option2'], 'course_verification_date' : procedures_context['course_verification_date'], 'submitted_course_list' : procedures_context['submitted_course_list'], 'result_year' : procedures_context['result_year'], 'batch_grade_data' :", "# user_details - the details of the current user # desig_id - checking", "Course List of Registered Students @param: request - contains metadata about the requested", "semester from current time now - get current time year - getcurrent year", "is used to add new curriculum in database It checkes the authentication of", "that contains senator # student - the list students that is a senator", "subtitle - formatting variable of subtitle the workbook normaltext - formatting variable for", "= BytesIO() book = Workbook(output,{'in_memory':True}) title = book.add_format({'bold': True, 'font_size': 22, 'align': 'center',", "desig_id - to check the designation of the user. # user_details - to", "minute object from the database. # @param: # request - contains metadata about", "== \"\" and request_branch == \"\" and request_programme==\"\" and request_sem==\"\": curriculum = None", "for the academic calendar event. c = object to save new event to", "the requested page. # @variables: # sem_cred = Get credit details from forms", "else: # return HttpResponseRedirect('/aims/') return HttpResponseRedirect('/aims/') def confirm_grades(request): # if user_check(request): # return", "file mothers_name - details of student from file category - details of student", "@variables: data - data of delete dictionary in post request t - Object", "contains metadata about the requested page. @variables: acadTtForm - data of delete dictionary", "- the list students that is a senator # hDes - the holdDesignation", "added \"\"\" # if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\":", "timetable, 'academic_calendar': calendar, 'next_sem_course': next_sem_courses, 'this_sem_course': this_sem_courses, 'curriculum': curriculum, 'pgstudent' : pgstudent, 'assistant_list'", "- check for designation acadadmin - designation for Acadadmin final_user - final designation", "optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) batch=batch+1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme)", "exam_t - all the exam timetable objects timetable - all the academic timetable", "data = request.POST['delete'] t = Exam_timetable.objects.get(exam_time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def add_calendar(request):", "template @param: request - contains metadata about the requested page @variables: acadTtForm -", "that contains co convenor # student - the student object with the given", "{ 'tab_id' :['5','1'] } if request.method == 'POST': try: request_batch = request.POST['batch'] request_branch", "page # @variables: # current_user - gets the data of current user. #", "def delete_grade(request): # \"\"\" # It deletes the grade of the student #", "\"ais/ais.html\", context) context= { 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) @login_required def", "objects of the students context - the datas to be displayed in the", "return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def float_course_submit(request): \"\"\" to", "\"\"\" This function is used to add new curriculum in database It checkes", "event to the academic calendar. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all()", "user=user, working=user, designation=desig, ) sem_id = Semester.objects.get(curriculum = batch.curriculum, semester_no = sem) course_slots", "desig - get designation object of student holds_desig - get hold_desig object of", "new senate meeting minute object to the database. # @param: # request -", "being deleted from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] }", "exam timetable exam_t - all the exam timetable objects timetable - all the", "= Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','1'] }", "# else: # hDes.designation = p # hDes.save() # data = { #", "from form.REQUEST course_id - course_id from database credits - credits from form.REQUEST optional", "'tab_id' :['2','1'] } if request.method == 'POST' and request.FILES: profiles=request.FILES['profiles'] excel = xlrd.open_workbook(file_contents=profiles.read())", "== \"POST\": dele = Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete() curriculum = Curriculum.objects.select_related().filter(branch = request.POST['branch']).filter(batch = request.POST['batch']).filter(programme=", "No (in formated data) z - temporary array to add data to variable", "cpi - student's cpi # hall - hall no of where the student", "to_date=to_date, description=desc) c.save() HttpResponse(\"Calendar Added\") return render(request, \"ais/ais.html\", context) @login_required def update_calendar(request): \"\"\"", "= int(now.year) batch = year-1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) if", "= { # 'name': name, # 'rollno': roll.id, # 'programme': programme, # 'phoneno':", "@csrf_exempt def add_basic_profile(request): # \"\"\" # It adds the basic profile information like", "\"\"\" This function is used to delete curriculum entry in database It checkes", "object to store that the particualr student is holding the senator designation #", "category = category, hall_no = hall_no, specialization = specialization, curr_semester_no=sem, ) desig =", "= datetime.datetime.now() year = int(now.year) batch = year-1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme", "'tab_id' :['4','1'] } if request.method == \"POST\": try: from_date = request.POST.getlist('from_date') to_date =", "# u.delete() # return JsonResponse(data)# ######################################################### # ''' # # view to add", "- details of student from file user - new user created in database", "def float_course(request): \"\"\" to float courses for the next sem and store data", "type of courses \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') course_list = sem_for_generate_sheet() if(course_list[0]==1): course_list_2", "== None: hall_no=3 else: hall_no=int(hall_no) programme_name=request.POST['Programme'] batch_year=request.POST['Batch'] batch = Batch.objects.all().filter(name = programme_name, discipline__acronym", "course_list = sem_for_generate_sheet() if(course_list[0]==1): course_list_2 = [2, 4, 6, 8] else: course_list_2 =", "the student # s - the student object of the student # \"\"\"", "to float courses for the next sem and store data in databsae. User", "file address - details of student from file department - details of student", "# roll = ExtraInfo.objects.get(id=request.POST.get('rollno')) # programme = request.POST.get('programme') # batch = request.POST.get('batch') #", "pass context = { 'acadTtForm': acadTtForm, 'examTtForm': examTtForm, 'courses': courses, 'courses_list': courses_list, 'course_type':", "all meeting objects held in senator meetings minuteForm - the form to add", "entry.course_code=course_code entry.course_id=course_id entry.credits=credits entry.optional=optional entry.course_type=course_type entry.save() curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme=", "delete the outdated timetable from the server. @param: request - contains metadata about", "# s - the student object of the student # \"\"\" e =", "1 for i in unregistered_students: z = [] z.append(m) m += 1 z.append(i.id.user.username)", "course_registration.objects.all().filter(course_id = course) except Exception as e: batch=\"\" course=\"\" curr_key=\"\" obj=\"\" registered_courses =", "if request.POST['option'] == '1': new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch,", "# form.save() # return HttpResponse('sucess') # else: # return HttpResponse('not uploaded') # return", "Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # next_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # courses = Course.objects.all() # course_type = Constants.COURSE_TYPE", "year batch - gets the batch from form sem - stores the next", "= request.POST.get('mother') # add = request.POST.get('address') # hall = request.POST.get('hall') # room =", "- batch form form curriculum - curriculum details form database ins - Inster", "= request.POST.get('designation') # hDes = HoldsDesignation() # hDes.user = extraInfo.user # hDes.working =", "student_id=stud_data ) new_reg.append(reg) course_registration.objects.bulk_create(new_reg) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context)", "{} # return JsonResponse(data) # else: # data = {} # return JsonResponse(data)", "arr = st.split(\"-\") # stu = arr[0] # if Student.objects.get(id=stu): # s =", "phone_no=phone_no, user_type='student', department=department, ) sem=1 stud_data = Student.objects.create( id=einfo, programme = programme_name, batch=batch_year,", "about the requested page @variables: current_user - get user from request user_details -", "# 'designation': hDes.designation.name, # } # return JsonResponse(data) # else: # data =", "student with that rollno # s - designation object of Convenor # p", "dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13 ).value department=DepartmentInfo.objects.all().filter(name=dept).first() if", "ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum)", "upload the exam timtable of the ongoing semester. @param: request - contains metadata", "obj = json.dumps({'html':html}) #return render(request, \"ais/ais.html\", context) return HttpResponse(obj,content_type='application/json') else: return render(request, \"ais/ais.html\",", "Sl. No (in formated data) z - temporary array to add data to", "in enumerate(request.POST.getlist(str(i)+'_fac')): inst = get_object_or_404(User, username = i) inst = ExtraInfo.objects.select_related('user','department').get(user=inst) if c==0:", "page. @variables: from_date - The starting date for the academic calendar event. to_date", "@login_required def update_calendar(request): \"\"\" to update an entry to the academic calendar to", "chief_inst=False, ) new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst) else: break i+=1 return render(request, \"ais/ais.html\", context) # #", "def min_cred(request): # \"\"\" # to set minimum credit for a current semester", "context={ 'tab_id' :['3','2'] } if request.method == 'POST': i=0 new_curr=[] while True: if", "basic gata from database to send to template @param: request - contains metadata", "mother - mother's name of the student # add - student's address #", "requested page @variables: sem - get current semester from current time now -", "== \"\" : logging.warning(\"No faculty\") else: flot = Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated = True flot.save()", "def update_calendar(request): \"\"\" to update an entry to the academic calendar to be", "# temp = HoldsDesignation.objects.all().filter(designation = desig_id).first() # print (temp) # print (current_user) #", "# \"\"\" # Deletes the student from the database # @param: # request", "add = request.POST.get('address') # hall = request.POST.get('hall') # room = request.POST.get('room') # cpi", "HttpResponseRedirect, JsonResponse from django.shortcuts import get_object_or_404, render from django.template.loader import get_template from django.views.decorators.csrf", "des.designation == s or des.designation == c: # designation = des.designation.name # des.delete()", "} if request.method == 'POST': try: id=request.POST['id'] programme=request.POST['programme'] batch=request.POST['batch'] branch=request.POST['branch'] sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"]", "- formatting variable of title text dep - temporary variables z - temporary", "request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code') faculty_list = get_faculty_list() courses = Course.objects.all() course_type = Constants.COURSE_TYPE", "request_programme - Programme from form request_sem - Semester from form curriculum - Get", "# return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # curr_id=request.POST['course'] # print(curr_id) #", "return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def add_curriculum(request): \"\"\" This", "datetime.datetime(*to_date).date() except Exception as e: from_date=\"\" to_date=\"\" desc=\"\" pass c = Calendar( from_date=from_date,", "current datetime month - current month \"\"\" now = datetime.datetime.now() month = int(now.month)", "choices - selected addtional courses by the academic person. # course - Course", "title=title, sex=sex, date_of_birth=dob, address=address, phone_no=phone_no, user_type='student', department=department, ) sem=1 stud_data = Student.objects.create( id=einfo,", "context) return HttpResponse(obj,content_type='application/json') else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required", "'valign': 'vcenter'}) normaltext = book.add_format({'bold': False, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) sheet", ":['10','1'] } acadTtForm = AcademicTimetableForm() if request.method == 'POST' and request.FILES: acadTtForm =", "JsonResponse(data)# ###################################################### # # ##########Senate meeting Minute################## # @csrf_exempt def addMinute(request): # \"\"\"", "user = get_object_or_404(User, username = e.user.username) # s = get_object_or_404(Student, id=e) # data", "{ # 'name': extraInfo.user.username, # 'rollno': extraInfo.id, # 'programme': student.programme, # 'branch': extraInfo.department.name", "- details of student from file department - details of student from file", "# return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST': # print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") # rollno", "= obj.account_status except Exception as e: examTtForm = \"\" acadTtForm = \"\" calendar", "= datetime.datetime(*to_date).date() get_calendar_details = Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description = desc get_calendar_details.from_date = from_date get_calendar_details.to_date =", "to edit curriculum in database It checkes the authentication of the user and", "from django.template.loader import render_to_string from django.contrib.auth.decorators import login_required from applications.academic_procedures.models import MinimumCredits, Register,", "request.method == \"POST\": i=1 while True: if str(i)+\"_ccode\" in request.POST: if str(i)+\"_fac\" in", "logging from io import BytesIO from xlsxwriter.workbook import Workbook from xhtml2pdf import pisa", "and edit entries in a curriculum. It checkes the authentication of the user", "new senator # data - data of the student to be displayed in", "curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) context= { 'curriculumm' :curriculum, 'tab_id' :['3','3']", "request.POST['option'] == '1': new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem,", "page. @variables: data - data of delete dictionary in post request t -", "# else: # data = {} # return JsonResponse(data) # @csrf_exempt def delete_basic_profile(request,", "if the user has searched for any particular curriculum if request_batch == \"\"", "the student is available # desig_id - mother 's name of the student", "desig_id).first() # print (temp) # print (current_user) # acadadmin = temp.working # k", "file category - details of student from file phone_no - details of student", "faculty - details of faculty of data faculty_list - list of faculty \"\"\"", "request.method == \"POST\": # if(Grades.objects.filter(student_id=id, sem=sem)): # s = Grades.objects.filter(student_id=id, sem=sem) # for", "Designation.objects.get(name='Co Convenor') # result = request.POST.get('designation') # hDes = HoldsDesignation() # hDes.user =", "# print(request.POST.get('rollno')) # extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Senator') # hDes =", "data = [] m = 1 for i in unregistered_students: z = []", "- contains metadata about the requested page # @variables: # current_user - the", "- credits from form.REQUEST optional - optional from form.REQUEST course_type - course_type from", "academic calendar event. to_date - The ending date for the academic caldendar event.", "sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',60) sheet.set_column('D:D',15) sheet.set_column('E:E',30) k = 4 num = 1", "= extraInfo.user # if result == \"Convenor\": # hDes.designation = s # else:", "discipline__acronym = dept, year = batch_year).first() user = User.objects.create_user( username=roll_no, password='<PASSWORD>', first_name=first_name, last_name=last_name,", "It deletes the grade of the student # @param: # request - contains", "- hostel room no # \"\"\" current_user = get_object_or_404(User, username=request.user.username) # user_details =", "about the requested page # @variables: # rollno - rollno of the student", "assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(acad_approval = False) assistant_approve_list = AssistantshipClaim.objects.filter(ta_supervisor_remark", "timetable Dean - the extraInfo objects that holds the designation as a dean", "user # sem - current semester of the student # data - tag", "faculty_list.append(i) return faculty_list @login_required def float_course(request): \"\"\" to float courses for the next", "contains metadata about the requested page # @variables: # s - the designation", "temp = str(i[3]).split() dep = str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext) k+=1 book.close() output.seek(0) response", "student object of the new senator # data - data of the student", "+= 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('registered') data.append(z) output = BytesIO() book =", "used to set up the homepage of the application. It checkes the authentication", "user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # print(\"confirm hone wala", "contains metadata about the requested page # pk - the primary key of", "Exception as e: f1=f2=f3=\"\" pass faculty = list(chain(f1,f2,f3)) faculty_list = [] for i", "import json import os import xlrd import logging from io import BytesIO from", "of the student with that rollno # s - designation object of senator", "einfo = ExtraInfo.objects.create( id=roll_no, user=user, title=title, sex=sex, date_of_birth=dob, address=address, phone_no=phone_no, user_type='student', department=department, )", "student - the students as a senator extra - all the extraInfor objects", "z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('registered') data.append(z) output = BytesIO() book = Workbook(output,{'in_memory':True}) title =", "from system year - current year batch - batch form form curriculum -", "branch).filter(batch = batch).filter(programme= programme) courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses':", "- student's address # final_user - details of the user # sem -", "database to send to template @param: request - contains metadata about the requested", "except Exception as e: programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\"", "\"ais/ais.html\", context) return HttpResponse(obj,content_type='application/json') else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context)", "get_object_or_404(Designation, name=\"Convenor\") c = get_object_or_404(Designation, name=\"Co Convenor\") # student = get_object_or_404(ExtraInfo, id=pk) #", "of the required user. # desig_id - used to check the designation ID.", "return render(request, \"ais/ais.html\", context) context= { 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context)", "# @variables: # current_user - gets the data of current user. # user_details", "data: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] a,b,c,d,e = str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp = str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext)", "# p = Designation.objects.get(name='Co Convenor') # result = request.POST.get('designation') # hDes = HoldsDesignation()", "for new batch. It checkes the authentication of the user and also fetches", "print(k) # final_user = k[2] # if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/')", "object of Co Convenor # result - the data that contains where the", "the student # programme - the programme the student is enrolled in #", "from form request_programme - Programme from form request_sem - Semester from form \"\"\"", "= extraInfo.user # hDes.working = extraInfo.user # hDes.designation = s # hDes.save() #", "AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(hod_approval = True) assistant_list_length = len(assistant_list.filter(acad_approval = False))", "from django.views.decorators.csrf import csrf_exempt from django.template.loader import render_to_string from django.contrib.auth.decorators import login_required from", "except Exception as e: id=\"\" programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\"", "programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) batch=batch+1", "for the next sem and store data in databsae. User must be logged", "id = d[0] # course = d[2] # sem = int(d[3]) # if", "# request - contains metadata about the requested page. # @variables: # sem_cred", "- contains metadata about the requested page. @variables: profiles - gets the excel", "# It deletes the grade of the student # @param: # request -", "the requested page. @variables: f1,f2,f3 - temporary varibles faculty - details of faculty", "Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') # result = request.POST.get('designation') # hDes =", "of the user # sem - current semester of the student # data", "registered_courses = [] for i in obj: if i.student_id.batch_id.year == int(batch): registered_courses.append(i) ans", "# to delete an existing senate meeting minute object from the database. #", "- the students as a senator extra - all the extraInfor objects exam_t", "= User.objects.create_user( username=roll_no, password='<PASSWORD>', first_name=first_name, last_name=last_name, email=email, ) einfo = ExtraInfo.objects.create( id=roll_no, user=user,", "from the server. @param: request - contains metadata about the requested page. @variables:", "decide curriculum for new batch. It checkes the authentication of the user and", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": data = request.POST['delete'] t =", "return render(request, \"ais/ais.html\", context) @login_required def edit_curriculum(request): \"\"\" This function is used to", "= {} # return JsonResponse(data) # @csrf_exempt def delete_basic_profile(request, pk): # \"\"\" #", "that contains convenor # c - the designation object that contains co convenor", "timetable - all the academic timetable objects calendar - all the academic calender", "HoldsDesignation() # hDes.user = extraInfo.user # hDes.working = extraInfo.user # if result ==", "} return render(request, \"ais/ais.html\", context) else: context= { 'tab_id' :['3','2'] } return render(request,", "import get_object_or_404, render from django.template.loader import get_template from django.views.decorators.csrf import csrf_exempt from django.template.loader", "True # course.save() # courses = Course.objects.all() # for i in courses: #", "- all the departments in the college attendance - all the attendance objects", "details of student from file fathers_name - details of student from file mothers_name", "of student from file title - details of student from file dob -", "to check if the student is available # mother - mother's name of", "# student = get_object_or_404(ExtraInfo, id=pk) # hDes = HoldsDesignation.objects.filter(user = student.user) # designation", "Formated data for context m - counter for Sl. No (in formated data)", "curriculum_courses, # } # return render(request, \"ais/ais.html\", context) # else: # return render(request,", "= Course.objects.all() courses_list = Courses.objects.all() course_type = Constants.COURSE_TYPE timetable = Timetable.objects.all() exam_t =", "@variables: senates - the extraInfo objects that holds the designation as a senator", "the student object of the new convenor/coconvenor # data - data of the", "of the student # batch - the current batch of the student #", "p.delete() # else: # return HttpResponse(\"Unable to delete data\") return HttpResponse(\"Data Deleted SuccessFully\")", "HttpResponse(\"Data Deleted Successfully\") def add_advanced_profile(request): # \"\"\" # It adds the advance profile", "in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == 'POST': programme =", "ans.append(k) ans.sort() output = BytesIO() book = Workbook(output,{'in_memory':True}) title = book.add_format({'bold': True, 'font_size':", "sem = int(d[3]) # if request.method == \"POST\": # if(Grades.objects.filter(student_id=id, sem=sem)): # s", "== \"POST\": i=1 while True: if str(i)+\"_ccode\" in request.POST: if str(i)+\"_fac\" in request.POST:", "Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() acadadmin = temp.working k = str(user_details).split()", "database desig - get designation object of student holds_desig - get hold_desig object", "faculty_list = [] for i in faculty: faculty_list.append(i) return faculty_list @login_required def float_course(request):", "= ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() acadadmin", "deleteSenator(request, pk): # \"\"\" # to remove a senator from the position #", "pk, # } # s.delete() # e.delete() # u.delete() # return JsonResponse(data)# #########################################################", "@variables: # sem_cred = Get credit details from forms and the append it", "the data of next semester courses courses - all the courses in curriculum", "requested page. # @variables: # sem_cred = Get credit details from forms and", "of the ongoing semester. @param: request - contains metadata about the requested page.", "\"POST\": data = request.POST['delete'] t = Timetable.objects.get(time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def", "the excel file having data excel - excel file sheet - sheet no", ") new_curr_inst.append(ins) else: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=False, ) new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst) else: break i+=1", "entry.branch=branch entry.sem=sem entry.course_code=course_code entry.course_id=course_id entry.credits=credits entry.optional=optional entry.course_type=course_type entry.save() curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch", "from form request_sem - Semester from form curriculum - Get data about curriculum", "workbook subtitle - formatting variable of subtitle the workbook normaltext - formatting variable", "<reponame>29rj/Fusion<gh_stars>10-100 import datetime import json import os import xlrd import logging from io", "= AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(acad_approval = False) assistant_approve_list = AssistantshipClaim.objects.filter(ta_supervisor_remark =", "in s: # if (str(p.course_id) == course): # print(p.course_id) # p.delete() # else:", "the students as a senator extra - all the extraInfor objects exam_t -", "import AcademicTimetableForm, ExamTimetableForm, MinuteForm from .models import (Calendar, Course, Exam_timetable, Grades, Curriculum_Instructor,Constants, Meeting,", "= ExamTimetableForm() if request.method == 'POST' and request.FILES: examTtForm = ExamTimetableForm(request.POST, request.FILES) if", "delete_advanced_profile(request): # \"\"\" # to delete the advance information of the student #", "\"\"\" acad-admin can delete the outdated exam timetable. @param: request - contains metadata", "name of the student # user_details - the rollno of the student required", "request - contains metadata about the requested page @variables: acadTtForm - the form", "\"\"\" This function gets basic gata from database to send to template @param:", "'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) normaltext = book.add_format({'bold': False, 'font_size': 15, 'align':", "calendar. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context= { 'academic_calendar' :calendar,", "User object of the student # s - the student object of the", "be displayed in the webpage \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request)", "programme=request.POST['AddProgramme'] batch=request.POST['AddBatch'] branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)] if \"optional_\"+str(i) in request.POST: optional=True", "\"semester_\"+str(i) in request.POST: try: programme=request.POST['AddProgramme'] batch=request.POST['AddBatch'] branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)] if", "as a senator students - all the objects in the Student class Convenor", "add academic calender examTtForm - the form required to add exam timetable Dean", "and the append it to an array. # sem - Get the object", "= Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme) courses = Course.objects.all() course_type = Constants.COURSE_TYPE", "data in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == 'POST': programme", "= student.user) # hDes.delete() # return HttpResponseRedirect('/aims/') # else: # return HttpResponseRedirect('/aims/')# ####################################################", "date from system year - current year batch - batch form form curriculum", "to_date - The ending date for the academic caldendar event. desc - Description", "courses = Course.objects.all() courses_list = Courses.objects.all() course_type = Constants.COURSE_TYPE timetable = Timetable.objects.all() exam_t", "f1 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Assistant Professor\")) f2 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Professor\")) f3 =", "college attendance - all the attendance objects of the students context - the", "s - the designation object that contains senator # student - the list", "= ' + batch.name + batch.discipline.acronym + str(batch.year) + '-preresgistration.xlsx' response['Content-Disposition'] = st", "JsonResponse(data) # else: # return HttpResponseRedirect('/aims/') # @csrf_exempt def deleteSenator(request, pk): # \"\"\"", "# name - the name of the student # roll - the rollno", "gets the batch from form sem - stores the next semester obj -", "take # @param: # request - contains metadata about the requested page. #", "this_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses = Course.objects.all() courses_list = Courses.objects.all() course_type", "examTtForm = ExamTimetableForm() acadTtForm = AcademicTimetableForm() calendar = Calendar.objects.all() this_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses", "'next_sem_course': next_sem_courses, 'this_sem_course': this_sem_courses, 'curriculum': curriculum, 'pgstudent' : pgstudent, 'assistant_list' : assistant_list, 'assistant_approve_list'", "file having data excel - excel file sheet - sheet no in excel", "exam_t = Exam_timetable.objects.all() pgstudent = Student.objects.filter(programme = \"M.Tech\") | Student.objects.filter(programme = \"PhD\") assistant_list", "for i in courses: # if i.course_id not in choices: # i.acad_selection =", "be deleted \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": data =", "(str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # print(request.POST)", "acadTtForm = AcademicTimetableForm() if request.method == 'POST' and request.FILES: acadTtForm = AcademicTimetableForm(request.POST, request.FILES)", "having data excel - excel file sheet - sheet no in excel file", "# hDes.delete() # return HttpResponseRedirect('/aims/') # else: # return HttpResponseRedirect('/aims/')# #################################################### # #", "\"ais/ais.html\", context) @login_required def add_curriculum(request): \"\"\" This function is used to add new", "examTtForm.is_valid(): examTtForm.save() return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context) return render(request,", "# db.id = roll # db.batch = batch # db.programme = programme #", "book.add_format({'bold': True, 'font_size': 22, 'align': 'center', 'valign': 'vcenter'}) subtitle = book.add_format({'bold': True, 'font_size':", "= get_object_or_404(ExtraInfo, id=pk) # user = get_object_or_404(User, username = e.user.username) # s =", "a student # @param: # request - contains metadata about the requested page", "for the minimum credits from the database and the update it. # \"\"\"", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) context['tab_id'][0]='6' if request.method == 'POST':", "\"ais/ais.html\", context) @login_required def add_exam_timetable(request): \"\"\" acad-admin can upload the exam timtable of", "sheet=excel.sheet_by_index(0) for i in range(sheet.nrows): roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value) if sex ==", "get_object_or_404(ExtraInfo, id=pk) # hDes = HoldsDesignation.objects.filter(user = student.user) # designation = [] #", "page # pk - the primary key of that particular student field #", "return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # print(request.POST) # rollno=request.POST.get('roll') # print(rollno)", "= temp.working k = str(user_details).split() final_user = k[2] except Exception as e: acadadmin=\"\"", "batch # db.programme = programme # st.phone_no = ph # db.save() # st.save()", "django.template.loader import get_template from django.views.decorators.csrf import csrf_exempt from django.template.loader import render_to_string from django.contrib.auth.decorators", "- details of student from file hall_no - details of student from file", "= p # hDes.save() # data = { # 'name': extraInfo.user.username, # 'rollno_convenor':", "extraInfo objects that holds the designation as a dean student - the students", "faculty = list(chain(f1,f2,f3)) faculty_list = [] for i in faculty: faculty_list.append(i) return faculty_list", "if Student.objects.get(id=stu): # s = Student.objects.get(id=stu) # s.father_name = \"\" # s.mother_name =", "student.save() # s = Student.objects.get(id=student) # s.father_name=father # s.mother_name=mother # s.hall_no = hall", "== 0: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).order_by('sem') else: curriculum =", "- Description for the academic calendar event. c = object to save new", "extraInfo.user.username, # 'rollno_convenor': extraInfo.id, # 'designation': hDes.designation.name, # } # return JsonResponse(data) #", "print(curr_id) # curr_course = Curriculum.objects.filter(curriculum_id=curr_id) # grades = Grades.objects.filter(curriculum_id=curr_course) # context= { #", "except Exception as e: examTtForm = \"\" acadTtForm = \"\" calendar = \"\"", "form.REQUEST sem - semester from form.REQUEST course_code - course_code from form.REQUEST course_name -", "@variables: batch - gets the batch course - gets the course curr_key -", "t - the minute object received from id to be deleted # \"\"\"", "from file first_name - details of student from file last_name - details of", "of student from file department - details of student from file specialization -", "if request.method == \"POST\": i=1 while True: if str(i)+\"_ccode\" in request.POST: if str(i)+\"_fac\"", "calendar = \"\" this_sem_courses = \"\" next_sem_courses = \"\" courses = \"\" course_type", "that rollno # s - designation object of Convenor # p - designation", "i=1 while True: if str(i)+\"_ccode\" in request.POST: if str(i)+\"_fac\" in request.POST: if request.POST[str(i)+\"_fac\"]", "= Designation.objects.get(name='student') hold_des = HoldsDesignation.objects.create( user=user, working=user, designation=desig, ) sem_id = Semester.objects.get(curriculum =", "- the student object with the given pk # hDes - the holdDesignation", "== 'POST': try: id=request.POST['id'] programme=request.POST['programme'] batch=request.POST['batch'] branch=request.POST['branch'] sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"] if", "calendar event. c = object to save new event to the academic calendar.", "render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj = json.dumps({'html':html}) #return render(request, \"ais/ais.html\", context) return HttpResponse(obj,content_type='application/json') else: return render(request,", "'tab_id' :['3','1'] # } courses = Course.objects.all() course_type = Constants.COURSE_TYPE html = render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request)", "import os import xlrd import logging from io import BytesIO from xlsxwriter.workbook import", "normaltext = book.add_format({'bold': False, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) sheet = book.add_worksheet()", "Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).order_by('sem') else: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch =", "[1, 3, 5, 7] # examTtForm = ExamTimetableForm() # acadTtForm = AcademicTimetableForm() #", "= str(user_details).split() # print(k) # final_user = k[2] # if (str(acadadmin) != str(final_user)):", "curr_id=request.POST['course'] # print(curr_id) # curr_course = Curriculum.objects.filter(curriculum_id=curr_id) # grades = Grades.objects.filter(curriculum_id=curr_course) # context=", "student from file programme - details of student from file batch - details", "= Constants.COURSE_TYPE # context= { # 'courses': courses, # 'course_type': course_type, # 'curriculum_course':", "i in range(sheet.nrows): roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value) if sex == 'F': title='Ms.'", "user - the User object of the student # s - the student", "'query_option1': procedures_context['query_option1'], 'query_option2': procedures_context['query_option2'], 'course_verification_date' : procedures_context['course_verification_date'], 'submitted_course_list' : procedures_context['submitted_course_list'], 'result_year' : procedures_context['result_year'],", "= Student.objects.filter(programme = \"M.Tech\") | Student.objects.filter(programme = \"PhD\") assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark", "the requested page @variables: senates - the extraInfo objects that holds the designation", "student is holding the senator designation # student - the student object of", "the databases to display it on the page. @param: request - contains metadata", "- checking the designation of the current user # acadadmin - deatils of", "which the grade has to be added sem - semester of the student", "addtional courses by the academic person. # course - Course details which is", "student from file dob - details of student from file fathers_name - details", "context) return render(request, \"ais/ais.html\", context) def get_faculty_list(): \"\"\" to get faculty list from", "= list(chain(f1,f2,f3)) faculty_list = [] for i in faculty: faculty_list.append(i) return faculty_list @login_required", "uploaded') # return render(request, \"ais/ais.html\", {}) def deleteMinute(request): # \"\"\" # to delete", "return JsonResponse(data) # else: # data = {} # return JsonResponse(data) # @csrf_exempt", "no, room no, # profile picture, about me etc of a student #", "the requested page @variables: batch - gets the batch course - gets the", "from current time now - get current time year - getcurrent year batch", "'course_type': course_type, 'curriculum': curriculum, 'faculty_list': faculty_list, 'tab_id' :['5','1'] } return render(request, \"ais/ais.html\", context)", "Exam_timetable.objects.all() pgstudent = Student.objects.filter(programme = \"M.Tech\") | Student.objects.filter(programme = \"PhD\") assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark", "= \"\" # s.save() # else: # return HttpResponse(\"Data Does Not Exist\") #", "Added\") return render(request, \"ais/ais.html\", context) @login_required def update_calendar(request): \"\"\" to update an entry", "details from forms and the append it to an array. # sem -", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','2'] } if request.method == 'POST': i=0", "extraInfo.department.name # } # return HttpResponseRedirect('/aims/') # # return JsonResponse(data) # else: #", "6, 8] @login_required def generatexlsheet(request): \"\"\" to generate Course List of Registered Students", "def edit_curriculum(request): \"\"\" This function is used to edit curriculum in database It", "email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value) if sex == 'F': title='Ms.' else: title='Mr.' dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value)", "Exception as e: from_date=\"\" to_date=\"\" desc=\"\" pass c = Calendar( from_date=from_date, to_date=to_date, description=desc)", "if request.POST[str(i)+\"_fac\"] == \"\" : logging.warning(\"No faculty\") else: flot = Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated =", "now - current date from system year - current year batch - batch", "that rollno # s - designation object of senator # hDes - holdsDesignation", "'examTtForm': examTtForm, 'courses': courses, 'courses_list': courses_list, 'course_type': course_type, 'exam': exam_t, 'timetable': timetable, 'academic_calendar':", "about the requested page. @variables: f1,f2,f3 - temporary varibles faculty - details of", "advance profile information like hall no, room no, # profile picture, about me", "from_date[0].split('-') from_date = [int(i) for i in from_date] from_date = datetime.datetime(*from_date).date() to_date =", "= None #Curriculum.objects.all() else: if int(request_sem) == 0: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch", "return HttpResponseRedirect('/aims/') # else: # return HttpResponseRedirect('/aims/')# #################################################### # # ##########covenors and coconvenors##################", "of where the student stays # room no - hostel room no #", "of the calendar instance from the database for the previous Description. \"\"\" if", "desig_id).first() acadadmin = temp.working k = str(user_details).split() final_user = k[2] except Exception as", "registered_students: z = [] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('registered')", ": course_type, # 'curriculum' : curriculum, # 'tab_id' :['3','1'] # } courses =", "return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # print(\"confirm hone wala hai\") #", "next_curriculum(request): \"\"\" This function is used to decide curriculum for new batch. It", "request.method == 'POST': i=0 new_curr=[] while True: if \"semester_\"+str(i) in request.POST: try: programme=request.POST['AddProgramme']", ": \"+str(str(batch)))) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle)", "student # rollno - the rollno of the student required to check if", "of faculty \"\"\" try: f1 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Assistant Professor\")) f2 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name", "request.method == \"POST\": # st = request.POST['delete'] # arr = st.split(\"-\") # stu", "+ \" \" + str(room) # student.save() # s = Student.objects.get(id=student) # s.father_name=father", "the details of the current user # desig_id - checking the designation of", "add_convenor(request): # \"\"\" # to add a new student convenor/coconvenor # @param: #", "object to save new event to the academic calendar. \"\"\" if user_check(request): return", "roll # db.batch = batch # db.programme = programme # st.phone_no = ph", "= Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') # if request.method == 'POST': #", "acadadmin - designation for Acadadmin final_user - final designation of request user \"\"\"", "searched for any particular curriculum if request_batch == \"\" and request_branch == \"\"", "else: return [2, 4, 6, 8] @login_required def generatexlsheet(request): \"\"\" to generate Course", "return [1, 3, 5, 7] else: return [2, 4, 6, 8] @login_required def", "authentication of the user. @param: request - contains metadata about the requested page", "object of student currs - get curriculum details reg - create registeration object", "== c: # designation = des.designation.name # des.delete() # data = { #", ") new_curr.append(ins) else: break i+=1 Curriculum.objects.bulk_create(new_curr) curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme=", "# if request.method == \"POST\": # st = request.POST['delete'] # arr = st.split(\"-\")", "str(i[3]).split() dep = str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type", "in range(1, 9): # sem = MinimumCredits.objects.all().filter(semester=i).first() # sem.credits = sem_cred[i+1] # sem.save()", "Description for the previous event which is to be updated. get_calendar_details = Get", "MinimumCredits, Register, InitialRegistration, course_registration, AssistantshipClaim,Assistantship_status from applications.globals.models import (Designation, ExtraInfo, HoldsDesignation, DepartmentInfo) from", "extraInfo objects that holds the designation as a coconvenor meetings - the all", "timetable from the server. @param: request - contains metadata about the requested page.", "= get_context(request) context['tab_id'][0]='6' if request.method == 'POST': try: request_batch = request.POST['batch'] request_branch =", "sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',50) sheet.set_column('D:D',15) sheet.set_column('E:E',15) k", "# print(request.POST['delete']) # data = request.POST['delete'] # d = data.split(\"-\") # id =", "#for checking if the user has searched for any particular curriculum if request_batch", "- course ofwhich the grade is added \"\"\" # if user_check(request): # return", "sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)] if \"optional_\"+str(i) in request.POST: optional=True else: optional=False course_type=request.POST[\"course_type_\"+str(i)]", "######################################################### # ''' # # view to add attendance data to database #", "k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department) ans.append(k) ans.sort() output = BytesIO() book = Workbook(output,{'in_memory':True}) title =", "curriculum, # 'tab_id' :['3','1'] # } courses = Course.objects.all() course_type = Constants.COURSE_TYPE html", "# s = get_object_or_404(Student, id=e) # data = { # 'rollno': pk, #", "Register, InitialRegistration, course_registration, AssistantshipClaim,Assistantship_status from applications.globals.models import (Designation, ExtraInfo, HoldsDesignation, DepartmentInfo) from .forms", "database @param: request - contains metadata about the requested page. @variables: f1,f2,f3 -", "# ##########covenors and coconvenors################## # @csrf_exempt def add_convenor(request): # \"\"\" # to add", "in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, )", "# convenor or coconvenor # hDes - holdsDesignation object to store that the", ": assistant_approve_list, 'assistant_list_length' : assistant_list_length, 'tab_id': ['1','1'], 'context': procedures_context['context'], 'lists': procedures_context['lists'], 'date': procedures_context['date'],", "id=pk) # hDes = HoldsDesignation.objects.filter(user = student.user) # designation = [] # for", "add data to formatted array/variable output - io Bytes object to write to", "# if request.method == \"POST\": # if(Grades.objects.filter(student_id=id, sem=sem)): # s = Grades.objects.filter(student_id=id, sem=sem)", "{ 'tab_id' :['5','1'] } if request.method == \"POST\": i=1 while True: if str(i)+\"_ccode\"", "- tag whether to delete it or not # course - get the", "check if the student is available desig_id - mother's name of the student", "+ str(batch.year)) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle)", "a senator from the position # @param: # request - contains metadata about", "gets the course curr_key - gets the curriculum from database obj - get", "# sem - current semester of the student # data - tag whether", "excel = xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) for i in range(sheet.nrows): roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value)", "'POST': # print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") # rollno = request.POST.getlist('Roll Number')[0] # # print(request.POST.get('rollno')) #", "batch - batch from form.REQUEST branch - branch from form.REQUEST sem - semester", "add attendance data to database # def curriculum(request): # ''' def delete_advanced_profile(request): #", "= Get credit details from forms and the append it to an array.", "new user created in database einfo - new extrainfo object created in database", "- details of the current user. # desig_id - to check the designation", "k = str(user_details).split() final_user = k[2] except Exception as e: acadadmin=\"\" final_user=\"\" pass", "request - contains metadata about the requested page @variables: senates - the extraInfo", "from file dob - details of student from file fathers_name - details of", "student # user_details - the rollno of the student required to check if", "of senator # hDes - holdsDesignation object to store that the particualr student", "- tha data of thsi semester courses next_sem_courses - the data of next", "about the requested page @variables: current_user - father's name of the student user_details", "= get_object_or_404(User, username = i) inst = ExtraInfo.objects.select_related('user','department').get(user=inst) if c==0: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst,", "from file fathers_name - details of student from file mothers_name - details of", "= book.add_worksheet() title_text = (\"Pre-registeration : \"+ batch.name + str(\" \") + batch.discipline.acronym", "minimum credits from the database and the update it. # \"\"\" if request.method==\"POST\":", "- contains metadata about the requested page @variables: senates - the extraInfo objects", "database # @param: # request - contains metadata about the requested page #", "for course_slot in course_slots: courses += course_slot.courses.all() new_reg=[] for c in courses: reg=course_registration(", ": logging.warning(\"No faculty\") else: flot = Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated = True flot.save() new_curr_inst=[] for", "the basic profile information like username,password, name, # rollno, etc of a student", "objects department - all the departments in the college attendance - all the", "registered') data.append(z) for i in registered_students: z = [] z.append(m) m += 1", "stores the next semester obj - All the registration details appended into one", "= batch).filter(programme = programme) if request.POST['option'] == '1': new_curriculum=[] for i in curriculum:", "variable of title text dep - temporary variables z - temporary variables for", "# s.save() # else: # return HttpResponse(\"Data Does Not Exist\") # return HttpResponse(\"Data", "= 'application/vnd.ms-excel') st = 'attachment; filename = ' + course.code + '.xlsx' response['Content-Disposition']", "data = { # 'rollno': pk, # } # s.delete() # e.delete() #", "[] # for des in hDes: # if des.designation == s or des.designation", "excel file roll_no - details of student from file first_name - details of", "the grade has to be added sem - semester of the student grade", "HoldsDesignation.objects.create( user=user, working=user, designation=desig, ) sem_id = Semester.objects.get(curriculum = batch.curriculum, semester_no = sem)", "# @variables: # sem_cred = Get credit details from forms and the append", "to decide curriculum for new batch. It checkes the authentication of the user", "credits=\"\" optional=\"\" course_type=\"\" pass ins=Curriculum( programme=programme, batch=batch, branch=branch, sem=sem, course_code=course_code, course_id=course_id, credits=credits, optional=optional,", ") einfo = ExtraInfo.objects.create( id=roll_no, user=user, title=title, sex=sex, date_of_birth=dob, address=address, phone_no=phone_no, user_type='student', department=department,", "sheet = book.add_worksheet() title_text = (\"Pre-registeration : \"+ batch.name + str(\" \") +", "update it. # \"\"\" if request.method==\"POST\": sem_cred = [] # sem_cred.append(0) # for", "# if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # curr_id=request.POST['course']", "father = request.POST.get('father') # mother = request.POST.get('mother') # add = request.POST.get('address') # hall", "course - get the course details # \"\"\" # current_user = get_object_or_404(User, username=request.user.username)", "'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context) context= { 'tab_id' :['3','1'] } return", "print(data) # return JsonResponse(data) # else: # data = {} # return JsonResponse(data)", "page @variables: programme - programme from form.REQUEST batch - batch from form.REQUEST branch", "curriculum if request_batch == \"\" and request_branch == \"\" and request_programme==\"\" and request_sem==\"\":", "No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',50) sheet.set_column('D:D',15) sheet.set_column('E:E',15) k = 4 num", "request.method == \"POST\": # curr_id=request.POST['course'] # print(curr_id) # curr_course = Curriculum.objects.filter(curriculum_id=curr_id) # grades", "# room = request.POST.get('room') # cpi = request.POST.get('cpi') # student.address = str(hall) +", "of delete dictionary in post request t - Object of time table to", "for stu in obj: registered_students.add(stu.student_id) students = Student.objects.filter(batch_id = batch_id) for stu in", "enumerate(request.POST.getlist(str(i)+'_fac')): inst = get_object_or_404(User, username = i) inst = ExtraInfo.objects.select_related('user','department').get(user=inst) if c==0: ins=Curriculum_Instructor(", "- used to check the designation ID. # extraInfo - extraInfo object of", "- contains metadata about the requested page. @variables: acadTtForm - data of delete", "== \"POST\": data = request.POST['delete'] t = Exam_timetable.objects.get(exam_time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required", "the extraInfo objects that holds the designation as a senator students - all", "and the update it. # \"\"\" if request.method==\"POST\": sem_cred = [] # sem_cred.append(0)", "# current_user - the username of the logged in user # user_details -", "credits=request.POST[\"credits_\"+str(i)] if \"optional_\"+str(i) in request.POST: optional=True else: optional=False course_type=request.POST[\"course_type_\"+str(i)] except Exception as e:", "s # else: # hDes.designation = p # hDes.save() # data = {", "= from_date get_calendar_details.to_date = to_date get_calendar_details.save() except Exception as e: from_date=\"\" to_date=\"\" desc=\"\"", "the designation object that contains convenor # c - the designation object that", "requested page # @variables: # rollno - rollno of the student to become", "particualr student is holding the senator designation # student - the student object", "= ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') # result", "outdated timetable from the server. @param: request - contains metadata about the requested", "= ExtraInfo.objects.select_related('user','department').get(user=inst) if c==0: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=True, ) new_curr_inst.append(ins) else: ins=Curriculum_Instructor( curriculum_id=flot,", "the student grade - grade to be added in the student course -", "= ' + course.code + '.xlsx' response['Content-Disposition'] = st return response @login_required def", "context) @login_required def add_exam_timetable(request): \"\"\" acad-admin can upload the exam timtable of the", "to check if the student is available # desig_id - mother 's name", "''' def delete_advanced_profile(request): # \"\"\" # to delete the advance information of the", "the page. @param: request - contains metadata about the requested page @variables: senates", "output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st = 'attachment; filename = ' +", "new convenor/coconvenor # data - data of the student to be displayed in", "# acadadmin = temp.working # k = str(user_details).split() # print(k) # final_user =", "return JsonResponse(data) # else: # return HttpResponseRedirect('/aims/') # @csrf_exempt def deleteSenator(request, pk): #", "about the requested page @variables: programme - programme from form.REQUEST batch - batch", "entry to the academic calendar to be updated. @param: request - contains metadata", "== 'POST': try: request_batch = request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme'] except", "# return JsonResponse(data)# ######################################################### # ''' # # view to add attendance data", "request - contains metadata about the requested page. @variables: f1,f2,f3 - temporary varibles", "function is used to check the type of user. It checkes the authentication", "with that rollno # s - designation object of Convenor # p -", "request_batch == \"\" and request_branch == \"\" and request_programme==\"\" and request_sem==\"\": curriculum =", "exam_t, 'timetable': timetable, 'tab_id' :['10','2'] } examTtForm = ExamTimetableForm() if request.method == 'POST'", "acadTtForm - data of delete dictionary in post request timetable - all timetable", "return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context= { 'academic_calendar' :calendar, 'tab_id' :['4','1'] } if", "senator # \"\"\" pass # if request.POST: # s = get_object_or_404(Designation, name=\"Senator\") #", "get courses from database courses_type - get course types from database \"\"\" if", "academic calender objects department - all the departments in the college attendance -", "= Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','2'] } examTtForm =", "HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','2'] } if request.method == 'POST': i=0 new_curr=[] while True:", "st = request.POST['delete'] # arr = st.split(\"-\") # stu = arr[0] # if", "batch).filter(programme= programme).filter(sem = sem) # print(curriculum_courses) # courses = Course.objects.all() # course_type =", "sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',50) sheet.set_column('D:D',15) sheet.set_column('E:E',15) k = 4 num = 1", "\"ais/ais.html\") def delete_grade(request): # \"\"\" # It deletes the grade of the student", "deleted from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if", "# data - the id of the minute object to be deleted #", "acadadmin - student's address subject - subject of which the grade has to", "extract details of user from database desig_id - check for designation acadadmin -", "from .forms import AcademicTimetableForm, ExamTimetableForm, MinuteForm from .models import (Calendar, Course, Exam_timetable, Grades,", "= Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) context= { 'curriculumm' :curriculum, 'tab_id' :['3','3'] }", "database ans - Formatted Array to be converted to xlsx k -temporary array", "= room # s.save() # return HttpResponseRedirect('/academic-procedures/') # return HttpResponseRedirect('/academic-procedures/') def add_optional(request): #", "@login_required def verify_grade(request): \"\"\" It verify the grades of the student @param: request", "details form database ins - Inster data in database \"\"\" if user_check(request): return", "mother's name of the student acadadmin - student's address subject - subject of", "int(now.year) batch = year-1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) if request.POST['option']", "context= { 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context) context= { 'tab_id' :['3','1']", "dep - temporary variables z - temporary variables for final output b -", "in choices: # course = Course.objects.all().filter(course_id=i).first() # course.acad_selection = True # course.save() #", "context = get_context(request) return render(request, \"ais/ais.html\", context) # #################################### # # curriculum #", "MinuteForm(request.POST, request.FILES) # if form.is_valid(): # form.save() # return HttpResponse('sucess') # else: #", "context - the datas to be displayed in the webpage \"\"\" if user_check(request):", "the user. @param: request - contains metadata about the requested page @variables: current_user", "'hod_flag' : hod_flag, 'account_flag' : account_flag } return context @login_required def homepage(request): \"\"\"", "HttpResponse(\"TimeTable Deleted\") @login_required def delete_exam_timetable(request): \"\"\" acad-admin can delete the outdated exam timetable.", "fathers_name - details of student from file mothers_name - details of student from", ": curriculum, # 'tab_id' :['3','1'] # } courses = Course.objects.all() course_type = Constants.COURSE_TYPE", "the student object from the requested rollno # \"\"\" current_user = get_object_or_404(User, username=request.user.username)", "'valign': 'vcenter'}) sheet = book.add_worksheet() title_text = (\"Pre-registeration : \"+ batch.name + str(\"", "a student must take # @param: # request - contains metadata about the", "a senator extra - all the extraInfor objects exam_t - all the exam", "= ExtraInfo.objects.get(id=rollno) # print(student.address) # if not student: # data = {} #", "###################################################### # # ##########Senate meeting Minute################## # @csrf_exempt def addMinute(request): # \"\"\" #", "os import xlrd import logging from io import BytesIO from xlsxwriter.workbook import Workbook", "assistant_flag = obj.student_status hod_flag = obj.hod_status account_flag = obj.account_status except Exception as e:", "== \"POST\": # programme=request.POST['programme'] # batch=request.POST['batch'] # branch=request.POST['branch'] # sem=request.POST['sem'] # curriculum_courses =", "Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) if request.POST['option'] == '1': new_curriculum=[] for i in", "key of that particular student field # @variables: # s - the designation", "as e: batch=\"\" course=\"\" curr_key=\"\" obj=\"\" registered_courses = [] for i in obj:", "= e.user.username) # s = get_object_or_404(Student, id=e) # data = { # 'rollno':", "pk): # \"\"\" # to remove a convenor/coconvenor from the position # @param:", "= request.POST['programme'] request_sem = request.POST['sem'] except Exception as e: request_batch = \"\" request_branch", "to get the details of the required user. # \"\"\" # current_user =", "by the academic admin. # \"\"\" if request.method == \"POST\": pass # print(request.POST)", "get_faculty_list(): \"\"\" to get faculty list from database @param: request - contains metadata", "the database # @param: # request - contains metadata about the requested page", "requested page. @variables: profiles - gets the excel file having data excel -", "= 1 for i in unregistered_students: z = [] z.append(m) m += 1", "= \"Professor\")) f3 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Associate Professor\")) except Exception as e: f1=f2=f3=\"\"", "if request.method == \"POST\": # print(\"confirm hone wala hai\") # print(request.POST) return HttpResponseRedirect('/aims/')", "'programme': programme, # 'phoneno': ph, # 'batch': batch # } # print(data) #", "- contains metadata about the requested page. @variables: examTtForm - data of delete", "= ExtraInfo.objects.create( id=roll_no, user=user, title=title, sex=sex, date_of_birth=dob, address=address, phone_no=phone_no, user_type='student', department=department, ) sem=1", "# } # return render(request, \"ais/ais.html\", context) # else: # return render(request, \"ais/ais.html\")", "batch=request.POST['batch'] branch=request.POST['branch'] sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"] if request.POST['optional'] == \"on\": optional=True else:", "= Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description = desc get_calendar_details.from_date = from_date get_calendar_details.to_date = to_date get_calendar_details.save() except", "objects that holds the designation as a senator students - all the objects", "current_user - gets the data of current user. # user_details - gets the", "Courses, Batch, Semester, Programme, Discipline) from applications.academic_procedures.views import acad_proced_global_context from applications.programme_curriculum.models import Batch", "return render(request, \"ais/ais.html\", context) #Generate Attendance Sheet def sem_for_generate_sheet(): \"\"\" This function generates", "Course.objects.all() # for i in courses: # if i.course_id not in choices: #", "'valign': 'vcenter'}) subtitle = book.add_format({'bold': True, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) normaltext", "senator # @param: # request - contains metadata about the requested page #", "# @variables: # e - the extraInfo objects of the student # user", "view_course(request): # if request.method == \"POST\": # programme=request.POST['programme'] # batch=request.POST['batch'] # branch=request.POST['branch'] #", "\"\"\" s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') # if request.method ==", "t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def add_calendar(request): \"\"\" to add an entry to", "HttpResponse('not uploaded') # return render(request, \"ais/ais.html\", {}) def deleteMinute(request): # \"\"\" # to", "for i in range(1, 9): # sem = MinimumCredits.objects.all().filter(semester=i).first() # sem.credits = sem_cred[i+1]", "add_timetable(request): \"\"\" acad-admin can upload the time table(any type of) of the semester.", "for des in hDes: # if des.designation == s or des.designation == c:", "request.POST.get('name') # roll = ExtraInfo.objects.get(id=request.POST.get('rollno')) # programme = request.POST.get('programme') # batch = request.POST.get('batch')", "hall_no=int(hall_no) programme_name=request.POST['Programme'] batch_year=request.POST['Batch'] batch = Batch.objects.all().filter(name = programme_name, discipline__acronym = dept, year =", "designation, # } # return JsonResponse(data)# ###################################################### # # ##########Senate meeting Minute################## #", "xlsx k -temporary array to add data to formatted array/variable output - io", "form.REQUEST course_name - course-name from form.REQUEST course_id - course_id from database credits -", "like hall no, room no, # profile picture, about me etc of a", "# hDes.working = extraInfo.user # if result == \"Convenor\": # hDes.designation = s", "obj in assis_stat: assistant_flag = obj.student_status hod_flag = obj.hod_status account_flag = obj.account_status except", "# \"\"\" # to remove a convenor/coconvenor from the position # @param: #", "# student - the student object of the new senator # data -", "in a curriculum. It checkes the authentication of the user and also fetches", "id=request.POST['id'] programme=request.POST['programme'] batch=request.POST['batch'] branch=request.POST['branch'] sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"] if request.POST['optional'] == \"on\":", "== \"\" and request_programme==\"\": curriculum = None #Curriculum.objects.all() else: sem = sem_for_generate_sheet() now", "# courses = Course.objects.all() # for i in courses: # if i.course_id not", "courses from database courses_type - get course types from database \"\"\" if user_check(request):", "\"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def add_exam_timetable(request): \"\"\" acad-admin can upload", "== \"POST\": try: from_date = request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] prev_desc", "= False # i.save() # return HttpResponseRedirect('/academic-procedures/') def min_cred(request): # \"\"\" # to", "request - contains metadata about the requested page @variables: request_batch - Batch from", "[] for i in registered_courses: k = [] k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department) ans.append(k)", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['2','1'] } if request.method ==", "data - the id of the minute object to be deleted # t", "= \"\" request_programme = \"\" if request_batch == \"\" and request_branch == \"\"", "HttpResponseRedirect('/academic-procedures/') # print(request.POST['delete']) # data = request.POST['delete'] # d = data.split(\"-\") # id", "'curriculum': curriculum, 'pgstudent' : pgstudent, 'assistant_list' : assistant_list, 'assistant_approve_list' : assistant_approve_list, 'assistant_list_length' :", "\"ais/ais.html\", context) else: context= { 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context) context=", "get_object_or_404(Designation, name=\"Senator\") # student = get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0]) # hDes = get_object_or_404( HoldsDesignation, user", "for i in to_date] to_date = datetime.datetime(*to_date).date() get_calendar_details = Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description = desc", "it. # \"\"\" if request.method==\"POST\": sem_cred = [] # sem_cred.append(0) # for i", "= Student.objects.filter(batch_id = batch_id) for stu in students: if stu not in registered_students:", "courses_list = Courses.objects.all() course_type = Constants.COURSE_TYPE timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() pgstudent", "import (CourseSlot, Course as Courses, Batch, Semester, Programme, Discipline) from applications.academic_procedures.views import acad_proced_global_context", "1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('registered') data.append(z) output = BytesIO() book = Workbook(output,{'in_memory':True})", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() context= { 'exam':", "\"+str(str(batch)))) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20)", "username = e.user.username) # s = get_object_or_404(Student, id=e) # data = { #", "time table(any type of) of the semester. @param: request - contains metadata about", "course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) batch=batch+1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme", "@variables: # current_user - gets the data of current user. # user_details -", "# It adds the advance profile information like hall no, room no, #", "the homepage of the application. It checkes the authentication of the user and", "request - contains metadata about the requested page @variables: programme - programme from", "room no, # profile picture, about me etc of a student # @param:", "request.POST: try: programme=request.POST['AddProgramme'] batch=request.POST['AddBatch'] branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)] if \"optional_\"+str(i) in", "# # ---------------------senator------------------ # @csrf_exempt def senator(request): # \"\"\" # to add a", "senate meeting minutes acadTtForm - the form to add academic calender examTtForm -", "final_user = k[2] # if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if", "f3 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Associate Professor\")) except Exception as e: f1=f2=f3=\"\" pass faculty", "required to check if the student is available desig_id - mother's name of", "if sex == 'F': title='Ms.' else: title='Mr.' dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value)", "request_programme = request.POST['programme'] except Exception as e: request_batch = \"\" request_branch = \"\"", "True: if str(i)+\"_ccode\" in request.POST: if str(i)+\"_fac\" in request.POST: if request.POST[str(i)+\"_fac\"] == \"\"", "request - contains metadata about the requested page # @variables: # s -", "extraInfo objects that holds the designation as a convenor CoConvenor - the extraInfo", "i in from_date] from_date = datetime.datetime(*from_date).date() to_date = to_date[0].split('-') to_date = [int(i) for", "details appended into one data - Formated data for context m - counter", "z,b,c = str(i[0]),i[1],i[2] a,b,c,d,e = str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp = str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext)", "form form curriculum - curriculum details form database ins - Inster data in", "return render(request, \"ais/ais.html\", context) # #################################### # # curriculum # # #################################### @login_required", "django.views.decorators.csrf import csrf_exempt from django.template.loader import render_to_string from django.contrib.auth.decorators import login_required from applications.academic_procedures.models", "s.room_no = room # s.save() # return HttpResponseRedirect('/academic-procedures/') # return HttpResponseRedirect('/academic-procedures/') def add_optional(request):", "request - contains metadata about the requested page. # @variables: # sem_cred =", "course_slots = CourseSlot.objects.all().filter(semester = sem_id) courses = [] for course_slot in course_slots: courses", "from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) context['tab_id'][0]='6' if request.method", "= datetime.datetime(*to_date).date() except Exception as e: from_date=\"\" to_date=\"\" desc=\"\" pass c = Calendar(", "= True).filter(hod_approval =True).filter(acad_approval = False) assistant_approve_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(hod_approval", "array/variable output - io Bytes object to write to xlsx file book -", "# else: # data = {} # return JsonResponse(data) # @csrf_exempt def deleteConvenor(request,", "context) return render(request, \"ais/ais.html\", context) @login_required def delete_curriculum(request): \"\"\" This function is used", "get_calendar_details.to_date = to_date get_calendar_details.save() except Exception as e: from_date=\"\" to_date=\"\" desc=\"\" return render(request,", "Semester.objects.get(curriculum = batch.curriculum, semester_no = sem) course_slots = CourseSlot.objects.all().filter(semester = sem_id) courses =", "Inster data in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == 'POST':", "courses = Course.objects.all() course_type = Constants.COURSE_TYPE html = render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj = json.dumps({'html':html}) #return", "request.POST['batch']).filter(programme= request.POST['programme']) courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses': courses, 'course_type':", "- the extraInfo objects that holds the designation as a dean student -", "if \"optional_\"+str(i) in request.POST: optional=True else: optional=False course_type=request.POST[\"course_type_\"+str(i)] except Exception as e: programme=\"\"", "'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) @login_required def add_timetable(request): \"\"\" acad-admin can", "# cpi = request.POST.get('cpi') # student.address = str(hall) + \" \" + str(room)", "context) @login_required def add_curriculum(request): \"\"\" This function is used to add new curriculum", "the object for the minimum credits from the database and the update it.", "- to check the designation of the user. # user_details - to get", "student from file user - new user created in database einfo - new", "used to check the designation ID. # extraInfo - extraInfo object of the", "# @variables: # current_user - father's name of the student # user_details -", "str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # print(request.POST['delete']) # data = request.POST['delete'] # d =", "HttpResponse(obj,content_type='application/json') else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def add_curriculum(request):", "the id of the minute object to be deleted # t - the", "for a current semester that a student must take # @param: # request", "= Grades.objects.filter(curriculum_id=curr_course) # context= { # 'grades': grades, # 'tab_id' :\"2\" # }", "to update the additional courses # @param: # request - contains metadata about", "all the extraInfor objects exam_t - all the exam timetable objects timetable -", "the database. # @param: # request - contains metadata about the requested page", "name, # 'rollno': roll.id, # 'programme': programme, # 'phoneno': ph, # 'batch': batch", "programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme", "HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st = 'attachment; filename = ' + batch.name + batch.discipline.acronym", "of subtitle the workbook normaltext - formatting variable for normal text sheet -", "- final designation of request user \"\"\" try: current_user = get_object_or_404(User, username=request.user.username) user_details", "st return response @login_required def generate_preregistration_report(request): \"\"\" to generate preresgistration report after pre-registration", "programme - programme from form.REQUEST now - current date from system year -", "be logged in and must be acadadmin @param: request - contains metadata about", "request.POST['delete'] # arr = st.split(\"-\") # stu = arr[0] # if Student.objects.get(id=stu): #", "== 'POST' and request.FILES: examTtForm = ExamTimetableForm(request.POST, request.FILES) if examTtForm.is_valid(): examTtForm.save() return render(request,", "Description for the academic calendar event. prev_desc - Description for the previous event", "mothers_name - details of student from file category - details of student from", "that holds the designation as a convenor CoConvenor - the extraInfo objects that", "== 'POST': # print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") # rollno = request.POST.getlist('Roll Number')[0] # # print(request.POST.get('rollno'))", "@login_required def curriculum(request): \"\"\" This function is used to see curriculum and edit", "- contains metadata about the requested page. @variables: from_date - The starting date", "'result_year' : procedures_context['result_year'], 'batch_grade_data' : procedures_context['batch_grade_data'], 'batch_branch_data' : procedures_context['batch_branch_data'], 'assistant_flag' : assistant_flag, 'hod_flag'", "date_of_birth=dob, address=address, phone_no=phone_no, user_type='student', department=department, ) sem=1 stud_data = Student.objects.create( id=einfo, programme =", "acadadmin=\"\" final_user=\"\" pass if (str(acadadmin) != str(final_user)): return True else: return False def", "ans.sort() output = BytesIO() book = Workbook(output,{'in_memory':True}) title = book.add_format({'bold': True, 'font_size': 22,", ":calendar, 'tab_id' :['4','1'] } if request.method == \"POST\": try: from_date = request.POST.getlist('from_date') to_date", "update an entry to the academic calendar to be updated. @param: request -", "courses by the academic person. # course - Course details which is selected", "gata from database to send to template @param: request - contains metadata about", "'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context)", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') try: batch = request.POST['batch'] course = Courses.objects.get(id = request.POST['course'])", "to be hidden in the webpage # \"\"\" # s = get_object_or_404(Designation, name=\"Convenor\")", "== course): # print(p.course_id) # p.delete() # else: # return HttpResponse(\"Unable to delete", "next_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses = Course.objects.all() courses_list = Courses.objects.all() course_type = Constants.COURSE_TYPE timetable", "stdents data from database ans - Formatted Array to be converted to xlsx", "in senator meetings minuteForm - the form to add a senate meeting minutes", "and request.FILES: examTtForm = ExamTimetableForm(request.POST, request.FILES) if examTtForm.is_valid(): examTtForm.save() return render(request, \"ais/ais.html\", context)", "object of the calendar instance from the database for the previous Description. \"\"\"", "= hall # s.room_no = room # s.save() # return HttpResponseRedirect('/academic-procedures/') # return", "in course_slots: courses += course_slot.courses.all() new_reg=[] for c in courses: reg=course_registration( course_id =", "Convenor # p - designation object of Co Convenor # result - the", "= sem_for_generate_sheet() if(course_list[0]==1): course_list_2 = [2, 4, 6, 8] else: course_list_2 = [1,", "return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST' and request.FILES: # form = MinuteForm(request.POST,", "s - the designation object that contains convenor # c - the designation", "\"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def float_course_submit(request): \"\"\" to float courses", "contains metadata about the requested page. @variables: profiles - gets the excel file", "if(Grades.objects.filter(student_id=id, sem=sem)): # s = Grades.objects.filter(student_id=id, sem=sem) # for p in s: #", "event. prev_desc - Description for the previous event which is to be updated.", "to remove a convenor/coconvenor from the position # @param: # request - contains", "the requested page @variables: programme - programme from form.REQUEST batch - batch from", "curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code') faculty_list = get_faculty_list() courses =", "name of the student # rollno - the rollno of the student required", "- all the objects in the Student class Convenor - the extraInfo objects", "acad-admin can upload the exam timtable of the ongoing semester. @param: request -", "context) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def add_exam_timetable(request):", "student to be displayed in the webpage # \"\"\" s = Designation.objects.get(name='Convenor') #", "= branch).filter(batch = batch).filter(programme= programme) courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= {", "# if Student.objects.get(id=stu): # s = Student.objects.get(id=stu) # s.father_name = \"\" # s.mother_name", "- temporary variables z - temporary variables for final output b - temporary", "about the requested page @variables: dele - data being deleted from database \"\"\"", "room = request.POST.get('room') # cpi = request.POST.get('cpi') # student.address = str(hall) + \"", "- the form required to add exam timetable Dean - the extraInfo objects", "user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1'] } if request.method == \"POST\": i=1", "return HttpResponse('not uploaded') # return render(request, \"ais/ais.html\", {}) def deleteMinute(request): # \"\"\" #", "data = request.POST['delete'] # d = data.split(\"-\") # id = d[0] # course", "gets the details of the required user. # desig_id - used to check", "the academic caldendar event. desc - Description for the academic calendar event. prev_desc", "request.POST['delete'] t = Timetable.objects.get(time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def delete_exam_timetable(request): \"\"\" acad-admin", "print(rollno) # student = ExtraInfo.objects.get(id=rollno) # print(student.address) # if not student: # data", "student to become the convenor/coconvenor # extraInfo - extraInfo object of the student", "request - contains metadata about the requested page # @variables: # current_user -", "course_type, 'curriculum': curriculum, 'faculty_list': faculty_list, 'tab_id' :['5','1'] } return render(request, \"ais/ais.html\", context) else:", "programme = request.POST['programme'] now = datetime.datetime.now() year = int(now.year) batch = year-1 curriculum", "programme_name, discipline__acronym = dept, year = batch_year).first() user = User.objects.create_user( username=roll_no, password='<PASSWORD>', first_name=first_name,", "holds_desig - get hold_desig object of student currs - get curriculum details reg", "- temporary variables for final output st - temporary variables for final output", "request.method == 'POST' and request.FILES: acadTtForm = AcademicTimetableForm(request.POST, request.FILES) if acadTtForm.is_valid(): acadTtForm.save() return", "request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code') faculty_list = get_faculty_list() courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= {", "- The starting date for the academic calendar event. to_date - The ending", "# sem = MinimumCredits.objects.all().filter(semester=i).first() # sem.credits = sem_cred[i+1] # sem.save() # return HttpResponse(\"Worked\")", "- get current semester from current time now - get current time year", "!= str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # print(request.POST['delete']) # data = request.POST['delete'] # d", "False, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) sheet = book.add_worksheet() title_text = ((str(course.name)+\"", "5, 7] # examTtForm = ExamTimetableForm() # acadTtForm = AcademicTimetableForm() # calendar =", "desig_id - used to check the designation ID. # extraInfo - extraInfo object", "= HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() # print (temp) # print (current_user) # acadadmin =", "# data = { # 'name': name, # 'rollno': roll.id, # 'programme': programme,", "delete the outdated exam timetable. @param: request - contains metadata about the requested", "This function is used to delete curriculum entry in database It checkes the", "from form \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1'] } if", "the requested page # pk - the primary key of that particular student", "designation as a coconvenor meetings - the all meeting objects held in senator", "request.POST['optional'] == \"on\": optional=True else: optional=False course_type=request.POST[\"course_type\"] except Exception as e: id=\"\" programme=\"\"", "check the designation of the user. # user_details - to get the details", "requested page. @variables: request_batch - Batch from form request_branch - Branch from form", "available # desig_id - mother 's name of the student # acadadmin -", "= book.add_format({'bold': True, 'font_size': 22, 'align': 'center', 'valign': 'vcenter'}) subtitle = book.add_format({'bold': True,", "number of the student # \"\"\" if request.method == \"POST\": name = request.POST.get('name')", "# print(rollno) # student = ExtraInfo.objects.get(id=rollno) # print(student.address) # if not student: #", "# batch - the current batch of the student # programme - the", "#Generate Attendance Sheet def sem_for_generate_sheet(): \"\"\" This function generates semester grade sheet @variables:", "# print (current_user) # acadadmin = temp.working # k = str(user_details).split() # print(k)", "contains metadata about the requested page @variables: current_user - father's name of the", "the requested page. # @variables: # choices - selected addtional courses by the", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1'] } if request.method == \"POST\":", "# rollno=request.POST.get('roll') # print(rollno) # student = ExtraInfo.objects.get(id=rollno) # print(student.address) # if not", "\"\"\" acad-admin can upload the exam timtable of the ongoing semester. @param: request", "Student.objects.create( id=einfo, programme = programme_name, batch=batch_year, batch_id = batch, father_name = fathers_name, mother_name", "Curriculum.objects.filter(branch = branch).filter(batch = batch).filter(programme= programme).filter(sem = sem) # print(curriculum_courses) # courses =", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1'] } if request.method ==", "to be displayed in the webpage \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context =", "ExtraInfo.objects.get(id=request.POST.get('rollno')) # programme = request.POST.get('programme') # batch = request.POST.get('batch') # ph = request.POST.get('phoneno')", "the objects in the Student class Convenor - the extraInfo objects that holds", "- programme from form.REQUEST batch - batch from form.REQUEST branch - branch from", "Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','2'] } examTtForm = ExamTimetableForm()", "s.hall_no = hall # s.room_no = room # s.save() # return HttpResponseRedirect('/academic-procedures/') #", "Timetable,Curriculum) from applications.programme_curriculum.models import (CourseSlot, Course as Courses, Batch, Semester, Programme, Discipline) from", "types from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) context['tab_id'][0]='6' if", "hall_no == None: hall_no=3 else: hall_no=int(hall_no) programme_name=request.POST['Programme'] batch_year=request.POST['Batch'] batch = Batch.objects.all().filter(name = programme_name,", "stores the # information that the particular student is a convenor/coconvenor to be", "AssistantshipClaim,Assistantship_status from applications.globals.models import (Designation, ExtraInfo, HoldsDesignation, DepartmentInfo) from .forms import AcademicTimetableForm, ExamTimetableForm,", "if request.method == \"POST\": # data = request.POST['delete'] # t = Meeting.objects.get(id=data) #", "int(request_sem) == 0: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).order_by('sem') else: curriculum", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context= { 'academic_calendar' :calendar, 'tab_id' :['4','1']", "return [2, 4, 6, 8] @login_required def generatexlsheet(request): \"\"\" to generate Course List", "that particular student field # @variables: # s - the designation object that", "# else: # return HttpResponse(\"Unable to delete data\") return HttpResponse(\"Data Deleted SuccessFully\") @login_required", "= [] k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department) ans.append(k) ans.sort() output = BytesIO() book =", "'align': 'center', 'valign': 'vcenter'}) sheet = book.add_worksheet() title_text = ((str(course.name)+\" : \"+str(str(batch)))) sheet.set_default_row(25)", "+ batch.discipline.acronym + str(\" \") + str(batch.year)) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle)", "request.method == \"POST\": dele = Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete() curriculum = Curriculum.objects.select_related().filter(branch = request.POST['branch']).filter(batch =", "= sem) course_slots = CourseSlot.objects.all().filter(semester = sem_id) courses = [] for course_slot in", "# db = Student() # st = ExtraInfo.objects.get(id=roll.id) # db.name = name.upper() #", "convenor/coconvenor to be deleted # data - data of the student to be", "temp.working k = str(user_details).split() final_user = k[2] except Exception as e: acadadmin=\"\" final_user=\"\"", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') course_list = sem_for_generate_sheet() if(course_list[0]==1): course_list_2 = [2, 4, 6,", "to check the designation ID. # extraInfo - extraInfo object of the student", "assistant_list_length, 'tab_id': ['1','1'], 'context': procedures_context['context'], 'lists': procedures_context['lists'], 'date': procedures_context['date'], 'query_option1': procedures_context['query_option1'], 'query_option2': procedures_context['query_option2'],", "- contains metadata about the requested page # @variables: # current_user - details", "to generate Course List of Registered Students @param: request - contains metadata about", "Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme) courses = Course.objects.all() course_type = Constants.COURSE_TYPE context=", "request.POST.getlist('description')[0] from_date = from_date[0].split('-') from_date = [int(i) for i in from_date] from_date =", "= set() unregistered_students = set() for stu in obj: registered_students.add(stu.student_id) students = Student.objects.filter(batch_id", "- get designation object of student holds_desig - get hold_desig object of student", "== \"Convenor\": # hDes.designation = s # else: # hDes.designation = p #", "is selected by the academic admin. # \"\"\" if request.method == \"POST\": pass", "---------------------senator------------------ # @csrf_exempt def senator(request): # \"\"\" # to add a new student", "programme=request.POST['programme'] # batch=request.POST['batch'] # branch=request.POST['branch'] # sem=request.POST['sem'] # curriculum_courses = Curriculum.objects.filter(branch = branch).filter(batch", "@variables: now - current datetime month - current month \"\"\" now = datetime.datetime.now()", "'rollno': extraInfo.id, # 'programme': student.programme, # 'branch': extraInfo.department.name # } # return HttpResponseRedirect('/aims/')", "acadadmin @param: request - contains metadata about the requested page. @variables: request_batch -", "contains metadata about the requested page @variables: programme - programme from form.REQUEST batch", "checkes the authentication of the user. @param: request - contains metadata about the", "page. @variables: acadTtForm - data of delete dictionary in post request timetable -", "= get_object_or_404(Designation, name=\"Senator\") # student = get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0]) # hDes = get_object_or_404( HoldsDesignation,", "= True # course.save() # courses = Course.objects.all() # for i in courses:", "extraInfo.id, # 'programme': student.programme, # 'branch': extraInfo.department.name # } # return HttpResponseRedirect('/aims/') #", "hDes.save() # data = { # 'name': extraInfo.user.username, # 'rollno_convenor': extraInfo.id, # 'designation':", "= HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Associate Professor\")) except Exception as e: f1=f2=f3=\"\" pass faculty =", "curriculum - curriculum details form database ins - Inster data in database \"\"\"", "in user # user_details - the details of the current user # desig_id", "get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk') #", "of the student # user - the User object of the student #", "0, category = category, hall_no = hall_no, specialization = specialization, curr_semester_no=sem, ) desig", "t.delete() return HttpResponseRedirect('/aims/') # # ###################################################### # # ##########Student basic profile################## # @csrf_exempt", "Exception as e: id=\"\" programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\"", "user_check(request): return HttpResponseRedirect('/academic-procedures/') course_list = sem_for_generate_sheet() if(course_list[0]==1): course_list_2 = [2, 4, 6, 8]", "page @variables: sem - get current semester from current time now - get", "details of student from file specialization - details of student from file hall_no", "object that stores the # information that the particular student is a convenor/coconvenor", "from file title - details of student from file dob - details of", "calendar instance from the database for the previous Description. \"\"\" if user_check(request): return", "output st - temporary variables for final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "float_course_submit(request): \"\"\" to float courses for the next sem and store data in", "= st return response @login_required def add_new_profile (request): \"\"\" To add details of", "= Timetable.objects.get(time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def delete_exam_timetable(request): \"\"\" acad-admin can delete", "# # print(request.POST.get('rollno')) # extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Senator') # hDes", "the student required to check if the student is available # desig_id -", "where the student stays # room no - hostel room no # \"\"\"", "delete_curriculum(request): \"\"\" This function is used to delete curriculum entry in database It", "b - temporary variables for final output c - temporary variables for final", "for stu in students: if stu not in registered_students: unregistered_students.add(stu) data = []", "entry.sem=sem entry.course_code=course_code entry.course_id=course_id entry.credits=credits entry.optional=optional entry.course_type=course_type entry.save() curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch =", "request.POST.get('phoneno') # if not Student.objects.filter(id=roll).exists(): # db = Student() # st = ExtraInfo.objects.get(id=roll.id)", "= \"\" this_sem_courses = \"\" next_sem_courses = \"\" courses = \"\" course_type =", "the extraInfo objects that holds the designation as a coconvenor meetings - the", "pk): # \"\"\" # Deletes the student from the database # @param: #", "of new upcoming students in the database.User must be logged in and must", "entry.batch=batch entry.branch=branch entry.sem=sem entry.course_code=course_code entry.course_id=course_id entry.credits=credits entry.optional=optional entry.course_type=course_type entry.save() curriculum = Curriculum.objects.select_related().filter(branch =", "the academic caldendar event. desc - Description for the academic calendar event. c", "HttpResponseRedirect('/aims/') def confirm_grades(request): # if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if request.method ==", "curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) if request.POST['option'] == '1': new_curriculum=[] for", "i=0 new_curr=[] while True: if \"semester_\"+str(i) in request.POST: try: programme=request.POST['AddProgramme'] batch=request.POST['AddBatch'] branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)]", "- details of student from file phone_no - details of student from file", "minuteForm - the form to add a senate meeting minutes acadTtForm - the", "= book.add_format({'bold': True, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) normaltext = book.add_format({'bold': False,", "current semester from current time now - get current time year - getcurrent", ": procedures_context['batch_branch_data'], 'assistant_flag' : assistant_flag, 'hod_flag' : hod_flag, 'account_flag' : account_flag } return", "# final_user - details of the user # sem - current semester of", "requested page # @variables: # current_user - the username of the logged in", "(in formated data) z - temporary array to add data to variable data", "function is used to edit curriculum in database It checkes the authentication of", "# course = d[2] # sem = int(d[3]) # if request.method == \"POST\":", "existing senate meeting minute object from the database. # @param: # request -", "to_date = [int(i) for i in to_date] to_date = datetime.datetime(*to_date).date() get_calendar_details = Calendar.objects.all().filter(description=prev_desc).first()", "- details of student from file specialization - details of student from file", "profile picture, about me etc of a student # @param: # request -", "student user_details - the rollno of the student required to check if the", "= True).filter(hod_approval =True).filter(hod_approval = True) assistant_list_length = len(assistant_list.filter(acad_approval = False)) assis_stat = Assistantship_status.objects.all()", "Timetable.objects.all() exam_t = Exam_timetable.objects.all() pgstudent = Student.objects.filter(programme = \"M.Tech\") | Student.objects.filter(programme = \"PhD\")", "- father's name of the student # rollno - the rollno of the", "t - Object of time table to be deleted \"\"\" if user_check(request): return", "programme from form.REQUEST batch - batch from form.REQUEST branch - branch from form.REQUEST", "the batch course - gets the course curr_key - gets the curriculum from", "def add_optional(request): # \"\"\" # acadmic admin to update the additional courses #", "page. @param: request - contains metadata about the requested page @variables: dele -", "user_details - gets the details of the required user. # desig_id - used", "return JsonResponse(data) # @csrf_exempt def delete_basic_profile(request, pk): # \"\"\" # Deletes the student", "no - hostel room no # \"\"\" current_user = get_object_or_404(User, username=request.user.username) # user_details", "name of the student # roll - the rollno of the student #", "= Course.objects.all() # course_type = Constants.COURSE_TYPE # context= { # 'courses': courses, #", "\"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def delete_timetable(request): \"\"\" acad-admin can delete", "i in to_date] to_date = datetime.datetime(*to_date).date() get_calendar_details = Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description = desc get_calendar_details.from_date", "- Semester from form curriculum - Get data about curriculum from database courses", "stored in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','2'] } if", "data = {} # return JsonResponse(data) # @csrf_exempt def deleteConvenor(request, pk): # \"\"\"", "a new student convenor/coconvenor # @param: # request - contains metadata about the", "# return HttpResponse('not uploaded') # return render(request, \"ais/ais.html\", {}) def deleteMinute(request): # \"\"\"", "batch = year-1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) if request.POST['option'] ==", "courses = [] for course_slot in course_slots: courses += course_slot.courses.all() new_reg=[] for c", "print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") # rollno = request.POST.getlist('Roll Number')[0] # # print(request.POST.get('rollno')) # extraInfo =", "db.batch = batch # db.programme = programme # st.phone_no = ph # db.save()", "# 'designation': designation, # } # return JsonResponse(data)# ###################################################### # # ##########Senate meeting", "fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13 ).value department=DepartmentInfo.objects.all().filter(name=dept).first() if specialization ==", "- contains metadata about the requested page @variables: current_user - get user from", "programme_name, batch=batch_year, batch_id = batch, father_name = fathers_name, mother_name = mothers_name, cpi =", "of data faculty_list - list of faculty \"\"\" try: f1 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name =", "# student = Student.objects.get(id=extraInfo) # data = { # 'name': extraInfo.user.username, # 'rollno':", "= ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk') # temp = HoldsDesignation.objects.all().filter(designation =", "branch from form.REQUEST sem - semester from form.REQUEST course_code - course_code from form.REQUEST", "== \"on\": optional=True else: optional=False course_type=request.POST[\"course_type\"] except Exception as e: id=\"\" programme=\"\" batch=\"\"", "# hDes.designation = s # else: # hDes.designation = p # hDes.save() #", "from database credits - credits from form.REQUEST optional - optional from form.REQUEST course_type", "{ 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\",", "JsonResponse(data) # @csrf_exempt def deleteConvenor(request, pk): # \"\"\" # to remove a convenor/coconvenor", "return JsonResponse(data)# ######################################################### # ''' # # view to add attendance data to", "of the student # data - tag whether to delete it or not", "xlrd import logging from io import BytesIO from xlsxwriter.workbook import Workbook from xhtml2pdf", "- the primary key of that particular student field # @variables: # s", "is used to see curriculum and edit entries in a curriculum. It checkes", "become the convenor/coconvenor # extraInfo - extraInfo object of the student with that", "else: # return HttpResponse(\"Unable to delete data\") return HttpResponse(\"Data Deleted SuccessFully\") @login_required def", "to_date = datetime.datetime(*to_date).date() get_calendar_details = Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description = desc get_calendar_details.from_date = from_date get_calendar_details.to_date", "deleted # \"\"\" # if request.method == \"POST\": # data = request.POST['delete'] #", "Assistantship_status.objects.all() for obj in assis_stat: assistant_flag = obj.student_status hod_flag = obj.hod_status account_flag =", "'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'faculty_list': faculty_list, 'tab_id' :['5','1'] } return render(request,", "i in data: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] a,b,c,d,e = str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp =", "student grade - grade to be added in the student course - course", "break i+=1 return render(request, \"ais/ais.html\", context) # # ---------------------senator------------------ # @csrf_exempt def senator(request):", "curriculum(request): # ''' def delete_advanced_profile(request): # \"\"\" # to delete the advance information", "timetable, 'tab_id' :['10','2'] } examTtForm = ExamTimetableForm() if request.method == 'POST' and request.FILES:", "batch.discipline.acronym + str(\" \") + str(batch.year)) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll", "holds the designation as a dean student - the students as a senator", "\"\"\" # to delete the advance information of the student # @param: #", "object for the minimum credits from the database and the update it. #", "= Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses = Course.objects.all() courses_list = Courses.objects.all() course_type =", "student's address # final_user - details of the user # sem - current", "HoldsDesignation, DepartmentInfo) from .forms import AcademicTimetableForm, ExamTimetableForm, MinuteForm from .models import (Calendar, Course,", "= [] for i in obj: if i.student_id.batch_id.year == int(batch): registered_courses.append(i) ans =", "return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if request.method == 'POST': try: id=request.POST['id'] programme=request.POST['programme']", "dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13 ).value department=DepartmentInfo.objects.all().filter(name=dept).first() if specialization", "reg - create registeration object in registeration table \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "render(request, \"ais/ais.html\", context) @login_required def add_exam_timetable(request): \"\"\" acad-admin can upload the exam timtable", "student = get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0]) # hDes = get_object_or_404( HoldsDesignation, user = student.user) #", "db = Student() # st = ExtraInfo.objects.get(id=roll.id) # db.name = name.upper() # db.id", "curriculum = None #Curriculum.objects.all() else: if int(request_sem) == 0: curriculum = Curriculum.objects.select_related().filter(branch =", "add_optional(request): # \"\"\" # acadmic admin to update the additional courses # @param:", "} return render(request, \"ais/ais.html\", context) context= { 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\",", "the ongoing semester. @param: request - contains metadata about the requested page. @variables:", "about the requested page @variables: acadTtForm - the form to add academic calender", "next semester obj - All the registration details appended into one data -", "{ 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'faculty_list': faculty_list, 'tab_id' :['5','1'] } return", "f2 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Professor\")) f3 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Associate Professor\")) except Exception", "ins - Inster data in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method", "about the requested page. @variables: request_batch - Batch from form request_branch - Branch", "be deleted # \"\"\" # if request.method == \"POST\": # data = request.POST['delete']", "HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Professor\")) f3 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Associate Professor\")) except Exception as e:", "new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits,", "HttpResponseRedirect('/aims/') # else: # return HttpResponseRedirect('/aims/')# #################################################### # # ##########covenors and coconvenors################## #", "procedures_context['submitted_course_list'], 'result_year' : procedures_context['result_year'], 'batch_grade_data' : procedures_context['batch_grade_data'], 'batch_branch_data' : procedures_context['batch_branch_data'], 'assistant_flag' : assistant_flag,", "preresgistration report after pre-registration @param: request - contains metadata about the requested page", "teh webpage # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first()", "workbook of xlsx file title - formatting variable of title the workbook subtitle", "def add_advanced_profile(request): # \"\"\" # It adds the advance profile information like hall", "= Course.objects.all() course_type = Constants.COURSE_TYPE html = render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj = json.dumps({'html':html}) #return render(request,", "the curriculum from database obj - get stdents data from database ans -", "book = Workbook(output,{'in_memory':True}) title = book.add_format({'bold': True, 'font_size': 22, 'align': 'center', 'valign': 'vcenter'})", "HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # st = request.POST['delete'] # arr =", "of the current user # acadadmin - deatils of the acad admin #", "# extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor')", "= s # hDes.save() # student = Student.objects.get(id=extraInfo) # data = { #", "# information that the particular student is a convenor/coconvenor to be deleted #", "on the page. @param: request - contains metadata about the requested page @variables:", "the rollno of the student required to check if the student is available", "must take # @param: # request - contains metadata about the requested page.", "# if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # print(request.POST['delete']) # data =", "current user. # user_details - gets the details of the required user. #", "of current user. # user_details - gets the details of the required user.", "return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) def get_faculty_list(): \"\"\" to get", "contains metadata about the requested page # @variables: # current_user - the username", "curriculum, 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) return render(request, 'ais/ais.html', context) @login_required", "adds the basic profile information like username,password, name, # rollno, etc of a", "- designation object of Co Convenor # result - the data that contains", "convenor/coconvenor from the position # @param: # request - contains metadata about the", "# to remove a convenor/coconvenor from the position # @param: # request -", "context) context= { 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) @login_required def add_timetable(request):", "of the logged in user # user_details - the details of the current", "the student's record in the database table # @variables: # e - the", "courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context) else:", "as e: id=\"\" programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\"", "@variables: # current_user - details of the current user. # desig_id - to", "exam timetable. @param: request - contains metadata about the requested page. @variables: data", "= request.POST['programme'] except Exception as e: request_batch = \"\" request_branch = \"\" request_programme", "requested page @variables: dele - data being deleted from database \"\"\" if user_check(request):", "acadTtForm.is_valid(): acadTtForm.save() return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context) return render(request,", "the student is enrolled in # ph - the phone number of the", "edit curriculum in database It checkes the authentication of the user and also", "requested page @variables: programme - programme from form.REQUEST now - current date from", "4, 6, 8] else: course_list_2 = [1, 3, 5, 7] # examTtForm =", "= st return response @login_required def generate_preregistration_report(request): \"\"\" to generate preresgistration report after", "JsonResponse(data) # else: # father = request.POST.get('father') # mother = request.POST.get('mother') # add", "True else: return False def get_context(request): \"\"\" This function gets basic gata from", "category, hall_no = hall_no, specialization = specialization, curr_semester_no=sem, ) desig = Designation.objects.get(name='student') hold_des", "if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # print(request.POST['delete']) # data = request.POST['delete']", "hidden in the webpage # \"\"\" # s = get_object_or_404(Designation, name=\"Convenor\") c =", "course details # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first()", "from xlsxwriter.workbook import Workbook from xhtml2pdf import pisa from itertools import chain from", "database einfo - new extrainfo object created in database stud_data - new student", "from file sex - details of student from file title - details of", "from request user_details - extract details of user from database desig_id - check", "book.add_format({'bold': False, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) sheet = book.add_worksheet() title_text =", "Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','1'] } return", "Curriculum_Instructor.objects.bulk_create(new_curr_inst) else: break i+=1 return render(request, \"ais/ais.html\", context) # # ---------------------senator------------------ # @csrf_exempt", "return HttpResponseRedirect('/aims/')# #################################################### # # ##########covenors and coconvenors################## # @csrf_exempt def add_convenor(request): #", "objects held in senator meetings minuteForm - the form to add a senate", "page # @variables: # current_user - father's name of the student # user_details", "last_name - details of student from file email - details of student from", "- contains metadata about the requested page. @variables: f1,f2,f3 - temporary varibles faculty", "stays # room no - hostel room no # \"\"\" current_user = get_object_or_404(User,", "= Course.objects.all().filter(course_id=i).first() # course.acad_selection = True # course.save() # courses = Course.objects.all() #", "requested page. @variables: f1,f2,f3 - temporary varibles faculty - details of faculty of", "request_sem = \"\" #for checking if the user has searched for any particular", "= json.dumps({'html':html}) #return render(request, \"ais/ais.html\", context) return HttpResponse(obj,content_type='application/json') else: return render(request, \"ais/ais.html\", context)", "student is available # desig_id - mother 's name of the student #", "= obj.student_status hod_flag = obj.hod_status account_flag = obj.account_status except Exception as e: examTtForm", "# extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Senator') # hDes = HoldsDesignation() #", "} # return JsonResponse(data) # else: # data = {} # return JsonResponse(data)", "temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() acadadmin = temp.working k = str(user_details).split() final_user =", "Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses = Course.objects.all() courses_list = Courses.objects.all() course_type = Constants.COURSE_TYPE timetable = Timetable.objects.all()", "elif request.POST['option'] == '2': new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch,", "= request.POST['branch'] request_programme = request.POST['programme'] except Exception as e: request_batch = \"\" request_branch", "for final output b - temporary variables for final output c - temporary", "form request_programme - Programme from form request_sem - Semester from form \"\"\" if", "the next sem and store data in databsae. User must be logged in", "# s.delete() # e.delete() # u.delete() # return JsonResponse(data)# ######################################################### # ''' #", "email - details of student from file sex - details of student from", "assistant_approve_list, 'assistant_list_length' : assistant_list_length, 'tab_id': ['1','1'], 'context': procedures_context['context'], 'lists': procedures_context['lists'], 'date': procedures_context['date'], 'query_option1':", "t - Object of Exam time table to be deleted \"\"\" if user_check(request):", "database ins - Inster data in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if", "e: id=\"\" programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass", "Course.objects.all() # course_type = Constants.COURSE_TYPE # context= { # 'courses': courses, # 'course_type':", "+= course_slot.courses.all() new_reg=[] for c in courses: reg=course_registration( course_id = c, semester_id=sem_id, student_id=stud_data", "from form.REQUEST batch - batch from form.REQUEST branch - branch from form.REQUEST sem", "# } # return HttpResponseRedirect('/aims/') # # return JsonResponse(data) # else: # return", "object to store that the particualr student is # holding the convenor/coconvenor designation", "request - contains metadata about the requested page @variables: sem - get current", "It checkes the authentication of the user. @param: request - contains metadata about", "it to an array. # sem - Get the object for the minimum", "add data to variable data k -temporary array to add data to formatted", "- the programme the student is enrolled in # ph - the phone", "requested page # pk - the primary key of that particular student field", "= Student.objects.get(id=extraInfo) # data = { # 'name': extraInfo.user.username, # 'rollno': extraInfo.id, #", "student's cpi # hall - hall no of where the student stays #", "timetable - all timetable from database exam_t - all exam timetable from database", "'rollno': pk, # } # s.delete() # e.delete() # u.delete() # return JsonResponse(data)#", "rollno - the rollno of the student required to check if the student", "add a new senate meeting minute object to the database. # @param: #", "st.split(\"-\") # stu = arr[0] # if Student.objects.get(id=stu): # s = Student.objects.get(id=stu) #", "# hDes.save() # data = { # 'name': extraInfo.user.username, # 'rollno_convenor': extraInfo.id, #", "This function is used to set up the homepage of the application. It", "from applications.academic_procedures.models import MinimumCredits, Register, InitialRegistration, course_registration, AssistantshipClaim,Assistantship_status from applications.globals.models import (Designation, ExtraInfo,", "and must be acadadmin @param: request - contains metadata about the requested page.", "calendar to be updated. @param: request - contains metadata about the requested page.", "generatexlsheet(request): \"\"\" to generate Course List of Registered Students @param: request - contains", "s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') # if request.method == 'POST':", "- the primary key of the student's record in the database table #", "def next_curriculum(request): \"\"\" This function is used to decide curriculum for new batch.", "@variables: # data - the id of the minute object to be deleted", "title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',50) sheet.set_column('D:D',15)", "user and also fetches the available data from the databases to display it", "academic calendar to be uploaded @param: request - contains metadata about the requested", ": procedures_context['submitted_course_list'], 'result_year' : procedures_context['result_year'], 'batch_grade_data' : procedures_context['batch_grade_data'], 'batch_branch_data' : procedures_context['batch_branch_data'], 'assistant_flag' :", "Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() # print (temp) # print", "request.POST['branch'] request_programme = request.POST['programme'] except Exception as e: request_batch = \"\" request_branch =", "view to add attendance data to database # def curriculum(request): # ''' def", "= Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code') faculty_list = get_faculty_list() courses = Course.objects.all()", "if request.method == \"POST\": # print(request.POST) # rollno=request.POST.get('roll') # print(rollno) # student =", "\"\"\" It verify the grades of the student @param: request - contains metadata", "cpi # hall - hall no of where the student stays # room", "next_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # courses = Course.objects.all() # course_type = Constants.COURSE_TYPE # timetable", "semester. @param: request - contains metadata about the requested page. @variables: examTtForm -", "db.name = name.upper() # db.id = roll # db.batch = batch # db.programme", "tag whether to delete it or not # course - get the course", "request_programme = \"\" if request_batch == \"\" and request_branch == \"\" and request_programme==\"\":", "student # \"\"\" e = get_object_or_404(ExtraInfo, id=pk) # user = get_object_or_404(User, username =", "sem and store data in databsae. User must be logged in and must", "@variables: programme - programme from form.REQUEST now - current date from system year", "rollno of the student required to check if the student is available desig_id", "@variables: dele - data being deleted from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "obj.account_status except Exception as e: examTtForm = \"\" acadTtForm = \"\" calendar =", "previous event which is to be updated. get_calendar_details = Get the object of", "= hall_no, specialization = specialization, curr_semester_no=sem, ) desig = Designation.objects.get(name='student') hold_des = HoldsDesignation.objects.create(", "of courses \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') course_list = sem_for_generate_sheet() if(course_list[0]==1): course_list_2 =", "# to delete the advance information of the student # @param: # request", "required user. # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first()", "= get_object_or_404(Designation, name=\"Co Convenor\") # student = get_object_or_404(ExtraInfo, id=pk) # hDes = HoldsDesignation.objects.filter(user", "# hDes = HoldsDesignation() # hDes.user = extraInfo.user # hDes.working = extraInfo.user #", "- the User object of the student # s - the student object", "\" \" + str(room) # student.save() # s = Student.objects.get(id=student) # s.father_name=father #", "} # return render(request,\"ais/ais.html\", context) # else: # return HttpResponseRedirect('/aims/') return HttpResponseRedirect('/aims/') def", "= get_faculty_list() courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses': courses, 'course_type':", "batch = Batch.objects.all().filter(name = programme_name, discipline__acronym = dept, year = batch_year).first() user =", "# desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() # print", "form request_programme - Programme from form request_sem - Semester from form curriculum -", "to delete it or not # course - get the course details #", "!= str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # st =", "details of student from file programme - details of student from file batch", "hDes = HoldsDesignation() # hDes.user = extraInfo.user # hDes.working = extraInfo.user # hDes.designation", "data = {} # return JsonResponse(data) # @csrf_exempt def delete_basic_profile(request, pk): # \"\"\"", "# data = {} # return JsonResponse(data) # @csrf_exempt def deleteConvenor(request, pk): #", "hostel room no # \"\"\" current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first()", "render(request, \"ais/ais.html\", context) def get_faculty_list(): \"\"\" to get faculty list from database @param:", "if request.method == 'POST': try: request_batch = request.POST['batch'] request_branch = request.POST['branch'] request_programme =", "the student to be displayed in teh webpage # \"\"\" # current_user =", "year - getcurrent year batch - gets the batch from form sem -", "updated. get_calendar_details = Get the object of the calendar instance from the database", "chief_inst=True, ) new_curr_inst.append(ins) else: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=False, ) new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst) else: break", "= 'attachment; filename = ' + batch.name + batch.discipline.acronym + str(batch.year) + '-preresgistration.xlsx'", "return render(request, \"ais/ais.html\", context) else: context= { 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\",", "= request.POST.get('cpi') # student.address = str(hall) + \" \" + str(room) # student.save()", "the required user. # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) # user_details =", "# s.hall_no = 1 # s.room_no = \"\" # s.save() # else: #", "curriculum_id=flot, instructor_id=inst, chief_inst=True, ) new_curr_inst.append(ins) else: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=False, ) new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst)", ".models import (Calendar, Course, Exam_timetable, Grades, Curriculum_Instructor,Constants, Meeting, Student, Student_attendance, Timetable,Curriculum) from applications.programme_curriculum.models", "form \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1'] } if request.method", "'POST': i=0 new_curr=[] while True: if \"semester_\"+str(i) in request.POST: try: programme=request.POST['AddProgramme'] batch=request.POST['AddBatch'] branch=request.POST['AddBranch']", "be added in the student course - course ofwhich the grade is added", "context) #Generate Attendance Sheet def sem_for_generate_sheet(): \"\"\" This function generates semester grade sheet", "import Batch @login_required def user_check(request): \"\"\" This function is used to check the", "# to set minimum credit for a current semester that a student must", "student is a convenor/coconvenor to be deleted # data - data of the", "\"\"\" to generate preresgistration report after pre-registration @param: request - contains metadata about", "- xlsx sheet to be rendered titletext - formatting variable of title text", "the designation object that contains co convenor # student - the student object", "new student senator # @param: # request - contains metadata about the requested", "all the exam timetable objects timetable - all the academic timetable objects calendar", "form.REQUEST course_code - course_code from form.REQUEST course_name - course-name from form.REQUEST course_id -", "student # roll - the rollno of the student # batch - the", "context) # #################################### # # curriculum # # #################################### @login_required def curriculum(request): \"\"\"", "ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() #print", "= get_object_or_404(ExtraInfo, id=pk) # hDes = HoldsDesignation.objects.filter(user = student.user) # designation = []", "final_user=\"\" pass if (str(acadadmin) != str(final_user)): return True else: return False def get_context(request):", "to xlsx file book - workbook of xlsx file title - formatting variable", "= Courses.objects.all() course_type = Constants.COURSE_TYPE timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() pgstudent =", "entry.credits=credits entry.optional=optional entry.course_type=course_type entry.save() curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme) courses", "name of the student # acadadmin - student's address # final_user - details", "examTtForm - the form required to add exam timetable exam_t - all the", "in data: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] a,b,c,d,e = str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp = str(i[3]).split()", "sem_cred = Get credit details from forms and the append it to an", "object to the database. # @param: # request - contains metadata about the", "s.mother_name = \"\" # s.hall_no = 1 # s.room_no = \"\" # s.save()", "def view_course(request): # if request.method == \"POST\": # programme=request.POST['programme'] # batch=request.POST['batch'] # branch=request.POST['branch']", "HttpResponseRedirect('/academic-procedures/') # return HttpResponseRedirect('/academic-procedures/') def add_optional(request): # \"\"\" # acadmic admin to update", "room no # \"\"\" current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() #", "# return JsonResponse(data) # else: # return HttpResponseRedirect('/aims/') # @csrf_exempt def deleteSenator(request, pk):", "\"\"\" to add an entry to the academic calendar to be uploaded @param:", "if request.method == 'POST': # print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") # rollno = request.POST.getlist('Roll Number')[0] #", "course_type, 'curriculum': curriculum, 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context) else: return render(request,", "branch=request.POST['branch'] sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"] if request.POST['optional'] == \"on\": optional=True else: optional=False", "i in range(1, 10): # sem = \"sem_\"+\"1\" # sem_cred.append(request.POST.getlist(sem)[0]) # for i", "date for the academic caldendar event. desc - Description for the academic calendar", "User.objects.create_user( username=roll_no, password='<PASSWORD>', first_name=first_name, last_name=last_name, email=email, ) einfo = ExtraInfo.objects.create( id=roll_no, user=user, title=title,", "the batch from form sem - stores the next semester obj - All", "# request - contains metadata about the requested page. # @variables: # choices", "and request_branch == \"\" and request_programme==\"\" and request_sem==\"\": curriculum = None #Curriculum.objects.all() else:", "else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) def get_faculty_list(): \"\"\" to", "by the academic person. # course - Course details which is selected by", "that the particualr student is # holding the convenor/coconvenor designation # student -", "=True).filter(acad_approval = False) assistant_approve_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(hod_approval = True)", "Registered Students @param: request - contains metadata about the requested page @variables: batch", "- the form to add a senate meeting minutes acadTtForm - the form", "# rollno = request.POST.get('rollno_convenor') # extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Convenor') #", "'batch_grade_data' : procedures_context['batch_grade_data'], 'batch_branch_data' : procedures_context['batch_branch_data'], 'assistant_flag' : assistant_flag, 'hod_flag' : hod_flag, 'account_flag'", "# if request.method == 'POST' and request.FILES: # form = MinuteForm(request.POST, request.FILES) #", "from applications.academic_procedures.views import acad_proced_global_context from applications.programme_curriculum.models import Batch @login_required def user_check(request): \"\"\" This", "= programme) context= { 'curriculumm' :curriculum, 'tab_id' :['3','3'] } return render(request, \"ais/ais.html\", context)", "p # hDes.save() # data = { # 'name': extraInfo.user.username, # 'rollno_convenor': extraInfo.id,", "= Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated = True flot.save() new_curr_inst=[] for c,i in enumerate(request.POST.getlist(str(i)+'_fac')): inst =", "add_basic_profile(request): # \"\"\" # It adds the basic profile information like username,password, name,", "get the course details # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) # user_details", "if hall_no == None: hall_no=3 else: hall_no=int(hall_no) programme_name=request.POST['Programme'] batch_year=request.POST['Batch'] batch = Batch.objects.all().filter(name =", "@variables: # rollno - rollno of the student to become the convenor/coconvenor #", "title_text = ((str(course.name)+\" : \"+str(str(batch)))) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle)", "- new extrainfo object created in database stud_data - new student object created", "batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass ins=Curriculum( programme=programme, batch=batch,", "about the requested page # @variables: # current_user - details of the current", "\"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def", "@variables: acadTtForm - the form to add academic calender examTtForm - the form", "# ---------------------senator------------------ # @csrf_exempt def senator(request): # \"\"\" # to add a new", "- semester of the student grade - grade to be added in the", "student is enrolled in # ph - the phone number of the student", "'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context) return", "= Designation.objects.get(name='Co Convenor') # if request.method == 'POST': # rollno = request.POST.get('rollno_convenor') #", "from .models import (Calendar, Course, Exam_timetable, Grades, Curriculum_Instructor,Constants, Meeting, Student, Student_attendance, Timetable,Curriculum) from", "the webpage # \"\"\" # s = get_object_or_404(Designation, name=\"Convenor\") c = get_object_or_404(Designation, name=\"Co", "= \"sem_\"+\"1\" # sem_cred.append(request.POST.getlist(sem)[0]) # for i in range(1, 9): # sem =", "for designation acadadmin - designation for Acadadmin final_user - final designation of request", "return HttpResponseRedirect('/aims/') def confirm_grades(request): # if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if request.method", "- all the academic calender objects department - all the departments in the", "rollno # s - designation object of Convenor # p - designation object", "Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() # print (temp) # print (current_user) #", "from database @param: request - contains metadata about the requested page. @variables: f1,f2,f3", "page. @param: request - contains metadata about the requested page @variables: request_batch -", "the requested page # @variables: # current_user - gets the data of current", "request.POST.getlist('description')[0] prev_desc = request.POST.getlist('prev_desc')[0] from_date = from_date[0].split('-') from_date = [int(i) for i in", "# request - contains metadata about the requested page # @variables: # data", "False def get_context(request): \"\"\" This function gets basic gata from database to send", "render(request, \"ais/ais.html\", context) return HttpResponse(obj,content_type='application/json') else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\",", "1 # s.room_no = \"\" # s.save() # else: # return HttpResponse(\"Data Does", "# grades = Grades.objects.filter(curriculum_id=curr_course) # context= { # 'grades': grades, # 'tab_id' :\"2\"", "course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) elif request.POST['option'] == '2': new_curriculum=[]", ":['5','1'] } if request.method == \"POST\": i=1 while True: if str(i)+\"_ccode\" in request.POST:", "the requested page. @variables: profiles - gets the excel file having data excel", "request.method == \"POST\": sem = request.POST.get('semester_no') batch_id=request.POST.get('batch_branch') batch = Batch.objects.filter(id = batch_id).first() obj", "request.POST.get('designation') # hDes = HoldsDesignation() # hDes.user = extraInfo.user # hDes.working = extraInfo.user", "'phoneno': ph, # 'batch': batch # } # print(data) # return JsonResponse(data) #", "file batch - details of student from file user - new user created", "print(p.course_id) # p.delete() # else: # return HttpResponse(\"Unable to delete data\") return HttpResponse(\"Data", "return HttpResponse(obj,content_type='application/json') else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def", "form.REQUEST course_type - course_type from form.REQUEST ins - data is stored in database", "k = 4 num = 1 for i in ans: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c", "object of the student # s - the student object of the student", "grade of the student # @param: # request - contains metadata about the", "has searched for any particular curriculum if request_batch == \"\" and request_branch ==", "data = request.POST['delete'] t = Timetable.objects.get(time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def delete_exam_timetable(request):", "- Get data about curriculum from database courses - get courses from database", "the outdated timetable from the server. @param: request - contains metadata about the", "sem+=1 curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code') faculty_list = get_faculty_list() courses", "django.contrib.auth.models import User from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import get_object_or_404,", "course_type=\"\" pass ins=Curriculum( programme=programme, batch=batch, branch=branch, sem=sem, course_code=course_code, course_id=course_id, credits=credits, optional=optional, course_type=course_type, )", "now = datetime.datetime.now() year = int(now.year) batch = year-1 curriculum = Curriculum.objects.all().select_related().filter(batch =", "for i in choices: # course = Course.objects.all().filter(course_id=i).first() # course.acad_selection = True #", "faculty\") else: flot = Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated = True flot.save() new_curr_inst=[] for c,i in", "course types from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) context['tab_id'][0]='6'", "# \"\"\" e = get_object_or_404(ExtraInfo, id=pk) # user = get_object_or_404(User, username = e.user.username)", "k -temporary array to add data to formatted array/variable output - io Bytes", "must be logged in and must be acadadmin @param: request - contains metadata", "= \"\" request_sem = \"\" #for checking if the user has searched for", "@param: request - contains metadata about the requested page @variables: request_batch - Batch", "become # convenor or coconvenor # hDes - holdsDesignation object to store that", "user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) context['tab_id'][0]='6' if request.method == 'POST': try: request_batch", "@login_required def homepage(request): \"\"\" This function is used to set up the homepage", "required user. # desig_id - used to check the designation ID. # extraInfo", "# else: # data = {} # return JsonResponse(data) # else: # data", "= [int(i) for i in to_date] to_date = datetime.datetime(*to_date).date() except Exception as e:", "'curriculum': curriculum, 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\",", "Deleted\") @login_required def add_calendar(request): \"\"\" to add an entry to the academic calendar", "which is to be updated. get_calendar_details = Get the object of the calendar", "given pk # hDes - the holdDesignation object that stores the # information", "store data in databsae. User must be logged in and must be acadadmin", "batch = request.POST['batch'] course = Courses.objects.get(id = request.POST['course']) obj = course_registration.objects.all().filter(course_id = course)", "@param: request - contains metadata about the requested page @variables: acadTtForm - the", "final output c - temporary variables for final output st - temporary variables", "hall_no = hall_no, specialization = specialization, curr_semester_no=sem, ) desig = Designation.objects.get(name='student') hold_des =", "return render(request, \"ais/ais.html\", context) @login_required def delete_timetable(request): \"\"\" acad-admin can delete the outdated", "else: if int(request_sem) == 0: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).order_by('sem')", "from itertools import chain from django.contrib.auth.models import User from django.http import HttpResponse, HttpResponseRedirect,", "is a senator # \"\"\" pass # if request.POST: # s = get_object_or_404(Designation,", "def float_course_submit(request): \"\"\" to float courses for the next sem and store data", "delete_exam_timetable(request): \"\"\" acad-admin can delete the outdated exam timetable. @param: request - contains", "the advance information of the student # @param: # request - contains metadata", "be hidden in the webpage # \"\"\" # s = get_object_or_404(Designation, name=\"Convenor\") c", "semester_no = sem) course_slots = CourseSlot.objects.all().filter(semester = sem_id) courses = [] for course_slot", "contains metadata about the requested page # @variables: # current_user - gets the", "metadata about the requested page # @variables: # current_user - father's name of", "request.POST.get('rollno_convenor') # extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co", "batch - details of student from file user - new user created in", "programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) elif", "subtitle = book.add_format({'bold': True, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) normaltext = book.add_format({'bold':", "request.POST['branch'] request_programme = request.POST['programme'] request_sem = request.POST['sem'] except Exception as e: request_batch =", "Exception as e: from_date=\"\" to_date=\"\" desc=\"\" return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\",", "designation object that contains co convenor # student - the student object with", "Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete() curriculum = Curriculum.objects.select_related().filter(branch = request.POST['branch']).filter(batch = request.POST['batch']).filter(programme= request.POST['programme']) courses = Course.objects.all()", "True).filter(hod_approval =True).filter(hod_approval = True) assistant_list_length = len(assistant_list.filter(acad_approval = False)) assis_stat = Assistantship_status.objects.all() for", "requested page # @variables: # current_user - details of the current user. #", "return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # st = request.POST['delete'] # arr", "else: return False def get_context(request): \"\"\" This function gets basic gata from database", "# hDes - holdsDesignation object to store that the particualr student is holding", "created in database einfo - new extrainfo object created in database stud_data -", "if request_batch == \"\" and request_branch == \"\" and request_programme==\"\" and request_sem==\"\": curriculum", "= Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','1'] } acadTtForm =", "- details of student from file sex - details of student from file", "i in courses: # if i.course_id not in choices: # i.acad_selection = False", "examTtForm - data of delete dictionary in post request timetable - all timetable", "to delete curriculum entry in database It checkes the authentication of the user", "# hall = request.POST.get('hall') # room = request.POST.get('room') # cpi = request.POST.get('cpi') #", "procedures_context['course_verification_date'], 'submitted_course_list' : procedures_context['submitted_course_list'], 'result_year' : procedures_context['result_year'], 'batch_grade_data' : procedures_context['batch_grade_data'], 'batch_branch_data' : procedures_context['batch_branch_data'],", "form request_sem - Semester from form \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= {", "created in database stud_data - new student object created in database desig -", "# \"\"\" current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id =", "z.append(i.id.department.name) z.append('not registered') data.append(z) for i in registered_students: z = [] z.append(m) m", "response @login_required def add_new_profile (request): \"\"\" To add details of new upcoming students", "in the database table # @variables: # e - the extraInfo objects of", "for p in s: # if (str(p.course_id) == course): # print(p.course_id) # p.delete()", "Exception as e: acadadmin=\"\" final_user=\"\" pass if (str(acadadmin) != str(final_user)): return True else:", "This function is used to decide curriculum for new batch. It checkes the", "def add_timetable(request): \"\"\" acad-admin can upload the time table(any type of) of the", "json.dumps({'html':html}) #return render(request, \"ais/ais.html\", context) return HttpResponse(obj,content_type='application/json') else: return render(request, \"ais/ais.html\", context) return", "- the id of the minute object to be deleted # t -", "# return render(request, \"ais/ais.html\", {}) def deleteMinute(request): # \"\"\" # to delete an", "'course_type' : course_type, # 'curriculum' : curriculum, # 'tab_id' :['3','1'] # } courses", "- details of student from file fathers_name - details of student from file", "k.append(i.student_id.id.department) ans.append(k) ans.sort() output = BytesIO() book = Workbook(output,{'in_memory':True}) title = book.add_format({'bold': True,", "convenor/coconvenor # data - data of the student to be displayed in the", "str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST': # print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") #", "edit_curriculum(request): \"\"\" This function is used to edit curriculum in database It checkes", "'POST': # rollno = request.POST.get('rollno_convenor') # extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Convenor')", "title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',50) sheet.set_column('D:D',15) sheet.set_column('E:E',15)", "meetings minuteForm - the form to add a senate meeting minutes acadTtForm -", "- contains metadata about the requested page @variables: sem - get current semester", "user_check(request): return HttpResponseRedirect('/academic-procedures/') timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() context= { 'exam': exam_t,", "'assistant_list_length' : assistant_list_length, 'tab_id': ['1','1'], 'context': procedures_context['context'], 'lists': procedures_context['lists'], 'date': procedures_context['date'], 'query_option1': procedures_context['query_option1'],", "new_reg.append(reg) course_registration.objects.bulk_create(new_reg) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) def get_faculty_list():", "course_id - course_id from database credits - credits from form.REQUEST optional - optional", "# db.save() # st.save() # data = { # 'name': name, # 'rollno':", "True, 'font_size': 22, 'align': 'center', 'valign': 'vcenter'}) subtitle = book.add_format({'bold': True, 'font_size': 15,", "i in unregistered_students: z = [] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name))", "st = ExtraInfo.objects.get(id=roll.id) # db.name = name.upper() # db.id = roll # db.batch", "user created in database einfo - new extrainfo object created in database stud_data", "Student.objects.filter(id=roll).exists(): # db = Student() # st = ExtraInfo.objects.get(id=roll.id) # db.name = name.upper()", "= HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Assistant Professor\")) f2 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Professor\")) f3 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name", "@variables: # current_user - the username of the logged in user # user_details", "Batch, Semester, Programme, Discipline) from applications.academic_procedures.views import acad_proced_global_context from applications.programme_curriculum.models import Batch @login_required", "- optional from form.REQUEST course_type - course_type from form.REQUEST ins - data is", "@variables: # choices - selected addtional courses by the academic person. # course", "try: examTtForm = ExamTimetableForm() acadTtForm = AcademicTimetableForm() calendar = Calendar.objects.all() this_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True)", "the database for the previous Description. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar =", "from file batch - details of student from file user - new user", "request.POST['delete'] # d = data.split(\"-\") # id = d[0] # course = d[2]", "Semester, Programme, Discipline) from applications.academic_procedures.views import acad_proced_global_context from applications.programme_curriculum.models import Batch @login_required def", "datetime.datetime.now() month = int(now.month) if month >= 7 and month <= 12: return", "month \"\"\" now = datetime.datetime.now() month = int(now.month) if month >= 7 and", "= \"\" next_sem_courses = \"\" courses = \"\" course_type = \"\" timetable =", "\"\" #for checking if the user has searched for any particular curriculum if", "logged in user # user_details - the details of the current user #", "current user # acadadmin - deatils of the acad admin # s -", "\"\" # s.save() # else: # return HttpResponse(\"Data Does Not Exist\") # return", "i in to_date] to_date = datetime.datetime(*to_date).date() except Exception as e: from_date=\"\" to_date=\"\" desc=\"\"", "to add a new student senator # @param: # request - contains metadata", "page. @param: request - contains metadata about the requested page @variables: programme -", "'context': procedures_context['context'], 'lists': procedures_context['lists'], 'date': procedures_context['date'], 'query_option1': procedures_context['query_option1'], 'query_option2': procedures_context['query_option2'], 'course_verification_date' : procedures_context['course_verification_date'],", "# s = get_object_or_404(Designation, name=\"Convenor\") c = get_object_or_404(Designation, name=\"Co Convenor\") # student =", "next_sem_courses, 'this_sem_course': this_sem_courses, 'curriculum': curriculum, 'pgstudent' : pgstudent, 'assistant_list' : assistant_list, 'assistant_approve_list' :", "context) else: context= { 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context) context= {", "c - the designation object that contains co convenor # student - the", "see curriculum and edit entries in a curriculum. It checkes the authentication of", "= request_branch).filter(batch = request_batch).filter(programme= request_programme).order_by('sem') else: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme=", "get_template from django.views.decorators.csrf import csrf_exempt from django.template.loader import render_to_string from django.contrib.auth.decorators import login_required", "metadata about the requested page @variables: request_batch - Batch from form request_branch -", "'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context) else: return", "HoldsDesignation.objects.filter(user = student.user) # designation = [] # for des in hDes: #", "10): # sem = \"sem_\"+\"1\" # sem_cred.append(request.POST.getlist(sem)[0]) # for i in range(1, 9):", "#return render(request, \"ais/ais.html\", context) return HttpResponse(obj,content_type='application/json') else: return render(request, \"ais/ais.html\", context) return render(request,", "from_date = request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] from_date = from_date[0].split('-') from_date", "from applications.programme_curriculum.models import Batch @login_required def user_check(request): \"\"\" This function is used to", "!= str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST': # print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\")", "the requested page @variables: acadTtForm - the form to add academic calender examTtForm", "= year-1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) if request.POST['option'] == '1':", "the current user # acadadmin - deatils of the acad admin # father", "ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=True, ) new_curr_inst.append(ins) else: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=False, ) new_curr_inst.append(ins)", "all the attendance objects of the students context - the datas to be", "# ##########Student basic profile################## # @csrf_exempt def add_basic_profile(request): # \"\"\" # It adds", "procedures_context['query_option2'], 'course_verification_date' : procedures_context['course_verification_date'], 'submitted_course_list' : procedures_context['submitted_course_list'], 'result_year' : procedures_context['result_year'], 'batch_grade_data' : procedures_context['batch_grade_data'],", "holds the designation as a senator students - all the objects in the", "min_cred(request): # \"\"\" # to set minimum credit for a current semester that", "7] else: return [2, 4, 6, 8] @login_required def generatexlsheet(request): \"\"\" to generate", "sem=sem)): # s = Grades.objects.filter(student_id=id, sem=sem) # for p in s: # if", "sheet.set_column('D:D',15) sheet.set_column('E:E',30) k = 4 num = 1 for i in ans: sheet.write_number('A'+str(k),num,normaltext)", "course_type = \"\" timetable = \"\" exam_t = \"\" pass context = {", "if i.student_id.batch_id.year == int(batch): registered_courses.append(i) ans = [] for i in registered_courses: k", "} if request.method == \"POST\": dele = Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete() curriculum = Curriculum.objects.select_related().filter(branch =", "required to check if the student is available # desig_id - mother 's", "details of user from database desig_id - check for designation acadadmin - designation", "student # programme - the programme the student is enrolled in # ph", "- gets the excel file having data excel - excel file sheet -", "the student # user_details - the rollno of the student required to check", "= request.POST.get('address') # hall = request.POST.get('hall') # room = request.POST.get('room') # cpi =", "user. @param: request - contains metadata about the requested page @variables: current_user -", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if request.method == \"POST\":", "- the rollno of the student required to check if the student is", "Student() # st = ExtraInfo.objects.get(id=roll.id) # db.name = name.upper() # db.id = roll", "applications.academic_procedures.models import MinimumCredits, Register, InitialRegistration, course_registration, AssistantshipClaim,Assistantship_status from applications.globals.models import (Designation, ExtraInfo, HoldsDesignation,", "if request.method == \"POST\": # if(Grades.objects.filter(student_id=id, sem=sem)): # s = Grades.objects.filter(student_id=id, sem=sem) #", "# } # s.delete() # e.delete() # u.delete() # return JsonResponse(data)# ######################################################### #", "the datas to be displayed in the webpage \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "render(request, \"ais/ais.html\") def delete_grade(request): # \"\"\" # It deletes the grade of the", "e: acadadmin=\"\" final_user=\"\" pass if (str(acadadmin) != str(final_user)): return True else: return False", "= request.POST['delete'] t = Timetable.objects.get(time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def delete_exam_timetable(request): \"\"\"", ":['4','1'] } if request.method == \"POST\": try: from_date = request.POST.getlist('from_date') to_date = request.POST.getlist('to_date')", "= str(i[0]),i[1],i[2] a,b,c,d,e = str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp = str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext) k+=1", "of the current user. # desig_id - to check the designation of the", "# data = {} # return JsonResponse(data) # @csrf_exempt def delete_basic_profile(request, pk): #", "contains metadata about the requested page. # @variables: # choices - selected addtional", "category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13 ).value department=DepartmentInfo.objects.all().filter(name=dept).first() if specialization == \"\": specialization=\"None\"", "a current semester that a student must take # @param: # request -", "\"\"\" This function is used to decide curriculum for new batch. It checkes", "st - temporary variables for final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') try:", "user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # curr_id=request.POST['course'] # print(curr_id)", "holdDesignation object that stores the # information that the particular student is a", "metadata about the requested page. # @variables: # sem_cred = Get credit details", "Minute################## # @csrf_exempt def addMinute(request): # \"\"\" # to add a new senate", "data.split(\"-\") # id = d[0] # course = d[2] # sem = int(d[3])", "course=\"\" curr_key=\"\" obj=\"\" registered_courses = [] for i in obj: if i.student_id.batch_id.year ==", "= MinuteForm(request.POST, request.FILES) # if form.is_valid(): # form.save() # return HttpResponse('sucess') # else:", "sem - get current semester from current time now - get current time", "\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") # rollno = request.POST.getlist('Roll Number')[0] # # print(request.POST.get('rollno')) # extraInfo = ExtraInfo.objects.get(id=rollno)", "user # desig_id - checking the designation of the current user # acadadmin", "to_date] to_date = datetime.datetime(*to_date).date() get_calendar_details = Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description = desc get_calendar_details.from_date = from_date", "else: sem = sem_for_generate_sheet() now = datetime.datetime.now() year = int(now.year) if sem[0] ==", "desc=\"\" return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) #Generate Attendance Sheet def", "i.student_id.batch_id.year == int(batch): registered_courses.append(i) ans = [] for i in registered_courses: k =", "return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def delete_curriculum(request): \"\"\" This", "hDes.designation = p # hDes.save() # data = { # 'name': extraInfo.user.username, #", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": sem = request.POST.get('semester_no') batch_id=request.POST.get('batch_branch')", "- Programme from form request_sem - Semester from form curriculum - Get data", "from_date=from_date, to_date=to_date, description=desc) c.save() HttpResponse(\"Calendar Added\") return render(request, \"ais/ais.html\", context) @login_required def update_calendar(request):", "# \"\"\" # to add a new senate meeting minute object to the", "= CourseSlot.objects.all().filter(semester = sem_id) courses = [] for course_slot in course_slots: courses +=", "the student # add - student's address # cpi - student's cpi #", "request - contains metadata about the requested page # @variables: # data -", "objects calendar - all the academic calender objects context - the datas to", "The starting date for the academic calendar event. to_date - The ending date", "contains metadata about the requested page # @variables: # data - the id", "print(request.POST) # rollno=request.POST.get('roll') # print(rollno) # student = ExtraInfo.objects.get(id=rollno) # print(student.address) # if", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if request.method == 'POST':", "title='Ms.' else: title='Mr.' dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value)", "# } # return render(request,\"ais/ais.html\", context) # else: # return HttpResponseRedirect('/aims/') return HttpResponseRedirect('/aims/')", "book.close() output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st = 'attachment; filename = '", "data - data of the student to be displayed in teh webpage #", "except Exception as e: from_date=\"\" to_date=\"\" desc=\"\" pass c = Calendar( from_date=from_date, to_date=to_date,", "data of current user. # user_details - gets the details of the required", "required to add exam timetable exam_t - all the exam timetable objects timetable", "the designation as a coconvenor meetings - the all meeting objects held in", "in database desig - get designation object of student holds_desig - get hold_desig", "# # return JsonResponse(data) # else: # return HttpResponseRedirect('/aims/') # @csrf_exempt def deleteSenator(request,", "contains metadata about the requested page. @variables: request_batch - Batch from form request_branch", "6, 8] else: course_list_2 = [1, 3, 5, 7] # examTtForm = ExamTimetableForm()", "io import BytesIO from xlsxwriter.workbook import Workbook from xhtml2pdf import pisa from itertools", "'academic_calendar' :calendar, 'tab_id' :['4','1'] } if request.method == \"POST\": try: from_date = request.POST.getlist('from_date')", "get_calendar_details.save() except Exception as e: from_date=\"\" to_date=\"\" desc=\"\" return render(request, \"ais/ais.html\", context) return", "the departments in the college attendance - all the attendance objects of the", "# return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # st = request.POST['delete'] #", "the requested page # @variables: # current_user - the username of the logged", "'POST' and request.FILES: # form = MinuteForm(request.POST, request.FILES) # if form.is_valid(): # form.save()", "data of thsi semester courses next_sem_courses - the data of next semester courses", "if stu not in registered_students: unregistered_students.add(stu) data = [] m = 1 for", "{ 'curriculumm' :curriculum, 'tab_id' :['3','3'] } return render(request, \"ais/ais.html\", context) else: context= {", "== 'POST': # rollno = request.POST.get('rollno_convenor') # extraInfo = ExtraInfo.objects.get(id=rollno) # s =", "student # \"\"\" if request.method == \"POST\": name = request.POST.get('name') # roll =", "will become # convenor or coconvenor # hDes - holdsDesignation object to store", "user. # desig_id - to check the designation of the user. # user_details", "'s name of the student # acadadmin - student's address # final_user -", "render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def delete_timetable(request): \"\"\" acad-admin can", "the required user. # desig_id - used to check the designation ID. #", "to set minimum credit for a current semester that a student must take", "context) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def float_course_submit(request):", "as a dean student - the students as a senator extra - all", "- the form to add academic calender examTtForm - the form required to", "examTtForm = ExamTimetableForm(request.POST, request.FILES) if examTtForm.is_valid(): examTtForm.save() return render(request, \"ais/ais.html\", context) else: return", "return render(request, \"ais/ais.html\", context) @login_required def add_exam_timetable(request): \"\"\" acad-admin can upload the exam", "title text dep - temporary variables z - temporary variables for final output", "# @variables: # s - the designation object that contains convenor # c", "that holds the designation as a dean student - the students as a", "7 and month <= 12: return [1, 3, 5, 7] else: return [2,", "in registered_courses: k = [] k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department) ans.append(k) ans.sort() output =", "= [int(i) for i in from_date] from_date = datetime.datetime(*from_date).date() to_date = to_date[0].split('-') to_date", "course_type, 'curriculum': curriculum, 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) else: return render(request,", "current time now - get current time year - getcurrent year batch -", "the workbook normaltext - formatting variable for normal text sheet - xlsx sheet", "metadata about the requested page. @variables: from_date - The starting date for the", "formatting variable for normal text sheet - xlsx sheet to be rendered titletext", "current_user - father's name of the student # user_details - the rollno of", "year = int(now.year) if sem[0] == 2: sem = sem[year-int(request_batch)-1] else: sem =", "= datetime.datetime.now() month = int(now.month) if month >= 7 and month <= 12:", "xlsx file book - workbook of xlsx file title - formatting variable of", "if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST' and", "as e: acadadmin=\"\" final_user=\"\" pass if (str(acadadmin) != str(final_user)): return True else: return", "response['Content-Disposition'] = st return response @login_required def add_new_profile (request): \"\"\" To add details", "# if (str(p.course_id) == course): # print(p.course_id) # p.delete() # else: # return", "if request.method == 'POST' and request.FILES: # form = MinuteForm(request.POST, request.FILES) # if", "@param: request - contains metadata about the requested page. @variables: from_date - The", "student object from the requested rollno # \"\"\" current_user = get_object_or_404(User, username=request.user.username) #", "user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk') # temp = HoldsDesignation.objects.all().filter(designation", "one data - Formated data for context m - counter for Sl. No", "new_curr=[] while True: if \"semester_\"+str(i) in request.POST: try: programme=request.POST['AddProgramme'] batch=request.POST['AddBatch'] branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)]", "db.programme = programme # st.phone_no = ph # db.save() # st.save() # data", "last_name=last_name, email=email, ) einfo = ExtraInfo.objects.create( id=roll_no, user=user, title=title, sex=sex, date_of_birth=dob, address=address, phone_no=phone_no,", "about me etc of a student # @param: # request - contains metadata", "for the academic caldendar event. desc - Description for the academic calendar event.", "if (str(acadadmin) != str(final_user)): return True else: return False def get_context(request): \"\"\" This", "requested page # @variables: # current_user - gets the data of current user.", "Description. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context= { 'academic_calendar' :calendar,", "course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) elif request.POST['option'] == '2': new_curriculum=[] for i in curriculum:", "and request.FILES: acadTtForm = AcademicTimetableForm(request.POST, request.FILES) if acadTtForm.is_valid(): acadTtForm.save() return render(request, \"ais/ais.html\", context)", "details of student from file user - new user created in database einfo", "assis_stat = Assistantship_status.objects.all() for obj in assis_stat: assistant_flag = obj.student_status hod_flag = obj.hod_status", "the name of the student # roll - the rollno of the student", "rollno # \"\"\" current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id", "(request): \"\"\" To add details of new upcoming students in the database.User must", "contains where the student will become # convenor or coconvenor # hDes -", "context) # else: # return HttpResponseRedirect('/aims/') return HttpResponseRedirect('/aims/') def confirm_grades(request): # if user_check(request):", "sem_cred = [] # sem_cred.append(0) # for i in range(1, 10): # sem", "new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst) else: break i+=1 return render(request, \"ais/ais.html\", context) # # ---------------------senator------------------ #", "hall no, room no, # profile picture, about me etc of a student", "hDes.designation = s # hDes.save() # student = Student.objects.get(id=extraInfo) # data = {", "z = [] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('registered') data.append(z)", "of student from file last_name - details of student from file email -", "add a senate meeting minutes acadTtForm - the form to add academic calender", "the academic person. # course - Course details which is selected by the", "render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required", "user from database desig_id - check for designation acadadmin - designation for Acadadmin", "= 1 # s.room_no = \"\" # s.save() # else: # return HttpResponse(\"Data", "= Constants.COURSE_TYPE timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() pgstudent = Student.objects.filter(programme = \"M.Tech\")", "'lists': procedures_context['lists'], 'date': procedures_context['date'], 'query_option1': procedures_context['query_option1'], 'query_option2': procedures_context['query_option2'], 'course_verification_date' : procedures_context['course_verification_date'], 'submitted_course_list' :", "# curriculum # # #################################### @login_required def curriculum(request): \"\"\" This function is used", "username = i) inst = ExtraInfo.objects.select_related('user','department').get(user=inst) if c==0: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=True, )", "semester of the student # data - tag whether to delete it or", "((str(course.name)+\" : \"+str(str(batch)))) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle)", "course_type=course_type, ) new_curr.append(ins) else: break i+=1 Curriculum.objects.bulk_create(new_curr) curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch =", "final output b - temporary variables for final output c - temporary variables", "# 'phoneno': ph, # 'batch': batch # } # print(data) # return JsonResponse(data)", "import chain from django.contrib.auth.models import User from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from", "the database and the update it. # \"\"\" if request.method==\"POST\": sem_cred = []", "request timetable - all timetable from database exam_t - all exam timetable from", "stud_data = Student.objects.create( id=einfo, programme = programme_name, batch=batch_year, batch_id = batch, father_name =", "} # return render(request, \"ais/ais.html\", context) # else: # return render(request, \"ais/ais.html\") return", "4 num = 1 for i in ans: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2]", "attendance objects of the students context - the datas to be displayed in", "the next semester obj - All the registration details appended into one data", "return HttpResponseRedirect('/academic-procedures/') context = get_context(request) return render(request, \"ais/ais.html\", context) # #################################### # #", "\"\" # s.hall_no = 1 # s.room_no = \"\" # s.save() # else:", "for i in range(1, 10): # sem = \"sem_\"+\"1\" # sem_cred.append(request.POST.getlist(sem)[0]) # for", "verify the grades of the student @param: request - contains metadata about the", "the attendance objects of the students context - the datas to be displayed", "metadata about the requested page. @variables: profiles - gets the excel file having", "response @login_required def generate_preregistration_report(request): \"\"\" to generate preresgistration report after pre-registration @param: request", "exam_t = Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','2'] } examTtForm", "sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',60) sheet.set_column('D:D',15) sheet.set_column('E:E',30) k = 4 num =", "variables for final output c - temporary variables for final output st -", "text dep - temporary variables z - temporary variables for final output b", "branch=branch, sem=sem, course_code=course_code, course_id=course_id, credits=credits, optional=optional, course_type=course_type, ) new_curr.append(ins) else: break i+=1 Curriculum.objects.bulk_create(new_curr)", "- the data that contains where the student will become # convenor or", "= dept, year = batch_year).first() user = User.objects.create_user( username=roll_no, password='<PASSWORD>', first_name=first_name, last_name=last_name, email=email,", "to be added sem - semester of the student grade - grade to", "of which the grade has to be added sem - semester of the", "db.id = roll # db.batch = batch # db.programme = programme # st.phone_no", "ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Senator') # hDes = HoldsDesignation() # hDes.user = extraInfo.user", "temporary varibles faculty - details of faculty of data faculty_list - list of", "be acadadmin @param: request - contains metadata about the requested page. @variables: request_batch", "Description for the academic calendar event. c = object to save new event", "deleted \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": data = request.POST['delete']", "Deletes the student from the database # @param: # request - contains metadata", "request t - Object of Exam time table to be deleted \"\"\" if", "# return JsonResponse(data)# ###################################################### # # ##########Senate meeting Minute################## # @csrf_exempt def addMinute(request):", "curriculum, 'faculty_list': faculty_list, 'tab_id' :['5','1'] } return render(request, \"ais/ais.html\", context) else: return render(request,", "Discipline) from applications.academic_procedures.views import acad_proced_global_context from applications.programme_curriculum.models import Batch @login_required def user_check(request): \"\"\"", "the database.User must be logged in and must be acadadmin @param: request -", "= book.add_worksheet() title_text = ((str(course.name)+\" : \"+str(str(batch)))) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle)", "Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id'", "\"ais/ais.html\", context) @login_required def float_course_submit(request): \"\"\" to float courses for the next sem", "'F': title='Ms.' else: title='Mr.' dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value)", "str(\" \") + str(batch.year)) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle)", "current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division", "data - data of the student to be displayed in the webpage #", "that stores the # information that the particular student is a senator #", "request - contains metadata about the requested page. @variables: request_batch - Batch from", "the student required to check if the student is available desig_id - mother's", "[] for i in obj: if i.student_id.batch_id.year == int(batch): registered_courses.append(i) ans = []", "curriculum details form database ins - Inster data in database \"\"\" if user_check(request):", "- father's name of the student # user_details - the rollno of the", "in assis_stat: assistant_flag = obj.student_status hod_flag = obj.hod_status account_flag = obj.account_status except Exception", "Semester from form curriculum - Get data about curriculum from database courses -", ":['3','1'] # } courses = Course.objects.all() course_type = Constants.COURSE_TYPE html = render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj", "# roll - the rollno of the student # batch - the current", "context = { 'acadTtForm': acadTtForm, 'examTtForm': examTtForm, 'courses': courses, 'courses_list': courses_list, 'course_type': course_type,", "calendar = Calendar.objects.all() this_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses = Course.objects.all() courses_list", "- course-name from form.REQUEST course_id - course_id from database credits - credits from", "- the student object of the student # \"\"\" e = get_object_or_404(ExtraInfo, id=pk)", "@param: request - contains metadata about the requested page. @variables: profiles - gets", "sem_cred[i+1] # sem.save() # return HttpResponse(\"Worked\") def view_course(request): # if request.method == \"POST\":", "first_name=first_name, last_name=last_name, email=email, ) einfo = ExtraInfo.objects.create( id=roll_no, user=user, title=title, sex=sex, date_of_birth=dob, address=address,", "# ''' # # view to add attendance data to database # def", "programme) courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type,", "def sem_for_generate_sheet(): \"\"\" This function generates semester grade sheet @variables: now - current", "\"\"\" This function generates semester grade sheet @variables: now - current datetime month", "\"\" request_branch = \"\" request_programme = \"\" request_sem = \"\" #for checking if", "the academic admin. # \"\"\" if request.method == \"POST\": pass # print(request.POST) #", "@csrf_exempt def addMinute(request): # \"\"\" # to add a new senate meeting minute", "acadadmin = temp.working k = str(user_details).split() final_user = k[2] except Exception as e:", "for i in registered_students: z = [] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\"", "the convenor/coconvenor designation # student - the student object of the new convenor/coconvenor", "object of Convenor # p - designation object of Co Convenor # result", "# \"\"\" # s = get_object_or_404(Designation, name=\"Convenor\") c = get_object_or_404(Designation, name=\"Co Convenor\") #", "= (\"Pre-registeration : \"+ batch.name + str(\" \") + batch.discipline.acronym + str(\" \")", "students as a senator extra - all the extraInfor objects exam_t - all", "# st = ExtraInfo.objects.get(id=roll.id) # db.name = name.upper() # db.id = roll #", "e: f1=f2=f3=\"\" pass faculty = list(chain(f1,f2,f3)) faculty_list = [] for i in faculty:", "first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value) if sex == 'F': title='Ms.' else: title='Mr.' dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5)", "ph # db.save() # st.save() # data = { # 'name': name, #", "checking if the user has searched for any particular curriculum if request_batch ==", "variable data k -temporary array to add data to formatted array/variable output -", "phone number of the student # \"\"\" if request.method == \"POST\": name =", "return JsonResponse(data) # @csrf_exempt def deleteConvenor(request, pk): # \"\"\" # to remove a", "added sem - semester of the student grade - grade to be added", "add a new student convenor/coconvenor # @param: # request - contains metadata about", "course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) batch=batch+1 curriculum = Curriculum.objects.all().select_related().filter(batch =", "current batch of the student # programme - the programme the student is", "context) return render(request, \"ais/ais.html\", context) @login_required def delete_timetable(request): \"\"\" acad-admin can delete the", "# desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() #print (temp)", "# if form.is_valid(): # form.save() # return HttpResponse('sucess') # else: # return HttpResponse('not", "render(request, \"ais/ais.html\", context) #Generate Attendance Sheet def sem_for_generate_sheet(): \"\"\" This function generates semester", "in post request t - Object of Exam time table to be deleted", "the academic timetable objects calendar - all the academic calender objects department -", "can upload the exam timtable of the ongoing semester. @param: request - contains", "st = 'attachment; filename = ' + batch.name + batch.discipline.acronym + str(batch.year) +", "about the requested page @variables: batch - gets the batch course - gets", "return render(request, \"ais/ais.html\", context) @login_required def add_curriculum(request): \"\"\" This function is used to", "student.user) # hDes.delete() # return HttpResponseRedirect('/aims/') # else: # return HttpResponseRedirect('/aims/')# #################################################### #", "year = batch_year).first() user = User.objects.create_user( username=roll_no, password='<PASSWORD>', first_name=first_name, last_name=last_name, email=email, ) einfo", "variables for final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') try: batch = request.POST['batch']", "extraInfor objects exam_t - all the exam timetable objects timetable - all the", "Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() acadadmin = temp.working k =", "data.append(z) for i in registered_students: z = [] z.append(m) m += 1 z.append(i.id.user.username)", "= \"\" request_branch = \"\" request_programme = \"\" request_sem = \"\" #for checking", "= request.POST.get('programme') # batch = request.POST.get('batch') # ph = request.POST.get('phoneno') # if not", "user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": data = request.POST['delete'] t = Timetable.objects.get(time_table=data)", ": courses, # 'course_type' : course_type, # 'curriculum' : curriculum, # 'tab_id' :['3','1']", "@variables: acadTtForm - data of delete dictionary in post request timetable - all", "mother_name = mothers_name, cpi = 0, category = category, hall_no = hall_no, specialization", "if request.POST['optional'] == \"on\": optional=True else: optional=False course_type=request.POST[\"course_type\"] except Exception as e: id=\"\"", "page. @variables: f1,f2,f3 - temporary varibles faculty - details of faculty of data", "Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') # if request.method == 'POST': # rollno", "{ 'acadTtForm': acadTtForm, 'examTtForm': examTtForm, 'courses': courses, 'courses_list': courses_list, 'course_type': course_type, 'exam': exam_t,", "\" + str(room) # student.save() # s = Student.objects.get(id=student) # s.father_name=father # s.mother_name=mother", "next semester courses courses - all the courses in curriculum course_type - list", ") sem=1 stud_data = Student.objects.create( id=einfo, programme = programme_name, batch=batch_year, batch_id = batch,", "= programme # st.phone_no = ph # db.save() # st.save() # data =", "+ '.xlsx' response['Content-Disposition'] = st return response @login_required def generate_preregistration_report(request): \"\"\" to generate", "is a convenor/coconvenor to be deleted # data - data of the student", "= object to save new event to the academic calendar. \"\"\" if user_check(request):", "= HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() acadadmin = temp.working k = str(user_details).split() final_user = k[2]", "of title the workbook subtitle - formatting variable of subtitle the workbook normaltext", "request.POST.get('batch') # ph = request.POST.get('phoneno') # if not Student.objects.filter(id=roll).exists(): # db = Student()", "# data = {} # return JsonResponse(data) # else: # father = request.POST.get('father')", "- Semester from form \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1']", "= request.POST.getlist('description')[0] prev_desc = request.POST.getlist('prev_desc')[0] from_date = from_date[0].split('-') from_date = [int(i) for i", "course_list_2 = [1, 3, 5, 7] # examTtForm = ExamTimetableForm() # acadTtForm =", "temporary variables for final output c - temporary variables for final output st", "objects of the student # user - the User object of the student", "return HttpResponse(\"TimeTable Deleted\") @login_required def delete_exam_timetable(request): \"\"\" acad-admin can delete the outdated exam", "acadmic admin to update the additional courses # @param: # request - contains", "render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def add_curriculum(request): \"\"\" This function", "after pre-registration @param: request - contains metadata about the requested page @variables: sem", "u.delete() # return JsonResponse(data)# ######################################################### # ''' # # view to add attendance", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1'] } if request.method == 'POST':", "this_sem_courses, 'curriculum': curriculum, 'pgstudent' : pgstudent, 'assistant_list' : assistant_list, 'assistant_approve_list' : assistant_approve_list, 'assistant_list_length'", "file last_name - details of student from file email - details of student", "calendar - all the academic calender objects department - all the departments in", "acad_proced_global_context from applications.programme_curriculum.models import Batch @login_required def user_check(request): \"\"\" This function is used", "= request.POST.get('hall') # room = request.POST.get('room') # cpi = request.POST.get('cpi') # student.address =", "data = request.POST['delete'] # t = Meeting.objects.get(id=data) # t.delete() return HttpResponseRedirect('/aims/') # #", "pgstudent, 'assistant_list' : assistant_list, 'assistant_approve_list' : assistant_approve_list, 'assistant_list_length' : assistant_list_length, 'tab_id': ['1','1'], 'context':", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['2','1'] } if request.method == 'POST'", "= Calendar.objects.all() context= { 'academic_calendar' :calendar, 'tab_id' :['4','1'] } if request.method == \"POST\":", "deatils of the acad admin # father - father's name of the student", "cpi = request.POST.get('cpi') # student.address = str(hall) + \" \" + str(room) #", "request_sem) # context={ # 'courses' : courses, # 'course_type' : course_type, # 'curriculum'", "Exception as e: programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\"", "return render(request, \"ais/ais.html\", context) return render(request, 'ais/ais.html', context) @login_required def next_curriculum(request): \"\"\" This", "semester_id__semester_no=sem) registered_students = set() unregistered_students = set() for stu in obj: registered_students.add(stu.student_id) students", "as e: request_batch = \"\" request_branch = \"\" request_programme = \"\" if request_batch", "'academic_calendar': calendar, 'next_sem_course': next_sem_courses, 'this_sem_course': this_sem_courses, 'curriculum': curriculum, 'pgstudent' : pgstudent, 'assistant_list' :", "# \"\"\" # if request.method == \"POST\": # data = request.POST['delete'] # t", "to the academic calendar. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context=", "courses next_sem_courses - the data of next semester courses courses - all the", "request.method == \"POST\": try: from_date = request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0]", "'curriculum' : curriculum, # 'tab_id' :['3','1'] # } courses = Course.objects.all() course_type =", "\"\" course_type = \"\" timetable = \"\" exam_t = \"\" pass context =", "minute object to be deleted # t - the minute object received from", "from form.REQUEST sem - semester from form.REQUEST course_code - course_code from form.REQUEST course_name", "course_id=course_id, credits=credits, optional=optional, course_type=course_type, ) new_curr.append(ins) else: break i+=1 Curriculum.objects.bulk_create(new_curr) curriculum = Curriculum.objects.select_related().filter(branch", "def add_convenor(request): # \"\"\" # to add a new student convenor/coconvenor # @param:", "month >= 7 and month <= 12: return [1, 3, 5, 7] else:", "function is used to delete curriculum entry in database It checkes the authentication", "# print(p.course_id) # p.delete() # else: # return HttpResponse(\"Unable to delete data\") return", "= [] for i in registered_courses: k = [] k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department)", "user_details = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first()", "ans = [] for i in registered_courses: k = [] k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name)", "'date': procedures_context['date'], 'query_option1': procedures_context['query_option1'], 'query_option2': procedures_context['query_option2'], 'course_verification_date' : procedures_context['course_verification_date'], 'submitted_course_list' : procedures_context['submitted_course_list'], 'result_year'", "an entry to the academic calendar to be uploaded @param: request - contains", "# designation = des.designation.name # des.delete() # data = { # 'id': pk,", "= Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','2'] }", "outdated exam timetable. @param: request - contains metadata about the requested page. @variables:", "student stays # room no - hostel room no # \"\"\" current_user =", "department - details of student from file specialization - details of student from", "context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','1'] } return render(request,", "from_date] from_date = datetime.datetime(*from_date).date() to_date = to_date[0].split('-') to_date = [int(i) for i in", "Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses = Course.objects.all() courses_list = Courses.objects.all() course_type = Constants.COURSE_TYPE", "senator # hDes - holdsDesignation object to store that the particualr student is", "context= { 'curriculumm' :curriculum, 'tab_id' :['3','3'] } return render(request, \"ais/ais.html\", context) else: context=", "\"on\": optional=True else: optional=False course_type=request.POST[\"course_type\"] except Exception as e: id=\"\" programme=\"\" batch=\"\" branch=\"\"", "k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department) ans.append(k) ans.sort() output = BytesIO() book = Workbook(output,{'in_memory':True}) title = book.add_format({'bold':", "# if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST':", "designation as a convenor CoConvenor - the extraInfo objects that holds the designation", "rollno # s - designation object of senator # hDes - holdsDesignation object", "c = get_object_or_404(Designation, name=\"Co Convenor\") # student = get_object_or_404(ExtraInfo, id=pk) # hDes =", "+ '-preresgistration.xlsx' response['Content-Disposition'] = st return response @login_required def add_new_profile (request): \"\"\" To", "'designation': designation, # } # return JsonResponse(data)# ###################################################### # # ##########Senate meeting Minute##################", "z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('not registered') data.append(z) for i", "Exception as e: batch=\"\" course=\"\" curr_key=\"\" obj=\"\" registered_courses = [] for i in", "HttpResponseRedirect('/aims/') # # ###################################################### # # ##########Student basic profile################## # @csrf_exempt def add_basic_profile(request):", "sem=sem) # for p in s: # if (str(p.course_id) == course): # print(p.course_id)", "# return HttpResponseRedirect('/academic-procedures/') def min_cred(request): # \"\"\" # to set minimum credit for", "- the datas to be displayed in the webpage this_sem_course - tha data", "# request - contains metadata about the requested page # @variables: # s", "batch_id = batch, father_name = fathers_name, mother_name = mothers_name, cpi = 0, category", "xhtml2pdf import pisa from itertools import chain from django.contrib.auth.models import User from django.http", "branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass ins=Curriculum( programme=programme, batch=batch, branch=branch,", "course): # print(p.course_id) # p.delete() # else: # return HttpResponse(\"Unable to delete data\")", "from form curriculum - Get data about curriculum from database courses - get", "of) of the semester. @param: request - contains metadata about the requested page.", "data of next semester courses courses - all the courses in curriculum course_type", "desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() # print (temp)", "file email - details of student from file sex - details of student", "st return response @login_required def add_new_profile (request): \"\"\" To add details of new", "the application. It checkes the authentication of the user and also fetches the", "add_curriculum(request): \"\"\" This function is used to add new curriculum in database It", "Get data about curriculum from database courses - get courses from database courses_type", "} return context @login_required def homepage(request): \"\"\" This function is used to set", "# mother = request.POST.get('mother') # add = request.POST.get('address') # hall = request.POST.get('hall') #", "page. @variables: examTtForm - data of delete dictionary in post request timetable -", "return HttpResponseRedirect('/academic-procedures/') def add_optional(request): # \"\"\" # acadmic admin to update the additional", "st.save() # data = { # 'name': name, # 'rollno': roll.id, # 'programme':", "username=request.user.username) user_details = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation =", "to be updated. @param: request - contains metadata about the requested page. @variables:", "+ str(\" \") + str(batch.year)) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle)", "# rollno = request.POST.getlist('Roll Number')[0] # # print(request.POST.get('rollno')) # extraInfo = ExtraInfo.objects.get(id=rollno) #", "= request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] from_date = from_date[0].split('-') from_date =", "to be updated. get_calendar_details = Get the object of the calendar instance from", "def user_check(request): \"\"\" This function is used to check the type of user.", "sheet.write_string('D'+str(k),dep,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st = 'attachment; filename", "a senator students - all the objects in the Student class Convenor -", "sex - details of student from file title - details of student from", "the requested page # @variables: # s - the designation object that contains", "student object with the given pk # hDes - the holdDesignation object that", "for i in ans: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] name = str(b)+\" \"+str(c)", "@csrf_exempt def deleteConvenor(request, pk): # \"\"\" # to remove a convenor/coconvenor from the", "upcoming students in the database.User must be logged in and must be acadadmin", "from the database. # @param: # request - contains metadata about the requested", "\"POST\": # curr_id=request.POST['course'] # print(curr_id) # curr_course = Curriculum.objects.filter(curriculum_id=curr_id) # grades = Grades.objects.filter(curriculum_id=curr_course)", "of the required user. # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) # user_details", "father's name of the student # user_details - the rollno of the student", "convenor/coconvenor designation # student - the student object of the new convenor/coconvenor #", "if request.method == \"POST\": data = request.POST['delete'] t = Exam_timetable.objects.get(exam_time_table=data) t.delete() return HttpResponse(\"TimeTable", "'tab_id' :['3','3'] } return render(request, \"ais/ais.html\", context) else: context= { 'tab_id' :['3','2'] }", "page. # @variables: # sem_cred = Get credit details from forms and the", "django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import get_object_or_404, render from django.template.loader import", "specialization = specialization, curr_semester_no=sem, ) desig = Designation.objects.get(name='student') hold_des = HoldsDesignation.objects.create( user=user, working=user,", "= Student.objects.create( id=einfo, programme = programme_name, batch=batch_year, batch_id = batch, father_name = fathers_name,", "details of the current user # desig_id - checking the designation of the", "of the student grade - grade to be added in the student course", "sem[0] == 2: sem = sem[year-int(request_batch)-1] else: sem = sem[year-int(request_batch)] sem+=1 curriculum =", "request_programme).filter(sem=sem).order_by('course_code') faculty_list = get_faculty_list() courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses':", "extraInfo objects that holds the designation as a senator students - all the", "to write to xlsx file book - workbook of xlsx file title -", "Timetable.objects.all() # exam_t = Exam_timetable.objects.all() procedures_context = acad_proced_global_context() try: examTtForm = ExamTimetableForm() acadTtForm", "This function is used to add new curriculum in database It checkes the", "data of delete dictionary in post request timetable - all timetable from database", "data being deleted from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1']", "# 'name': extraInfo.user.username, # 'rollno_convenor': extraInfo.id, # 'designation': hDes.designation.name, # } # return", "# print (temp) # print (current_user) # acadadmin = temp.working # k =", "# room no - hostel room no # \"\"\" current_user = get_object_or_404(User, username=request.user.username)", "pisa from itertools import chain from django.contrib.auth.models import User from django.http import HttpResponse,", "object created in database stud_data - new student object created in database desig", "of student from file address - details of student from file department -", "# return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # print(request.POST) # rollno=request.POST.get('roll') #", "course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme entry.batch=batch entry.branch=branch entry.sem=sem entry.course_code=course_code entry.course_id=course_id", "JsonResponse(data)# ######################################################### # ''' # # view to add attendance data to database", "metadata about the requested page @variables: programme - programme from form.REQUEST now -", "of that particular student field # @variables: # s - the designation object", "def add_curriculum(request): \"\"\" This function is used to add new curriculum in database", "in faculty: faculty_list.append(i) return faculty_list @login_required def float_course(request): \"\"\" to float courses for", "faculty_list @login_required def float_course(request): \"\"\" to float courses for the next sem and", "student from the database # @param: # request - contains metadata about the", "render(request, \"ais/ais.html\", context) @login_required def update_calendar(request): \"\"\" to update an entry to the", "academic calender examTtForm - the form required to add exam timetable Dean -", "object of the student # \"\"\" e = get_object_or_404(ExtraInfo, id=pk) # user =", "Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() #print (temp) # print (current_user) #", "import (Designation, ExtraInfo, HoldsDesignation, DepartmentInfo) from .forms import AcademicTimetableForm, ExamTimetableForm, MinuteForm from .models", "= 'application/vnd.ms-excel') st = 'attachment; filename = ' + batch.name + batch.discipline.acronym +", "- all the attendance objects of the students context - the datas to", "False, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) sheet = book.add_worksheet() title_text = (\"Pre-registeration", "# t - the minute object received from id to be deleted #", "that the particualr student is holding the senator designation # student - the", "Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','2'] } return", "'submitted_course_list' : procedures_context['submitted_course_list'], 'result_year' : procedures_context['result_year'], 'batch_grade_data' : procedures_context['batch_grade_data'], 'batch_branch_data' : procedures_context['batch_branch_data'], 'assistant_flag'", "# holding the convenor/coconvenor designation # student - the student object of the", "students that is a senator # hDes - the holdDesignation object that stores", "the extraInfo objects that holds the designation as a dean student - the", "as e: programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass", "batch from form.REQUEST branch - branch from form.REQUEST sem - semester from form.REQUEST", "set() for stu in obj: registered_students.add(stu.student_id) students = Student.objects.filter(batch_id = batch_id) for stu", "assistant_list_length = len(assistant_list.filter(acad_approval = False)) assis_stat = Assistantship_status.objects.all() for obj in assis_stat: assistant_flag", "= request.POST['programme'] now = datetime.datetime.now() year = int(now.year) batch = year-1 curriculum =", "post request t - Object of time table to be deleted \"\"\" if", "[2, 4, 6, 8] else: course_list_2 = [1, 3, 5, 7] # examTtForm", "= request.POST.getlist('choice') # for i in choices: # course = Course.objects.all().filter(course_id=i).first() # course.acad_selection", "- the holdDesignation object that stores the # information that the particular student", "displayed in teh webpage # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) # user_details", "if request.method == 'POST' and request.FILES: acadTtForm = AcademicTimetableForm(request.POST, request.FILES) if acadTtForm.is_valid(): acadTtForm.save()", "sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st =", "batch=batch+1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) context= { 'curriculumm' :curriculum, 'tab_id'", "programme # st.phone_no = ph # db.save() # st.save() # data = {", "person. # course - Course details which is selected by the academic admin.", "senates - the extraInfo objects that holds the designation as a senator students", "in post request t - Object of time table to be deleted \"\"\"", "admin # father - father's name of the student # rollno - the", "edit entries in a curriculum. It checkes the authentication of the user and", "student course - course ofwhich the grade is added \"\"\" # if user_check(request):", "academic caldendar event. desc - Description for the academic calendar event. c =", "request_branch == \"\" and request_programme==\"\" and request_sem==\"\": curriculum = None #Curriculum.objects.all() else: if", "of student from file dob - details of student from file fathers_name -", "\"POST\": # print(request.POST) # rollno=request.POST.get('roll') # print(rollno) # student = ExtraInfo.objects.get(id=rollno) # print(student.address)", "str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel')", "# def curriculum(request): # ''' def delete_advanced_profile(request): # \"\"\" # to delete the", "'1': new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id,", "str(i[0]),i[1],i[2] a,b,c,d,e = str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp = str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext) k+=1 book.close()", "meeting objects held in senator meetings minuteForm - the form to add a", "Curriculum.objects.bulk_create(new_curriculum) batch=batch+1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) context= { 'curriculumm' :curriculum,", "acad-admin can delete the outdated exam timetable. @param: request - contains metadata about", "= Curriculum.objects.filter(curriculum_id=curr_id) # grades = Grades.objects.filter(curriculum_id=curr_course) # context= { # 'grades': grades, #", "the acad admin # father - father's name of the student # rollno", "courses_list, 'course_type': course_type, 'exam': exam_t, 'timetable': timetable, 'academic_calendar': calendar, 'next_sem_course': next_sem_courses, 'this_sem_course': this_sem_courses,", "s = Grades.objects.filter(student_id=id, sem=sem) # for p in s: # if (str(p.course_id) ==", "course curr_key - gets the curriculum from database obj - get stdents data", "from_date = request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] prev_desc = request.POST.getlist('prev_desc')[0] from_date", "about the requested page # pk - the primary key of that particular", "= request.POST.getlist('prev_desc')[0] from_date = from_date[0].split('-') from_date = [int(i) for i in from_date] from_date", "form database ins - Inster data in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "'vcenter'}) sheet = book.add_worksheet() title_text = (\"Pre-registeration : \"+ batch.name + str(\" \")", "'tab_id' :['5','1'] } if request.method == \"POST\": i=1 while True: if str(i)+\"_ccode\" in", "programme) context= { 'curriculumm' :curriculum, 'tab_id' :['3','3'] } return render(request, \"ais/ais.html\", context) else:", "temporary array to add data to variable data k -temporary array to add", "request_batch == \"\" and request_branch == \"\" and request_programme==\"\": curriculum = None #Curriculum.objects.all()", "= get_object_or_404( HoldsDesignation, user = student.user) # hDes.delete() # return HttpResponseRedirect('/aims/') # else:", "request.POST['option'] == '2': new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem,", "(CourseSlot, Course as Courses, Batch, Semester, Programme, Discipline) from applications.academic_procedures.views import acad_proced_global_context from", "requested page @variables: acadTtForm - the form to add academic calender examTtForm -", "if not student: # data = {} # return JsonResponse(data) # else: #", "choices: # i.acad_selection = False # i.save() # return HttpResponseRedirect('/academic-procedures/') def min_cred(request): #", "\"POST\": try: from_date = request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] from_date =", "details of student from file address - details of student from file department", "file first_name - details of student from file last_name - details of student", "\"PhD\") assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(acad_approval = False) assistant_approve_list =", "metadata about the requested page @variables: senates - the extraInfo objects that holds", "import MinimumCredits, Register, InitialRegistration, course_registration, AssistantshipClaim,Assistantship_status from applications.globals.models import (Designation, ExtraInfo, HoldsDesignation, DepartmentInfo)", "as e: from_date=\"\" to_date=\"\" desc=\"\" return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context)", "# data - data of the student to be displayed in the webpage", "request - contains metadata about the requested page @variables: current_user - get user", "= Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete() curriculum = Curriculum.objects.select_related().filter(branch = request.POST['branch']).filter(batch = request.POST['batch']).filter(programme= request.POST['programme']) courses =", "acadTtForm.save() return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\",", "admin. # \"\"\" if request.method == \"POST\": pass # print(request.POST) # choices =", "if request.method == \"POST\": # programme=request.POST['programme'] # batch=request.POST['batch'] # branch=request.POST['branch'] # sem=request.POST['sem'] #", "extraInfo.user # if result == \"Convenor\": # hDes.designation = s # else: #", "= to_date get_calendar_details.save() except Exception as e: from_date=\"\" to_date=\"\" desc=\"\" return render(request, \"ais/ais.html\",", "return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if request.method == \"POST\": dele = Curriculum.objects.select_related().filter(curriculum_id=request.POST['id'])", "= Designation.objects.get(name='Co Convenor') # result = request.POST.get('designation') # hDes = HoldsDesignation() # hDes.user", "get_object_or_404( HoldsDesignation, user = student.user) # hDes.delete() # return HttpResponseRedirect('/aims/') # else: #", "\"ais/ais.html\", {}) def deleteMinute(request): # \"\"\" # to delete an existing senate meeting", "id=e) # data = { # 'rollno': pk, # } # s.delete() #", "curriculum. It checkes the authentication of the user and also fetches the available", "current time year - getcurrent year batch - gets the batch from form", "for Sl. No (in formated data) z - temporary array to add data", "name of the student user_details - the rollno of the student required to", "to add attendance data to database # def curriculum(request): # ''' def delete_advanced_profile(request):", "\"\"\" This function is used to edit curriculum in database It checkes the", "sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st =", "database desig_id - check for designation acadadmin - designation for Acadadmin final_user -", "student is # holding the convenor/coconvenor designation # student - the student object", "phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13 ).value department=DepartmentInfo.objects.all().filter(name=dept).first() if specialization == \"\": specialization=\"None\" if", "= None #Curriculum.objects.all() else: sem = sem_for_generate_sheet() now = datetime.datetime.now() year = int(now.year)", "(str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST' and request.FILES:", "the student user_details - the rollno of the student required to check if", "@login_required def float_course(request): \"\"\" to float courses for the next sem and store", "addMinute(request): # \"\"\" # to add a new senate meeting minute object to", "e: batch=\"\" course=\"\" curr_key=\"\" obj=\"\" registered_courses = [] for i in obj: if", "to be displayed in the webpage # \"\"\" s = Designation.objects.get(name='Convenor') # p", "# db.batch = batch # db.programme = programme # st.phone_no = ph #", "for i in unregistered_students: z = [] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\"", "grades, # 'tab_id' :\"2\" # } # return render(request,\"ais/ais.html\", context) # else: #", "book - workbook of xlsx file title - formatting variable of title the", "Curriculum.objects.bulk_create(new_curr) curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme) courses = Course.objects.all() course_type", "obj.student_status hod_flag = obj.hod_status account_flag = obj.account_status except Exception as e: examTtForm =" ]
[ "License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "writing, software # distributed under the License is distributed on an \"AS IS\"", "Unless required by applicable law or agreed to in writing, software # distributed", "subject.cmd.replicator ' 'compare az1:9292 az2:9292 --debug' % (sys.executable,)) exitcode, out, err = execute(cmd,", "See the # License for the specific language governing permissions and limitations #", "https://bugs.launchpad.net/glance/+bug/1598928 cmd = ('%s -m subject.cmd.replicator ' 'compare az1:9292 az2:9292 --debug' % (sys.executable,))", "\"License\"); you may # not use this file except in compliance with the", "Apache License, Version 2.0 (the \"License\"); you may # not use this file", "the License. You may obtain # a copy of the License at #", "cmd = ('%s -m subject.cmd.replicator ' 'compare az1:9292 az2:9292 --debug' % (sys.executable,)) exitcode,", "law or agreed to in writing, software # distributed under the License is", "may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "the Apache License, Version 2.0 (the \"License\"); you may # not use this", "subject.tests.utils import execute class TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional tests for subject-replicator\"\"\" def test_compare(self): # Test", "' 'compare az1:9292 az2:9292 --debug' % (sys.executable,)) exitcode, out, err = execute(cmd, raise_error=False)", "express or implied. See the # License for the specific language governing permissions", "language governing permissions and limitations # under the License. \"\"\"Functional test cases for", "subject.tests import functional from subject.tests.utils import execute class TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional tests for subject-replicator\"\"\"", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "CONDITIONS OF ANY KIND, either express or implied. See the # License for", "not use this file except in compliance with the License. You may obtain", "execute class TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional tests for subject-replicator\"\"\" def test_compare(self): # Test for issue:", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "with the License. You may obtain # a copy of the License at", "Licensed under the Apache License, Version 2.0 (the \"License\"); you may # not", "-m subject.cmd.replicator ' 'compare az1:9292 az2:9292 --debug' % (sys.executable,)) exitcode, out, err =", "--debug' % (sys.executable,)) exitcode, out, err = execute(cmd, raise_error=False) self.assertIn( 'Request: GET http://az1:9292/v1/subjects/detail?is_public=None',", "the specific language governing permissions and limitations # under the License. \"\"\"Functional test", "License for the specific language governing permissions and limitations # under the License.", "the License. \"\"\"Functional test cases for subject-replicator\"\"\" import sys from subject.tests import functional", "subject-replicator\"\"\" def test_compare(self): # Test for issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd = ('%s -m subject.cmd.replicator", "under the License. \"\"\"Functional test cases for subject-replicator\"\"\" import sys from subject.tests import", "test_compare(self): # Test for issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd = ('%s -m subject.cmd.replicator ' 'compare", "'compare az1:9292 az2:9292 --debug' % (sys.executable,)) exitcode, out, err = execute(cmd, raise_error=False) self.assertIn(", "2.0 (the \"License\"); you may # not use this file except in compliance", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "subject-replicator\"\"\" import sys from subject.tests import functional from subject.tests.utils import execute class TestGlanceReplicator(functional.FunctionalTest):", "\"\"\"Functional tests for subject-replicator\"\"\" def test_compare(self): # Test for issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd =", "use this file except in compliance with the License. You may obtain #", "# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the #", "compliance with the License. You may obtain # a copy of the License", "License, Version 2.0 (the \"License\"); you may # not use this file except", "\"\"\"Functional test cases for subject-replicator\"\"\" import sys from subject.tests import functional from subject.tests.utils", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "('%s -m subject.cmd.replicator ' 'compare az1:9292 az2:9292 --debug' % (sys.executable,)) exitcode, out, err", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "implied. See the # License for the specific language governing permissions and limitations", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "OF ANY KIND, either express or implied. See the # License for the", "def test_compare(self): # Test for issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd = ('%s -m subject.cmd.replicator '", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "tests for subject-replicator\"\"\" def test_compare(self): # Test for issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd = ('%s", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the", "you may # not use this file except in compliance with the License.", "agreed to in writing, software # distributed under the License is distributed on", "for subject-replicator\"\"\" def test_compare(self): # Test for issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd = ('%s -m", "(the \"License\"); you may # not use this file except in compliance with", "test cases for subject-replicator\"\"\" import sys from subject.tests import functional from subject.tests.utils import", "KIND, either express or implied. See the # License for the specific language", "may # not use this file except in compliance with the License. You", "for issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd = ('%s -m subject.cmd.replicator ' 'compare az1:9292 az2:9292 --debug'", "either express or implied. See the # License for the specific language governing", "for the specific language governing permissions and limitations # under the License. \"\"\"Functional", "# # Unless required by applicable law or agreed to in writing, software", "# Test for issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd = ('%s -m subject.cmd.replicator ' 'compare az1:9292", "file except in compliance with the License. You may obtain # a copy", "issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd = ('%s -m subject.cmd.replicator ' 'compare az1:9292 az2:9292 --debug' %", "this file except in compliance with the License. You may obtain # a", "# under the License. \"\"\"Functional test cases for subject-replicator\"\"\" import sys from subject.tests", "# Unless required by applicable law or agreed to in writing, software #", "sys from subject.tests import functional from subject.tests.utils import execute class TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional tests", "class TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional tests for subject-replicator\"\"\" def test_compare(self): # Test for issue: https://bugs.launchpad.net/glance/+bug/1598928", "by applicable law or agreed to in writing, software # distributed under the", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "functional from subject.tests.utils import execute class TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional tests for subject-replicator\"\"\" def test_compare(self):", "under the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "or implied. See the # License for the specific language governing permissions and", "governing permissions and limitations # under the License. \"\"\"Functional test cases for subject-replicator\"\"\"", "az2:9292 --debug' % (sys.executable,)) exitcode, out, err = execute(cmd, raise_error=False) self.assertIn( 'Request: GET", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "License. You may obtain # a copy of the License at # #", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "and limitations # under the License. \"\"\"Functional test cases for subject-replicator\"\"\" import sys", "(sys.executable,)) exitcode, out, err = execute(cmd, raise_error=False) self.assertIn( 'Request: GET http://az1:9292/v1/subjects/detail?is_public=None', err )", "% (sys.executable,)) exitcode, out, err = execute(cmd, raise_error=False) self.assertIn( 'Request: GET http://az1:9292/v1/subjects/detail?is_public=None', err", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "specific language governing permissions and limitations # under the License. \"\"\"Functional test cases", "import execute class TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional tests for subject-replicator\"\"\" def test_compare(self): # Test for", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "ANY KIND, either express or implied. See the # License for the specific", "the # License for the specific language governing permissions and limitations # under", "except in compliance with the License. You may obtain # a copy of", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "to in writing, software # distributed under the License is distributed on an", "You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "az1:9292 az2:9292 --debug' % (sys.executable,)) exitcode, out, err = execute(cmd, raise_error=False) self.assertIn( 'Request:", "required by applicable law or agreed to in writing, software # distributed under", "TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional tests for subject-replicator\"\"\" def test_compare(self): # Test for issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd", "import functional from subject.tests.utils import execute class TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional tests for subject-replicator\"\"\" def", "applicable law or agreed to in writing, software # distributed under the License", "= ('%s -m subject.cmd.replicator ' 'compare az1:9292 az2:9292 --debug' % (sys.executable,)) exitcode, out,", "distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT #", "OR CONDITIONS OF ANY KIND, either express or implied. See the # License", "obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "Test for issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd = ('%s -m subject.cmd.replicator ' 'compare az1:9292 az2:9292", "License. \"\"\"Functional test cases for subject-replicator\"\"\" import sys from subject.tests import functional from", "in compliance with the License. You may obtain # a copy of the", "# Licensed under the Apache License, Version 2.0 (the \"License\"); you may #", "# not use this file except in compliance with the License. You may", "or agreed to in writing, software # distributed under the License is distributed", "for subject-replicator\"\"\" import sys from subject.tests import functional from subject.tests.utils import execute class", "permissions and limitations # under the License. \"\"\"Functional test cases for subject-replicator\"\"\" import", "# License for the specific language governing permissions and limitations # under the", "from subject.tests import functional from subject.tests.utils import execute class TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional tests for", "from subject.tests.utils import execute class TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional tests for subject-replicator\"\"\" def test_compare(self): #", "import sys from subject.tests import functional from subject.tests.utils import execute class TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional", "under the Apache License, Version 2.0 (the \"License\"); you may # not use", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "in writing, software # distributed under the License is distributed on an \"AS", "cases for subject-replicator\"\"\" import sys from subject.tests import functional from subject.tests.utils import execute", "Version 2.0 (the \"License\"); you may # not use this file except in", "limitations # under the License. \"\"\"Functional test cases for subject-replicator\"\"\" import sys from" ]
[ "date(1970, 5, 30), date(1971, 5, 31), date(1997, 5, 26), date(1999, 5, 31), date(2000,", "4, 15), self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.BtwDates(current_date, future_date)) # if __name__ ==", "nc_marketholidayss) nc_marketholidayss.observed = True def test_new_years_eve(self): ky_marketholidayss = marketholidays.US() self.assertNotIn(date(2012, 12, 31), ky_marketholidayss)", "year in range(1900, 2100): dt = date(year, 12, 25) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt +", "# marketanalysis # ---------------- # A fast, efficient Python library for generating country,", "date(2015, 5, 25), date(2016, 5, 30), date(2020, 5, 25), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt", "[ date(1997, 11, 27), date(1999, 11, 25), date(2000, 11, 23), date(2012, 11, 22),", "12, 25) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010,", "self.assertNotIn(date(year, 12, 24), self.marketholidayss) # self.assertIn(date(year, 12, 24), as_marketholidayss) self.assertNotIn(date(2016, 12, 23), as_marketholidayss)", "Version: 0.1 (April 7, 2021) import unittest from datetime import date from dateutil.relativedelta", "self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt, ky_marketholidayss) def test_future_list(self): current_date = '2021-04-13' lookup_step = 10 self.assertIn(date(2021,", "self.assertNotIn( \"Christmas Eve (Observed)\", as_marketholidayss.get_list(date(2017, 12, 22)), ) def test_christmas_day(self): for year in", "self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 7, 5), self.marketholidayss) self.assertIn(date(2020, 7, 3), self.marketholidayss) def", "datetime import date from dateutil.relativedelta import relativedelta # import sys # sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/')", "24), as_marketholidayss) self.assertNotIn(date(2016, 12, 23), as_marketholidayss) self.assertNotIn( \"Christmas Eve (Observed)\", as_marketholidayss.get_list(date(2017, 12, 22)),", "2, 17), date(2015, 2, 16), date(2016, 2, 15), date(2020, 2, 17), ]: self.assertIn(dt,", "15), date(2000, 2, 21), date(2012, 2, 20), date(2013, 2, 18), date(2014, 2, 17),", "Python library for generating country, province and state # specific sets of marketmarketholidayss", "date(1986, 1, 20), date(1999, 1, 18), date(2000, 1, 17), date(2012, 1, 16), date(2013,", "self.marketholidayss) def test_martin_luther(self): for dt in [ date(1986, 1, 20), date(1999, 1, 18),", "= markettradingdays.USA() def test_new_years(self): self.assertNotIn(date(2010, 12, 31), self.marketholidayss) self.assertNotIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed", "18), self.markettradingdayss.future_list(current_date, lookup_step)) def test_prevDays(self): current_date = '2021-04-13' lookback_step = 4 self.assertIn(date(2021, 4,", "20), date(1999, 1, 18), date(2000, 1, 17), date(2012, 1, 16), date(2013, 1, 21),", "province and state # specific sets of marketmarketholidayss on the fly. It aims", "12, 27), nc_marketholidayss) nc_marketholidayss.observed = True def test_new_years_eve(self): ky_marketholidayss = marketholidays.US() self.assertNotIn(date(2012, 12,", "= True self.assertIn(date(2010, 12, 31), self.marketholidayss) self.assertIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = False", "marketholidays.US() for dt in [ date(1900, 4, 13), date(1901, 4, 5), date(1902, 3,", "17), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertIn(dt,", "12, 24), self.marketholidayss) self.assertNotIn(date(2016, 12, 26), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 24),", "self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertIn(dt, de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"),", "the fly. It aims to make determining whether a # specific date is", "self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_christmas_eve(self): as_marketholidayss = marketholidays.US() self.marketholidayss.observed = False for", "= marketholidays.US(observed=False) self.assertNotIn(date(2015, 12, 28), nc_marketholidayss) self.assertNotIn(date(2016, 12, 27), nc_marketholidayss) nc_marketholidayss.observed = True", "2), self.marketholidayss) self.marketholidayss.observed = False for year in range(1900, 2100): dt = date(year,", "relativedelta(days=+1), self.marketholidayss) def test_thanksgiving_day(self): for dt in [ date(1997, 11, 27), date(1999, 11,", "test_labor_day(self): for dt in [ date(1997, 9, 1), date(1999, 9, 6), date(2000, 9,", "self.assertNotIn(date(2012, 12, 31), ky_marketholidayss) for dt in [date(2013, 12, 31), date(2016, 12, 30)]:", "2), date(2014, 9, 1), date(2015, 9, 7), date(2016, 9, 5), date(2020, 9, 7),", "30), date(2020, 5, 25), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt +", "relativedelta(days=+1), self.marketholidayss) def test_christmas_eve(self): as_marketholidayss = marketholidays.US() self.marketholidayss.observed = False for year in", "]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_thanksgiving_day(self):", "date from dateutil.relativedelta import relativedelta # import sys # sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from marketanalysis", "self.assertNotIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 31), self.marketholidayss) self.assertIn(date(2017, 1,", "date(2015, 2, 16), date(2016, 2, 15), date(2020, 2, 17), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt", "unittest from datetime import date from dateutil.relativedelta import relativedelta # import sys #", "20), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def", "range(1900, 2100): dt = date(year, 1, 1) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss)", "self.assertIn(date(2010, 12, 31), self.marketholidayss) self.assertIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = False for year", "2, 15), date(2000, 2, 21), date(2012, 2, 20), date(2013, 2, 18), date(2014, 2,", "12, 22)), ) def test_christmas_day(self): for year in range(1900, 2100): dt = date(year,", "date(1997, 5, 26), date(1999, 5, 31), date(2000, 5, 29), date(2012, 5, 28), date(2013,", "31), date(2016, 12, 30)]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt, ky_marketholidayss) def test_future_list(self): current_date = '2021-04-13'", "+ relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 7, 5), self.marketholidayss) self.assertNotIn(date(2020, 7,", "2, 22), date(1971, 2, 15), date(1997, 2, 17), date(1999, 2, 15), date(2000, 2,", "= True self.assertIn(date(2010, 7, 5), self.marketholidayss) self.assertIn(date(2020, 7, 3), self.marketholidayss) def test_labor_day(self): for", "in range(1900, 2100): dt = date(year, 12, 25) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1),", "<<EMAIL>> # Website: https://github.com/OmoMicheal/trading_days # License: MIT (see LICENSE file) # Version: 0.1", "Day\") def test_good_friday(self): marketholidayss_US = marketholidays.US() for dt in [ date(1900, 4, 13),", "1, 20), date(1999, 1, 18), date(2000, 1, 17), date(2012, 1, 16), date(2013, 1,", "[ date(1969, 2, 22), date(1970, 2, 22), date(1971, 2, 15), date(1997, 2, 17),", "import marketholidays from marketanalysis import markettradingdays class TestUS(unittest.TestCase): def setUp(self): self.marketholidayss = marketholidays.USA(observed=False)", "12, 24), self.marketholidayss) self.assertIn(date(2016, 12, 26), self.marketholidayss) def test_day_after_christmas(self): nc_marketholidayss = marketholidays.US(observed=False) self.assertNotIn(date(2015,", "+ relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_thanksgiving_day(self): for dt in [", "date(1902, 3, 28), date(1999, 4, 2), date(2000, 4, 21), date(2010, 4, 2), date(2018,", "5), date(1902, 3, 28), date(1999, 4, 2), date(2000, 4, 21), date(2010, 4, 2),", "coding: utf-8 -*- # marketanalysis # ---------------- # A fast, efficient Python library", "True def test_new_years_eve(self): ky_marketholidayss = marketholidays.US() self.assertNotIn(date(2012, 12, 31), ky_marketholidayss) for dt in", "\"Christmas Eve (Observed)\", as_marketholidayss.get_list(date(2017, 12, 22)), ) def test_christmas_day(self): for year in range(1900,", "in [ date(1997, 9, 1), date(1999, 9, 6), date(2000, 9, 4), date(2012, 9,", "and flexible as possible. # # Author: MichealOmojola <<EMAIL>> # Website: https://github.com/OmoMicheal/trading_days #", "22), date(2013, 11, 28), date(2014, 11, 27), date(2015, 11, 26), date(2016, 11, 24),", "# A fast, efficient Python library for generating country, province and state #", "self.marketholidayss) self.assertNotIn(date(2020, 7, 3), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 7, 5), self.marketholidayss) self.assertIn(date(2020,", "self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 7, 5), self.marketholidayss) self.assertNotIn(date(2020, 7, 3), self.marketholidayss) self.marketholidayss.observed", "11), self.markettradingdayss.prevDays(current_date, lookback_step)) def test_BtwDates(self): current_date = '2021-04-13' future_date = '2021-04-20' self.assertIn(date(2021, 4,", "4, 18), self.markettradingdayss.future_list(current_date, lookup_step)) def test_prevDays(self): current_date = '2021-04-13' lookback_step = 4 self.assertIn(date(2021,", "26), ]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_independence_day(self): for year in range(1900, 2100): dt", "dateutil.relativedelta import relativedelta # import sys # sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from marketanalysis import marketholidays", "date(2012, 2, 20), date(2013, 2, 18), date(2014, 2, 17), date(2015, 2, 16), date(2016,", "self.assertIn(date(2021, 4, 9), self.markettradingdayss.prevDays(current_date, lookback_step)) self.assertNotIn(date(2021, 4, 11), self.markettradingdayss.prevDays(current_date, lookback_step)) def test_BtwDates(self): current_date", "relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_christmas_eve(self): as_marketholidayss = marketholidays.US() self.marketholidayss.observed =", "2, 15), date(1997, 2, 17), date(1999, 2, 15), date(2000, 2, 21), date(2012, 2,", "3), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 7, 5), self.marketholidayss) self.assertIn(date(2020, 7, 3), self.marketholidayss)", "self.assertIn(date(2010, 12, 24), self.marketholidayss) self.assertIn(date(2016, 12, 26), self.marketholidayss) def test_day_after_christmas(self): nc_marketholidayss = marketholidays.US(observed=False)", "# sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from marketanalysis import marketholidays from marketanalysis import markettradingdays class TestUS(unittest.TestCase):", "relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_washingtons_birthday(self): de_marketholidayss = marketholidays.US() for dt", "self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 7, 5), self.marketholidayss) self.assertNotIn(date(2020,", "dt = date(year, 12, 25) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt +", "self.markettradingdayss = markettradingdays.USA() def test_new_years(self): self.assertNotIn(date(2010, 12, 31), self.marketholidayss) self.assertNotIn(date(2017, 1, 2), self.marketholidayss)", "de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents' Day\") def test_good_friday(self): marketholidayss_US = marketholidays.US() for dt in [", "2, 16), date(2016, 2, 15), date(2020, 2, 17), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt +", "date is a holiday as fast and flexible as possible. # # Author:", "lookback_step)) def test_BtwDates(self): current_date = '2021-04-13' future_date = '2021-04-20' self.assertIn(date(2021, 4, 15), self.markettradingdayss.BtwDates(current_date,", "date(1970, 2, 22), date(1971, 2, 15), date(1997, 2, 17), date(1999, 2, 15), date(2000,", "= True self.assertIn(date(2010, 12, 24), self.marketholidayss) self.assertIn(date(2016, 12, 26), self.marketholidayss) def test_day_after_christmas(self): nc_marketholidayss", "self.markettradingdayss.prevDays(current_date, lookback_step)) def test_BtwDates(self): current_date = '2021-04-13' future_date = '2021-04-20' self.assertIn(date(2021, 4, 15),", "date(2013, 1, 21), date(2014, 1, 20), date(2015, 1, 19), date(2016, 1, 18), date(2020,", "self.marketholidayss) # self.assertIn(date(year, 12, 24), as_marketholidayss) self.assertNotIn(date(2016, 12, 23), as_marketholidayss) self.assertNotIn( \"Christmas Eve", "relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_martin_luther(self): for dt in [ date(1986,", "https://github.com/OmoMicheal/trading_days # License: MIT (see LICENSE file) # Version: 0.1 (April 7, 2021)", "4 self.assertIn(date(2021, 4, 9), self.markettradingdayss.prevDays(current_date, lookback_step)) self.assertNotIn(date(2021, 4, 11), self.markettradingdayss.prevDays(current_date, lookback_step)) def test_BtwDates(self):", "holiday as fast and flexible as possible. # # Author: MichealOmojola <<EMAIL>> #", "0.1 (April 7, 2021) import unittest from datetime import date from dateutil.relativedelta import", "1, 20), date(2015, 1, 19), date(2016, 1, 18), date(2020, 1, 20), ]: self.assertIn(dt,", "date(1999, 4, 2), date(2000, 4, 21), date(2010, 4, 2), date(2018, 3, 30), date(2019,", "for generating country, province and state # specific sets of marketmarketholidayss on the", "26), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 24), self.marketholidayss) self.assertIn(date(2016, 12, 26), self.marketholidayss)", "def test_martin_luther(self): for dt in [ date(1986, 1, 20), date(1999, 1, 18), date(2000,", "def test_christmas_eve(self): as_marketholidayss = marketholidays.US() self.marketholidayss.observed = False for year in range(1900, 2050):", "4) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 7,", "12, 23), as_marketholidayss) self.assertNotIn( \"Christmas Eve (Observed)\", as_marketholidayss.get_list(date(2017, 12, 22)), ) def test_christmas_day(self):", "marketanalysis import markettradingdays class TestUS(unittest.TestCase): def setUp(self): self.marketholidayss = marketholidays.USA(observed=False) self.markettradingdayss = markettradingdays.USA()", "2, 17), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss)", "29), date(2012, 5, 28), date(2013, 5, 27), date(2014, 5, 26), date(2015, 5, 25),", "11, 24), date(2020, 11, 26), ]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt", "date(1997, 9, 1), date(1999, 9, 6), date(2000, 9, 4), date(2012, 9, 3), date(2013,", "date(2015, 11, 26), date(2016, 11, 24), date(2020, 11, 26), ]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt", "4, 10), ]: self.assertIn(dt, self.marketholidayss) self.assertIn(dt, marketholidayss_US) def test_memorial_day(self): for dt in [", "test_washingtons_birthday(self): de_marketholidayss = marketholidays.US() for dt in [ date(1969, 2, 22), date(1970, 2,", "relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_thanksgiving_day(self): for dt in [ date(1997,", "21), date(2010, 4, 2), date(2018, 3, 30), date(2019, 4, 19), date(2020, 4, 10),", "date(2020, 2, 17), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1),", "marketanalysis # ---------------- # A fast, efficient Python library for generating country, province", "date(2014, 11, 27), date(2015, 11, 26), date(2016, 11, 24), date(2020, 11, 26), ]:", "1, 17), date(2012, 1, 16), date(2013, 1, 21), date(2014, 1, 20), date(2015, 1,", "in [ date(1900, 4, 13), date(1901, 4, 5), date(1902, 3, 28), date(1999, 4,", "+ relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_martin_luther(self): for dt in [", "def test_christmas_day(self): for year in range(1900, 2100): dt = date(year, 12, 25) self.assertIn(dt,", "def test_new_years_eve(self): ky_marketholidayss = marketholidays.US() self.assertNotIn(date(2012, 12, 31), ky_marketholidayss) for dt in [date(2013,", "whether a # specific date is a holiday as fast and flexible as", "import unittest from datetime import date from dateutil.relativedelta import relativedelta # import sys", "5, 28), date(2013, 5, 27), date(2014, 5, 26), date(2015, 5, 25), date(2016, 5,", "# Author: MichealOmojola <<EMAIL>> # Website: https://github.com/OmoMicheal/trading_days # License: MIT (see LICENSE file)", "self.assertIn(date(2016, 12, 26), self.marketholidayss) def test_day_after_christmas(self): nc_marketholidayss = marketholidays.US(observed=False) self.assertNotIn(date(2015, 12, 28), nc_marketholidayss)", "import date from dateutil.relativedelta import relativedelta # import sys # sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from", "marketholidays.US() for dt in [ date(1969, 2, 22), date(1970, 2, 22), date(1971, 2,", "11, 23), date(2012, 11, 22), date(2013, 11, 28), date(2014, 11, 27), date(2015, 11,", "+ relativedelta(days=+1), self.marketholidayss) def test_christmas_eve(self): as_marketholidayss = marketholidays.US() self.marketholidayss.observed = False for year", "1, 16), date(2013, 1, 21), date(2014, 1, 20), date(2015, 1, 19), date(2016, 1,", "7, 2021) import unittest from datetime import date from dateutil.relativedelta import relativedelta #", "# Version: 0.1 (April 7, 2021) import unittest from datetime import date from", "for year in range(1900, 2100): dt = date(year, 7, 4) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt", "self.marketholidayss.observed = True self.assertIn(date(2010, 12, 31), self.marketholidayss) self.assertIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed =", "relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_independence_day(self): for year in range(1900, 2100):", "sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from marketanalysis import marketholidays from marketanalysis import markettradingdays class TestUS(unittest.TestCase): def", "7, 5), self.marketholidayss) self.assertNotIn(date(2020, 7, 3), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 7, 5),", "date(2013, 11, 28), date(2014, 11, 27), date(2015, 11, 26), date(2016, 11, 24), date(2020,", "test_day_after_christmas(self): nc_marketholidayss = marketholidays.US(observed=False) self.assertNotIn(date(2015, 12, 28), nc_marketholidayss) self.assertNotIn(date(2016, 12, 27), nc_marketholidayss) nc_marketholidayss.observed", "class TestUS(unittest.TestCase): def setUp(self): self.marketholidayss = marketholidays.USA(observed=False) self.markettradingdayss = markettradingdays.USA() def test_new_years(self): self.assertNotIn(date(2010,", "def test_washingtons_birthday(self): de_marketholidayss = marketholidays.US() for dt in [ date(1969, 2, 22), date(1970,", "marketholidays.US() self.assertNotIn(date(2012, 12, 31), ky_marketholidayss) for dt in [date(2013, 12, 31), date(2016, 12,", "import markettradingdays class TestUS(unittest.TestCase): def setUp(self): self.marketholidayss = marketholidays.USA(observed=False) self.markettradingdayss = markettradingdays.USA() def", "Author: MichealOmojola <<EMAIL>> # Website: https://github.com/OmoMicheal/trading_days # License: MIT (see LICENSE file) #", "marketholidayss_US) def test_memorial_day(self): for dt in [ date(1969, 5, 30), date(1970, 5, 30),", "self.assertNotIn(date(2010, 7, 5), self.marketholidayss) self.assertNotIn(date(2020, 7, 3), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 7,", "lookback_step)) self.assertNotIn(date(2021, 4, 11), self.markettradingdayss.prevDays(current_date, lookback_step)) def test_BtwDates(self): current_date = '2021-04-13' future_date =", "self.marketholidayss) self.assertNotIn(date(2010, 12, 24), self.marketholidayss) self.assertNotIn(date(2016, 12, 26), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010,", "relativedelta(days=+1), self.marketholidayss) def test_martin_luther(self): for dt in [ date(1986, 1, 20), date(1999, 1,", "'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from marketanalysis import marketholidays from marketanalysis import markettradingdays class TestUS(unittest.TestCase): def setUp(self):", "self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_independence_day(self): for year in range(1900, 2100): dt =", "date(2000, 2, 21), date(2012, 2, 20), date(2013, 2, 18), date(2014, 2, 17), date(2015,", "setUp(self): self.marketholidayss = marketholidays.USA(observed=False) self.markettradingdayss = markettradingdays.USA() def test_new_years(self): self.assertNotIn(date(2010, 12, 31), self.marketholidayss)", "self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertIn(dt, de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents' Day\")", "date(year, 12, 25) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss)", "date(year, 7, 4) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss)", "5, 31), date(2000, 5, 29), date(2012, 5, 28), date(2013, 5, 27), date(2014, 5,", "date(1969, 2, 22), date(1970, 2, 22), date(1971, 2, 15), date(1997, 2, 17), date(1999,", "state # specific sets of marketmarketholidayss on the fly. It aims to make", "nc_marketholidayss.observed = True def test_new_years_eve(self): ky_marketholidayss = marketholidays.US() self.assertNotIn(date(2012, 12, 31), ky_marketholidayss) for", "self.markettradingdayss.future_list(current_date, lookup_step)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.future_list(current_date, lookup_step)) def test_prevDays(self): current_date = '2021-04-13' lookback_step", "lookup_step = 10 self.assertIn(date(2021, 4, 16), self.markettradingdayss.future_list(current_date, lookup_step)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.future_list(current_date, lookup_step))", "5, 29), date(2012, 5, 28), date(2013, 5, 27), date(2014, 5, 26), date(2015, 5,", "date(year, 1, 1) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss)", "15), self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.BtwDates(current_date, future_date)) # if __name__ == \"__main__\":", "self.marketholidayss) self.assertIn(date(2020, 7, 3), self.marketholidayss) def test_labor_day(self): for dt in [ date(1997, 9,", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_martin_luther(self): for dt in [ date(1986, 1,", "5, 25), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss)", "in range(1900, 2050): self.assertNotIn(date(year, 12, 24), self.marketholidayss) # self.assertIn(date(year, 12, 24), as_marketholidayss) self.assertNotIn(date(2016,", "7, 3), self.marketholidayss) def test_labor_day(self): for dt in [ date(1997, 9, 1), date(1999,", "date(2013, 9, 2), date(2014, 9, 1), date(2015, 9, 7), date(2016, 9, 5), date(2020,", "dt in [ date(1997, 11, 27), date(1999, 11, 25), date(2000, 11, 23), date(2012,", "# Website: https://github.com/OmoMicheal/trading_days # License: MIT (see LICENSE file) # Version: 0.1 (April", "12, 28), nc_marketholidayss) self.assertNotIn(date(2016, 12, 27), nc_marketholidayss) nc_marketholidayss.observed = True def test_new_years_eve(self): ky_marketholidayss", "for dt in [ date(1997, 9, 1), date(1999, 9, 6), date(2000, 9, 4),", "test_new_years_eve(self): ky_marketholidayss = marketholidays.US() self.assertNotIn(date(2012, 12, 31), ky_marketholidayss) for dt in [date(2013, 12,", "def test_memorial_day(self): for dt in [ date(1969, 5, 30), date(1970, 5, 30), date(1971,", "def test_good_friday(self): marketholidayss_US = marketholidays.US() for dt in [ date(1900, 4, 13), date(1901,", "4), date(2012, 9, 3), date(2013, 9, 2), date(2014, 9, 1), date(2015, 9, 7),", "15), date(2020, 2, 17), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt +", "-*- coding: utf-8 -*- # marketanalysis # ---------------- # A fast, efficient Python", "9, 7), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss)", "self.marketholidayss) def test_christmas_eve(self): as_marketholidayss = marketholidays.US() self.marketholidayss.observed = False for year in range(1900,", "12, 24), self.marketholidayss) # self.assertIn(date(year, 12, 24), as_marketholidayss) self.assertNotIn(date(2016, 12, 23), as_marketholidayss) self.assertNotIn(", "marketanalysis import marketholidays from marketanalysis import markettradingdays class TestUS(unittest.TestCase): def setUp(self): self.marketholidayss =", "date(2016, 11, 24), date(2020, 11, 26), ]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss)", "+ relativedelta(days=+1), self.marketholidayss) def test_thanksgiving_day(self): for dt in [ date(1997, 11, 27), date(1999,", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 7, 5), self.marketholidayss)", "self.assertNotIn(date(2010, 12, 31), self.marketholidayss) self.assertNotIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12,", "22), date(1971, 2, 15), date(1997, 2, 17), date(1999, 2, 15), date(2000, 2, 21),", "# # Author: MichealOmojola <<EMAIL>> # Website: https://github.com/OmoMicheal/trading_days # License: MIT (see LICENSE", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertIn(dt, de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents' Day\") def test_good_friday(self): marketholidayss_US", "9, 3), date(2013, 9, 2), date(2014, 9, 1), date(2015, 9, 7), date(2016, 9,", "test_christmas_eve(self): as_marketholidayss = marketholidays.US() self.marketholidayss.observed = False for year in range(1900, 2050): self.assertNotIn(date(year,", "dt in [date(2013, 12, 31), date(2016, 12, 30)]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt, ky_marketholidayss) def", "in [date(2013, 12, 31), date(2016, 12, 30)]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt, ky_marketholidayss) def test_future_list(self):", "31), date(1997, 5, 26), date(1999, 5, 31), date(2000, 5, 29), date(2012, 5, 28),", "dt = date(year, 7, 4) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt +", "= marketholidays.USA(observed=False) self.markettradingdayss = markettradingdays.USA() def test_new_years(self): self.assertNotIn(date(2010, 12, 31), self.marketholidayss) self.assertNotIn(date(2017, 1,", "1, 2), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 31), self.marketholidayss) self.assertIn(date(2017, 1, 2),", "16), date(2013, 1, 21), date(2014, 1, 20), date(2015, 1, 19), date(2016, 1, 18),", "2050): self.assertNotIn(date(year, 12, 24), self.marketholidayss) # self.assertIn(date(year, 12, 24), as_marketholidayss) self.assertNotIn(date(2016, 12, 23),", "test_future_list(self): current_date = '2021-04-13' lookup_step = 10 self.assertIn(date(2021, 4, 16), self.markettradingdayss.future_list(current_date, lookup_step)) self.assertNotIn(date(2021,", "<reponame>OmoMicheal/marketanalysis<gh_stars>1-10 # -*- coding: utf-8 -*- # marketanalysis # ---------------- # A fast,", "5, 26), date(2015, 5, 25), date(2016, 5, 30), date(2020, 5, 25), ]: self.assertIn(dt,", "date(2016, 1, 18), date(2020, 1, 20), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss)", "fast, efficient Python library for generating country, province and state # specific sets", "date(1999, 2, 15), date(2000, 2, 21), date(2012, 2, 20), date(2013, 2, 18), date(2014,", "5, 30), date(2020, 5, 25), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt", "self.markettradingdayss.prevDays(current_date, lookback_step)) self.assertNotIn(date(2021, 4, 11), self.markettradingdayss.prevDays(current_date, lookback_step)) def test_BtwDates(self): current_date = '2021-04-13' future_date", "]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_christmas_eve(self):", "year in range(1900, 2100): dt = date(year, 1, 1) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt +", "2), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 31), self.marketholidayss) self.assertIn(date(2017, 1, 2), self.marketholidayss)", "# specific date is a holiday as fast and flexible as possible. #", "25), date(2000, 11, 23), date(2012, 11, 22), date(2013, 11, 28), date(2014, 11, 27),", "31), ky_marketholidayss) for dt in [date(2013, 12, 31), date(2016, 12, 30)]: self.assertNotIn(dt, self.marketholidayss)", "17), date(2015, 2, 16), date(2016, 2, 15), date(2020, 2, 17), ]: self.assertIn(dt, self.marketholidayss)", "def test_independence_day(self): for year in range(1900, 2100): dt = date(year, 7, 4) self.assertIn(dt,", "date(2000, 5, 29), date(2012, 5, 28), date(2013, 5, 27), date(2014, 5, 26), date(2015,", "11, 25), date(2000, 11, 23), date(2012, 11, 22), date(2013, 11, 28), date(2014, 11,", "as possible. # # Author: MichealOmojola <<EMAIL>> # Website: https://github.com/OmoMicheal/trading_days # License: MIT", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_thanksgiving_day(self): for dt in [ date(1997, 11,", "9, 5), date(2020, 9, 7), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt", "for dt in [ date(1900, 4, 13), date(1901, 4, 5), date(1902, 3, 28),", "test_thanksgiving_day(self): for dt in [ date(1997, 11, 27), date(1999, 11, 25), date(2000, 11,", "self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.BtwDates(current_date, future_date)) # if __name__ == \"__main__\": #", "file) # Version: 0.1 (April 7, 2021) import unittest from datetime import date", "def test_new_years(self): self.assertNotIn(date(2010, 12, 31), self.marketholidayss) self.assertNotIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = True", "make determining whether a # specific date is a holiday as fast and", "self.assertIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = False for year in range(1900, 2100): dt", "17), date(1999, 2, 15), date(2000, 2, 21), date(2012, 2, 20), date(2013, 2, 18),", "True self.assertIn(date(2010, 12, 24), self.marketholidayss) self.assertIn(date(2016, 12, 26), self.marketholidayss) def test_day_after_christmas(self): nc_marketholidayss =", "date(2020, 11, 26), ]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1),", "relativedelta(days=+1), self.marketholidayss) def test_independence_day(self): for year in range(1900, 2100): dt = date(year, 7,", "date(2000, 9, 4), date(2012, 9, 3), date(2013, 9, 2), date(2014, 9, 1), date(2015,", "9, 2), date(2014, 9, 1), date(2015, 9, 7), date(2016, 9, 5), date(2020, 9,", "5, 27), date(2014, 5, 26), date(2015, 5, 25), date(2016, 5, 30), date(2020, 5,", "self.assertNotIn(date(2016, 12, 26), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 24), self.marketholidayss) self.assertIn(date(2016, 12,", "self.assertNotIn(date(2015, 12, 28), nc_marketholidayss) self.assertNotIn(date(2016, 12, 27), nc_marketholidayss) nc_marketholidayss.observed = True def test_new_years_eve(self):", "markettradingdays.USA() def test_new_years(self): self.assertNotIn(date(2010, 12, 31), self.marketholidayss) self.assertNotIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed =", "]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_independence_day(self):", "28), date(2014, 11, 27), date(2015, 11, 26), date(2016, 11, 24), date(2020, 11, 26),", "1) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_martin_luther(self):", "24), self.marketholidayss) self.assertIn(date(2016, 12, 26), self.marketholidayss) def test_day_after_christmas(self): nc_marketholidayss = marketholidays.US(observed=False) self.assertNotIn(date(2015, 12,", "4, 13), date(1901, 4, 5), date(1902, 3, 28), date(1999, 4, 2), date(2000, 4,", "self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 12, 24), self.marketholidayss) self.assertNotIn(date(2016,", "test_memorial_day(self): for dt in [ date(1969, 5, 30), date(1970, 5, 30), date(1971, 5,", "self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_thanksgiving_day(self): for", "+ relativedelta(days=+1), self.marketholidayss) self.assertIn(dt, de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents' Day\") def test_good_friday(self): marketholidayss_US = marketholidays.US()", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_christmas_eve(self): as_marketholidayss = marketholidays.US() self.marketholidayss.observed = False", "10 self.assertIn(date(2021, 4, 16), self.markettradingdayss.future_list(current_date, lookup_step)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.future_list(current_date, lookup_step)) def test_prevDays(self):", "'2021-04-20' self.assertIn(date(2021, 4, 15), self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.BtwDates(current_date, future_date)) # if", "self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_washingtons_birthday(self): de_marketholidayss", "16), self.markettradingdayss.future_list(current_date, lookup_step)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.future_list(current_date, lookup_step)) def test_prevDays(self): current_date = '2021-04-13'", "Website: https://github.com/OmoMicheal/trading_days # License: MIT (see LICENSE file) # Version: 0.1 (April 7,", "1), date(2015, 9, 7), date(2016, 9, 5), date(2020, 9, 7), ]: self.assertIn(dt, self.marketholidayss)", "current_date = '2021-04-13' future_date = '2021-04-20' self.assertIn(date(2021, 4, 15), self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021, 4,", "self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_martin_luther(self): for dt in [ date(1986, 1, 20),", "LICENSE file) # Version: 0.1 (April 7, 2021) import unittest from datetime import", "26), date(1999, 5, 31), date(2000, 5, 29), date(2012, 5, 28), date(2013, 5, 27),", "self.marketholidayss) self.assertNotIn(date(2010, 7, 5), self.marketholidayss) self.assertNotIn(date(2020, 7, 3), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010,", "fast and flexible as possible. # # Author: MichealOmojola <<EMAIL>> # Website: https://github.com/OmoMicheal/trading_days", "]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_washingtons_birthday(self):", "date(2013, 2, 18), date(2014, 2, 17), date(2015, 2, 16), date(2016, 2, 15), date(2020,", "+ relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_independence_day(self): for year in range(1900,", "self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 7, 5),", "range(1900, 2100): dt = date(year, 12, 25) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss)", "1, 2), self.marketholidayss) self.marketholidayss.observed = False for year in range(1900, 2100): dt =", "2, 22), date(1970, 2, 22), date(1971, 2, 15), date(1997, 2, 17), date(1999, 2,", "21), date(2012, 2, 20), date(2013, 2, 18), date(2014, 2, 17), date(2015, 2, 16),", "(Observed)\", as_marketholidayss.get_list(date(2017, 12, 22)), ) def test_christmas_day(self): for year in range(1900, 2100): dt", "lookup_step)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.future_list(current_date, lookup_step)) def test_prevDays(self): current_date = '2021-04-13' lookback_step =", "date(2012, 9, 3), date(2013, 9, 2), date(2014, 9, 1), date(2015, 9, 7), date(2016,", "+ relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 12, 24), self.marketholidayss) self.assertNotIn(date(2016, 12,", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertIn(dt, de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents'", "Eve (Observed)\", as_marketholidayss.get_list(date(2017, 12, 22)), ) def test_christmas_day(self): for year in range(1900, 2100):", "on the fly. It aims to make determining whether a # specific date", "self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 12, 24),", "28), date(1999, 4, 2), date(2000, 4, 21), date(2010, 4, 2), date(2018, 3, 30),", "date(2016, 9, 5), date(2020, 9, 7), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss)", "= 4 self.assertIn(date(2021, 4, 9), self.markettradingdayss.prevDays(current_date, lookback_step)) self.assertNotIn(date(2021, 4, 11), self.markettradingdayss.prevDays(current_date, lookback_step)) def", "import relativedelta # import sys # sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from marketanalysis import marketholidays from", "5), self.marketholidayss) self.assertNotIn(date(2020, 7, 3), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 7, 5), self.marketholidayss)", "as_marketholidayss = marketholidays.US() self.marketholidayss.observed = False for year in range(1900, 2050): self.assertNotIn(date(year, 12,", "date(1969, 5, 30), date(1970, 5, 30), date(1971, 5, 31), date(1997, 5, 26), date(1999,", "date(1999, 5, 31), date(2000, 5, 29), date(2012, 5, 28), date(2013, 5, 27), date(2014,", "date(2016, 5, 30), date(2020, 5, 25), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss)", "self.marketholidayss) def test_day_after_christmas(self): nc_marketholidayss = marketholidays.US(observed=False) self.assertNotIn(date(2015, 12, 28), nc_marketholidayss) self.assertNotIn(date(2016, 12, 27),", "date(2014, 1, 20), date(2015, 1, 19), date(2016, 1, 18), date(2020, 1, 20), ]:", "from marketanalysis import marketholidays from marketanalysis import markettradingdays class TestUS(unittest.TestCase): def setUp(self): self.marketholidayss", "self.assertIn(date(2010, 7, 5), self.marketholidayss) self.assertIn(date(2020, 7, 3), self.marketholidayss) def test_labor_day(self): for dt in", "3, 28), date(1999, 4, 2), date(2000, 4, 21), date(2010, 4, 2), date(2018, 3,", "31), self.marketholidayss) self.assertNotIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 31), self.marketholidayss)", "= False for year in range(1900, 2100): dt = date(year, 1, 1) self.assertIn(dt,", "of marketmarketholidayss on the fly. It aims to make determining whether a #", "def test_thanksgiving_day(self): for dt in [ date(1997, 11, 27), date(1999, 11, 25), date(2000,", "and state # specific sets of marketmarketholidayss on the fly. It aims to", "self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_independence_day(self): for year in", "# import sys # sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from marketanalysis import marketholidays from marketanalysis import", "4, 21), date(2010, 4, 2), date(2018, 3, 30), date(2019, 4, 19), date(2020, 4,", "23), as_marketholidayss) self.assertNotIn( \"Christmas Eve (Observed)\", as_marketholidayss.get_list(date(2017, 12, 22)), ) def test_christmas_day(self): for", "7, 4) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010,", "25), date(2016, 5, 30), date(2020, 5, 25), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1),", "for dt in [date(2013, 12, 31), date(2016, 12, 30)]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt, ky_marketholidayss)", "31), date(2000, 5, 29), date(2012, 5, 28), date(2013, 5, 27), date(2014, 5, 26),", "dt in [ date(1986, 1, 20), date(1999, 1, 18), date(2000, 1, 17), date(2012,", "self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_martin_luther(self): for", "4, 19), date(2020, 4, 10), ]: self.assertIn(dt, self.marketholidayss) self.assertIn(dt, marketholidayss_US) def test_memorial_day(self): for", "for dt in [ date(1969, 5, 30), date(1970, 5, 30), date(1971, 5, 31),", "(see LICENSE file) # Version: 0.1 (April 7, 2021) import unittest from datetime", "# specific sets of marketmarketholidayss on the fly. It aims to make determining", "= date(year, 7, 4) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1),", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_washingtons_birthday(self): de_marketholidayss = marketholidays.US() for dt in", "date(1971, 2, 15), date(1997, 2, 17), date(1999, 2, 15), date(2000, 2, 21), date(2012,", "1, 21), date(2014, 1, 20), date(2015, 1, 19), date(2016, 1, 18), date(2020, 1,", "relativedelta(days=+1), self.marketholidayss) self.assertIn(dt, de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents' Day\") def test_good_friday(self): marketholidayss_US = marketholidays.US() for", "2), date(2018, 3, 30), date(2019, 4, 19), date(2020, 4, 10), ]: self.assertIn(dt, self.marketholidayss)", "self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_martin_luther(self): for dt in", "12, 24), as_marketholidayss) self.assertNotIn(date(2016, 12, 23), as_marketholidayss) self.assertNotIn( \"Christmas Eve (Observed)\", as_marketholidayss.get_list(date(2017, 12,", "self.marketholidayss) self.assertIn(dt, marketholidayss_US) def test_memorial_day(self): for dt in [ date(1969, 5, 30), date(1970,", "date(2000, 4, 21), date(2010, 4, 2), date(2018, 3, 30), date(2019, 4, 19), date(2020,", "self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_independence_day(self): for", "country, province and state # specific sets of marketmarketholidayss on the fly. It", "# ---------------- # A fast, efficient Python library for generating country, province and", "def setUp(self): self.marketholidayss = marketholidays.USA(observed=False) self.markettradingdayss = markettradingdays.USA() def test_new_years(self): self.assertNotIn(date(2010, 12, 31),", "30), date(2019, 4, 19), date(2020, 4, 10), ]: self.assertIn(dt, self.marketholidayss) self.assertIn(dt, marketholidayss_US) def", "= '2021-04-13' future_date = '2021-04-20' self.assertIn(date(2021, 4, 15), self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021, 4, 18),", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_thanksgiving_day(self): for dt", "def test_BtwDates(self): current_date = '2021-04-13' future_date = '2021-04-20' self.assertIn(date(2021, 4, 15), self.markettradingdayss.BtwDates(current_date, future_date))", "= marketholidays.US() self.marketholidayss.observed = False for year in range(1900, 2050): self.assertNotIn(date(year, 12, 24),", "nc_marketholidayss) self.assertNotIn(date(2016, 12, 27), nc_marketholidayss) nc_marketholidayss.observed = True def test_new_years_eve(self): ky_marketholidayss = marketholidays.US()", "30), date(1970, 5, 30), date(1971, 5, 31), date(1997, 5, 26), date(1999, 5, 31),", "year in range(1900, 2100): dt = date(year, 7, 4) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt +", "31), self.marketholidayss) self.assertIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = False for year in range(1900,", "self.assertIn(dt, de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents' Day\") def test_good_friday(self): marketholidayss_US = marketholidays.US() for dt in", "1, 18), date(2000, 1, 17), date(2012, 1, 16), date(2013, 1, 21), date(2014, 1,", "self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents' Day\") def test_good_friday(self): marketholidayss_US = marketholidays.US() for dt in [ date(1900,", "= 10 self.assertIn(date(2021, 4, 16), self.markettradingdayss.future_list(current_date, lookup_step)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.future_list(current_date, lookup_step)) def", "def test_day_after_christmas(self): nc_marketholidayss = marketholidays.US(observed=False) self.assertNotIn(date(2015, 12, 28), nc_marketholidayss) self.assertNotIn(date(2016, 12, 27), nc_marketholidayss)", "self.assertIn(date(2020, 7, 3), self.marketholidayss) def test_labor_day(self): for dt in [ date(1997, 9, 1),", "date(1999, 11, 25), date(2000, 11, 23), date(2012, 11, 22), date(2013, 11, 28), date(2014,", "specific date is a holiday as fast and flexible as possible. # #", "1, 20), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss)", "date(2016, 12, 30)]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt, ky_marketholidayss) def test_future_list(self): current_date = '2021-04-13' lookup_step", "'2021-04-13' lookback_step = 4 self.assertIn(date(2021, 4, 9), self.markettradingdayss.prevDays(current_date, lookback_step)) self.assertNotIn(date(2021, 4, 11), self.markettradingdayss.prevDays(current_date,", "4, 9), self.markettradingdayss.prevDays(current_date, lookback_step)) self.assertNotIn(date(2021, 4, 11), self.markettradingdayss.prevDays(current_date, lookback_step)) def test_BtwDates(self): current_date =", "= '2021-04-13' lookup_step = 10 self.assertIn(date(2021, 4, 16), self.markettradingdayss.future_list(current_date, lookup_step)) self.assertNotIn(date(2021, 4, 18),", "19), date(2020, 4, 10), ]: self.assertIn(dt, self.marketholidayss) self.assertIn(dt, marketholidayss_US) def test_memorial_day(self): for dt", "3), date(2013, 9, 2), date(2014, 9, 1), date(2015, 9, 7), date(2016, 9, 5),", "de_marketholidayss = marketholidays.US() for dt in [ date(1969, 2, 22), date(1970, 2, 22),", "MIT (see LICENSE file) # Version: 0.1 (April 7, 2021) import unittest from", "as_marketholidayss.get_list(date(2017, 12, 22)), ) def test_christmas_day(self): for year in range(1900, 2100): dt =", "7, 3), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 7, 5), self.marketholidayss) self.assertIn(date(2020, 7, 3),", "[ date(1969, 5, 30), date(1970, 5, 30), date(1971, 5, 31), date(1997, 5, 26),", "self.marketholidayss.observed = False for year in range(1900, 2100): dt = date(year, 1, 1)", "21), date(2014, 1, 20), date(2015, 1, 19), date(2016, 1, 18), date(2020, 1, 20),", "'2021-04-13' lookup_step = 10 self.assertIn(date(2021, 4, 16), self.markettradingdayss.future_list(current_date, lookup_step)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.future_list(current_date,", "self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_washingtons_birthday(self): de_marketholidayss = marketholidays.US()", "2100): dt = date(year, 12, 25) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt", "17), date(2012, 1, 16), date(2013, 1, 21), date(2014, 1, 20), date(2015, 1, 19),", "20), date(2013, 2, 18), date(2014, 2, 17), date(2015, 2, 16), date(2016, 2, 15),", "relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 12, 24), self.marketholidayss) self.assertNotIn(date(2016, 12, 26),", "self.marketholidayss.observed = False for year in range(1900, 2050): self.assertNotIn(date(year, 12, 24), self.marketholidayss) #", "aims to make determining whether a # specific date is a holiday as", "12, 31), self.marketholidayss) self.assertNotIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 31),", "26), date(2015, 5, 25), date(2016, 5, 30), date(2020, 5, 25), ]: self.assertIn(dt, self.marketholidayss)", "in range(1900, 2100): dt = date(year, 7, 4) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1),", "11, 26), date(2016, 11, 24), date(2020, 11, 26), ]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt +", "12, 26), self.marketholidayss) def test_day_after_christmas(self): nc_marketholidayss = marketholidays.US(observed=False) self.assertNotIn(date(2015, 12, 28), nc_marketholidayss) self.assertNotIn(date(2016,", "10), ]: self.assertIn(dt, self.marketholidayss) self.assertIn(dt, marketholidayss_US) def test_memorial_day(self): for dt in [ date(1969,", "self.assertNotIn(date(2016, 12, 23), as_marketholidayss) self.assertNotIn( \"Christmas Eve (Observed)\", as_marketholidayss.get_list(date(2017, 12, 22)), ) def", "2, 15), date(2020, 2, 17), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt", "= marketholidays.US() self.assertNotIn(date(2012, 12, 31), ky_marketholidayss) for dt in [date(2013, 12, 31), date(2016,", "date(1900, 4, 13), date(1901, 4, 5), date(1902, 3, 28), date(1999, 4, 2), date(2000,", "27), date(1999, 11, 25), date(2000, 11, 23), date(2012, 11, 22), date(2013, 11, 28),", "2100): dt = date(year, 1, 1) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt", "date(2013, 5, 27), date(2014, 5, 26), date(2015, 5, 25), date(2016, 5, 30), date(2020,", "# -*- coding: utf-8 -*- # marketanalysis # ---------------- # A fast, efficient", "5, 30), date(1971, 5, 31), date(1997, 5, 26), date(1999, 5, 31), date(2000, 5,", "generating country, province and state # specific sets of marketmarketholidayss on the fly.", "date(1999, 9, 6), date(2000, 9, 4), date(2012, 9, 3), date(2013, 9, 2), date(2014,", "date(2015, 9, 7), date(2016, 9, 5), date(2020, 9, 7), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt", "18), date(2020, 1, 20), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt +", "7), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def", "import sys # sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from marketanalysis import marketholidays from marketanalysis import markettradingdays", "\"Presidents' Day\") def test_good_friday(self): marketholidayss_US = marketholidays.US() for dt in [ date(1900, 4,", "18), date(2014, 2, 17), date(2015, 2, 16), date(2016, 2, 15), date(2020, 2, 17),", "12, 26), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 24), self.marketholidayss) self.assertIn(date(2016, 12, 26),", "utf-8 -*- # marketanalysis # ---------------- # A fast, efficient Python library for", "20), date(2015, 1, 19), date(2016, 1, 18), date(2020, 1, 20), ]: self.assertIn(dt, self.marketholidayss)", "self.marketholidayss.observed = True self.assertIn(date(2010, 12, 24), self.marketholidayss) self.assertIn(date(2016, 12, 26), self.marketholidayss) def test_day_after_christmas(self):", "date(1971, 5, 31), date(1997, 5, 26), date(1999, 5, 31), date(2000, 5, 29), date(2012,", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_independence_day(self): for year", "self.markettradingdayss.future_list(current_date, lookup_step)) def test_prevDays(self): current_date = '2021-04-13' lookback_step = 4 self.assertIn(date(2021, 4, 9),", "2, 20), date(2013, 2, 18), date(2014, 2, 17), date(2015, 2, 16), date(2016, 2,", "date(2014, 9, 1), date(2015, 9, 7), date(2016, 9, 5), date(2020, 9, 7), ]:", "18), date(2000, 1, 17), date(2012, 1, 16), date(2013, 1, 21), date(2014, 1, 20),", "test_new_years(self): self.assertNotIn(date(2010, 12, 31), self.marketholidayss) self.assertNotIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010,", "self.marketholidayss) def test_independence_day(self): for year in range(1900, 2100): dt = date(year, 7, 4)", "relativedelta(days=+1), self.marketholidayss) def test_washingtons_birthday(self): de_marketholidayss = marketholidays.US() for dt in [ date(1969, 2,", "markettradingdays class TestUS(unittest.TestCase): def setUp(self): self.marketholidayss = marketholidays.USA(observed=False) self.markettradingdayss = markettradingdays.USA() def test_new_years(self):", "+ relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_washingtons_birthday(self): de_marketholidayss = marketholidays.US() for", "1, 19), date(2016, 1, 18), date(2020, 1, 20), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt +", "test_BtwDates(self): current_date = '2021-04-13' future_date = '2021-04-20' self.assertIn(date(2021, 4, 15), self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021,", "specific sets of marketmarketholidayss on the fly. It aims to make determining whether", "2, 21), date(2012, 2, 20), date(2013, 2, 18), date(2014, 2, 17), date(2015, 2,", "date(2014, 2, 17), date(2015, 2, 16), date(2016, 2, 15), date(2020, 2, 17), ]:", "date(2012, 11, 22), date(2013, 11, 28), date(2014, 11, 27), date(2015, 11, 26), date(2016,", "relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertIn(dt, de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents' Day\") def test_good_friday(self):", "24), self.marketholidayss) # self.assertIn(date(year, 12, 24), as_marketholidayss) self.assertNotIn(date(2016, 12, 23), as_marketholidayss) self.assertNotIn( \"Christmas", "11, 27), date(2015, 11, 26), date(2016, 11, 24), date(2020, 11, 26), ]: self.assertNotIn(dt,", "MichealOmojola <<EMAIL>> # Website: https://github.com/OmoMicheal/trading_days # License: MIT (see LICENSE file) # Version:", "date(2020, 1, 20), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1),", "test_good_friday(self): marketholidayss_US = marketholidays.US() for dt in [ date(1900, 4, 13), date(1901, 4,", "marketholidays.US() self.marketholidayss.observed = False for year in range(1900, 2050): self.assertNotIn(date(year, 12, 24), self.marketholidayss)", "2), date(2000, 4, 21), date(2010, 4, 2), date(2018, 3, 30), date(2019, 4, 19),", "dt in [ date(1969, 2, 22), date(1970, 2, 22), date(1971, 2, 15), date(1997,", "from datetime import date from dateutil.relativedelta import relativedelta # import sys # sys.path.insert(0,", "self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_thanksgiving_day(self): for dt in", "for year in range(1900, 2050): self.assertNotIn(date(year, 12, 24), self.marketholidayss) # self.assertIn(date(year, 12, 24),", "self.assertNotIn(date(2010, 12, 24), self.marketholidayss) self.assertNotIn(date(2016, 12, 26), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12,", "22), date(1970, 2, 22), date(1971, 2, 15), date(1997, 2, 17), date(1999, 2, 15),", "27), nc_marketholidayss) nc_marketholidayss.observed = True def test_new_years_eve(self): ky_marketholidayss = marketholidays.US() self.assertNotIn(date(2012, 12, 31),", "test_martin_luther(self): for dt in [ date(1986, 1, 20), date(1999, 1, 18), date(2000, 1,", "26), self.marketholidayss) def test_day_after_christmas(self): nc_marketholidayss = marketholidays.US(observed=False) self.assertNotIn(date(2015, 12, 28), nc_marketholidayss) self.assertNotIn(date(2016, 12,", "to make determining whether a # specific date is a holiday as fast", "is a holiday as fast and flexible as possible. # # Author: MichealOmojola", "25) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 12,", "self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_thanksgiving_day(self): for dt in [ date(1997, 11, 27),", "1, 18), date(2020, 1, 20), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt", "True self.assertIn(date(2010, 7, 5), self.marketholidayss) self.assertIn(date(2020, 7, 3), self.marketholidayss) def test_labor_day(self): for dt", "9, 1), date(2015, 9, 7), date(2016, 9, 5), date(2020, 9, 7), ]: self.assertIn(dt,", "date(2012, 1, 16), date(2013, 1, 21), date(2014, 1, 20), date(2015, 1, 19), date(2016,", "def test_future_list(self): current_date = '2021-04-13' lookup_step = 10 self.assertIn(date(2021, 4, 16), self.markettradingdayss.future_list(current_date, lookup_step))", "marketmarketholidayss on the fly. It aims to make determining whether a # specific", "self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 31), self.marketholidayss) self.assertIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed", "7, 5), self.marketholidayss) self.assertIn(date(2020, 7, 3), self.marketholidayss) def test_labor_day(self): for dt in [", "+ relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 12, 24), self.marketholidayss) self.assertNotIn(date(2016, 12, 26), self.marketholidayss) self.marketholidayss.observed =", "5), date(2020, 9, 7), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt +", "self.marketholidayss) def test_washingtons_birthday(self): de_marketholidayss = marketholidays.US() for dt in [ date(1969, 2, 22),", "date(2020, 5, 25), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1),", "dt in [ date(1900, 4, 13), date(1901, 4, 5), date(1902, 3, 28), date(1999,", "marketholidays.US(observed=False) self.assertNotIn(date(2015, 12, 28), nc_marketholidayss) self.assertNotIn(date(2016, 12, 27), nc_marketholidayss) nc_marketholidayss.observed = True def", "4, 11), self.markettradingdayss.prevDays(current_date, lookback_step)) def test_BtwDates(self): current_date = '2021-04-13' future_date = '2021-04-20' self.assertIn(date(2021,", "date(1901, 4, 5), date(1902, 3, 28), date(1999, 4, 2), date(2000, 4, 21), date(2010,", "9, 1), date(1999, 9, 6), date(2000, 9, 4), date(2012, 9, 3), date(2013, 9,", "self.assertIn(date(2021, 4, 16), self.markettradingdayss.future_list(current_date, lookup_step)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.future_list(current_date, lookup_step)) def test_prevDays(self): current_date", "4, 2), date(2018, 3, 30), date(2019, 4, 19), date(2020, 4, 10), ]: self.assertIn(dt,", "'2021-04-13' future_date = '2021-04-20' self.assertIn(date(2021, 4, 15), self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.BtwDates(current_date,", "5, 30), date(1970, 5, 30), date(1971, 5, 31), date(1997, 5, 26), date(1999, 5,", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_washingtons_birthday(self): de_marketholidayss =", "28), date(2013, 5, 27), date(2014, 5, 26), date(2015, 5, 25), date(2016, 5, 30),", "self.marketholidayss) def test_thanksgiving_day(self): for dt in [ date(1997, 11, 27), date(1999, 11, 25),", "# self.assertIn(date(year, 12, 24), as_marketholidayss) self.assertNotIn(date(2016, 12, 23), as_marketholidayss) self.assertNotIn( \"Christmas Eve (Observed)\",", "3), self.marketholidayss) def test_labor_day(self): for dt in [ date(1997, 9, 1), date(1999, 9,", "lookback_step = 4 self.assertIn(date(2021, 4, 9), self.markettradingdayss.prevDays(current_date, lookback_step)) self.assertNotIn(date(2021, 4, 11), self.markettradingdayss.prevDays(current_date, lookback_step))", "= date(year, 12, 25) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1),", "date(2000, 1, 17), date(2012, 1, 16), date(2013, 1, 21), date(2014, 1, 20), date(2015,", "relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 12, 24), self.marketholidayss) self.assertNotIn(date(2016, 12, 26), self.marketholidayss) self.marketholidayss.observed = True", "self.assertIn(dt, marketholidayss_US) def test_memorial_day(self): for dt in [ date(1969, 5, 30), date(1970, 5,", "= '2021-04-13' lookback_step = 4 self.assertIn(date(2021, 4, 9), self.markettradingdayss.prevDays(current_date, lookback_step)) self.assertNotIn(date(2021, 4, 11),", "self.marketholidayss) self.assertIn(date(2016, 12, 26), self.marketholidayss) def test_day_after_christmas(self): nc_marketholidayss = marketholidays.US(observed=False) self.assertNotIn(date(2015, 12, 28),", "dt = date(year, 1, 1) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt +", "9, 4), date(2012, 9, 3), date(2013, 9, 2), date(2014, 9, 1), date(2015, 9,", "in [ date(1997, 11, 27), date(1999, 11, 25), date(2000, 11, 23), date(2012, 11,", "15), date(1997, 2, 17), date(1999, 2, 15), date(2000, 2, 21), date(2012, 2, 20),", "year in range(1900, 2050): self.assertNotIn(date(year, 12, 24), self.marketholidayss) # self.assertIn(date(year, 12, 24), as_marketholidayss)", "in range(1900, 2100): dt = date(year, 1, 1) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1),", "24), self.marketholidayss) self.assertNotIn(date(2016, 12, 26), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 24), self.marketholidayss)", "future_date)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.BtwDates(current_date, future_date)) # if __name__ == \"__main__\": # unittest.main()", "2021) import unittest from datetime import date from dateutil.relativedelta import relativedelta # import", "from dateutil.relativedelta import relativedelta # import sys # sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from marketanalysis import", "current_date = '2021-04-13' lookback_step = 4 self.assertIn(date(2021, 4, 9), self.markettradingdayss.prevDays(current_date, lookback_step)) self.assertNotIn(date(2021, 4,", "current_date = '2021-04-13' lookup_step = 10 self.assertIn(date(2021, 4, 16), self.markettradingdayss.future_list(current_date, lookup_step)) self.assertNotIn(date(2021, 4,", "self.marketholidayss.observed = True self.assertIn(date(2010, 7, 5), self.marketholidayss) self.assertIn(date(2020, 7, 3), self.marketholidayss) def test_labor_day(self):", "12, 31), self.marketholidayss) self.assertIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = False for year in", "for dt in [ date(1997, 11, 27), date(1999, 11, 25), date(2000, 11, 23),", "26), date(2016, 11, 24), date(2020, 11, 26), ]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1),", "12, 31), date(2016, 12, 30)]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt, ky_marketholidayss) def test_future_list(self): current_date =", "self.marketholidayss) self.assertIn(dt, de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents' Day\") def test_good_friday(self): marketholidayss_US = marketholidays.US() for dt", "self.assertNotIn(dt, ky_marketholidayss) def test_future_list(self): current_date = '2021-04-13' lookup_step = 10 self.assertIn(date(2021, 4, 16),", "date(2000, 11, 23), date(2012, 11, 22), date(2013, 11, 28), date(2014, 11, 27), date(2015,", "4, 2), date(2000, 4, 21), date(2010, 4, 2), date(2018, 3, 30), date(2019, 4,", "possible. # # Author: MichealOmojola <<EMAIL>> # Website: https://github.com/OmoMicheal/trading_days # License: MIT (see", "self.marketholidayss) self.assertIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = False for year in range(1900, 2100):", "5, 25), date(2016, 5, 30), date(2020, 5, 25), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt +", "23), date(2012, 11, 22), date(2013, 11, 28), date(2014, 11, 27), date(2015, 11, 26),", ") def test_christmas_day(self): for year in range(1900, 2100): dt = date(year, 12, 25)", "= marketholidays.US() for dt in [ date(1900, 4, 13), date(1901, 4, 5), date(1902,", "self.assertIn(date(year, 12, 24), as_marketholidayss) self.assertNotIn(date(2016, 12, 23), as_marketholidayss) self.assertNotIn( \"Christmas Eve (Observed)\", as_marketholidayss.get_list(date(2017,", "self.marketholidayss) self.assertNotIn(dt, ky_marketholidayss) def test_future_list(self): current_date = '2021-04-13' lookup_step = 10 self.assertIn(date(2021, 4,", "sets of marketmarketholidayss on the fly. It aims to make determining whether a", "27), date(2015, 11, 26), date(2016, 11, 24), date(2020, 11, 26), ]: self.assertNotIn(dt, self.marketholidayss)", "+ relativedelta(days=+1), self.marketholidayss) def test_washingtons_birthday(self): de_marketholidayss = marketholidays.US() for dt in [ date(1969,", "date(2016, 2, 15), date(2020, 2, 17), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss)", "5, 26), date(1999, 5, 31), date(2000, 5, 29), date(2012, 5, 28), date(2013, 5,", "+ relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_christmas_eve(self): as_marketholidayss = marketholidays.US() self.marketholidayss.observed", "self.marketholidayss = marketholidays.USA(observed=False) self.markettradingdayss = markettradingdays.USA() def test_new_years(self): self.assertNotIn(date(2010, 12, 31), self.marketholidayss) self.assertNotIn(date(2017,", "in [ date(1969, 5, 30), date(1970, 5, 30), date(1971, 5, 31), date(1997, 5,", "for year in range(1900, 2100): dt = date(year, 1, 1) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt", "future_date = '2021-04-20' self.assertIn(date(2021, 4, 15), self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.BtwDates(current_date, future_date))", "4, 5), date(1902, 3, 28), date(1999, 4, 2), date(2000, 4, 21), date(2010, 4,", "self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_washingtons_birthday(self): de_marketholidayss = marketholidays.US() for dt in [", "9), self.markettradingdayss.prevDays(current_date, lookback_step)) self.assertNotIn(date(2021, 4, 11), self.markettradingdayss.prevDays(current_date, lookback_step)) def test_BtwDates(self): current_date = '2021-04-13'", "self.marketholidayss) self.assertNotIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 31), self.marketholidayss) self.assertIn(date(2017,", "13), date(1901, 4, 5), date(1902, 3, 28), date(1999, 4, 2), date(2000, 4, 21),", "marketholidayss_US = marketholidays.US() for dt in [ date(1900, 4, 13), date(1901, 4, 5),", "11, 27), date(1999, 11, 25), date(2000, 11, 23), date(2012, 11, 22), date(2013, 11,", "flexible as possible. # # Author: MichealOmojola <<EMAIL>> # Website: https://github.com/OmoMicheal/trading_days # License:", "efficient Python library for generating country, province and state # specific sets of", "2, 18), date(2014, 2, 17), date(2015, 2, 16), date(2016, 2, 15), date(2020, 2,", "+ relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertIn(dt, de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents' Day\") def", "TestUS(unittest.TestCase): def setUp(self): self.marketholidayss = marketholidays.USA(observed=False) self.markettradingdayss = markettradingdays.USA() def test_new_years(self): self.assertNotIn(date(2010, 12,", "3, 30), date(2019, 4, 19), date(2020, 4, 10), ]: self.assertIn(dt, self.marketholidayss) self.assertIn(dt, marketholidayss_US)", "date(1997, 11, 27), date(1999, 11, 25), date(2000, 11, 23), date(2012, 11, 22), date(2013,", "range(1900, 2100): dt = date(year, 7, 4) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss)", "22)), ) def test_christmas_day(self): for year in range(1900, 2100): dt = date(year, 12,", "for year in range(1900, 2100): dt = date(year, 12, 25) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt", "True self.assertIn(date(2010, 12, 31), self.marketholidayss) self.assertIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = False for", "self.assertNotIn(date(2020, 7, 3), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 7, 5), self.marketholidayss) self.assertIn(date(2020, 7,", "date(2020, 9, 7), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1),", "self.marketholidayss) self.marketholidayss.observed = False for year in range(1900, 2100): dt = date(year, 1,", "fly. It aims to make determining whether a # specific date is a", "-*- # marketanalysis # ---------------- # A fast, efficient Python library for generating", "as fast and flexible as possible. # # Author: MichealOmojola <<EMAIL>> # Website:", "[date(2013, 12, 31), date(2016, 12, 30)]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt, ky_marketholidayss) def test_future_list(self): current_date", "from marketanalysis import markettradingdays class TestUS(unittest.TestCase): def setUp(self): self.marketholidayss = marketholidays.USA(observed=False) self.markettradingdayss =", "[ date(1997, 9, 1), date(1999, 9, 6), date(2000, 9, 4), date(2012, 9, 3),", "range(1900, 2050): self.assertNotIn(date(year, 12, 24), self.marketholidayss) # self.assertIn(date(year, 12, 24), as_marketholidayss) self.assertNotIn(date(2016, 12,", "self.assertNotIn(date(2016, 12, 27), nc_marketholidayss) nc_marketholidayss.observed = True def test_new_years_eve(self): ky_marketholidayss = marketholidays.US() self.assertNotIn(date(2012,", "= True def test_new_years_eve(self): ky_marketholidayss = marketholidays.US() self.assertNotIn(date(2012, 12, 31), ky_marketholidayss) for dt", "self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_christmas_eve(self): as_marketholidayss = marketholidays.US()", "6), date(2000, 9, 4), date(2012, 9, 3), date(2013, 9, 2), date(2014, 9, 1),", "ky_marketholidayss = marketholidays.US() self.assertNotIn(date(2012, 12, 31), ky_marketholidayss) for dt in [date(2013, 12, 31),", "# License: MIT (see LICENSE file) # Version: 0.1 (April 7, 2021) import", "dt in [ date(1969, 5, 30), date(1970, 5, 30), date(1971, 5, 31), date(1997,", "24), date(2020, 11, 26), ]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt +", "---------------- # A fast, efficient Python library for generating country, province and state", "lookup_step)) def test_prevDays(self): current_date = '2021-04-13' lookback_step = 4 self.assertIn(date(2021, 4, 9), self.markettradingdayss.prevDays(current_date,", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 12, 24), self.marketholidayss) self.assertNotIn(date(2016, 12, 26), self.marketholidayss)", "for dt in [ date(1986, 1, 20), date(1999, 1, 18), date(2000, 1, 17),", "]: self.assertIn(dt, self.marketholidayss) self.assertIn(dt, marketholidayss_US) def test_memorial_day(self): for dt in [ date(1969, 5,", "4, 16), self.markettradingdayss.future_list(current_date, lookup_step)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.future_list(current_date, lookup_step)) def test_prevDays(self): current_date =", "+ relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 7, 5), self.marketholidayss) self.assertNotIn(date(2020, 7, 3), self.marketholidayss) self.marketholidayss.observed =", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_martin_luther(self): for dt", "False for year in range(1900, 2100): dt = date(year, 1, 1) self.assertIn(dt, self.marketholidayss)", "for dt in [ date(1969, 2, 22), date(1970, 2, 22), date(1971, 2, 15),", "+ relativedelta(days=+1), self.marketholidayss) def test_independence_day(self): for year in range(1900, 2100): dt = date(year,", "date(2020, 4, 10), ]: self.assertIn(dt, self.marketholidayss) self.assertIn(dt, marketholidayss_US) def test_memorial_day(self): for dt in", "11, 28), date(2014, 11, 27), date(2015, 11, 26), date(2016, 11, 24), date(2020, 11,", "12, 31), ky_marketholidayss) for dt in [date(2013, 12, 31), date(2016, 12, 30)]: self.assertNotIn(dt,", "[ date(1986, 1, 20), date(1999, 1, 18), date(2000, 1, 17), date(2012, 1, 16),", "in [ date(1969, 2, 22), date(1970, 2, 22), date(1971, 2, 15), date(1997, 2,", "30), date(1971, 5, 31), date(1997, 5, 26), date(1999, 5, 31), date(2000, 5, 29),", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_christmas_eve(self): as_marketholidayss =", "in [ date(1986, 1, 20), date(1999, 1, 18), date(2000, 1, 17), date(2012, 1,", "self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_christmas_eve(self): as_marketholidayss", "11, 26), ]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss)", "28), nc_marketholidayss) self.assertNotIn(date(2016, 12, 27), nc_marketholidayss) nc_marketholidayss.observed = True def test_new_years_eve(self): ky_marketholidayss =", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 7, 5), self.marketholidayss) self.assertNotIn(date(2020, 7, 3), self.marketholidayss)", "7), date(2016, 9, 5), date(2020, 9, 7), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1),", "11, 22), date(2013, 11, 28), date(2014, 11, 27), date(2015, 11, 26), date(2016, 11,", "]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertIn(dt, de_marketholidayss)", "25), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def", "= date(year, 1, 1) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1),", "date(1997, 2, 17), date(1999, 2, 15), date(2000, 2, 21), date(2012, 2, 20), date(2013,", "self.marketholidayss) def test_labor_day(self): for dt in [ date(1997, 9, 1), date(1999, 9, 6),", "a holiday as fast and flexible as possible. # # Author: MichealOmojola <<EMAIL>>", "date(2014, 5, 26), date(2015, 5, 25), date(2016, 5, 30), date(2020, 5, 25), ]:", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 12, 24), self.marketholidayss)", "date(2019, 4, 19), date(2020, 4, 10), ]: self.assertIn(dt, self.marketholidayss) self.assertIn(dt, marketholidayss_US) def test_memorial_day(self):", "30)]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt, ky_marketholidayss) def test_future_list(self): current_date = '2021-04-13' lookup_step = 10", "library for generating country, province and state # specific sets of marketmarketholidayss on", "[ date(1900, 4, 13), date(1901, 4, 5), date(1902, 3, 28), date(1999, 4, 2),", "self.assertIn(dt, self.marketholidayss) self.assertIn(dt, marketholidayss_US) def test_memorial_day(self): for dt in [ date(1969, 5, 30),", "= False for year in range(1900, 2050): self.assertNotIn(date(year, 12, 24), self.marketholidayss) # self.assertIn(date(year,", "self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertIn(dt, de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents' Day\") def test_good_friday(self): marketholidayss_US =", "date(2018, 3, 30), date(2019, 4, 19), date(2020, 4, 10), ]: self.assertIn(dt, self.marketholidayss) self.assertIn(dt,", "self.assertIn(date(2021, 4, 15), self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.BtwDates(current_date, future_date)) # if __name__", "sys # sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from marketanalysis import marketholidays from marketanalysis import markettradingdays class", "ky_marketholidayss) for dt in [date(2013, 12, 31), date(2016, 12, 30)]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt,", "relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 7, 5), self.marketholidayss) self.assertNotIn(date(2020, 7, 3),", "def test_labor_day(self): for dt in [ date(1997, 9, 1), date(1999, 9, 6), date(2000,", "1, 1) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def", "date(2012, 5, 28), date(2013, 5, 27), date(2014, 5, 26), date(2015, 5, 25), date(2016,", "self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 12, 24), self.marketholidayss) self.assertNotIn(date(2016, 12, 26), self.marketholidayss) self.marketholidayss.observed", "9, 7), date(2016, 9, 5), date(2020, 9, 7), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt +", "def test_prevDays(self): current_date = '2021-04-13' lookback_step = 4 self.assertIn(date(2021, 4, 9), self.markettradingdayss.prevDays(current_date, lookback_step))", "test_independence_day(self): for year in range(1900, 2100): dt = date(year, 7, 4) self.assertIn(dt, self.marketholidayss)", "marketholidays from marketanalysis import markettradingdays class TestUS(unittest.TestCase): def setUp(self): self.marketholidayss = marketholidays.USA(observed=False) self.markettradingdayss", "test_christmas_day(self): for year in range(1900, 2100): dt = date(year, 12, 25) self.assertIn(dt, self.marketholidayss)", "License: MIT (see LICENSE file) # Version: 0.1 (April 7, 2021) import unittest", "1), date(1999, 9, 6), date(2000, 9, 4), date(2012, 9, 3), date(2013, 9, 2),", "relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 7, 5), self.marketholidayss) self.assertNotIn(date(2020, 7, 3), self.marketholidayss) self.marketholidayss.observed = True", "9, 6), date(2000, 9, 4), date(2012, 9, 3), date(2013, 9, 2), date(2014, 9,", "It aims to make determining whether a # specific date is a holiday", "16), date(2016, 2, 15), date(2020, 2, 17), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1),", "+ relativedelta(days=+1), self.marketholidayss) def test_martin_luther(self): for dt in [ date(1986, 1, 20), date(1999,", "5, 31), date(1997, 5, 26), date(1999, 5, 31), date(2000, 5, 29), date(2012, 5,", "a # specific date is a holiday as fast and flexible as possible.", "(April 7, 2021) import unittest from datetime import date from dateutil.relativedelta import relativedelta", "5), self.marketholidayss) self.assertIn(date(2020, 7, 3), self.marketholidayss) def test_labor_day(self): for dt in [ date(1997,", "ky_marketholidayss) def test_future_list(self): current_date = '2021-04-13' lookup_step = 10 self.assertIn(date(2021, 4, 16), self.markettradingdayss.future_list(current_date,", "relativedelta # import sys # sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from marketanalysis import marketholidays from marketanalysis", "2, 17), date(1999, 2, 15), date(2000, 2, 21), date(2012, 2, 20), date(2013, 2,", "test_prevDays(self): current_date = '2021-04-13' lookback_step = 4 self.assertIn(date(2021, 4, 9), self.markettradingdayss.prevDays(current_date, lookback_step)) self.assertNotIn(date(2021,", "False for year in range(1900, 2050): self.assertNotIn(date(year, 12, 24), self.marketholidayss) # self.assertIn(date(year, 12,", "19), date(2016, 1, 18), date(2020, 1, 20), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1),", "determining whether a # specific date is a holiday as fast and flexible", "self.assertNotIn(date(2021, 4, 11), self.markettradingdayss.prevDays(current_date, lookback_step)) def test_BtwDates(self): current_date = '2021-04-13' future_date = '2021-04-20'", "27), date(2014, 5, 26), date(2015, 5, 25), date(2016, 5, 30), date(2020, 5, 25),", "= '2021-04-20' self.assertIn(date(2021, 4, 15), self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.BtwDates(current_date, future_date)) #", "as_marketholidayss) self.assertNotIn(date(2016, 12, 23), as_marketholidayss) self.assertNotIn( \"Christmas Eve (Observed)\", as_marketholidayss.get_list(date(2017, 12, 22)), )", "nc_marketholidayss = marketholidays.US(observed=False) self.assertNotIn(date(2015, 12, 28), nc_marketholidayss) self.assertNotIn(date(2016, 12, 27), nc_marketholidayss) nc_marketholidayss.observed =", "self.marketholidayss) self.assertNotIn(date(2016, 12, 26), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 24), self.marketholidayss) self.assertIn(date(2016,", "date(2010, 4, 2), date(2018, 3, 30), date(2019, 4, 19), date(2020, 4, 10), ]:", "self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 24), self.marketholidayss) self.assertIn(date(2016, 12, 26), self.marketholidayss) def", "date(2015, 1, 19), date(2016, 1, 18), date(2020, 1, 20), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt", "12, 30)]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt, ky_marketholidayss) def test_future_list(self): current_date = '2021-04-13' lookup_step =", "= marketholidays.US() for dt in [ date(1969, 2, 22), date(1970, 2, 22), date(1971,", "self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.future_list(current_date, lookup_step)) def test_prevDays(self): current_date = '2021-04-13' lookback_step = 4", "2100): dt = date(year, 7, 4) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt", "A fast, efficient Python library for generating country, province and state # specific", "as_marketholidayss) self.assertNotIn( \"Christmas Eve (Observed)\", as_marketholidayss.get_list(date(2017, 12, 22)), ) def test_christmas_day(self): for year", "marketholidays.USA(observed=False) self.markettradingdayss = markettradingdays.USA() def test_new_years(self): self.assertNotIn(date(2010, 12, 31), self.marketholidayss) self.assertNotIn(date(2017, 1, 2),", "date(1999, 1, 18), date(2000, 1, 17), date(2012, 1, 16), date(2013, 1, 21), date(2014,", "dt in [ date(1997, 9, 1), date(1999, 9, 6), date(2000, 9, 4), date(2012," ]
[ "#!/usr/bin/env python from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup(", "import setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'}, scripts=['scripts/rosmsg',", "catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'}, scripts=['scripts/rosmsg', 'scripts/rosmsg-proto', 'scripts/rossrv'], requires=['genmsg',", "from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'}, scripts=['scripts/rosmsg', 'scripts/rosmsg-proto', 'scripts/rossrv'],", "<reponame>jungleni/ros_code_reading #!/usr/bin/env python from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup d =", "setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'}, scripts=['scripts/rosmsg', 'scripts/rosmsg-proto',", "python from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['rosmsg'],", "distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'},", "from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['rosmsg'], package_dir={'':", "generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'}, scripts=['scripts/rosmsg', 'scripts/rosmsg-proto', 'scripts/rossrv'], requires=['genmsg', 'rosbag', 'roslib', 'rospkg'] ) setup(**d)", "= generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'}, scripts=['scripts/rosmsg', 'scripts/rosmsg-proto', 'scripts/rossrv'], requires=['genmsg', 'rosbag', 'roslib', 'rospkg'] )", "generate_distutils_setup d = generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'}, scripts=['scripts/rosmsg', 'scripts/rosmsg-proto', 'scripts/rossrv'], requires=['genmsg', 'rosbag', 'roslib',", "import generate_distutils_setup d = generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'}, scripts=['scripts/rosmsg', 'scripts/rosmsg-proto', 'scripts/rossrv'], requires=['genmsg', 'rosbag',", "d = generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'}, scripts=['scripts/rosmsg', 'scripts/rosmsg-proto', 'scripts/rossrv'], requires=['genmsg', 'rosbag', 'roslib', 'rospkg']" ]
[ "= None def insert(self, value): self.list = Node(value, self.list) def start_iter(self): return self.list", "\"\"\" Main execution function \"\"\" if test: return ############################################################################### # Executable code ###############################################################################", "test_Linked_list_class__basic_functionality(self): \"\"\" Linked_list class basic testing \"\"\" d = Linked_list() self.assertEqual(d.list, None) d.insert(1)", "# Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_Linked_list_class__basic_functionality(self): \"\"\" Linked_list class basic testing", "return result def run(self, test=False): \"\"\" Main execution function \"\"\" if test: return", "sb = Linked_list(\" \".join(sys.argv[1:])) sb.run() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def", "re import random import subprocess import getpass import shutil # Additional modules ###############################################################################", "def __init__(self): \"\"\" Default constructor \"\"\" self.list = None def insert(self, value): self.list", "result def run(self, test=False): \"\"\" Main execution function \"\"\" if test: return ###############################################################################", "if test: return ############################################################################### # Executable code ############################################################################### def main(): # Sandbox sb", "# Executable code ############################################################################### def main(): # Sandbox sb = Linked_list(\" \".join(sys.argv[1:])) sb.run()", "Class ############################################################################### class Node: def __init__(self, value, tail): self.value = value self.next =", "\"\"\" Linked_list class basic testing \"\"\" d = Linked_list() self.assertEqual(d.list, None) d.insert(1) self.assertEqual(d.list.value,", "self.list) def start_iter(self): return self.list def next_iter(self, iter): if iter is not None:", "iter = d.start_iter() self.assertEqual(iter.value, 2) iter = d.next_iter(iter) self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(), [2, 1])", "iter is not None: return iter.next else: return iter def tolist(self): result =", "#!/usr/bin/env python # linked_list.py - Linked list implementation in Python by Sergey 2015", "python # linked_list.py - Linked list implementation in Python by Sergey 2015 \"\"\"", "self.list def next_iter(self, iter): if iter is not None: return iter.next else: return", "1) d.insert(2) self.assertEqual(d.list.next.value, 1) iter = d.start_iter() self.assertEqual(iter.value, 2) iter = d.next_iter(iter) self.assertEqual(iter.value,", "in Python \"\"\" # Standard modules import unittest import sys import os import", "iter = self.next_iter(iter) if not iter: break return result def run(self, test=False): \"\"\"", "execution function \"\"\" if test: return ############################################################################### # Executable code ############################################################################### def main():", "testing \"\"\" d = Linked_list() self.assertEqual(d.list, None) d.insert(1) self.assertEqual(d.list.value, 1) d.insert(2) self.assertEqual(d.list.next.value, 1)", "self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(), [2, 1]) if __name__ == \"__main__\": if sys.argv[-1] == \"-ut\":", "############################################################################### class Node: def __init__(self, value, tail): self.value = value self.next = tail", "main(): # Sandbox sb = Linked_list(\" \".join(sys.argv[1:])) sb.run() ############################################################################### # Unit Tests ###############################################################################", "# linked_list.py - Linked list implementation in Python by Sergey 2015 \"\"\" Linked", "modules import unittest import sys import os import argparse import re import random", "tolist(self): result = [] iter = self.start_iter() while True: result.append(iter.value) iter = self.next_iter(iter)", "random import subprocess import getpass import shutil # Additional modules ############################################################################### # Linked_list", "Linked list implementation in Python by Sergey 2015 \"\"\" Linked list implementation in", "class basic testing \"\"\" d = Linked_list() self.assertEqual(d.list, None) d.insert(1) self.assertEqual(d.list.value, 1) d.insert(2)", "############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_Linked_list_class__basic_functionality(self): \"\"\" Linked_list class basic", "\"\"\" self.list = None def insert(self, value): self.list = Node(value, self.list) def start_iter(self):", "import shutil # Additional modules ############################################################################### # Linked_list Class ############################################################################### class Node: def", "2015 \"\"\" Linked list implementation in Python \"\"\" # Standard modules import unittest", "Linked_list(\" \".join(sys.argv[1:])) sb.run() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_Linked_list_class__basic_functionality(self): \"\"\"", "\"\"\" d = Linked_list() self.assertEqual(d.list, None) d.insert(1) self.assertEqual(d.list.value, 1) d.insert(2) self.assertEqual(d.list.next.value, 1) iter", "self.start_iter() while True: result.append(iter.value) iter = self.next_iter(iter) if not iter: break return result", "start_iter(self): return self.list def next_iter(self, iter): if iter is not None: return iter.next", "# Sandbox sb = Linked_list(\" \".join(sys.argv[1:])) sb.run() ############################################################################### # Unit Tests ############################################################################### class", "Standard modules import unittest import sys import os import argparse import re import", "def __init__(self, value, tail): self.value = value self.next = tail class Linked_list: \"\"\"", "tail class Linked_list: \"\"\" Linked_list representation \"\"\" def __init__(self): \"\"\" Default constructor \"\"\"", "insert(self, value): self.list = Node(value, self.list) def start_iter(self): return self.list def next_iter(self, iter):", "Default constructor \"\"\" self.list = None def insert(self, value): self.list = Node(value, self.list)", "def insert(self, value): self.list = Node(value, self.list) def start_iter(self): return self.list def next_iter(self,", "1) iter = d.start_iter() self.assertEqual(iter.value, 2) iter = d.next_iter(iter) self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(), [2,", "implementation in Python by Sergey 2015 \"\"\" Linked list implementation in Python \"\"\"", "[] iter = self.start_iter() while True: result.append(iter.value) iter = self.next_iter(iter) if not iter:", "self.assertEqual(d.list.next.value, 1) iter = d.start_iter() self.assertEqual(iter.value, 2) iter = d.next_iter(iter) self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(),", "next_iter(self, iter): if iter is not None: return iter.next else: return iter def", "self.list = None def insert(self, value): self.list = Node(value, self.list) def start_iter(self): return", "implementation in Python \"\"\" # Standard modules import unittest import sys import os", "d.insert(2) self.assertEqual(d.list.next.value, 1) iter = d.start_iter() self.assertEqual(iter.value, 2) iter = d.next_iter(iter) self.assertEqual(iter.value, 1)", "Linked_list class basic testing \"\"\" d = Linked_list() self.assertEqual(d.list, None) d.insert(1) self.assertEqual(d.list.value, 1)", "return iter def tolist(self): result = [] iter = self.start_iter() while True: result.append(iter.value)", "function \"\"\" if test: return ############################################################################### # Executable code ############################################################################### def main(): #", "class Linked_list: \"\"\" Linked_list representation \"\"\" def __init__(self): \"\"\" Default constructor \"\"\" self.list", "iter: break return result def run(self, test=False): \"\"\" Main execution function \"\"\" if", "\"\"\" def __init__(self): \"\"\" Default constructor \"\"\" self.list = None def insert(self, value):", "value, tail): self.value = value self.next = tail class Linked_list: \"\"\" Linked_list representation", "Python by Sergey 2015 \"\"\" Linked list implementation in Python \"\"\" # Standard", "Linked_list Class ############################################################################### class Node: def __init__(self, value, tail): self.value = value self.next", "Linked_list: \"\"\" Linked_list representation \"\"\" def __init__(self): \"\"\" Default constructor \"\"\" self.list =", "Linked list implementation in Python \"\"\" # Standard modules import unittest import sys", "return ############################################################################### # Executable code ############################################################################### def main(): # Sandbox sb = Linked_list(\"", "\".join(sys.argv[1:])) sb.run() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_Linked_list_class__basic_functionality(self): \"\"\" Linked_list", "self.next_iter(iter) if not iter: break return result def run(self, test=False): \"\"\" Main execution", "= [] iter = self.start_iter() while True: result.append(iter.value) iter = self.next_iter(iter) if not", "self.next = tail class Linked_list: \"\"\" Linked_list representation \"\"\" def __init__(self): \"\"\" Default", "1) self.assertEqual(d.tolist(), [2, 1]) if __name__ == \"__main__\": if sys.argv[-1] == \"-ut\": unittest.main(argv=[\"", "import re import random import subprocess import getpass import shutil # Additional modules", "tail): self.value = value self.next = tail class Linked_list: \"\"\" Linked_list representation \"\"\"", "representation \"\"\" def __init__(self): \"\"\" Default constructor \"\"\" self.list = None def insert(self,", "by Sergey 2015 \"\"\" Linked list implementation in Python \"\"\" # Standard modules", "Node: def __init__(self, value, tail): self.value = value self.next = tail class Linked_list:", "= Node(value, self.list) def start_iter(self): return self.list def next_iter(self, iter): if iter is", "d = Linked_list() self.assertEqual(d.list, None) d.insert(1) self.assertEqual(d.list.value, 1) d.insert(2) self.assertEqual(d.list.next.value, 1) iter =", "modules ############################################################################### # Linked_list Class ############################################################################### class Node: def __init__(self, value, tail): self.value", "############################################################################### class unitTests(unittest.TestCase): def test_Linked_list_class__basic_functionality(self): \"\"\" Linked_list class basic testing \"\"\" d =", "= self.next_iter(iter) if not iter: break return result def run(self, test=False): \"\"\" Main", "def run(self, test=False): \"\"\" Main execution function \"\"\" if test: return ############################################################################### #", "while True: result.append(iter.value) iter = self.next_iter(iter) if not iter: break return result def", "Sandbox sb = Linked_list(\" \".join(sys.argv[1:])) sb.run() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase):", "subprocess import getpass import shutil # Additional modules ############################################################################### # Linked_list Class ###############################################################################", "self.list = Node(value, self.list) def start_iter(self): return self.list def next_iter(self, iter): if iter", "self.assertEqual(iter.value, 2) iter = d.next_iter(iter) self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(), [2, 1]) if __name__ ==", "iter.next else: return iter def tolist(self): result = [] iter = self.start_iter() while", "Linked_list representation \"\"\" def __init__(self): \"\"\" Default constructor \"\"\" self.list = None def", "[2, 1]) if __name__ == \"__main__\": if sys.argv[-1] == \"-ut\": unittest.main(argv=[\" \"]) main()", "sb.run() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_Linked_list_class__basic_functionality(self): \"\"\" Linked_list class", "argparse import re import random import subprocess import getpass import shutil # Additional", "= Linked_list() self.assertEqual(d.list, None) d.insert(1) self.assertEqual(d.list.value, 1) d.insert(2) self.assertEqual(d.list.next.value, 1) iter = d.start_iter()", "d.next_iter(iter) self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(), [2, 1]) if __name__ == \"__main__\": if sys.argv[-1] ==", "None) d.insert(1) self.assertEqual(d.list.value, 1) d.insert(2) self.assertEqual(d.list.next.value, 1) iter = d.start_iter() self.assertEqual(iter.value, 2) iter", "= d.next_iter(iter) self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(), [2, 1]) if __name__ == \"__main__\": if sys.argv[-1]", "= self.start_iter() while True: result.append(iter.value) iter = self.next_iter(iter) if not iter: break return", "import subprocess import getpass import shutil # Additional modules ############################################################################### # Linked_list Class", "constructor \"\"\" self.list = None def insert(self, value): self.list = Node(value, self.list) def", "= d.start_iter() self.assertEqual(iter.value, 2) iter = d.next_iter(iter) self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(), [2, 1]) if", "= Linked_list(\" \".join(sys.argv[1:])) sb.run() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_Linked_list_class__basic_functionality(self):", "shutil # Additional modules ############################################################################### # Linked_list Class ############################################################################### class Node: def __init__(self,", "d.start_iter() self.assertEqual(iter.value, 2) iter = d.next_iter(iter) self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(), [2, 1]) if __name__", "- Linked list implementation in Python by Sergey 2015 \"\"\" Linked list implementation", "else: return iter def tolist(self): result = [] iter = self.start_iter() while True:", "import unittest import sys import os import argparse import re import random import", "None: return iter.next else: return iter def tolist(self): result = [] iter =", "not iter: break return result def run(self, test=False): \"\"\" Main execution function \"\"\"", "\"\"\" if test: return ############################################################################### # Executable code ############################################################################### def main(): # Sandbox", "Python \"\"\" # Standard modules import unittest import sys import os import argparse", "import os import argparse import re import random import subprocess import getpass import", "\"\"\" Linked list implementation in Python \"\"\" # Standard modules import unittest import", "\"\"\" # Standard modules import unittest import sys import os import argparse import", "class Node: def __init__(self, value, tail): self.value = value self.next = tail class", "Linked_list() self.assertEqual(d.list, None) d.insert(1) self.assertEqual(d.list.value, 1) d.insert(2) self.assertEqual(d.list.next.value, 1) iter = d.start_iter() self.assertEqual(iter.value,", "self.assertEqual(d.list, None) d.insert(1) self.assertEqual(d.list.value, 1) d.insert(2) self.assertEqual(d.list.next.value, 1) iter = d.start_iter() self.assertEqual(iter.value, 2)", "run(self, test=False): \"\"\" Main execution function \"\"\" if test: return ############################################################################### # Executable", "# Linked_list Class ############################################################################### class Node: def __init__(self, value, tail): self.value = value", "self.assertEqual(d.list.value, 1) d.insert(2) self.assertEqual(d.list.next.value, 1) iter = d.start_iter() self.assertEqual(iter.value, 2) iter = d.next_iter(iter)", "import argparse import re import random import subprocess import getpass import shutil #", "None def insert(self, value): self.list = Node(value, self.list) def start_iter(self): return self.list def", "__init__(self, value, tail): self.value = value self.next = tail class Linked_list: \"\"\" Linked_list", "list implementation in Python by Sergey 2015 \"\"\" Linked list implementation in Python", "is not None: return iter.next else: return iter def tolist(self): result = []", "unitTests(unittest.TestCase): def test_Linked_list_class__basic_functionality(self): \"\"\" Linked_list class basic testing \"\"\" d = Linked_list() self.assertEqual(d.list,", "sys import os import argparse import re import random import subprocess import getpass", "import random import subprocess import getpass import shutil # Additional modules ############################################################################### #", "# Additional modules ############################################################################### # Linked_list Class ############################################################################### class Node: def __init__(self, value,", "Tests ############################################################################### class unitTests(unittest.TestCase): def test_Linked_list_class__basic_functionality(self): \"\"\" Linked_list class basic testing \"\"\" d", "result.append(iter.value) iter = self.next_iter(iter) if not iter: break return result def run(self, test=False):", "Additional modules ############################################################################### # Linked_list Class ############################################################################### class Node: def __init__(self, value, tail):", "Executable code ############################################################################### def main(): # Sandbox sb = Linked_list(\" \".join(sys.argv[1:])) sb.run() ###############################################################################", "result = [] iter = self.start_iter() while True: result.append(iter.value) iter = self.next_iter(iter) if", "def tolist(self): result = [] iter = self.start_iter() while True: result.append(iter.value) iter =", "############################################################################### # Executable code ############################################################################### def main(): # Sandbox sb = Linked_list(\" \".join(sys.argv[1:]))", "############################################################################### # Linked_list Class ############################################################################### class Node: def __init__(self, value, tail): self.value =", "value): self.list = Node(value, self.list) def start_iter(self): return self.list def next_iter(self, iter): if", "def next_iter(self, iter): if iter is not None: return iter.next else: return iter", "Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_Linked_list_class__basic_functionality(self): \"\"\" Linked_list class basic testing \"\"\"", "self.assertEqual(d.tolist(), [2, 1]) if __name__ == \"__main__\": if sys.argv[-1] == \"-ut\": unittest.main(argv=[\" \"])", "True: result.append(iter.value) iter = self.next_iter(iter) if not iter: break return result def run(self,", "break return result def run(self, test=False): \"\"\" Main execution function \"\"\" if test:", "############################################################################### def main(): # Sandbox sb = Linked_list(\" \".join(sys.argv[1:])) sb.run() ############################################################################### # Unit", "# Standard modules import unittest import sys import os import argparse import re", "self.value = value self.next = tail class Linked_list: \"\"\" Linked_list representation \"\"\" def", "iter): if iter is not None: return iter.next else: return iter def tolist(self):", "test=False): \"\"\" Main execution function \"\"\" if test: return ############################################################################### # Executable code", "def main(): # Sandbox sb = Linked_list(\" \".join(sys.argv[1:])) sb.run() ############################################################################### # Unit Tests", "iter def tolist(self): result = [] iter = self.start_iter() while True: result.append(iter.value) iter", "linked_list.py - Linked list implementation in Python by Sergey 2015 \"\"\" Linked list", "def test_Linked_list_class__basic_functionality(self): \"\"\" Linked_list class basic testing \"\"\" d = Linked_list() self.assertEqual(d.list, None)", "iter = self.start_iter() while True: result.append(iter.value) iter = self.next_iter(iter) if not iter: break", "basic testing \"\"\" d = Linked_list() self.assertEqual(d.list, None) d.insert(1) self.assertEqual(d.list.value, 1) d.insert(2) self.assertEqual(d.list.next.value,", "list implementation in Python \"\"\" # Standard modules import unittest import sys import", "= value self.next = tail class Linked_list: \"\"\" Linked_list representation \"\"\" def __init__(self):", "= tail class Linked_list: \"\"\" Linked_list representation \"\"\" def __init__(self): \"\"\" Default constructor", "\"\"\" Linked_list representation \"\"\" def __init__(self): \"\"\" Default constructor \"\"\" self.list = None", "iter = d.next_iter(iter) self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(), [2, 1]) if __name__ == \"__main__\": if", "import sys import os import argparse import re import random import subprocess import", "if iter is not None: return iter.next else: return iter def tolist(self): result", "__init__(self): \"\"\" Default constructor \"\"\" self.list = None def insert(self, value): self.list =", "import getpass import shutil # Additional modules ############################################################################### # Linked_list Class ############################################################################### class", "d.insert(1) self.assertEqual(d.list.value, 1) d.insert(2) self.assertEqual(d.list.next.value, 1) iter = d.start_iter() self.assertEqual(iter.value, 2) iter =", "return self.list def next_iter(self, iter): if iter is not None: return iter.next else:", "class unitTests(unittest.TestCase): def test_Linked_list_class__basic_functionality(self): \"\"\" Linked_list class basic testing \"\"\" d = Linked_list()", "Node(value, self.list) def start_iter(self): return self.list def next_iter(self, iter): if iter is not", "unittest import sys import os import argparse import re import random import subprocess", "getpass import shutil # Additional modules ############################################################################### # Linked_list Class ############################################################################### class Node:", "2) iter = d.next_iter(iter) self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(), [2, 1]) if __name__ == \"__main__\":", "os import argparse import re import random import subprocess import getpass import shutil", "return iter.next else: return iter def tolist(self): result = [] iter = self.start_iter()", "if not iter: break return result def run(self, test=False): \"\"\" Main execution function", "test: return ############################################################################### # Executable code ############################################################################### def main(): # Sandbox sb =", "Sergey 2015 \"\"\" Linked list implementation in Python \"\"\" # Standard modules import", "in Python by Sergey 2015 \"\"\" Linked list implementation in Python \"\"\" #", "not None: return iter.next else: return iter def tolist(self): result = [] iter", "def start_iter(self): return self.list def next_iter(self, iter): if iter is not None: return", "code ############################################################################### def main(): # Sandbox sb = Linked_list(\" \".join(sys.argv[1:])) sb.run() ############################################################################### #", "Main execution function \"\"\" if test: return ############################################################################### # Executable code ############################################################################### def", "<filename>unsorted/linked_list.py #!/usr/bin/env python # linked_list.py - Linked list implementation in Python by Sergey", "\"\"\" Default constructor \"\"\" self.list = None def insert(self, value): self.list = Node(value,", "value self.next = tail class Linked_list: \"\"\" Linked_list representation \"\"\" def __init__(self): \"\"\"" ]
[ "of the spatial stencil discretisation. Defaults to 4. kernel : selects a visco-acoustic", "return rec, p, v, summary def adjoint(self, rec, srca=None, va=None, pa=None, vp=None, qp=None,", "or array-like The receiver data. Please note that these act as the source", "= r or TimeFunction(name=\"r\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Pick physical parameters", "the injected source term. rec : SparseTimeFunction or array_like, optional The interpolated receiver", "as the source term in the adjoint run. srca : SparseTimeFunction or array-like", "---------- rec : SparseTimeFunction or array-like The receiver data. Please note that these", "receiver data. Please note that these act as the source term in the", "= space_order self.kernel = kernel self.time_order = time_order self._kwargs = kwargs @property def", "rec : SparseTimeFunction or array-like The receiver data. Please note that these act", "entire (unrolled) wavefield. Returns ------- Receiver, wavefield and performance summary \"\"\" # Source", "TimeFunction(name=\"r\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Pick physical parameters from model unless", "SparseTimeFunction or array-like The resulting data for the interpolated at the original source", "# Pick physical parameters from model unless explicitly provided b = b or", "p = p or TimeFunction(name=\"p\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable:", "geometry, space_order=4, kernel='sls', time_order=2, **kwargs): self.model = model self.model._initialize_bcs(bcs=\"mask\") self.geometry = geometry self.space_order", "@property def dt(self): return self.model.critical_dt @memoized_meth def op_fwd(self, save=None): \"\"\"Cached operator for forward", "self.op_fwd(save).apply(src=src, rec=rec, qp=qp, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) return rec, p, v,", "p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) return rec, p, v, summary def adjoint(self,", "Deng and McMechan (2007) viscoacoustic equation Defaults to 'sls' 2nd order. \"\"\" def", "@memoized_meth def op_fwd(self, save=None): \"\"\"Cached operator for forward runs with buffered wavefield\"\"\" return", "optional Whether or not to save the entire (unrolled) wavefield. Returns ------- Receiver,", "a new adjoint source and receiver symbol srca = srca or PointSource(name='srca', grid=self.model.grid,", "quality factor. b : Function, optional The time-constant inverse density. r : TimeFunction,", "that provides operators for seismic inversion problems and encapsulates the time and space", "variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Pick", "# Execute operator and return wavefield and receiver data # Without Memory variable", "forward modelling operator. Parameters ---------- src : SparseTimeFunction or array_like, optional Time series", "from the options below: 'sls' (Standard Linear Solid) : 1st order - Blanch", "grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid,", "va=None, pa=None, vp=None, qp=None, b=None, r=None, **kwargs): \"\"\" Adjoint modelling function that creates", "pa : TimeFunction, optional Stores the computed wavefield. vp : Function or float,", "staggered=NODE) # Pick physical parameters from model unless explicitly provided b = b", "or VectorTimeFunction(name=\"va\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in va}) pa =", "Defaults to 'sls' 2nd order. \"\"\" def __init__(self, model, geometry, space_order=4, kernel='sls', time_order=2,", "PointSource(name='srca', grid=self.model.grid, time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions) if self.time_order == 1: va = va or VectorTimeFunction(name=\"va\",", "Adjoint modelling function that creates the necessary data objects for running an adjoint", ": 1st order - Blanch and Symes (1995) / Dutta and Schuster (2014)", "The P-wave quality factor. b : Function, optional The time-constant inverse density. vp", "wavefield and receiver data # With Memory variable summary = self.op_adj().apply(src=srca, rec=rec, pa=pa,", "Memory variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) #", "'ren' - Ren et al. (2014) viscoacoustic equation 'deng_mcmechan' - Deng and McMechan", "their position. space_order : int, optional Order of the spatial stencil discretisation. Defaults", "Solid) : 1st order - Blanch and Symes (1995) / Dutta and Schuster", "creates the necessary data objects for running a forward modelling operator. Parameters ----------", "options below: 'sls' (Standard Linear Solid) : 1st order - Blanch and Symes", "time_order=self.time_order, **self._kwargs) def forward(self, src=None, rec=None, v=None, r=None, p=None, qp=None, b=None, vp=None, save=None,", "space_order self.kernel = kernel self.time_order = time_order self._kwargs = kwargs @property def dt(self):", "vp : Function or float, optional The time-constant velocity. save : bool, optional", "The time-constant velocity. save : bool, optional Whether or not to save the", ": Function or float, optional The time-constant velocity. save : bool, optional Whether", "/ Dutta and Schuster (2014) viscoacoustic equation 2nd order - Bai et al.", "and return wavefield and receiver data # With Memory variable summary = self.op_fwd(save).apply(src=src,", "and performance summary \"\"\" # Source term is read-only, so re-use the default", "location. va : VectorTimeFunction, optional The computed particle velocity. pa : TimeFunction, optional", "self.model.b qp = qp or self.model.qp # Pick vp from model unless explicitly", "necessary data objects for running an adjoint modelling operator. Parameters ---------- rec :", "provides operators for seismic inversion problems and encapsulates the time and space discretization", "for running a forward modelling operator. Parameters ---------- src : SparseTimeFunction or array_like,", "Model Physical model with domain parameters. geometry : AcquisitionGeometry Geometry object that contains", "with buffered wavefield\"\"\" return ForwardOperator(self.model, save=save, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) @memoized_meth def", "SparseTimeFunction or array_like, optional The interpolated receiver data. v : VectorTimeFunction, optional The", "wavefield. qp : Function, optional The P-wave quality factor. b : Function, optional", "explicitly provided vp = vp or self.model.vp if self.kernel == 'sls': # Execute", ": VectorTimeFunction, optional The computed particle velocity. pa : TimeFunction, optional Stores the", "vp = vp or self.model.vp # Execute operator and return wavefield and receiver", "NODE from devito.tools import memoized_meth from examples.seismic import PointSource from examples.seismic.viscoacoustic.operators import (ForwardOperator,", "self.dt), **kwargs) else: summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, vp=vp, b=b, qp=qp, dt=kwargs.pop('dt', self.dt),", "TimeFunction, optional The computed memory variable. p : TimeFunction, optional Stores the computed", "(SparseTimeFunction) and their position. space_order : int, optional Order of the spatial stencil", "# Pick vp from model unless explicitly provided vp = vp or self.model.vp", "a visco-acoustic equation from the options below: 'sls' (Standard Linear Solid) : 1st", "from model unless explicitly provided vp = vp or self.model.vp if self.kernel ==", "McMechan (2007) viscoacoustic equation Defaults to 'sls' 2nd order. \"\"\" def __init__(self, model,", "data # Without Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, p=p, b=b, vp=vp,", "\"\"\" Adjoint modelling function that creates the necessary data objects for running an", "Bai et al. (2014) viscoacoustic equation 'ren' - Ren et al. (2014) viscoacoustic", "(ForwardOperator, AdjointOperator) class ViscoacousticWaveSolver(object): \"\"\" Solver object that provides operators for seismic inversion", "else: # Execute operator and return wavefield and receiver data # Without Memory", "b=None, r=None, **kwargs): \"\"\" Adjoint modelling function that creates the necessary data objects", "variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) b = b", "self.dt), **kwargs) else: # Execute operator and return wavefield and receiver data #", "equation Defaults to 'sls' 2nd order. \"\"\" def __init__(self, model, geometry, space_order=4, kernel='sls',", "that creates the necessary data objects for running a forward modelling operator. Parameters", "qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) else: summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, vp=vp, b=b, qp=qp,", "time-constant inverse density. r : TimeFunction, optional The computed memory variable. Returns -------", "The computed particle velocity. r : TimeFunction, optional The computed memory variable. p", "from devito.tools import memoized_meth from examples.seismic import PointSource from examples.seismic.viscoacoustic.operators import (ForwardOperator, AdjointOperator)", "if save else None if self.time_order == 1: v = v or VectorTimeFunction(name=\"v\",", "VectorTimeFunction, TimeFunction, NODE from devito.tools import memoized_meth from examples.seismic import PointSource from examples.seismic.viscoacoustic.operators", "kernel self.time_order = time_order self._kwargs = kwargs @property def dt(self): return self.model.critical_dt @memoized_meth", "def op_adj(self): \"\"\"Cached operator for adjoint runs\"\"\" return AdjointOperator(self.model, save=None, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel,", "and receivers (SparseTimeFunction) and their position. space_order : int, optional Order of the", "self.geometry = geometry self.space_order = space_order self.kernel = kernel self.time_order = time_order self._kwargs", "that contains the source (SparseTimeFunction) and receivers (SparseTimeFunction) and their position. space_order :", "operator for forward runs with buffered wavefield\"\"\" return ForwardOperator(self.model, save=save, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel,", "rec = rec or self.geometry.rec # Create all the fields v, p, r", "self.model.critical_dt @memoized_meth def op_fwd(self, save=None): \"\"\"Cached operator for forward runs with buffered wavefield\"\"\"", "save=save_t, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in v}) # Create the forward", "qp=qp, r=r, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) else: # Execute operator and", "The resulting data for the interpolated at the original source location. va :", "the necessary data objects for running a forward modelling operator. Parameters ---------- src", "time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in va}) pa = pa or TimeFunction(name=\"pa\",", "physical parameters from model unless explicitly provided b = b or self.model.b qp", "= geometry self.space_order = space_order self.kernel = kernel self.time_order = time_order self._kwargs =", "grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Pick physical parameters from model unless explicitly", "optional The computed particle velocity. r : TimeFunction, optional The computed memory variable.", "grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r = r or TimeFunction(name=\"r\",", "and receiver data # With Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, r=r,", "\"\"\"Cached operator for forward runs with buffered wavefield\"\"\" return ForwardOperator(self.model, save=save, geometry=self.geometry, space_order=self.space_order,", "Parameters ---------- model : Model Physical model with domain parameters. geometry : AcquisitionGeometry", "import (ForwardOperator, AdjointOperator) class ViscoacousticWaveSolver(object): \"\"\" Solver object that provides operators for seismic", "receiver data # With Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, r=r, p=p,", "kernel='sls', time_order=2, **kwargs): self.model = model self.model._initialize_bcs(bcs=\"mask\") self.geometry = geometry self.space_order = space_order", "optional The computed memory variable. p : TimeFunction, optional Stores the computed wavefield.", "r : TimeFunction, optional The computed memory variable. p : TimeFunction, optional Stores", "or not to save the entire (unrolled) wavefield. Returns ------- Receiver, wavefield and", "save=None): \"\"\"Cached operator for forward runs with buffered wavefield\"\"\" return ForwardOperator(self.model, save=save, geometry=self.geometry,", "from model unless explicitly provided vp = vp or self.model.vp # Execute operator", "**kwargs): \"\"\" Adjoint modelling function that creates the necessary data objects for running", "or self.model.vp # Execute operator and return wavefield and receiver data if self.kernel", ": SparseTimeFunction or array_like, optional Time series data for the injected source term.", "self.geometry.src # Create a new receiver object to store the result rec =", "TimeFunction, optional The computed memory variable. Returns ------- Adjoint source, wavefield and performance", "unless explicitly provided vp = vp or self.model.vp if self.kernel == 'sls': #", "= r or TimeFunction(name=\"r\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) b = b or self.model.b", "save_t = src.nt if save else None if self.time_order == 1: v =", "variable. Returns ------- Adjoint source, wavefield and performance summary. \"\"\" # Create a", "performance summary \"\"\" # Source term is read-only, so re-use the default src", "return wavefield and receiver data # With Memory variable summary = self.op_adj().apply(src=srca, rec=rec,", "Pick physical parameters from model unless explicitly provided b = b or self.model.b", "the entire (unrolled) wavefield. Returns ------- Receiver, wavefield and performance summary \"\"\" #", "kernel=self.kernel, time_order=self.time_order, **self._kwargs) @memoized_meth def op_adj(self): \"\"\"Cached operator for adjoint runs\"\"\" return AdjointOperator(self.model,", "self.kernel = kernel self.time_order = time_order self._kwargs = kwargs @property def dt(self): return", "= srca or PointSource(name='srca', grid=self.model.grid, time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions) if self.time_order == 1: va =", "memory variable. p : TimeFunction, optional Stores the computed wavefield. qp : Function,", "space_order : int, optional Order of the spatial stencil discretisation. Defaults to 4.", "adjoint(self, rec, srca=None, va=None, pa=None, vp=None, qp=None, b=None, r=None, **kwargs): \"\"\" Adjoint modelling", "examples.seismic import PointSource from examples.seismic.viscoacoustic.operators import (ForwardOperator, AdjointOperator) class ViscoacousticWaveSolver(object): \"\"\" Solver object", "def dt(self): return self.model.critical_dt @memoized_meth def op_fwd(self, save=None): \"\"\"Cached operator for forward runs", "the computed wavefield. vp : Function or float, optional The time-constant velocity. qp", "va}) pa = pa or TimeFunction(name=\"pa\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable:", "time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid, time_order=self.time_order,", "= time_order self._kwargs = kwargs @property def dt(self): return self.model.critical_dt @memoized_meth def op_fwd(self,", "dt=kwargs.pop('dt', self.dt), **kwargs) else: # Execute operator and return wavefield and receiver data", "computed particle velocity. pa : TimeFunction, optional Stores the computed wavefield. vp :", "b=b, vp=vp, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) else: summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, vp=vp,", "memoized_meth from examples.seismic import PointSource from examples.seismic.viscoacoustic.operators import (ForwardOperator, AdjointOperator) class ViscoacousticWaveSolver(object): \"\"\"", "model, geometry, space_order=4, kernel='sls', time_order=2, **kwargs): self.model = model self.model._initialize_bcs(bcs=\"mask\") self.geometry = geometry", "for adjoint runs\"\"\" return AdjointOperator(self.model, save=None, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) def forward(self,", "v, summary def adjoint(self, rec, srca=None, va=None, pa=None, vp=None, qp=None, b=None, r=None, **kwargs):", ": int, optional Order of the spatial stencil discretisation. Defaults to 4. kernel", "or self.model.vp if self.kernel == 'sls': # Execute operator and return wavefield and", "Dutta and Schuster (2014) viscoacoustic equation 2nd order - Bai et al. (2014)", "kernel=self.kernel, time_order=self.time_order, **self._kwargs) def forward(self, src=None, rec=None, v=None, r=None, p=None, qp=None, b=None, vp=None,", "staggered=NODE) # Memory variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order,", "AdjointOperator(self.model, save=None, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) def forward(self, src=None, rec=None, v=None, r=None,", "r = r or TimeFunction(name=\"r\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Pick physical", "The P-wave quality factor. b : Function, optional The time-constant inverse density. r", "Blanch and Symes (1995) / Dutta and Schuster (2014) viscoacoustic equation 2nd order", "Receiver, wavefield and performance summary \"\"\" # Source term is read-only, so re-use", "result rec = rec or self.geometry.rec # Create all the fields v, p,", "k in va}) pa = pa or TimeFunction(name=\"pa\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) #", "r or TimeFunction(name=\"r\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) b = b or self.model.b qp", "array_like, optional The interpolated receiver data. v : VectorTimeFunction, optional The computed particle", "Geometry object that contains the source (SparseTimeFunction) and receivers (SparseTimeFunction) and their position.", "'sls' (Standard Linear Solid) : 1st order - Blanch and Symes (1995) /", "qp=None, b=None, r=None, **kwargs): \"\"\" Adjoint modelling function that creates the necessary data", "wavefield and performance summary \"\"\" # Source term is read-only, so re-use the", "receiver data if self.kernel == 'sls': # Execute operator and return wavefield and", "if self.time_order == 1: v = v or VectorTimeFunction(name=\"v\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order)", "receiver data # With Memory variable summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, r=r, b=b,", "---------- src : SparseTimeFunction or array_like, optional Time series data for the injected", ": VectorTimeFunction, optional The computed particle velocity. r : TimeFunction, optional The computed", "velocity. pa : TimeFunction, optional Stores the computed wavefield. vp : Function or", "or TimeFunction(name=\"pa\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r = r or", "spatial stencil discretisation. Defaults to 4. kernel : selects a visco-acoustic equation from", "the source term in the adjoint run. srca : SparseTimeFunction or array-like The", "provided vp = vp or self.model.vp # Execute operator and return wavefield and", "v or VectorTimeFunction(name=\"v\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in v})", "Memory variable summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, r=r, b=b, vp=vp, qp=qp, dt=kwargs.pop('dt', self.dt),", "vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) else: # Execute operator and return wavefield and receiver", "problems and encapsulates the time and space discretization for a given problem setup.", "\"\"\"Cached operator for adjoint runs\"\"\" return AdjointOperator(self.model, save=None, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs)", "modelling function that creates the necessary data objects for running a forward modelling", "save=save, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) @memoized_meth def op_adj(self): \"\"\"Cached operator for adjoint", "save else None if self.time_order == 1: v = v or VectorTimeFunction(name=\"v\", grid=self.model.grid,", "Create a new adjoint source and receiver symbol srca = srca or PointSource(name='srca',", "source (SparseTimeFunction) and receivers (SparseTimeFunction) and their position. space_order : int, optional Order", "computed wavefield. vp : Function or float, optional The time-constant velocity. qp :", "modelling function that creates the necessary data objects for running an adjoint modelling", "**kwargs): self.model = model self.model._initialize_bcs(bcs=\"mask\") self.geometry = geometry self.space_order = space_order self.kernel =", "r save_t = src.nt if save else None if self.time_order == 1: v", "Execute operator and return wavefield and receiver data # With Memory variable summary", "density. r : TimeFunction, optional The computed memory variable. Returns ------- Adjoint source,", "return self.model.critical_dt @memoized_meth def op_fwd(self, save=None): \"\"\"Cached operator for forward runs with buffered", "buffered wavefield\"\"\" return ForwardOperator(self.model, save=save, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) @memoized_meth def op_adj(self):", "p : TimeFunction, optional Stores the computed wavefield. qp : Function, optional The", "the adjoint run. srca : SparseTimeFunction or array-like The resulting data for the", "at the original source location. va : VectorTimeFunction, optional The computed particle velocity.", "# Source term is read-only, so re-use the default src = src or", "srca : SparseTimeFunction or array-like The resulting data for the interpolated at the", "rec or self.geometry.rec # Create all the fields v, p, r save_t =", "quality factor. b : Function, optional The time-constant inverse density. vp : Function", "and Symes (1995) / Dutta and Schuster (2014) viscoacoustic equation 2nd order -", "VectorTimeFunction, optional The computed particle velocity. pa : TimeFunction, optional Stores the computed", "**self._kwargs) @memoized_meth def op_adj(self): \"\"\"Cached operator for adjoint runs\"\"\" return AdjointOperator(self.model, save=None, geometry=self.geometry,", "\"\"\" Solver object that provides operators for seismic inversion problems and encapsulates the", "qp : Function, optional The P-wave quality factor. b : Function, optional The", "object to store the result rec = rec or self.geometry.rec # Create all", "equation from the options below: 'sls' (Standard Linear Solid) : 1st order -", "VectorTimeFunction(name=\"va\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in va}) pa = pa", "= kernel self.time_order = time_order self._kwargs = kwargs @property def dt(self): return self.model.critical_dt", "object that provides operators for seismic inversion problems and encapsulates the time and", "(2014) viscoacoustic equation 'ren' - Ren et al. (2014) viscoacoustic equation 'deng_mcmechan' -", "Whether or not to save the entire (unrolled) wavefield. Returns ------- Receiver, wavefield", "p or TimeFunction(name=\"p\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r =", "wavefield and receiver data # With Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp,", "self.time_order == 1: va = va or VectorTimeFunction(name=\"va\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k", "wavefield and receiver data if self.kernel == 'sls': # Execute operator and return", "if not provided p = p or TimeFunction(name=\"p\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE)", "The time-constant velocity. qp : Function, optional The P-wave quality factor. b :", "seismic inversion problems and encapsulates the time and space discretization for a given", "Function, optional The P-wave quality factor. b : Function, optional The time-constant inverse", "qp or self.model.qp # Pick vp from model unless explicitly provided vp =", "Create a new receiver object to store the result rec = rec or", "Pick vp from model unless explicitly provided vp = vp or self.model.vp if", "setup. Parameters ---------- model : Model Physical model with domain parameters. geometry :", "data. Please note that these act as the source term in the adjoint", "float, optional The time-constant velocity. save : bool, optional Whether or not to", "equation 'ren' - Ren et al. (2014) viscoacoustic equation 'deng_mcmechan' - Deng and", "SparseTimeFunction or array_like, optional Time series data for the injected source term. rec", "model unless explicitly provided b = b or self.model.b qp = qp or", "time-constant velocity. qp : Function, optional The P-wave quality factor. b : Function,", "The computed memory variable. Returns ------- Adjoint source, wavefield and performance summary. \"\"\"", "kwargs.update({k.name: k for k in v}) # Create the forward wavefield if not", "v=None, r=None, p=None, qp=None, b=None, vp=None, save=None, **kwargs): \"\"\" Forward modelling function that", "b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) else: # Execute operator and return wavefield and", "space_order=self.space_order, staggered=NODE) # Memory variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order,", "data objects for running a forward modelling operator. Parameters ---------- src : SparseTimeFunction", "viscoacoustic equation 'deng_mcmechan' - Deng and McMechan (2007) viscoacoustic equation Defaults to 'sls'", "TimeFunction, NODE from devito.tools import memoized_meth from examples.seismic import PointSource from examples.seismic.viscoacoustic.operators import", "velocity. save : bool, optional Whether or not to save the entire (unrolled)", "b = b or self.model.b qp = qp or self.model.qp # Pick vp", "src=None, rec=None, v=None, r=None, p=None, qp=None, b=None, vp=None, save=None, **kwargs): \"\"\" Forward modelling", "Pick vp from model unless explicitly provided vp = vp or self.model.vp #", "k for k in v}) # Create the forward wavefield if not provided", "Solver object that provides operators for seismic inversion problems and encapsulates the time", "or self.geometry.rec # Create all the fields v, p, r save_t = src.nt", "unless explicitly provided vp = vp or self.model.vp # Execute operator and return", "summary \"\"\" # Source term is read-only, so re-use the default src =", "wavefield and receiver data # Without Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp,", "and encapsulates the time and space discretization for a given problem setup. Parameters", "time-constant inverse density. vp : Function or float, optional The time-constant velocity. save", "wavefield if not provided p = p or TimeFunction(name=\"p\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order,", "TimeFunction, optional Stores the computed wavefield. qp : Function, optional The P-wave quality", "is read-only, so re-use the default src = src or self.geometry.src # Create", "TimeFunction, optional Stores the computed wavefield. vp : Function or float, optional The", "va = va or VectorTimeFunction(name=\"va\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in", "# Memory variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) b", "Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, r=r, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt),", "1: v = v or VectorTimeFunction(name=\"v\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for", "for a given problem setup. Parameters ---------- model : Model Physical model with", "= pa or TimeFunction(name=\"pa\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r =", "summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) return rec,", "self.model = model self.model._initialize_bcs(bcs=\"mask\") self.geometry = geometry self.space_order = space_order self.kernel = kernel", "the computed wavefield. qp : Function, optional The P-wave quality factor. b :", "TimeFunction(name=\"p\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r = r or", "for the interpolated at the original source location. va : VectorTimeFunction, optional The", "visco-acoustic equation from the options below: 'sls' (Standard Linear Solid) : 1st order", "and receiver symbol srca = srca or PointSource(name='srca', grid=self.model.grid, time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions) if self.time_order", ": Function, optional The P-wave quality factor. b : Function, optional The time-constant", "et al. (2014) viscoacoustic equation 'ren' - Ren et al. (2014) viscoacoustic equation", "save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid,", "src = src or self.geometry.src # Create a new receiver object to store", "operator and return wavefield and receiver data if self.kernel == 'sls': # Execute", "problem setup. Parameters ---------- model : Model Physical model with domain parameters. geometry", "wavefield. Returns ------- Receiver, wavefield and performance summary \"\"\" # Source term is", ": AcquisitionGeometry Geometry object that contains the source (SparseTimeFunction) and receivers (SparseTimeFunction) and", "\"\"\" def __init__(self, model, geometry, space_order=4, kernel='sls', time_order=2, **kwargs): self.model = model self.model._initialize_bcs(bcs=\"mask\")", "# With Memory variable summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, r=r, b=b, vp=vp, qp=qp,", "(SparseTimeFunction) and receivers (SparseTimeFunction) and their position. space_order : int, optional Order of", "= self.op_adj().apply(src=srca, rec=rec, pa=pa, vp=vp, b=b, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) return srca, pa,", "space_order=self.space_order) kwargs.update({k.name: k for k in va}) pa = pa or TimeFunction(name=\"pa\", grid=self.model.grid,", "the default src = src or self.geometry.src # Create a new receiver object", "time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid, save=save_t,", "Symes (1995) / Dutta and Schuster (2014) viscoacoustic equation 2nd order - Bai", "None if self.time_order == 1: v = v or VectorTimeFunction(name=\"v\", grid=self.model.grid, save=save_t, time_order=self.time_order,", "symbol srca = srca or PointSource(name='srca', grid=self.model.grid, time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions) if self.time_order == 1:", "Order of the spatial stencil discretisation. Defaults to 4. kernel : selects a", "# Create a new adjoint source and receiver symbol srca = srca or", "**kwargs) else: summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, vp=vp, b=b, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs)", "@memoized_meth def op_adj(self): \"\"\"Cached operator for adjoint runs\"\"\" return AdjointOperator(self.model, save=None, geometry=self.geometry, space_order=self.space_order,", "Ren et al. (2014) viscoacoustic equation 'deng_mcmechan' - Deng and McMechan (2007) viscoacoustic", "2nd order. \"\"\" def __init__(self, model, geometry, space_order=4, kernel='sls', time_order=2, **kwargs): self.model =", "new receiver object to store the result rec = rec or self.geometry.rec #", "Forward modelling function that creates the necessary data objects for running a forward", "return ForwardOperator(self.model, save=save, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) @memoized_meth def op_adj(self): \"\"\"Cached operator", "to 'sls' 2nd order. \"\"\" def __init__(self, model, geometry, space_order=4, kernel='sls', time_order=2, **kwargs):", "variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, r=r, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs)", "VectorTimeFunction(name=\"v\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in v}) # Create", "viscoacoustic equation 2nd order - Bai et al. (2014) viscoacoustic equation 'ren' -", "al. (2014) viscoacoustic equation 'deng_mcmechan' - Deng and McMechan (2007) viscoacoustic equation Defaults", "operator for adjoint runs\"\"\" return AdjointOperator(self.model, save=None, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) def", "provided vp = vp or self.model.vp if self.kernel == 'sls': # Execute operator", "def op_fwd(self, save=None): \"\"\"Cached operator for forward runs with buffered wavefield\"\"\" return ForwardOperator(self.model,", "(Standard Linear Solid) : 1st order - Blanch and Symes (1995) / Dutta", "optional Time series data for the injected source term. rec : SparseTimeFunction or", "wavefield\"\"\" return ForwardOperator(self.model, save=save, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) @memoized_meth def op_adj(self): \"\"\"Cached", "optional The interpolated receiver data. v : VectorTimeFunction, optional The computed particle velocity.", "4. kernel : selects a visco-acoustic equation from the options below: 'sls' (Standard", "class ViscoacousticWaveSolver(object): \"\"\" Solver object that provides operators for seismic inversion problems and", "time_order=self.time_order, **self._kwargs) @memoized_meth def op_adj(self): \"\"\"Cached operator for adjoint runs\"\"\" return AdjointOperator(self.model, save=None,", "kernel : selects a visco-acoustic equation from the options below: 'sls' (Standard Linear", "time-constant velocity. save : bool, optional Whether or not to save the entire", "= src or self.geometry.src # Create a new receiver object to store the", "= src.nt if save else None if self.time_order == 1: v = v", "self.op_adj().apply(src=srca, rec=rec, pa=pa, r=r, b=b, vp=vp, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) else: summary =", "vp : Function or float, optional The time-constant velocity. qp : Function, optional", "unless explicitly provided b = b or self.model.b qp = qp or self.model.qp", "the options below: 'sls' (Standard Linear Solid) : 1st order - Blanch and", "= self.op_adj().apply(src=srca, rec=rec, pa=pa, r=r, b=b, vp=vp, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) else: summary", "= self.op_fwd(save).apply(src=src, rec=rec, qp=qp, r=r, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) else: #", "Adjoint source, wavefield and performance summary. \"\"\" # Create a new adjoint source", "\"\"\" # Create a new adjoint source and receiver symbol srca = srca", "grid=self.model.grid, time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions) if self.time_order == 1: va = va or VectorTimeFunction(name=\"va\", grid=self.model.grid,", "the fields v, p, r save_t = src.nt if save else None if", "coordinates=self.geometry.src_positions) if self.time_order == 1: va = va or VectorTimeFunction(name=\"va\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order)", "encapsulates the time and space discretization for a given problem setup. Parameters ----------", "VectorTimeFunction, optional The computed particle velocity. r : TimeFunction, optional The computed memory", "forward runs with buffered wavefield\"\"\" return ForwardOperator(self.model, save=save, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs)", "v}) # Create the forward wavefield if not provided p = p or", "wavefield. vp : Function or float, optional The time-constant velocity. qp : Function,", "qp=None, b=None, vp=None, save=None, **kwargs): \"\"\" Forward modelling function that creates the necessary", "Physical model with domain parameters. geometry : AcquisitionGeometry Geometry object that contains the", "data if self.kernel == 'sls': # Execute operator and return wavefield and receiver", "= v or VectorTimeFunction(name=\"v\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in", "__init__(self, model, geometry, space_order=4, kernel='sls', time_order=2, **kwargs): self.model = model self.model._initialize_bcs(bcs=\"mask\") self.geometry =", "in va}) pa = pa or TimeFunction(name=\"pa\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory", "import VectorTimeFunction, TimeFunction, NODE from devito.tools import memoized_meth from examples.seismic import PointSource from", "The receiver data. Please note that these act as the source term in", "vp=vp, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) else: summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, vp=vp, b=b,", "function that creates the necessary data objects for running an adjoint modelling operator.", "equation 2nd order - Bai et al. (2014) viscoacoustic equation 'ren' - Ren", "vp or self.model.vp # Execute operator and return wavefield and receiver data if", "and receiver data if self.kernel == 'sls': # Execute operator and return wavefield", "equation 'deng_mcmechan' - Deng and McMechan (2007) viscoacoustic equation Defaults to 'sls' 2nd", "data for the interpolated at the original source location. va : VectorTimeFunction, optional", "and their position. space_order : int, optional Order of the spatial stencil discretisation.", "operator and return wavefield and receiver data # With Memory variable summary =", "save=None, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) def forward(self, src=None, rec=None, v=None, r=None, p=None,", "running an adjoint modelling operator. Parameters ---------- rec : SparseTimeFunction or array-like The", "optional The time-constant inverse density. vp : Function or float, optional The time-constant", "qp = qp or self.model.qp # Pick vp from model unless explicitly provided", "optional The time-constant velocity. save : bool, optional Whether or not to save", "return AdjointOperator(self.model, save=None, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) def forward(self, src=None, rec=None, v=None,", "array-like The receiver data. Please note that these act as the source term", "optional The time-constant velocity. qp : Function, optional The P-wave quality factor. b", "not provided p = p or TimeFunction(name=\"p\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) #", "summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, r=r, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) else:", "**kwargs) else: # Execute operator and return wavefield and receiver data # Without", "runs\"\"\" return AdjointOperator(self.model, save=None, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) def forward(self, src=None, rec=None,", "the forward wavefield if not provided p = p or TimeFunction(name=\"p\", grid=self.model.grid, save=save_t,", ": Function or float, optional The time-constant velocity. qp : Function, optional The", "and receiver data # With Memory variable summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, r=r,", "array_like, optional Time series data for the injected source term. rec : SparseTimeFunction", "variable summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, r=r, b=b, vp=vp, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs)", "def __init__(self, model, geometry, space_order=4, kernel='sls', time_order=2, **kwargs): self.model = model self.model._initialize_bcs(bcs=\"mask\") self.geometry", "ForwardOperator(self.model, save=save, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) @memoized_meth def op_adj(self): \"\"\"Cached operator for", "al. (2014) viscoacoustic equation 'ren' - Ren et al. (2014) viscoacoustic equation 'deng_mcmechan'", "to 4. kernel : selects a visco-acoustic equation from the options below: 'sls'", "the result rec = rec or self.geometry.rec # Create all the fields v,", "for the injected source term. rec : SparseTimeFunction or array_like, optional The interpolated", "wavefield and performance summary. \"\"\" # Create a new adjoint source and receiver", "r=r, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) else: # Execute operator and return", "srca=None, va=None, pa=None, vp=None, qp=None, b=None, r=None, **kwargs): \"\"\" Adjoint modelling function that", "- Deng and McMechan (2007) viscoacoustic equation Defaults to 'sls' 2nd order. \"\"\"", "data # With Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, r=r, p=p, b=b,", "(1995) / Dutta and Schuster (2014) viscoacoustic equation 2nd order - Bai et", "array-like The resulting data for the interpolated at the original source location. va", "and return wavefield and receiver data # Without Memory variable summary = self.op_fwd(save).apply(src=src,", "grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in v}) # Create the", "and performance summary. \"\"\" # Create a new adjoint source and receiver symbol", "p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) else: # Execute operator and return wavefield", ": TimeFunction, optional Stores the computed wavefield. vp : Function or float, optional", "time_order=self.time_order, space_order=self.space_order, staggered=NODE) b = b or self.model.b qp = qp or self.model.qp", "variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) return", "space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) @memoized_meth def op_adj(self): \"\"\"Cached operator for adjoint runs\"\"\" return", "== 1: v = v or VectorTimeFunction(name=\"v\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k", "time and space discretization for a given problem setup. Parameters ---------- model :", "else: summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, vp=vp, b=b, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) return", "or float, optional The time-constant velocity. qp : Function, optional The P-wave quality", ": SparseTimeFunction or array-like The receiver data. Please note that these act as", "store the result rec = rec or self.geometry.rec # Create all the fields", "and McMechan (2007) viscoacoustic equation Defaults to 'sls' 2nd order. \"\"\" def __init__(self,", "model unless explicitly provided vp = vp or self.model.vp if self.kernel == 'sls':", "k for k in va}) pa = pa or TimeFunction(name=\"pa\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order,", "data. v : VectorTimeFunction, optional The computed particle velocity. r : TimeFunction, optional", "rec=None, v=None, r=None, p=None, qp=None, b=None, vp=None, save=None, **kwargs): \"\"\" Forward modelling function", "space_order=self.space_order, staggered=NODE) b = b or self.model.b qp = qp or self.model.qp #", "'sls' 2nd order. \"\"\" def __init__(self, model, geometry, space_order=4, kernel='sls', time_order=2, **kwargs): self.model", "inversion problems and encapsulates the time and space discretization for a given problem", "k in v}) # Create the forward wavefield if not provided p =", "= vp or self.model.vp # Execute operator and return wavefield and receiver data", "= self.op_fwd(save).apply(src=src, rec=rec, qp=qp, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) return rec, p,", "2nd order - Bai et al. (2014) viscoacoustic equation 'ren' - Ren et", "if self.kernel == 'sls': # Execute operator and return wavefield and receiver data", "the spatial stencil discretisation. Defaults to 4. kernel : selects a visco-acoustic equation", "adjoint modelling operator. Parameters ---------- rec : SparseTimeFunction or array-like The receiver data.", "summary def adjoint(self, rec, srca=None, va=None, pa=None, vp=None, qp=None, b=None, r=None, **kwargs): \"\"\"", "receiver object to store the result rec = rec or self.geometry.rec # Create", "parameters from model unless explicitly provided b = b or self.model.b qp =", "that creates the necessary data objects for running an adjoint modelling operator. Parameters", "or array-like The resulting data for the interpolated at the original source location.", "discretization for a given problem setup. Parameters ---------- model : Model Physical model", "a forward modelling operator. Parameters ---------- src : SparseTimeFunction or array_like, optional Time", "import PointSource from examples.seismic.viscoacoustic.operators import (ForwardOperator, AdjointOperator) class ViscoacousticWaveSolver(object): \"\"\" Solver object that", "geometry : AcquisitionGeometry Geometry object that contains the source (SparseTimeFunction) and receivers (SparseTimeFunction)", "and Schuster (2014) viscoacoustic equation 2nd order - Bai et al. (2014) viscoacoustic", "Function, optional The time-constant inverse density. r : TimeFunction, optional The computed memory", "**kwargs): \"\"\" Forward modelling function that creates the necessary data objects for running", "discretisation. Defaults to 4. kernel : selects a visco-acoustic equation from the options", "all the fields v, p, r save_t = src.nt if save else None", "order. \"\"\" def __init__(self, model, geometry, space_order=4, kernel='sls', time_order=2, **kwargs): self.model = model", "dt=kwargs.pop('dt', self.dt), **kwargs) return rec, p, v, summary def adjoint(self, rec, srca=None, va=None,", "vp = vp or self.model.vp if self.kernel == 'sls': # Execute operator and", "r or TimeFunction(name=\"r\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Pick physical parameters from", "self.model.vp if self.kernel == 'sls': # Execute operator and return wavefield and receiver", "devito import VectorTimeFunction, TimeFunction, NODE from devito.tools import memoized_meth from examples.seismic import PointSource", "# With Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, r=r, p=p, b=b, vp=vp,", "particle velocity. r : TimeFunction, optional The computed memory variable. p : TimeFunction,", "'deng_mcmechan' - Deng and McMechan (2007) viscoacoustic equation Defaults to 'sls' 2nd order.", ": Function, optional The time-constant inverse density. r : TimeFunction, optional The computed", "model self.model._initialize_bcs(bcs=\"mask\") self.geometry = geometry self.space_order = space_order self.kernel = kernel self.time_order =", "\"\"\" # Source term is read-only, so re-use the default src = src", "necessary data objects for running a forward modelling operator. Parameters ---------- src :", "modelling operator. Parameters ---------- rec : SparseTimeFunction or array-like The receiver data. Please", "Source term is read-only, so re-use the default src = src or self.geometry.src", "Memory variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) b =", "source and receiver symbol srca = srca or PointSource(name='srca', grid=self.model.grid, time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions) if", "return wavefield and receiver data if self.kernel == 'sls': # Execute operator and", "The computed particle velocity. pa : TimeFunction, optional Stores the computed wavefield. vp", "Parameters ---------- rec : SparseTimeFunction or array-like The receiver data. Please note that", "---------- model : Model Physical model with domain parameters. geometry : AcquisitionGeometry Geometry", "read-only, so re-use the default src = src or self.geometry.src # Create a", "grid=self.model.grid, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in va}) pa = pa or", "resulting data for the interpolated at the original source location. va : VectorTimeFunction,", "va or VectorTimeFunction(name=\"va\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in va}) pa", "data for the injected source term. rec : SparseTimeFunction or array_like, optional The", "def forward(self, src=None, rec=None, v=None, r=None, p=None, qp=None, b=None, vp=None, save=None, **kwargs): \"\"\"", "new adjoint source and receiver symbol srca = srca or PointSource(name='srca', grid=self.model.grid, time_range=self.geometry.time_axis,", "or self.geometry.src # Create a new receiver object to store the result rec", "time_order self._kwargs = kwargs @property def dt(self): return self.model.critical_dt @memoized_meth def op_fwd(self, save=None):", "and space discretization for a given problem setup. Parameters ---------- model : Model", "model unless explicitly provided vp = vp or self.model.vp # Execute operator and", "Create the forward wavefield if not provided p = p or TimeFunction(name=\"p\", grid=self.model.grid,", "interpolated receiver data. v : VectorTimeFunction, optional The computed particle velocity. r :", "# Memory variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE)", "space_order=self.space_order, staggered=NODE) # Memory variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid, save=save_t, time_order=self.time_order,", "# Create the forward wavefield if not provided p = p or TimeFunction(name=\"p\",", "kwargs @property def dt(self): return self.model.critical_dt @memoized_meth def op_fwd(self, save=None): \"\"\"Cached operator for", "self.model.qp # Pick vp from model unless explicitly provided vp = vp or", "the interpolated at the original source location. va : VectorTimeFunction, optional The computed", "or self.model.b qp = qp or self.model.qp # Pick vp from model unless", "explicitly provided b = b or self.model.b qp = qp or self.model.qp #", "not to save the entire (unrolled) wavefield. Returns ------- Receiver, wavefield and performance", "vp from model unless explicitly provided vp = vp or self.model.vp if self.kernel", "vp=None, save=None, **kwargs): \"\"\" Forward modelling function that creates the necessary data objects", "return wavefield and receiver data # With Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec,", "self.time_order = time_order self._kwargs = kwargs @property def dt(self): return self.model.critical_dt @memoized_meth def", "1: va = va or VectorTimeFunction(name=\"va\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k", "= b or self.model.b qp = qp or self.model.qp # Pick vp from", "for forward runs with buffered wavefield\"\"\" return ForwardOperator(self.model, save=save, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order,", "self.model._initialize_bcs(bcs=\"mask\") self.geometry = geometry self.space_order = space_order self.kernel = kernel self.time_order = time_order", "b : Function, optional The time-constant inverse density. vp : Function or float,", "int, optional Order of the spatial stencil discretisation. Defaults to 4. kernel :", "density. vp : Function or float, optional The time-constant velocity. save : bool,", "self._kwargs = kwargs @property def dt(self): return self.model.critical_dt @memoized_meth def op_fwd(self, save=None): \"\"\"Cached", "time_order=2, **kwargs): self.model = model self.model._initialize_bcs(bcs=\"mask\") self.geometry = geometry self.space_order = space_order self.kernel", "objects for running a forward modelling operator. Parameters ---------- src : SparseTimeFunction or", "ViscoacousticWaveSolver(object): \"\"\" Solver object that provides operators for seismic inversion problems and encapsulates", "b=None, vp=None, save=None, **kwargs): \"\"\" Forward modelling function that creates the necessary data", "self.kernel == 'sls': # Execute operator and return wavefield and receiver data #", "operator and return wavefield and receiver data # Without Memory variable summary =", "rec=rec, pa=pa, vp=vp, b=b, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) return srca, pa, va, summary", "function that creates the necessary data objects for running a forward modelling operator.", "bool, optional Whether or not to save the entire (unrolled) wavefield. Returns -------", "Please note that these act as the source term in the adjoint run.", "for seismic inversion problems and encapsulates the time and space discretization for a", "adjoint source and receiver symbol srca = srca or PointSource(name='srca', grid=self.model.grid, time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions)", "or array_like, optional Time series data for the injected source term. rec :", "or self.model.qp # Pick vp from model unless explicitly provided vp = vp", "staggered=NODE) b = b or self.model.b qp = qp or self.model.qp # Pick", "the original source location. va : VectorTimeFunction, optional The computed particle velocity. pa", "Without Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt),", "memory variable. Returns ------- Adjoint source, wavefield and performance summary. \"\"\" # Create", "------- Adjoint source, wavefield and performance summary. \"\"\" # Create a new adjoint", "contains the source (SparseTimeFunction) and receivers (SparseTimeFunction) and their position. space_order : int,", "default src = src or self.geometry.src # Create a new receiver object to", ": Function, optional The time-constant inverse density. vp : Function or float, optional", "P-wave quality factor. b : Function, optional The time-constant inverse density. vp :", "op_fwd(self, save=None): \"\"\"Cached operator for forward runs with buffered wavefield\"\"\" return ForwardOperator(self.model, save=save,", "geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) def forward(self, src=None, rec=None, v=None, r=None, p=None, qp=None,", "src or self.geometry.src # Create a new receiver object to store the result", "vp=None, qp=None, b=None, r=None, **kwargs): \"\"\" Adjoint modelling function that creates the necessary", "self.model.vp # Execute operator and return wavefield and receiver data if self.kernel ==", "Function or float, optional The time-constant velocity. save : bool, optional Whether or", "rec=rec, pa=pa, r=r, b=b, vp=vp, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) else: summary = self.op_adj().apply(src=srca,", "to store the result rec = rec or self.geometry.rec # Create all the", "pa or TimeFunction(name=\"pa\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r = r", "data # With Memory variable summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, r=r, b=b, vp=vp,", "dt=kwargs.pop('dt', self.dt), **kwargs) else: summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, vp=vp, b=b, qp=qp, dt=kwargs.pop('dt',", "r=None, p=None, qp=None, b=None, vp=None, save=None, **kwargs): \"\"\" Forward modelling function that creates", "devito.tools import memoized_meth from examples.seismic import PointSource from examples.seismic.viscoacoustic.operators import (ForwardOperator, AdjointOperator) class", "position. space_order : int, optional Order of the spatial stencil discretisation. Defaults to", "source location. va : VectorTimeFunction, optional The computed particle velocity. pa : TimeFunction,", "fields v, p, r save_t = src.nt if save else None if self.time_order", "va : VectorTimeFunction, optional The computed particle velocity. pa : TimeFunction, optional Stores", "r = r or TimeFunction(name=\"r\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) b = b or", "provided b = b or self.model.b qp = qp or self.model.qp # Pick", "rec, p, v, summary def adjoint(self, rec, srca=None, va=None, pa=None, vp=None, qp=None, b=None,", "factor. b : Function, optional The time-constant inverse density. vp : Function or", "factor. b : Function, optional The time-constant inverse density. r : TimeFunction, optional", "optional The computed memory variable. Returns ------- Adjoint source, wavefield and performance summary.", "Function or float, optional The time-constant velocity. qp : Function, optional The P-wave", "for k in v}) # Create the forward wavefield if not provided p", "summary. \"\"\" # Create a new adjoint source and receiver symbol srca =", "space_order=self.space_order, staggered=NODE) # Pick physical parameters from model unless explicitly provided b =", "receiver symbol srca = srca or PointSource(name='srca', grid=self.model.grid, time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions) if self.time_order ==", "save=None, **kwargs): \"\"\" Forward modelling function that creates the necessary data objects for", "space discretization for a given problem setup. Parameters ---------- model : Model Physical", "computed memory variable. p : TimeFunction, optional Stores the computed wavefield. qp :", "r=r, b=b, vp=vp, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) else: summary = self.op_adj().apply(src=srca, rec=rec, pa=pa,", "et al. (2014) viscoacoustic equation 'deng_mcmechan' - Deng and McMechan (2007) viscoacoustic equation", "variable. p : TimeFunction, optional Stores the computed wavefield. qp : Function, optional", "= model self.model._initialize_bcs(bcs=\"mask\") self.geometry = geometry self.space_order = space_order self.kernel = kernel self.time_order", "a new receiver object to store the result rec = rec or self.geometry.rec", "= vp or self.model.vp if self.kernel == 'sls': # Execute operator and return", "time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in v}) # Create the forward wavefield", "'sls': # Execute operator and return wavefield and receiver data # With Memory", "self.dt), **kwargs) return rec, p, v, summary def adjoint(self, rec, srca=None, va=None, pa=None,", "source, wavefield and performance summary. \"\"\" # Create a new adjoint source and", "SparseTimeFunction or array-like The receiver data. Please note that these act as the", "or VectorTimeFunction(name=\"v\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in v}) #", "time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Pick physical parameters from model unless explicitly provided b", "float, optional The time-constant velocity. qp : Function, optional The P-wave quality factor.", "forward wavefield if not provided p = p or TimeFunction(name=\"p\", grid=self.model.grid, save=save_t, time_order=self.time_order,", "run. srca : SparseTimeFunction or array-like The resulting data for the interpolated at", "term is read-only, so re-use the default src = src or self.geometry.src #", "Function, optional The time-constant inverse density. vp : Function or float, optional The", "Defaults to 4. kernel : selects a visco-acoustic equation from the options below:", "**self._kwargs) def forward(self, src=None, rec=None, v=None, r=None, p=None, qp=None, b=None, vp=None, save=None, **kwargs):", "p, r save_t = src.nt if save else None if self.time_order == 1:", "provided p = p or TimeFunction(name=\"p\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory", "a given problem setup. Parameters ---------- model : Model Physical model with domain", "in v}) # Create the forward wavefield if not provided p = p", "op_adj(self): \"\"\"Cached operator for adjoint runs\"\"\" return AdjointOperator(self.model, save=None, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order,", "domain parameters. geometry : AcquisitionGeometry Geometry object that contains the source (SparseTimeFunction) and", "operators for seismic inversion problems and encapsulates the time and space discretization for", "# Create all the fields v, p, r save_t = src.nt if save", "= p or TimeFunction(name=\"p\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r", "optional The computed particle velocity. pa : TimeFunction, optional Stores the computed wavefield.", "Stores the computed wavefield. vp : Function or float, optional The time-constant velocity.", "1st order - Blanch and Symes (1995) / Dutta and Schuster (2014) viscoacoustic", "order - Bai et al. (2014) viscoacoustic equation 'ren' - Ren et al.", "and return wavefield and receiver data if self.kernel == 'sls': # Execute operator", "With Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, r=r, p=p, b=b, vp=vp, dt=kwargs.pop('dt',", "import memoized_meth from examples.seismic import PointSource from examples.seismic.viscoacoustic.operators import (ForwardOperator, AdjointOperator) class ViscoacousticWaveSolver(object):", "AdjointOperator) class ViscoacousticWaveSolver(object): \"\"\" Solver object that provides operators for seismic inversion problems", "model : Model Physical model with domain parameters. geometry : AcquisitionGeometry Geometry object", "dt(self): return self.model.critical_dt @memoized_meth def op_fwd(self, save=None): \"\"\"Cached operator for forward runs with", "term in the adjoint run. srca : SparseTimeFunction or array-like The resulting data", "viscoacoustic equation Defaults to 'sls' 2nd order. \"\"\" def __init__(self, model, geometry, space_order=4,", "optional Stores the computed wavefield. qp : Function, optional The P-wave quality factor.", "# Execute operator and return wavefield and receiver data # With Memory variable", "r=None, **kwargs): \"\"\" Adjoint modelling function that creates the necessary data objects for", "Parameters ---------- src : SparseTimeFunction or array_like, optional Time series data for the", "or array_like, optional The interpolated receiver data. v : VectorTimeFunction, optional The computed", "rec : SparseTimeFunction or array_like, optional The interpolated receiver data. v : VectorTimeFunction,", "interpolated at the original source location. va : VectorTimeFunction, optional The computed particle", "injected source term. rec : SparseTimeFunction or array_like, optional The interpolated receiver data.", "model with domain parameters. geometry : AcquisitionGeometry Geometry object that contains the source", "computed wavefield. qp : Function, optional The P-wave quality factor. b : Function,", "examples.seismic.viscoacoustic.operators import (ForwardOperator, AdjointOperator) class ViscoacousticWaveSolver(object): \"\"\" Solver object that provides operators for", "- Bai et al. (2014) viscoacoustic equation 'ren' - Ren et al. (2014)", "creates the necessary data objects for running an adjoint modelling operator. Parameters ----------", "Execute operator and return wavefield and receiver data if self.kernel == 'sls': #", "velocity. qp : Function, optional The P-wave quality factor. b : Function, optional", "space_order=4, kernel='sls', time_order=2, **kwargs): self.model = model self.model._initialize_bcs(bcs=\"mask\") self.geometry = geometry self.space_order =", "receiver data # Without Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, p=p, b=b,", "The computed memory variable. p : TimeFunction, optional Stores the computed wavefield. qp", "act as the source term in the adjoint run. srca : SparseTimeFunction or", "or PointSource(name='srca', grid=self.model.grid, time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions) if self.time_order == 1: va = va or", "vp from model unless explicitly provided vp = vp or self.model.vp # Execute", "so re-use the default src = src or self.geometry.src # Create a new", "**kwargs) return rec, p, v, summary def adjoint(self, rec, srca=None, va=None, pa=None, vp=None,", "rec, srca=None, va=None, pa=None, vp=None, qp=None, b=None, r=None, **kwargs): \"\"\" Adjoint modelling function", "- Blanch and Symes (1995) / Dutta and Schuster (2014) viscoacoustic equation 2nd", "self.op_adj().apply(src=srca, rec=rec, pa=pa, vp=vp, b=b, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) return srca, pa, va,", "with domain parameters. geometry : AcquisitionGeometry Geometry object that contains the source (SparseTimeFunction)", "PointSource from examples.seismic.viscoacoustic.operators import (ForwardOperator, AdjointOperator) class ViscoacousticWaveSolver(object): \"\"\" Solver object that provides", "computed particle velocity. r : TimeFunction, optional The computed memory variable. p :", "p=None, qp=None, b=None, vp=None, save=None, **kwargs): \"\"\" Forward modelling function that creates the", "The time-constant inverse density. r : TimeFunction, optional The computed memory variable. Returns", "AcquisitionGeometry Geometry object that contains the source (SparseTimeFunction) and receivers (SparseTimeFunction) and their", "re-use the default src = src or self.geometry.src # Create a new receiver", "summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, r=r, b=b, vp=vp, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) else:", "explicitly provided vp = vp or self.model.vp # Execute operator and return wavefield", "# Create a new receiver object to store the result rec = rec", "v : VectorTimeFunction, optional The computed particle velocity. r : TimeFunction, optional The", "Create all the fields v, p, r save_t = src.nt if save else", "in the adjoint run. srca : SparseTimeFunction or array-like The resulting data for", "adjoint runs\"\"\" return AdjointOperator(self.model, save=None, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) def forward(self, src=None,", ": Model Physical model with domain parameters. geometry : AcquisitionGeometry Geometry object that", "(2007) viscoacoustic equation Defaults to 'sls' 2nd order. \"\"\" def __init__(self, model, geometry,", "= va or VectorTimeFunction(name=\"va\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in va})", "src : SparseTimeFunction or array_like, optional Time series data for the injected source", "these act as the source term in the adjoint run. srca : SparseTimeFunction", "runs with buffered wavefield\"\"\" return ForwardOperator(self.model, save=save, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) @memoized_meth", "original source location. va : VectorTimeFunction, optional The computed particle velocity. pa :", ": TimeFunction, optional Stores the computed wavefield. qp : Function, optional The P-wave", "note that these act as the source term in the adjoint run. srca", "self.space_order = space_order self.kernel = kernel self.time_order = time_order self._kwargs = kwargs @property", "or float, optional The time-constant velocity. save : bool, optional Whether or not", "b or self.model.b qp = qp or self.model.qp # Pick vp from model", "qp=qp, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) return rec, p, v, summary def", "source term in the adjoint run. srca : SparseTimeFunction or array-like The resulting", "the time and space discretization for a given problem setup. Parameters ---------- model", "geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) @memoized_meth def op_adj(self): \"\"\"Cached operator for adjoint runs\"\"\"", "space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) def forward(self, src=None, rec=None, v=None, r=None, p=None, qp=None, b=None,", "from devito import VectorTimeFunction, TimeFunction, NODE from devito.tools import memoized_meth from examples.seismic import", "geometry self.space_order = space_order self.kernel = kernel self.time_order = time_order self._kwargs = kwargs", "vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) return rec, p, v, summary def adjoint(self, rec, srca=None,", "b : Function, optional The time-constant inverse density. r : TimeFunction, optional The", "space_order=self.space_order) kwargs.update({k.name: k for k in v}) # Create the forward wavefield if", "forward(self, src=None, rec=None, v=None, r=None, p=None, qp=None, b=None, vp=None, save=None, **kwargs): \"\"\" Forward", "from examples.seismic.viscoacoustic.operators import (ForwardOperator, AdjointOperator) class ViscoacousticWaveSolver(object): \"\"\" Solver object that provides operators", "== 1: va = va or VectorTimeFunction(name=\"va\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for", "for k in va}) pa = pa or TimeFunction(name=\"pa\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE)", "Execute operator and return wavefield and receiver data # Without Memory variable summary", "staggered=NODE) # Memory variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE)", "else None if self.time_order == 1: v = v or VectorTimeFunction(name=\"v\", grid=self.model.grid, save=save_t,", "grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) b = b or self.model.b qp = qp or", "save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Pick physical parameters from model unless explicitly provided", "performance summary. \"\"\" # Create a new adjoint source and receiver symbol srca", "self.op_fwd(save).apply(src=src, rec=rec, qp=qp, r=r, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) else: # Execute", "velocity. r : TimeFunction, optional The computed memory variable. p : TimeFunction, optional", "source term. rec : SparseTimeFunction or array_like, optional The interpolated receiver data. v", "v, p, r save_t = src.nt if save else None if self.time_order ==", ": TimeFunction, optional The computed memory variable. p : TimeFunction, optional Stores the", "(2014) viscoacoustic equation 2nd order - Bai et al. (2014) viscoacoustic equation 'ren'", "an adjoint modelling operator. Parameters ---------- rec : SparseTimeFunction or array-like The receiver", ": SparseTimeFunction or array-like The resulting data for the interpolated at the original", "src.nt if save else None if self.time_order == 1: v = v or", "save the entire (unrolled) wavefield. Returns ------- Receiver, wavefield and performance summary \"\"\"", "= qp or self.model.qp # Pick vp from model unless explicitly provided vp", "pa=None, vp=None, qp=None, b=None, r=None, **kwargs): \"\"\" Adjoint modelling function that creates the", "v = v or VectorTimeFunction(name=\"v\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k", "P-wave quality factor. b : Function, optional The time-constant inverse density. r :", "optional Order of the spatial stencil discretisation. Defaults to 4. kernel : selects", "inverse density. vp : Function or float, optional The time-constant velocity. save :", "particle velocity. pa : TimeFunction, optional Stores the computed wavefield. vp : Function", "(unrolled) wavefield. Returns ------- Receiver, wavefield and performance summary \"\"\" # Source term", "self.time_order == 1: v = v or VectorTimeFunction(name=\"v\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name:", "\"\"\" Forward modelling function that creates the necessary data objects for running a", "and return wavefield and receiver data # With Memory variable summary = self.op_adj().apply(src=srca,", "rec=rec, qp=qp, r=r, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) else: # Execute operator", "= rec or self.geometry.rec # Create all the fields v, p, r save_t", ": bool, optional Whether or not to save the entire (unrolled) wavefield. Returns", "# Execute operator and return wavefield and receiver data if self.kernel == 'sls':", "inverse density. r : TimeFunction, optional The computed memory variable. Returns ------- Adjoint", "the necessary data objects for running an adjoint modelling operator. Parameters ---------- rec", "selects a visco-acoustic equation from the options below: 'sls' (Standard Linear Solid) :", "data objects for running an adjoint modelling operator. Parameters ---------- rec : SparseTimeFunction", "viscoacoustic equation 'ren' - Ren et al. (2014) viscoacoustic equation 'deng_mcmechan' - Deng", "With Memory variable summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, r=r, b=b, vp=vp, qp=qp, dt=kwargs.pop('dt',", "b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) return rec, p, v, summary def adjoint(self, rec,", ": SparseTimeFunction or array_like, optional The interpolated receiver data. v : VectorTimeFunction, optional", "= kwargs @property def dt(self): return self.model.critical_dt @memoized_meth def op_fwd(self, save=None): \"\"\"Cached operator", "or TimeFunction(name=\"r\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) b = b or self.model.b qp =", "time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions) if self.time_order == 1: va = va or VectorTimeFunction(name=\"va\", grid=self.model.grid, time_order=self.time_order,", "modelling operator. Parameters ---------- src : SparseTimeFunction or array_like, optional Time series data", "srca or PointSource(name='srca', grid=self.model.grid, time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions) if self.time_order == 1: va = va", "stencil discretisation. Defaults to 4. kernel : selects a visco-acoustic equation from the", "and receiver data # Without Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, p=p,", "optional Stores the computed wavefield. vp : Function or float, optional The time-constant", "receivers (SparseTimeFunction) and their position. space_order : int, optional Order of the spatial", "running a forward modelling operator. Parameters ---------- src : SparseTimeFunction or array_like, optional", "adjoint run. srca : SparseTimeFunction or array-like The resulting data for the interpolated", "pa=pa, r=r, b=b, vp=vp, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) else: summary = self.op_adj().apply(src=srca, rec=rec,", "# Without Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, p=p, b=b, vp=vp, dt=kwargs.pop('dt',", "summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, vp=vp, b=b, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) return srca,", "The time-constant inverse density. vp : Function or float, optional The time-constant velocity.", "- Ren et al. (2014) viscoacoustic equation 'deng_mcmechan' - Deng and McMechan (2007)", "Time series data for the injected source term. rec : SparseTimeFunction or array_like,", "for running an adjoint modelling operator. Parameters ---------- rec : SparseTimeFunction or array-like", "object that contains the source (SparseTimeFunction) and receivers (SparseTimeFunction) and their position. space_order", "term. rec : SparseTimeFunction or array_like, optional The interpolated receiver data. v :", "save : bool, optional Whether or not to save the entire (unrolled) wavefield.", "kwargs.update({k.name: k for k in va}) pa = pa or TimeFunction(name=\"pa\", grid=self.model.grid, time_order=self.time_order,", "computed memory variable. Returns ------- Adjoint source, wavefield and performance summary. \"\"\" #", ": selects a visco-acoustic equation from the options below: 'sls' (Standard Linear Solid)", "series data for the injected source term. rec : SparseTimeFunction or array_like, optional", "or TimeFunction(name=\"p\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r = r", "pa = pa or TimeFunction(name=\"pa\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r", "to save the entire (unrolled) wavefield. Returns ------- Receiver, wavefield and performance summary", "the source (SparseTimeFunction) and receivers (SparseTimeFunction) and their position. space_order : int, optional", "Returns ------- Receiver, wavefield and performance summary \"\"\" # Source term is read-only,", "below: 'sls' (Standard Linear Solid) : 1st order - Blanch and Symes (1995)", "== 'sls': # Execute operator and return wavefield and receiver data # With", "receiver data. v : VectorTimeFunction, optional The computed particle velocity. r : TimeFunction,", "(2014) viscoacoustic equation 'deng_mcmechan' - Deng and McMechan (2007) viscoacoustic equation Defaults to", "optional The time-constant inverse density. r : TimeFunction, optional The computed memory variable.", "operator. Parameters ---------- rec : SparseTimeFunction or array-like The receiver data. Please note", "------- Receiver, wavefield and performance summary \"\"\" # Source term is read-only, so", "Schuster (2014) viscoacoustic equation 2nd order - Bai et al. (2014) viscoacoustic equation", "optional The P-wave quality factor. b : Function, optional The time-constant inverse density.", "operator. Parameters ---------- src : SparseTimeFunction or array_like, optional Time series data for", "Stores the computed wavefield. qp : Function, optional The P-wave quality factor. b", "self.geometry.rec # Create all the fields v, p, r save_t = src.nt if", "if self.time_order == 1: va = va or VectorTimeFunction(name=\"va\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name:", "rec=rec, qp=qp, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) return rec, p, v, summary", "srca = srca or PointSource(name='srca', grid=self.model.grid, time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions) if self.time_order == 1: va", "Linear Solid) : 1st order - Blanch and Symes (1995) / Dutta and", "that these act as the source term in the adjoint run. srca :", "objects for running an adjoint modelling operator. Parameters ---------- rec : SparseTimeFunction or", "from model unless explicitly provided b = b or self.model.b qp = qp", "TimeFunction(name=\"r\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) b = b or self.model.b qp = qp", "or TimeFunction(name=\"r\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Pick physical parameters from model", "def adjoint(self, rec, srca=None, va=None, pa=None, vp=None, qp=None, b=None, r=None, **kwargs): \"\"\" Adjoint", "r : TimeFunction, optional The computed memory variable. Returns ------- Adjoint source, wavefield", "return wavefield and receiver data # Without Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec,", "given problem setup. Parameters ---------- model : Model Physical model with domain parameters.", "p, v, summary def adjoint(self, rec, srca=None, va=None, pa=None, vp=None, qp=None, b=None, r=None,", "TimeFunction(name=\"pa\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r = r or TimeFunction(name=\"r\",", "vp or self.model.vp if self.kernel == 'sls': # Execute operator and return wavefield", "order - Blanch and Symes (1995) / Dutta and Schuster (2014) viscoacoustic equation", "Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs)", "Returns ------- Adjoint source, wavefield and performance summary. \"\"\" # Create a new", "parameters. geometry : AcquisitionGeometry Geometry object that contains the source (SparseTimeFunction) and receivers", "from examples.seismic import PointSource from examples.seismic.viscoacoustic.operators import (ForwardOperator, AdjointOperator) class ViscoacousticWaveSolver(object): \"\"\" Solver", "The interpolated receiver data. v : VectorTimeFunction, optional The computed particle velocity. r", ": TimeFunction, optional The computed memory variable. Returns ------- Adjoint source, wavefield and" ]
[ "') itemSetList.append(list(map(int, cates))) def myApriori(): te = TransactionEncoder() te_ary = te.fit(itemSetList).transform(itemSetList) df =", "TransactionEncoder() te_ary = te.fit(itemSetList).transform(itemSetList) df = pd.DataFrame(te_ary, columns=te.columns_) return df def dataInit(): if", "= line.replace('\\n', '') cates = line.split(' ') itemSetList.append(list(map(int, cates))) def myApriori(): te =", "as f: for k, v in tqdm(user_category.items()): f.write(' '.join(sorted(list(map(str, v))))+'\\n') if __name__ ==", "te_ary = te.fit(itemSetList).transform(itemSetList) df = pd.DataFrame(te_ary, columns=te.columns_) return df def dataInit(): if os.path.exists(os.path.join(dataPath,", "desc=\"category data generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID']) with open(os.path.join(dataPath, \"aprioriData.csv\"), 'w+') as f: for k, v", "loadDataSet() df = myApriori() frequent_itemsets = apriori(df, min_support=0.0035, use_colnames=True) frequent_itemsets['length'] = frequent_itemsets['itemsets'].apply(lambda x:", "pd.DataFrame(te_ary, columns=te.columns_) return df def dataInit(): if os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")): return df = pd.read_csv(\"data/static/static.csv\")", "tqdm import tqdm from collections import defaultdict from mlxtend.preprocessing import TransactionEncoder from mlxtend.frequent_patterns", "= pd.DataFrame(te_ary, columns=te.columns_) return df def dataInit(): if os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")): return df =", "total=df.shape[0], desc=\"category data generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID']) with open(os.path.join(dataPath, \"aprioriData.csv\"), 'w+') as f: for k,", "tqdm(df.iterrows(), total=df.shape[0], desc=\"category data generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID']) with open(os.path.join(dataPath, \"aprioriData.csv\"), 'w+') as f: for", "'w+') as f: for k, v in tqdm(user_category.items()): f.write(' '.join(sorted(list(map(str, v))))+'\\n') if __name__", "with open(os.path.join(dataPath, \"aprioriData.csv\"), 'r') as f: for line in f.readlines(): line = line.replace('\\n',", "frequent_itemsets = apriori(df, min_support=0.0035, use_colnames=True) frequent_itemsets['length'] = frequent_itemsets['itemsets'].apply(lambda x: len(x)) print(frequent_itemsets[(frequent_itemsets['length'] >= 2)])", "itemSetList = [] def loadDataSet(): with open(os.path.join(dataPath, \"aprioriData.csv\"), 'r') as f: for line", "= [] def loadDataSet(): with open(os.path.join(dataPath, \"aprioriData.csv\"), 'r') as f: for line in", "v in tqdm(user_category.items()): f.write(' '.join(sorted(list(map(str, v))))+'\\n') if __name__ == '__main__': dataInit() loadDataSet() df", "dataInit(): if os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")): return df = pd.read_csv(\"data/static/static.csv\") user_category = defaultdict(set) for idx,", "row in tqdm(df.iterrows(), total=df.shape[0], desc=\"category data generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID']) with open(os.path.join(dataPath, \"aprioriData.csv\"), 'w+') as", "mlxtend.frequent_patterns import apriori dataPath = \"data/static\" itemSetList = [] def loadDataSet(): with open(os.path.join(dataPath,", "apriori dataPath = \"data/static\" itemSetList = [] def loadDataSet(): with open(os.path.join(dataPath, \"aprioriData.csv\"), 'r')", "f: for k, v in tqdm(user_category.items()): f.write(' '.join(sorted(list(map(str, v))))+'\\n') if __name__ == '__main__':", "line.replace('\\n', '') cates = line.split(' ') itemSetList.append(list(map(int, cates))) def myApriori(): te = TransactionEncoder()", "from mlxtend.frequent_patterns import apriori dataPath = \"data/static\" itemSetList = [] def loadDataSet(): with", "for k, v in tqdm(user_category.items()): f.write(' '.join(sorted(list(map(str, v))))+'\\n') if __name__ == '__main__': dataInit()", "dataPath = \"data/static\" itemSetList = [] def loadDataSet(): with open(os.path.join(dataPath, \"aprioriData.csv\"), 'r') as", "import tqdm from collections import defaultdict from mlxtend.preprocessing import TransactionEncoder from mlxtend.frequent_patterns import", "mlxtend.preprocessing import TransactionEncoder from mlxtend.frequent_patterns import apriori dataPath = \"data/static\" itemSetList = []", "import TransactionEncoder from mlxtend.frequent_patterns import apriori dataPath = \"data/static\" itemSetList = [] def", "cates))) def myApriori(): te = TransactionEncoder() te_ary = te.fit(itemSetList).transform(itemSetList) df = pd.DataFrame(te_ary, columns=te.columns_)", "df def dataInit(): if os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")): return df = pd.read_csv(\"data/static/static.csv\") user_category = defaultdict(set)", "os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")): return df = pd.read_csv(\"data/static/static.csv\") user_category = defaultdict(set) for idx, row in", "user_category[row['USER_ID']].add(row['CATEGORY_ID']) with open(os.path.join(dataPath, \"aprioriData.csv\"), 'w+') as f: for k, v in tqdm(user_category.items()): f.write('", "'r') as f: for line in f.readlines(): line = line.replace('\\n', '') cates =", "for idx, row in tqdm(df.iterrows(), total=df.shape[0], desc=\"category data generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID']) with open(os.path.join(dataPath, \"aprioriData.csv\"),", "import pandas as pd import os from tqdm import tqdm from collections import", "return df = pd.read_csv(\"data/static/static.csv\") user_category = defaultdict(set) for idx, row in tqdm(df.iterrows(), total=df.shape[0],", "user_category = defaultdict(set) for idx, row in tqdm(df.iterrows(), total=df.shape[0], desc=\"category data generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID'])", "= pd.read_csv(\"data/static/static.csv\") user_category = defaultdict(set) for idx, row in tqdm(df.iterrows(), total=df.shape[0], desc=\"category data", "for line in f.readlines(): line = line.replace('\\n', '') cates = line.split(' ') itemSetList.append(list(map(int,", "tqdm(user_category.items()): f.write(' '.join(sorted(list(map(str, v))))+'\\n') if __name__ == '__main__': dataInit() loadDataSet() df = myApriori()", "from mlxtend.preprocessing import TransactionEncoder from mlxtend.frequent_patterns import apriori dataPath = \"data/static\" itemSetList =", "import os from tqdm import tqdm from collections import defaultdict from mlxtend.preprocessing import", "generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID']) with open(os.path.join(dataPath, \"aprioriData.csv\"), 'w+') as f: for k, v in tqdm(user_category.items()):", "= myApriori() frequent_itemsets = apriori(df, min_support=0.0035, use_colnames=True) frequent_itemsets['length'] = frequent_itemsets['itemsets'].apply(lambda x: len(x)) print(frequent_itemsets[(frequent_itemsets['length']", "pd.read_csv(\"data/static/static.csv\") user_category = defaultdict(set) for idx, row in tqdm(df.iterrows(), total=df.shape[0], desc=\"category data generate\"):", "in tqdm(df.iterrows(), total=df.shape[0], desc=\"category data generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID']) with open(os.path.join(dataPath, \"aprioriData.csv\"), 'w+') as f:", "pandas as pd import os from tqdm import tqdm from collections import defaultdict", "= line.split(' ') itemSetList.append(list(map(int, cates))) def myApriori(): te = TransactionEncoder() te_ary = te.fit(itemSetList).transform(itemSetList)", "df = pd.DataFrame(te_ary, columns=te.columns_) return df def dataInit(): if os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")): return df", "line.split(' ') itemSetList.append(list(map(int, cates))) def myApriori(): te = TransactionEncoder() te_ary = te.fit(itemSetList).transform(itemSetList) df", "= \"data/static\" itemSetList = [] def loadDataSet(): with open(os.path.join(dataPath, \"aprioriData.csv\"), 'r') as f:", "df = pd.read_csv(\"data/static/static.csv\") user_category = defaultdict(set) for idx, row in tqdm(df.iterrows(), total=df.shape[0], desc=\"category", "loadDataSet(): with open(os.path.join(dataPath, \"aprioriData.csv\"), 'r') as f: for line in f.readlines(): line =", "from tqdm import tqdm from collections import defaultdict from mlxtend.preprocessing import TransactionEncoder from", "tqdm from collections import defaultdict from mlxtend.preprocessing import TransactionEncoder from mlxtend.frequent_patterns import apriori", "os from tqdm import tqdm from collections import defaultdict from mlxtend.preprocessing import TransactionEncoder", "= te.fit(itemSetList).transform(itemSetList) df = pd.DataFrame(te_ary, columns=te.columns_) return df def dataInit(): if os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")):", "defaultdict(set) for idx, row in tqdm(df.iterrows(), total=df.shape[0], desc=\"category data generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID']) with open(os.path.join(dataPath,", "v))))+'\\n') if __name__ == '__main__': dataInit() loadDataSet() df = myApriori() frequent_itemsets = apriori(df,", "if __name__ == '__main__': dataInit() loadDataSet() df = myApriori() frequent_itemsets = apriori(df, min_support=0.0035,", "open(os.path.join(dataPath, \"aprioriData.csv\"), 'w+') as f: for k, v in tqdm(user_category.items()): f.write(' '.join(sorted(list(map(str, v))))+'\\n')", "f: for line in f.readlines(): line = line.replace('\\n', '') cates = line.split(' ')", "\"aprioriData.csv\"), 'w+') as f: for k, v in tqdm(user_category.items()): f.write(' '.join(sorted(list(map(str, v))))+'\\n') if", "myApriori(): te = TransactionEncoder() te_ary = te.fit(itemSetList).transform(itemSetList) df = pd.DataFrame(te_ary, columns=te.columns_) return df", "def myApriori(): te = TransactionEncoder() te_ary = te.fit(itemSetList).transform(itemSetList) df = pd.DataFrame(te_ary, columns=te.columns_) return", "as f: for line in f.readlines(): line = line.replace('\\n', '') cates = line.split('", "\"data/static\" itemSetList = [] def loadDataSet(): with open(os.path.join(dataPath, \"aprioriData.csv\"), 'r') as f: for", "as pd import os from tqdm import tqdm from collections import defaultdict from", "line = line.replace('\\n', '') cates = line.split(' ') itemSetList.append(list(map(int, cates))) def myApriori(): te", "data generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID']) with open(os.path.join(dataPath, \"aprioriData.csv\"), 'w+') as f: for k, v in", "import defaultdict from mlxtend.preprocessing import TransactionEncoder from mlxtend.frequent_patterns import apriori dataPath = \"data/static\"", "defaultdict from mlxtend.preprocessing import TransactionEncoder from mlxtend.frequent_patterns import apriori dataPath = \"data/static\" itemSetList", "== '__main__': dataInit() loadDataSet() df = myApriori() frequent_itemsets = apriori(df, min_support=0.0035, use_colnames=True) frequent_itemsets['length']", "collections import defaultdict from mlxtend.preprocessing import TransactionEncoder from mlxtend.frequent_patterns import apriori dataPath =", "def loadDataSet(): with open(os.path.join(dataPath, \"aprioriData.csv\"), 'r') as f: for line in f.readlines(): line", "pd import os from tqdm import tqdm from collections import defaultdict from mlxtend.preprocessing", "itemSetList.append(list(map(int, cates))) def myApriori(): te = TransactionEncoder() te_ary = te.fit(itemSetList).transform(itemSetList) df = pd.DataFrame(te_ary,", "def dataInit(): if os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")): return df = pd.read_csv(\"data/static/static.csv\") user_category = defaultdict(set) for", "df = myApriori() frequent_itemsets = apriori(df, min_support=0.0035, use_colnames=True) frequent_itemsets['length'] = frequent_itemsets['itemsets'].apply(lambda x: len(x))", "columns=te.columns_) return df def dataInit(): if os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")): return df = pd.read_csv(\"data/static/static.csv\") user_category", "'.join(sorted(list(map(str, v))))+'\\n') if __name__ == '__main__': dataInit() loadDataSet() df = myApriori() frequent_itemsets =", "\"aprioriData.csv\")): return df = pd.read_csv(\"data/static/static.csv\") user_category = defaultdict(set) for idx, row in tqdm(df.iterrows(),", "cates = line.split(' ') itemSetList.append(list(map(int, cates))) def myApriori(): te = TransactionEncoder() te_ary =", "return df def dataInit(): if os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")): return df = pd.read_csv(\"data/static/static.csv\") user_category =", "'__main__': dataInit() loadDataSet() df = myApriori() frequent_itemsets = apriori(df, min_support=0.0035, use_colnames=True) frequent_itemsets['length'] =", "f.readlines(): line = line.replace('\\n', '') cates = line.split(' ') itemSetList.append(list(map(int, cates))) def myApriori():", "f.write(' '.join(sorted(list(map(str, v))))+'\\n') if __name__ == '__main__': dataInit() loadDataSet() df = myApriori() frequent_itemsets", "k, v in tqdm(user_category.items()): f.write(' '.join(sorted(list(map(str, v))))+'\\n') if __name__ == '__main__': dataInit() loadDataSet()", "__name__ == '__main__': dataInit() loadDataSet() df = myApriori() frequent_itemsets = apriori(df, min_support=0.0035, use_colnames=True)", "import apriori dataPath = \"data/static\" itemSetList = [] def loadDataSet(): with open(os.path.join(dataPath, \"aprioriData.csv\"),", "myApriori() frequent_itemsets = apriori(df, min_support=0.0035, use_colnames=True) frequent_itemsets['length'] = frequent_itemsets['itemsets'].apply(lambda x: len(x)) print(frequent_itemsets[(frequent_itemsets['length'] >=", "from collections import defaultdict from mlxtend.preprocessing import TransactionEncoder from mlxtend.frequent_patterns import apriori dataPath", "in tqdm(user_category.items()): f.write(' '.join(sorted(list(map(str, v))))+'\\n') if __name__ == '__main__': dataInit() loadDataSet() df =", "with open(os.path.join(dataPath, \"aprioriData.csv\"), 'w+') as f: for k, v in tqdm(user_category.items()): f.write(' '.join(sorted(list(map(str,", "[] def loadDataSet(): with open(os.path.join(dataPath, \"aprioriData.csv\"), 'r') as f: for line in f.readlines():", "= defaultdict(set) for idx, row in tqdm(df.iterrows(), total=df.shape[0], desc=\"category data generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID']) with", "\"aprioriData.csv\"), 'r') as f: for line in f.readlines(): line = line.replace('\\n', '') cates", "te = TransactionEncoder() te_ary = te.fit(itemSetList).transform(itemSetList) df = pd.DataFrame(te_ary, columns=te.columns_) return df def", "line in f.readlines(): line = line.replace('\\n', '') cates = line.split(' ') itemSetList.append(list(map(int, cates)))", "= TransactionEncoder() te_ary = te.fit(itemSetList).transform(itemSetList) df = pd.DataFrame(te_ary, columns=te.columns_) return df def dataInit():", "in f.readlines(): line = line.replace('\\n', '') cates = line.split(' ') itemSetList.append(list(map(int, cates))) def", "dataInit() loadDataSet() df = myApriori() frequent_itemsets = apriori(df, min_support=0.0035, use_colnames=True) frequent_itemsets['length'] = frequent_itemsets['itemsets'].apply(lambda", "if os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")): return df = pd.read_csv(\"data/static/static.csv\") user_category = defaultdict(set) for idx, row", "idx, row in tqdm(df.iterrows(), total=df.shape[0], desc=\"category data generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID']) with open(os.path.join(dataPath, \"aprioriData.csv\"), 'w+')", "TransactionEncoder from mlxtend.frequent_patterns import apriori dataPath = \"data/static\" itemSetList = [] def loadDataSet():", "te.fit(itemSetList).transform(itemSetList) df = pd.DataFrame(te_ary, columns=te.columns_) return df def dataInit(): if os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")): return", "open(os.path.join(dataPath, \"aprioriData.csv\"), 'r') as f: for line in f.readlines(): line = line.replace('\\n', '')", "'') cates = line.split(' ') itemSetList.append(list(map(int, cates))) def myApriori(): te = TransactionEncoder() te_ary" ]
[ "= request_json['name'] headers = { 'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type' }", "<reponame>FuriKuri/faas-playground def hello_world(request): request_json = request.get_json() name = 'World' if request_json and 'name'", "'Content-Type' } return ('Hello ' + name + '! From GCP + Python',", "request_json['name'] headers = { 'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type' } return", "'name' in request_json: name = request_json['name'] headers = { 'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET,", "and 'name' in request_json: name = request_json['name'] headers = { 'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods':", "name = request_json['name'] headers = { 'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type'", "= request.get_json() name = 'World' if request_json and 'name' in request_json: name =", "= { 'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type' } return ('Hello '", "hello_world(request): request_json = request.get_json() name = 'World' if request_json and 'name' in request_json:", "headers = { 'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type' } return ('Hello", "if request_json and 'name' in request_json: name = request_json['name'] headers = { 'Access-Control-Allow-Origin':", "= 'World' if request_json and 'name' in request_json: name = request_json['name'] headers =", "return ('Hello ' + name + '! From GCP + Python', 200, headers)", "'Access-Control-Allow-Headers': 'Content-Type' } return ('Hello ' + name + '! From GCP +", "name = 'World' if request_json and 'name' in request_json: name = request_json['name'] headers", "'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type' } return ('Hello ' + name", "'World' if request_json and 'name' in request_json: name = request_json['name'] headers = {", "in request_json: name = request_json['name'] headers = { 'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET, POST',", "request_json = request.get_json() name = 'World' if request_json and 'name' in request_json: name", "def hello_world(request): request_json = request.get_json() name = 'World' if request_json and 'name' in", "'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type' } return ('Hello ' + name + '!", "request_json and 'name' in request_json: name = request_json['name'] headers = { 'Access-Control-Allow-Origin': 'https://furikuri.net',", "POST', 'Access-Control-Allow-Headers': 'Content-Type' } return ('Hello ' + name + '! From GCP", "{ 'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type' } return ('Hello ' +", "'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type' } return ('Hello ' + name +", "request_json: name = request_json['name'] headers = { 'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers':", "'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type' } return ('Hello ' + name + '! From", "} return ('Hello ' + name + '! From GCP + Python', 200,", "request.get_json() name = 'World' if request_json and 'name' in request_json: name = request_json['name']" ]
[ "from tonclient.client import TonClient from tonclient.types import Abi, CallSet, Signer, ClientConfig, \\ ParamsOfEncodeMessage,", "signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params = ParamsOfProcessMessage( message_encode_params=encode_params, send_events=False) async_core_client.processing.process_message(params=process_params) def tonos_punch(): send_grams( address='0:b5e9240fc2d2f1ff8cbb1d1dee7fb7cae155e5f6320e585fcc685698994a19a5')", "GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config = ClientConfig() client_config.network.endpoints = ['https://tonos.freeton.surf'] async_core_client = TonClient(config=client_config) sync_core_client", "= ParamsOfEncodeMessage( abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params = ParamsOfProcessMessage( message_encode_params=encode_params, send_events=False) async_core_client.processing.process_message(params=process_params) def", "from tonclient.types import Abi, CallSet, Signer, ClientConfig, \\ ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR = os.path.dirname(__file__)", "async_core_client = TonClient(config=client_config) sync_core_client = TonClient(config=client_config, is_core_async=False) def send_grams(address: str): giver_abi = Abi.from_path(", "os from tonclient.client import TonClient from tonclient.types import Abi, CallSet, Signer, ClientConfig, \\", "'samples') GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config = ClientConfig() client_config.network.endpoints = ['https://tonos.freeton.surf'] async_core_client = TonClient(config=client_config)", "call_set = CallSet( function_name='grant', input={'dest': address}) encode_params = ParamsOfEncodeMessage( abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set)", "encode_params = ParamsOfEncodeMessage( abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params = ParamsOfProcessMessage( message_encode_params=encode_params, send_events=False) async_core_client.processing.process_message(params=process_params)", "os.path.dirname(__file__) SAMPLES_DIR = os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config = ClientConfig() client_config.network.endpoints =", "send_grams(address: str): giver_abi = Abi.from_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set = CallSet( function_name='grant', input={'dest': address})", "ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR = os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config", "import Abi, CallSet, Signer, ClientConfig, \\ ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR =", "client_config = ClientConfig() client_config.network.endpoints = ['https://tonos.freeton.surf'] async_core_client = TonClient(config=client_config) sync_core_client = TonClient(config=client_config, is_core_async=False)", "tonclient.client import TonClient from tonclient.types import Abi, CallSet, Signer, ClientConfig, \\ ParamsOfEncodeMessage, ParamsOfProcessMessage", "BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR = os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config = ClientConfig()", "is_core_async=False) def send_grams(address: str): giver_abi = Abi.from_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set = CallSet( function_name='grant',", "CallSet, Signer, ClientConfig, \\ ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR = os.path.join(BASE_DIR, 'samples')", "['https://tonos.freeton.surf'] async_core_client = TonClient(config=client_config) sync_core_client = TonClient(config=client_config, is_core_async=False) def send_grams(address: str): giver_abi =", "= Abi.from_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set = CallSet( function_name='grant', input={'dest': address}) encode_params = ParamsOfEncodeMessage(", "Abi, CallSet, Signer, ClientConfig, \\ ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR = os.path.join(BASE_DIR,", "path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set = CallSet( function_name='grant', input={'dest': address}) encode_params = ParamsOfEncodeMessage( abi=giver_abi, signer=Signer.NoSigner(),", "Abi.from_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set = CallSet( function_name='grant', input={'dest': address}) encode_params = ParamsOfEncodeMessage( abi=giver_abi,", "sync_core_client = TonClient(config=client_config, is_core_async=False) def send_grams(address: str): giver_abi = Abi.from_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set", "CallSet( function_name='grant', input={'dest': address}) encode_params = ParamsOfEncodeMessage( abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params =", "ClientConfig, \\ ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR = os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS =", "TonClient(config=client_config, is_core_async=False) def send_grams(address: str): giver_abi = Abi.from_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set = CallSet(", "giver_abi = Abi.from_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set = CallSet( function_name='grant', input={'dest': address}) encode_params =", "= os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config = ClientConfig() client_config.network.endpoints = ['https://tonos.freeton.surf'] async_core_client", "os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config = ClientConfig() client_config.network.endpoints = ['https://tonos.freeton.surf'] async_core_client =", "= ClientConfig() client_config.network.endpoints = ['https://tonos.freeton.surf'] async_core_client = TonClient(config=client_config) sync_core_client = TonClient(config=client_config, is_core_async=False) def", "def send_grams(address: str): giver_abi = Abi.from_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set = CallSet( function_name='grant', input={'dest':", "= CallSet( function_name='grant', input={'dest': address}) encode_params = ParamsOfEncodeMessage( abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params", "input={'dest': address}) encode_params = ParamsOfEncodeMessage( abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params = ParamsOfProcessMessage( message_encode_params=encode_params,", "= ['https://tonos.freeton.surf'] async_core_client = TonClient(config=client_config) sync_core_client = TonClient(config=client_config, is_core_async=False) def send_grams(address: str): giver_abi", "= os.path.dirname(__file__) SAMPLES_DIR = os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config = ClientConfig() client_config.network.endpoints", "Signer, ClientConfig, \\ ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR = os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS", "ParamsOfProcessMessage BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR = os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config =", "ClientConfig() client_config.network.endpoints = ['https://tonos.freeton.surf'] async_core_client = TonClient(config=client_config) sync_core_client = TonClient(config=client_config, is_core_async=False) def send_grams(address:", "tonclient.types import Abi, CallSet, Signer, ClientConfig, \\ ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR", "SAMPLES_DIR = os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config = ClientConfig() client_config.network.endpoints = ['https://tonos.freeton.surf']", "TonClient from tonclient.types import Abi, CallSet, Signer, ClientConfig, \\ ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR =", "'Giver.abi.json')) call_set = CallSet( function_name='grant', input={'dest': address}) encode_params = ParamsOfEncodeMessage( abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS,", "function_name='grant', input={'dest': address}) encode_params = ParamsOfEncodeMessage( abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params = ParamsOfProcessMessage(", "= TonClient(config=client_config, is_core_async=False) def send_grams(address: str): giver_abi = Abi.from_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set =", "\\ ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR = os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23'", "'0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config = ClientConfig() client_config.network.endpoints = ['https://tonos.freeton.surf'] async_core_client = TonClient(config=client_config) sync_core_client = TonClient(config=client_config,", "client_config.network.endpoints = ['https://tonos.freeton.surf'] async_core_client = TonClient(config=client_config) sync_core_client = TonClient(config=client_config, is_core_async=False) def send_grams(address: str):", "address}) encode_params = ParamsOfEncodeMessage( abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params = ParamsOfProcessMessage( message_encode_params=encode_params, send_events=False)", "<filename>tonclient/test/helpers.py<gh_stars>10-100 import os from tonclient.client import TonClient from tonclient.types import Abi, CallSet, Signer,", "import TonClient from tonclient.types import Abi, CallSet, Signer, ClientConfig, \\ ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR", "= TonClient(config=client_config) sync_core_client = TonClient(config=client_config, is_core_async=False) def send_grams(address: str): giver_abi = Abi.from_path( path=os.path.join(SAMPLES_DIR,", "abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params = ParamsOfProcessMessage( message_encode_params=encode_params, send_events=False) async_core_client.processing.process_message(params=process_params) def tonos_punch(): send_grams(", "TonClient(config=client_config) sync_core_client = TonClient(config=client_config, is_core_async=False) def send_grams(address: str): giver_abi = Abi.from_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json'))", "str): giver_abi = Abi.from_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set = CallSet( function_name='grant', input={'dest': address}) encode_params", "ParamsOfEncodeMessage( abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params = ParamsOfProcessMessage( message_encode_params=encode_params, send_events=False) async_core_client.processing.process_message(params=process_params) def tonos_punch():", "import os from tonclient.client import TonClient from tonclient.types import Abi, CallSet, Signer, ClientConfig,", "= '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config = ClientConfig() client_config.network.endpoints = ['https://tonos.freeton.surf'] async_core_client = TonClient(config=client_config) sync_core_client =" ]
[ "'/test_i18n': return s.upper() return s i18n.gettext = gettext def test_does_translations(app): \"\"\"Callback interface is", "we test for request path that only functions from this module could set", "# so we test for request path that only functions from this module", "== '/test_i18n': return s.upper() return s i18n.gettext = gettext def test_does_translations(app): \"\"\"Callback interface", "from flask import request from flask_kajiki import render_template # N. B. settting i18n.gettext", "return s i18n.gettext = gettext def test_does_translations(app): \"\"\"Callback interface is able to inject", "request from flask_kajiki import render_template # N. B. settting i18n.gettext would affect tests", "s.upper() return s i18n.gettext = gettext def test_does_translations(app): \"\"\"Callback interface is able to", "could set def gettext(s): if request.path == '/test_i18n': return s.upper() return s i18n.gettext", "app.test_request_context(path='/test_i18n'): rendered = render_template('i18n.html') # TODO DOCTYPE; see also render_args expected = '<p>HELLO!</p>'", "set def gettext(s): if request.path == '/test_i18n': return s.upper() return s i18n.gettext =", "from kajiki import i18n from flask import request from flask_kajiki import render_template #", "this module could set def gettext(s): if request.path == '/test_i18n': return s.upper() return", "flask_kajiki import render_template # N. B. settting i18n.gettext would affect tests from all", "i18n from flask import request from flask_kajiki import render_template # N. B. settting", "# N. B. settting i18n.gettext would affect tests from all modules, # so", "from all modules, # so we test for request path that only functions", "s i18n.gettext = gettext def test_does_translations(app): \"\"\"Callback interface is able to inject Translator", "to inject Translator filter\"\"\" with app.test_request_context(path='/test_i18n'): rendered = render_template('i18n.html') # TODO DOCTYPE; see", "so we test for request path that only functions from this module could", "for request path that only functions from this module could set def gettext(s):", "= gettext def test_does_translations(app): \"\"\"Callback interface is able to inject Translator filter\"\"\" with", "import request from flask_kajiki import render_template # N. B. settting i18n.gettext would affect", "from this module could set def gettext(s): if request.path == '/test_i18n': return s.upper()", "# TODO DOCTYPE; see also render_args expected = '<p>HELLO!</p>' assert rendered == expected", "is able to inject Translator filter\"\"\" with app.test_request_context(path='/test_i18n'): rendered = render_template('i18n.html') # TODO", "B. settting i18n.gettext would affect tests from all modules, # so we test", "with app.test_request_context(path='/test_i18n'): rendered = render_template('i18n.html') # TODO DOCTYPE; see also render_args expected =", "\"\"\"Callback interface is able to inject Translator filter\"\"\" with app.test_request_context(path='/test_i18n'): rendered = render_template('i18n.html')", "Translator filter\"\"\" with app.test_request_context(path='/test_i18n'): rendered = render_template('i18n.html') # TODO DOCTYPE; see also render_args", "import render_template # N. B. settting i18n.gettext would affect tests from all modules,", "test_does_translations(app): \"\"\"Callback interface is able to inject Translator filter\"\"\" with app.test_request_context(path='/test_i18n'): rendered =", "= render_template('i18n.html') # TODO DOCTYPE; see also render_args expected = '<p>HELLO!</p>' assert rendered", "rendered = render_template('i18n.html') # TODO DOCTYPE; see also render_args expected = '<p>HELLO!</p>' assert", "from flask_kajiki import render_template # N. B. settting i18n.gettext would affect tests from", "test for request path that only functions from this module could set def", "that only functions from this module could set def gettext(s): if request.path ==", "only functions from this module could set def gettext(s): if request.path == '/test_i18n':", "i18n.gettext would affect tests from all modules, # so we test for request", "would affect tests from all modules, # so we test for request path", "functions from this module could set def gettext(s): if request.path == '/test_i18n': return", "path that only functions from this module could set def gettext(s): if request.path", "interface is able to inject Translator filter\"\"\" with app.test_request_context(path='/test_i18n'): rendered = render_template('i18n.html') #", "able to inject Translator filter\"\"\" with app.test_request_context(path='/test_i18n'): rendered = render_template('i18n.html') # TODO DOCTYPE;", "filter\"\"\" with app.test_request_context(path='/test_i18n'): rendered = render_template('i18n.html') # TODO DOCTYPE; see also render_args expected", "module could set def gettext(s): if request.path == '/test_i18n': return s.upper() return s", "render_template # N. B. settting i18n.gettext would affect tests from all modules, #", "N. B. settting i18n.gettext would affect tests from all modules, # so we", "modules, # so we test for request path that only functions from this", "affect tests from all modules, # so we test for request path that", "tests from all modules, # so we test for request path that only", "def gettext(s): if request.path == '/test_i18n': return s.upper() return s i18n.gettext = gettext", "kajiki import i18n from flask import request from flask_kajiki import render_template # N.", "def test_does_translations(app): \"\"\"Callback interface is able to inject Translator filter\"\"\" with app.test_request_context(path='/test_i18n'): rendered", "gettext def test_does_translations(app): \"\"\"Callback interface is able to inject Translator filter\"\"\" with app.test_request_context(path='/test_i18n'):", "gettext(s): if request.path == '/test_i18n': return s.upper() return s i18n.gettext = gettext def", "request.path == '/test_i18n': return s.upper() return s i18n.gettext = gettext def test_does_translations(app): \"\"\"Callback", "flask import request from flask_kajiki import render_template # N. B. settting i18n.gettext would", "all modules, # so we test for request path that only functions from", "request path that only functions from this module could set def gettext(s): if", "if request.path == '/test_i18n': return s.upper() return s i18n.gettext = gettext def test_does_translations(app):", "import i18n from flask import request from flask_kajiki import render_template # N. B.", "render_template('i18n.html') # TODO DOCTYPE; see also render_args expected = '<p>HELLO!</p>' assert rendered ==", "i18n.gettext = gettext def test_does_translations(app): \"\"\"Callback interface is able to inject Translator filter\"\"\"", "return s.upper() return s i18n.gettext = gettext def test_does_translations(app): \"\"\"Callback interface is able", "inject Translator filter\"\"\" with app.test_request_context(path='/test_i18n'): rendered = render_template('i18n.html') # TODO DOCTYPE; see also", "settting i18n.gettext would affect tests from all modules, # so we test for" ]
[ "else: w_scale, h_scale = scale_factor[0], scale_factor[1] img_h = np.round(ori_shape[0] * h_scale.item()).astype( np.int32) img_w", "- y0) * 2 - 1 img_x = (img_x - x0) / (x1", "shape (n, 4/5) det_labels (Tensor): shape (n, ) img_shape (Tensor): shape (3, )", "mask_targets @force_fp32(apply_to=('mask_pred', )) def loss(self, mask_pred, mask_targets, labels): loss = dict() if mask_pred.size(0)", "bboxes / scale_factor N = len(mask_pred) # The actual implementation split the input", "x0_int, x1_int, device=device, dtype=torch.float32) + 0.5 img_y = (img_y - y0) / (y1", "def forward(self, x): for conv in self.convs: x = conv(x) if self.upsample is", "if self.upsample_method == 'deconv': x = self.relu(x) mask_pred = self.conv_logits(x) return mask_pred def", "= mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks, rcnn_train_cfg) return mask_targets @force_fp32(apply_to=('mask_pred', )) def loss(self, mask_pred, mask_targets,", "None, 'deconv', 'nearest', 'bilinear', 'carafe' ]: raise ValueError( f'Invalid upsample method {self.upsample_cfg[\"type\"]}, '", "if self.class_agnostic: loss_mask = self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels)) else: loss_mask = self.loss_mask(mask_pred, mask_targets, labels)", "' 'accepted methods are \"deconv\", \"nearest\", \"bilinear\", ' '\"carafe\"') self.num_convs = num_convs #", "A mask of shape (N, h', w') and its start and end coordinates", "else: # GPU benefits from parallelism for larger chunks, # but may have", "= self.upsample_cfg.pop('scale_factor', None) self.num_classes = num_classes self.class_agnostic = class_agnostic self.conv_cfg = conv_cfg self.norm_cfg", "rcnn_train_cfg) return mask_targets @force_fp32(apply_to=('mask_pred', )) def loss(self, mask_pred, mask_targets, labels): loss = dict()", "None].expand(N, img_y.size(1), img_x.size(1)) grid = torch.stack([gx, gy], dim=3) img_masks = F.grid_sample( masks.to(dtype=torch.float32), grid,", "H, W boxes (Tensor): N, 4 img_h (int): Height of the image to", ") + spatial_inds] = masks_chunk for i in range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return cls_segms def", "== 'deconv' else upsample_in_channels) self.conv_logits = Conv2d(logits_in_channel, out_channels, 1) self.relu = nn.ReLU(inplace=True) self.debug_imgs", "outside of this method. det_bboxes (Tensor): shape (n, 4/5) det_labels (Tensor): shape (n,", "img_h (int): Height of the image to be pasted. img_w (int): Width of", "masks.to(dtype=torch.float32), grid, align_corners=False) if skip_empty: return img_masks[:, 0], (slice(y0_int, y1_int), slice(x0_int, x1_int)) else:", "self.num_classes logits_in_channel = ( self.conv_out_channels if self.upsample_method == 'deconv' else upsample_in_channels) self.conv_logits =", "import ConvModule, build_upsample_layer from mmcv.ops import Conv2d from mmcv.ops.carafe import CARAFEPack from mmcv.runner", "= num_classes self.class_agnostic = class_agnostic self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled =", "w_scale, h_scale = scale_factor[0], scale_factor[1] img_h = np.round(ori_shape[0] * h_scale.item()).astype( np.int32) img_w =", "img_w * BYTES_PER_FLOAT / GPU_MEM_LIMIT)) assert (num_chunks <= N), 'Default GPU_MEM_LIMIT is too", "import mask_target from mmdet.models.builder import HEADS, build_loss BYTES_PER_FLOAT = 4 # TODO: This", "in_channels=upsample_in_channels, out_channels=self.conv_out_channels, kernel_size=self.scale_factor, stride=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) elif self.upsample_method == 'carafe': upsample_cfg_.update( channels=upsample_in_channels,", "# operations. num_chunks = N else: # GPU benefits from parallelism for larger", "acoording to boxes. This implementation is modified from https://github.com/facebookresearch/detectron2/ Args: masks (Tensor): N,", "return a mask of shape (N, img_h, img_w) and an empty tuple. If", "instance masks acoording to boxes. This implementation is modified from https://github.com/facebookresearch/detectron2/ Args: masks", "numpy as np import torch import torch.nn as nn import torch.nn.functional as F", "will be pasted. It will return a mask of shape (N, img_h, img_w)", "and bboxes. Args: mask_pred (Tensor or ndarray): shape (n, #class, h, w). For", "_do_paste_mask(masks, boxes, img_h, img_w, skip_empty=True): \"\"\"Paste instance masks acoording to boxes. This implementation", "on COCO-scale dataset. device = masks.device if skip_empty: x0_int, y0_int = torch.clamp( boxes.min(dim=0).values.floor()[:2]", "- y0) / (y1 - y0) * 2 - 1 img_x = (img_x", "logits_in_channel = ( self.conv_out_channels if self.upsample_method == 'deconv' else upsample_in_channels) self.conv_logits = Conv2d(logits_in_channel,", "[ None, 'deconv', 'nearest', 'bilinear', 'carafe' ]: raise ValueError( f'Invalid upsample method {self.upsample_cfg[\"type\"]},", "device.type == 'cpu': # CPU is most efficient when they are pasted one", "mmdet.core import mask_target from mmdet.models.builder import HEADS, build_loss BYTES_PER_FLOAT = 4 # TODO:", "== False, the whole image will be pasted. It will return a mask", "size Returns: list[list]: encoded masks \"\"\" if isinstance(mask_pred, torch.Tensor): mask_pred = mask_pred.sigmoid() else:", "= np.round(ori_shape[1] * w_scale.item()).astype( np.int32) scale_factor = 1.0 if not isinstance(scale_factor, (float, torch.Tensor)):", "- x0) * 2 - 1 # img_x, img_y have shapes (N, w),", "implementation is modified from https://github.com/facebookresearch/detectron2/ Args: masks (Tensor): N, 1, H, W boxes", "is modified from https://github.com/facebookresearch/detectron2/ Args: masks (Tensor): N, 1, H, W boxes (Tensor):", "else: mask_pred = det_bboxes.new_tensor(mask_pred) device = mask_pred.device cls_segms = [[] for _ in", "for res in sampling_results ] mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks, rcnn_train_cfg) return mask_targets", "import numpy as np import torch import torch.nn as nn import torch.nn.functional as", "build_upsample_layer(upsample_cfg_) out_channels = 1 if self.class_agnostic else self.num_classes logits_in_channel = ( self.conv_out_channels if", "upsample method {self.upsample_cfg[\"type\"]}, ' 'accepted methods are \"deconv\", \"nearest\", \"bilinear\", ' '\"carafe\"') self.num_convs", "W boxes (Tensor): N, 4 img_h (int): Height of the image to be", "mask_pred = det_bboxes.new_tensor(mask_pred) device = mask_pred.device cls_segms = [[] for _ in range(self.num_classes)", "torch.nn.modules.utils import _pair from mmdet.core import mask_target from mmdet.models.builder import HEADS, build_loss BYTES_PER_FLOAT", "torch.nn as nn import torch.nn.functional as F from mmcv.cnn import ConvModule, build_upsample_layer from", "mmcv.ops.carafe import CARAFEPack from mmcv.runner import auto_fp16, force_fp32 from torch.nn.modules.utils import _pair from", "input into chunks, # and paste them chunk by chunk. if device.type ==", "mask_pred.size(0) == 0: loss_mask = mask_pred.sum() * 0 else: if self.class_agnostic: loss_mask =", "(num_chunks <= N), 'Default GPU_MEM_LIMIT is too small; try increasing it' chunks =", "conv(x) if self.upsample is not None: x = self.upsample(x) if self.upsample_method == 'deconv':", "return mask_pred def get_targets(self, sampling_results, gt_masks, rcnn_train_cfg): pos_proposals = [res.pos_bboxes for res in", "= self.upsample_cfg.copy() if self.upsample_method is None: self.upsample = None elif self.upsample_method == 'deconv':", "(Tensor): N, 4 img_h (int): Height of the image to be pasted. img_w", "The actual implementation split the input into chunks, # and paste them chunk", "# by using the entire image to sample the masks # Compared to", "output of model, whose type is Tensor, while for multi-scale testing, it will", "scale_factor = 1.0 if not isinstance(scale_factor, (float, torch.Tensor)): scale_factor = bboxes.new_tensor(scale_factor) bboxes =", "that it performs minimal number of # operations. num_chunks = N else: #", "img_h, img_w, device=device, dtype=torch.bool if threshold >= 0 else torch.uint8) if not self.class_agnostic:", "np.ceil(N * img_h * img_w * BYTES_PER_FLOAT / GPU_MEM_LIMIT)) assert (num_chunks <= N),", "operations but is faster on COCO-scale dataset. device = masks.device if skip_empty: x0_int,", "import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import", "ori_shape[:2] else: if isinstance(scale_factor, float): img_h = np.round(ori_shape[0] * scale_factor).astype(np.int32) img_w = np.round(ori_shape[1]", "FCNMaskHead(nn.Module): def __init__(self, num_convs=4, roi_feat_size=14, in_channels=256, conv_kernel_size=3, conv_out_channels=256, num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None,", ":, None].expand(N, img_y.size(1), img_x.size(1)) grid = torch.stack([gx, gy], dim=3) img_masks = F.grid_sample( masks.to(dtype=torch.float32),", "(y1 - y0) * 2 - 1 img_x = (img_x - x0) /", "scale_factor=self.scale_factor, mode=self.upsample_method, align_corners=align_corners) self.upsample = build_upsample_layer(upsample_cfg_) out_channels = 1 if self.class_agnostic else self.num_classes", "elif isinstance(m, CARAFEPack): m.init_weights() else: nn.init.kaiming_normal_( m.weight, mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias, 0) @auto_fp16() def", "GPU_MEM_LIMIT = 1024**3 # 1 GB memory limit @HEADS.register_module() class FCNMaskHead(nn.Module): def __init__(self,", "4/5) det_labels (Tensor): shape (n, ) img_shape (Tensor): shape (3, ) rcnn_test_cfg (dict):", "m.init_weights() else: nn.init.kaiming_normal_( m.weight, mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias, 0) @auto_fp16() def forward(self, x): for", "BYTES_PER_FLOAT = 4 # TODO: This memory limit may be too much or", "is None: continue elif isinstance(m, CARAFEPack): m.init_weights() else: nn.init.kaiming_normal_( m.weight, mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias,", "+ 0.5 img_x = torch.arange( x0_int, x1_int, device=device, dtype=torch.float32) + 0.5 img_y =", "to chunk size) # by using the entire image to sample the masks", "mask_targets, labels): loss = dict() if mask_pred.size(0) == 0: loss_mask = mask_pred.sum() *", "chunks, # but may have memory issue num_chunks = int( np.ceil(N * img_h", "device=device), num_chunks) threshold = rcnn_test_cfg.mask_thr_binary im_mask = torch.zeros( N, img_h, img_w, device=device, dtype=torch.bool", "CPU. Returns: tuple: (Tensor, tuple). The first item is mask tensor, the second", "out_channels=self.conv_out_channels, kernel_size=self.scale_factor, stride=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) elif self.upsample_method == 'carafe': upsample_cfg_.update( channels=upsample_in_channels, scale_factor=self.scale_factor)", "0 if torch.isinf(img_y).any(): inds = torch.where(torch.isinf(img_y)) img_y[inds] = 0 gx = img_x[:, None,", "build_loss(loss_mask) self.convs = nn.ModuleList() for i in range(self.num_convs): in_channels = ( self.in_channels if", "= img_w, img_h x0, y0, x1, y1 = torch.split(boxes, 1, dim=1) # each", "# but may have memory issue num_chunks = int( np.ceil(N * img_h *", "cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return cls_segms def _do_paste_mask(masks, boxes, img_h, img_w, skip_empty=True): \"\"\"Paste instance masks acoording", "skip_empty=device.type == 'cpu') if threshold >= 0: masks_chunk = (masks_chunk >= threshold).to(dtype=torch.bool) else:", "im_mask[(inds, ) + spatial_inds] = masks_chunk for i in range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return cls_segms", "first item is mask tensor, the second one is the slice object. If", "shape (3, ) rcnn_test_cfg (dict): rcnn testing config ori_shape: original image size Returns:", "y0_int = 0, 0 x1_int, y1_int = img_w, img_h x0, y0, x1, y1", "method. det_bboxes (Tensor): shape (n, 4/5) det_labels (Tensor): shape (n, ) img_shape (Tensor):", "num_convs=4, roi_feat_size=14, in_channels=256, conv_kernel_size=3, conv_out_channels=256, num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None, norm_cfg=None, loss_mask=dict( type='CrossEntropyLoss',", "Conv2d from mmcv.ops.carafe import CARAFEPack from mmcv.runner import auto_fp16, force_fp32 from torch.nn.modules.utils import", "optimization for CPU. Returns: tuple: (Tensor, tuple). The first item is mask tensor,", "import _pair from mmdet.core import mask_target from mmdet.models.builder import HEADS, build_loss BYTES_PER_FLOAT =", "empty tuple. If skip_empty == True, only area around the mask will be", "if isinstance(scale_factor, float): img_h = np.round(ori_shape[0] * scale_factor).astype(np.int32) img_w = np.round(ori_shape[1] * scale_factor).astype(np.int32)", "0: masks_chunk = (masks_chunk >= threshold).to(dtype=torch.bool) else: # for visualization and debugging masks_chunk", "== 'deconv': upsample_cfg_.update( in_channels=upsample_in_channels, out_channels=self.conv_out_channels, kernel_size=self.scale_factor, stride=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) elif self.upsample_method ==", "torch.split(boxes, 1, dim=1) # each is Nx1 N = masks.shape[0] img_y = torch.arange(", "+ 0.5 img_y = (img_y - y0) / (y1 - y0) * 2", "when they are pasted one by one with # skip_empty=True, so that it", "self.conv_out_channels = conv_out_channels self.upsample_method = self.upsample_cfg.get('type') self.scale_factor = self.upsample_cfg.pop('scale_factor', None) self.num_classes = num_classes", "masks # Compared to pasting them one by one, # this has more", "segmentation masks from mask_pred and bboxes. Args: mask_pred (Tensor or ndarray): shape (n,", "/ scale_factor N = len(mask_pred) # The actual implementation split the input into", "det_labels, rcnn_test_cfg, ori_shape, scale_factor, rescale): \"\"\"Get segmentation masks from mask_pred and bboxes. Args:", "if torch.isinf(img_y).any(): inds = torch.where(torch.isinf(img_y)) img_y[inds] = 0 gx = img_x[:, None, :].expand(N,", "None] for inds in chunks: masks_chunk, spatial_inds = _do_paste_mask( mask_pred[inds], bboxes[inds], img_h, img_w,", "array outside of this method. det_bboxes (Tensor): shape (n, 4/5) det_labels (Tensor): shape", "= num_convs # WARN: roi_feat_size is reserved and not used self.roi_feat_size = _pair(roi_feat_size)", "# TODO: This memory limit may be too much or too little. It", "loss = dict() if mask_pred.size(0) == 0: loss_mask = mask_pred.sum() * 0 else:", "start and end coordinates in the original image will be returned. \"\"\" #", "grid = torch.stack([gx, gy], dim=3) img_masks = F.grid_sample( masks.to(dtype=torch.float32), grid, align_corners=False) if skip_empty:", "gt_masks, rcnn_train_cfg) return mask_targets @force_fp32(apply_to=('mask_pred', )) def loss(self, mask_pred, mask_targets, labels): loss =", "second one is the slice object. If skip_empty == False, the whole image", "- 1 img_x = (img_x - x0) / (x1 - x0) * 2", "self.relu = nn.ReLU(inplace=True) self.debug_imgs = None def init_weights(self): for m in [self.upsample, self.conv_logits]:", "= scale_factor[0], scale_factor[1] img_h = np.round(ori_shape[0] * h_scale.item()).astype( np.int32) img_w = np.round(ori_shape[1] *", "not self.class_agnostic: mask_pred = mask_pred[range(N), labels][:, None] for inds in chunks: masks_chunk, spatial_inds", "of shape (N, img_h, img_w) and an empty tuple. If skip_empty == True,", "in [ None, 'deconv', 'nearest', 'bilinear', 'carafe' ]: raise ValueError( f'Invalid upsample method", "# BG is not included in num_classes bboxes = det_bboxes[:, :4] labels =", "np.round(ori_shape[0] * h_scale.item()).astype( np.int32) img_w = np.round(ori_shape[1] * w_scale.item()).astype( np.int32) scale_factor = 1.0", "upsample_cfg.copy() if self.upsample_cfg['type'] not in [ None, 'deconv', 'nearest', 'bilinear', 'carafe' ]: raise", "= self.conv_logits(x) return mask_pred def get_targets(self, sampling_results, gt_masks, rcnn_train_cfg): pos_proposals = [res.pos_bboxes for", "== 0: loss_mask = mask_pred.sum() * 0 else: if self.class_agnostic: loss_mask = self.loss_mask(mask_pred,", "sampling_results, gt_masks, rcnn_train_cfg): pos_proposals = [res.pos_bboxes for res in sampling_results] pos_assigned_gt_inds = [", "rcnn_test_cfg, ori_shape, scale_factor, rescale): \"\"\"Get segmentation masks from mask_pred and bboxes. Args: mask_pred", "= bboxes.new_tensor(scale_factor) bboxes = bboxes / scale_factor N = len(mask_pred) # The actual", "(int): Height of the image to be pasted. img_w (int): Width of the", "mask_targets, torch.zeros_like(labels)) else: loss_mask = self.loss_mask(mask_pred, mask_targets, labels) loss['loss_mask'] = loss_mask return loss", "> 0 else in_channels) upsample_cfg_ = self.upsample_cfg.copy() if self.upsample_method is None: self.upsample =", "h', w') and its start and end coordinates in the original image will", "x0_int, y0_int = 0, 0 x1_int, y1_int = img_w, img_h x0, y0, x1,", "img_w, skip_empty=True): \"\"\"Paste instance masks acoording to boxes. This implementation is modified from", "else False) upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method, align_corners=align_corners) self.upsample = build_upsample_layer(upsample_cfg_) out_channels = 1 if", "threshold >= 0 else torch.uint8) if not self.class_agnostic: mask_pred = mask_pred[range(N), labels][:, None]", "= (masks_chunk >= threshold).to(dtype=torch.bool) else: # for visualization and debugging masks_chunk = (masks_chunk", "self.conv_out_channels if self.num_convs > 0 else in_channels) upsample_cfg_ = self.upsample_cfg.copy() if self.upsample_method is", "= self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels)) else: loss_mask = self.loss_mask(mask_pred, mask_targets, labels) loss['loss_mask'] = loss_mask", "if isinstance(mask_pred, torch.Tensor): mask_pred = mask_pred.sigmoid() else: mask_pred = det_bboxes.new_tensor(mask_pred) device = mask_pred.device", "self.num_convs > 0 else in_channels) upsample_cfg_ = self.upsample_cfg.copy() if self.upsample_method is None: self.upsample", "= masks.shape[0] img_y = torch.arange( y0_int, y1_int, device=device, dtype=torch.float32) + 0.5 img_x =", "If skip_empty == False, the whole image will be pasted. It will return", "For single-scale testing, mask_pred is the direct output of model, whose type is", "#class, h, w). For single-scale testing, mask_pred is the direct output of model,", "Width of the image to be pasted. skip_empty (bool): Only paste masks within", "pasted. A mask of shape (N, h', w') and its start and end", "= nn.ReLU(inplace=True) self.debug_imgs = None def init_weights(self): for m in [self.upsample, self.conv_logits]: if", "the whole image will be pasted. It will return a mask of shape", "(N, w), (N, h) if torch.isinf(img_x).any(): inds = torch.where(torch.isinf(img_x)) img_x[inds] = 0 if", "else: loss_mask = self.loss_mask(mask_pred, mask_targets, labels) loss['loss_mask'] = loss_mask return loss def get_seg_masks(self,", "y1 = torch.split(boxes, 1, dim=1) # each is Nx1 N = masks.shape[0] img_y", "scale_factor = bboxes.new_tensor(scale_factor) bboxes = bboxes / scale_factor N = len(mask_pred) # The", "ori_shape, scale_factor, rescale): \"\"\"Get segmentation masks from mask_pred and bboxes. Args: mask_pred (Tensor", "into chunks, # and paste them chunk by chunk. if device.type == 'cpu':", "stride=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) elif self.upsample_method == 'carafe': upsample_cfg_.update( channels=upsample_in_channels, scale_factor=self.scale_factor) self.upsample =", "class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None, norm_cfg=None, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)): super(FCNMaskHead, self).__init__() self.upsample_cfg =", "@auto_fp16() def forward(self, x): for conv in self.convs: x = conv(x) if self.upsample", "benefits from parallelism for larger chunks, # but may have memory issue num_chunks", "masks acoording to boxes. This implementation is modified from https://github.com/facebookresearch/detectron2/ Args: masks (Tensor):", "rcnn_test_cfg.mask_thr_binary im_mask = torch.zeros( N, img_h, img_w, device=device, dtype=torch.bool if threshold >= 0", "img_h = np.round(ori_shape[0] * scale_factor).astype(np.int32) img_w = np.round(ori_shape[1] * scale_factor).astype(np.int32) else: w_scale, h_scale", "rcnn_train_cfg): pos_proposals = [res.pos_bboxes for res in sampling_results] pos_assigned_gt_inds = [ res.pos_assigned_gt_inds for", "be pasted. skip_empty (bool): Only paste masks within the region that tightly bound", "img_h, img_w) and an empty tuple. If skip_empty == True, only area around", "implementation split the input into chunks, # and paste them chunk by chunk.", "img_y[inds] = 0 gx = img_x[:, None, :].expand(N, img_y.size(1), img_x.size(1)) gy = img_y[:,", "type is Tensor, while for multi-scale testing, it will be converted to numpy", "of shape (N, h', w') and its start and end coordinates in the", "torch.Tensor)): scale_factor = bboxes.new_tensor(scale_factor) bboxes = bboxes / scale_factor N = len(mask_pred) #", "= np.round(ori_shape[1] * scale_factor).astype(np.int32) else: w_scale, h_scale = scale_factor[0], scale_factor[1] img_h = np.round(ori_shape[0]", "be pasted. img_w (int): Width of the image to be pasted. skip_empty (bool):", "x1_int = torch.clamp( boxes[:, 2].max().ceil() + 1, max=img_w).to(dtype=torch.int32) y1_int = torch.clamp( boxes[:, 3].max().ceil()", "dict() if mask_pred.size(0) == 0: loss_mask = mask_pred.sum() * 0 else: if self.class_agnostic:", "# WARN: roi_feat_size is reserved and not used self.roi_feat_size = _pair(roi_feat_size) self.in_channels =", "paste them chunk by chunk. if device.type == 'cpu': # CPU is most", "in range(self.num_classes) ] # BG is not included in num_classes bboxes = det_bboxes[:,", "build_upsample_layer(upsample_cfg_) else: # suppress warnings align_corners = (None if self.upsample_method == 'nearest' else", "as nn import torch.nn.functional as F from mmcv.cnn import ConvModule, build_upsample_layer from mmcv.ops", "by using the entire image to sample the masks # Compared to pasting", "as np import torch import torch.nn as nn import torch.nn.functional as F from", "conv_out_channels self.upsample_method = self.upsample_cfg.get('type') self.scale_factor = self.upsample_cfg.pop('scale_factor', None) self.num_classes = num_classes self.class_agnostic =", "in [self.upsample, self.conv_logits]: if m is None: continue elif isinstance(m, CARAFEPack): m.init_weights() else:", "<= N), 'Default GPU_MEM_LIMIT is too small; try increasing it' chunks = torch.chunk(torch.arange(N,", "cls_segms def _do_paste_mask(masks, boxes, img_h, img_w, skip_empty=True): \"\"\"Paste instance masks acoording to boxes.", "4 # TODO: This memory limit may be too much or too little.", "= det_bboxes.new_tensor(mask_pred) device = mask_pred.device cls_segms = [[] for _ in range(self.num_classes) ]", "Returns: tuple: (Tensor, tuple). The first item is mask tensor, the second one", "# 1 GB memory limit @HEADS.register_module() class FCNMaskHead(nn.Module): def __init__(self, num_convs=4, roi_feat_size=14, in_channels=256,", "inds = torch.where(torch.isinf(img_x)) img_x[inds] = 0 if torch.isinf(img_y).any(): inds = torch.where(torch.isinf(img_y)) img_y[inds] =", "self.debug_imgs = None def init_weights(self): for m in [self.upsample, self.conv_logits]: if m is", "roi_feat_size=14, in_channels=256, conv_kernel_size=3, conv_out_channels=256, num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None, norm_cfg=None, loss_mask=dict( type='CrossEntropyLoss', use_mask=True,", "self.loss_mask = build_loss(loss_mask) self.convs = nn.ModuleList() for i in range(self.num_convs): in_channels = (", "pasted. img_w (int): Width of the image to be pasted. skip_empty (bool): Only", "return loss def get_seg_masks(self, mask_pred, det_bboxes, det_labels, rcnn_test_cfg, ori_shape, scale_factor, rescale): \"\"\"Get segmentation", "are pasted one by one with # skip_empty=True, so that it performs minimal", "sample the masks # Compared to pasting them one by one, # this", "self.loss_mask(mask_pred, mask_targets, labels) loss['loss_mask'] = loss_mask return loss def get_seg_masks(self, mask_pred, det_bboxes, det_labels,", "'cpu') if threshold >= 0: masks_chunk = (masks_chunk >= threshold).to(dtype=torch.bool) else: # for", "== True, only area around the mask will be pasted. A mask of", "be too much or too little. It would be better to # determine", "device = masks.device if skip_empty: x0_int, y0_int = torch.clamp( boxes.min(dim=0).values.floor()[:2] - 1, min=0).to(dtype=torch.int32)", "(img_y - y0) / (y1 - y0) * 2 - 1 img_x =", "shape (n, ) img_shape (Tensor): shape (3, ) rcnn_test_cfg (dict): rcnn testing config", "if threshold >= 0: masks_chunk = (masks_chunk >= threshold).to(dtype=torch.bool) else: # for visualization", "loss['loss_mask'] = loss_mask return loss def get_seg_masks(self, mask_pred, det_bboxes, det_labels, rcnn_test_cfg, ori_shape, scale_factor,", "- 1, min=0).to(dtype=torch.int32) x1_int = torch.clamp( boxes[:, 2].max().ceil() + 1, max=img_w).to(dtype=torch.int32) y1_int =", "= torch.chunk(torch.arange(N, device=device), num_chunks) threshold = rcnn_test_cfg.mask_thr_binary im_mask = torch.zeros( N, img_h, img_w,", "upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None, norm_cfg=None, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)): super(FCNMaskHead, self).__init__() self.upsample_cfg = upsample_cfg.copy()", "more operations but is faster on COCO-scale dataset. device = masks.device if skip_empty:", "self.convs.append( ConvModule( in_channels, self.conv_out_channels, self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels = ( self.conv_out_channels if", "nn.init.kaiming_normal_( m.weight, mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias, 0) @auto_fp16() def forward(self, x): for conv in", "\"deconv\", \"nearest\", \"bilinear\", ' '\"carafe\"') self.num_convs = num_convs # WARN: roi_feat_size is reserved", "torch.zeros_like(labels)) else: loss_mask = self.loss_mask(mask_pred, mask_targets, labels) loss['loss_mask'] = loss_mask return loss def", "\"\"\"Get segmentation masks from mask_pred and bboxes. Args: mask_pred (Tensor or ndarray): shape", "num_classes bboxes = det_bboxes[:, :4] labels = det_labels if rescale: img_h, img_w =", "img_y = torch.arange( y0_int, y1_int, device=device, dtype=torch.float32) + 0.5 img_x = torch.arange( x0_int,", "(bool): Only paste masks within the region that tightly bound all boxes, and", "1 GB memory limit @HEADS.register_module() class FCNMaskHead(nn.Module): def __init__(self, num_convs=4, roi_feat_size=14, in_channels=256, conv_kernel_size=3,", "self.upsample_cfg.get('type') self.scale_factor = self.upsample_cfg.pop('scale_factor', None) self.num_classes = num_classes self.class_agnostic = class_agnostic self.conv_cfg =", "warnings align_corners = (None if self.upsample_method == 'nearest' else False) upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method,", "in num_classes bboxes = det_bboxes[:, :4] labels = det_labels if rescale: img_h, img_w", "mask_pred = mask_pred.sigmoid() else: mask_pred = det_bboxes.new_tensor(mask_pred) device = mask_pred.device cls_segms = [[]", "F from mmcv.cnn import ConvModule, build_upsample_layer from mmcv.ops import Conv2d from mmcv.ops.carafe import", "mask_pred = self.conv_logits(x) return mask_pred def get_targets(self, sampling_results, gt_masks, rcnn_train_cfg): pos_proposals = [res.pos_bboxes", "use_mask=True, loss_weight=1.0)): super(FCNMaskHead, self).__init__() self.upsample_cfg = upsample_cfg.copy() if self.upsample_cfg['type'] not in [ None,", "+ 1, max=img_w).to(dtype=torch.int32) y1_int = torch.clamp( boxes[:, 3].max().ceil() + 1, max=img_h).to(dtype=torch.int32) else: x0_int,", "gx = img_x[:, None, :].expand(N, img_y.size(1), img_x.size(1)) gy = img_y[:, :, None].expand(N, img_y.size(1),", "1 img_x = (img_x - x0) / (x1 - x0) * 2 -", "F.grid_sample( masks.to(dtype=torch.float32), grid, align_corners=False) if skip_empty: return img_masks[:, 0], (slice(y0_int, y1_int), slice(x0_int, x1_int))", ") rcnn_test_cfg (dict): rcnn testing config ori_shape: original image size Returns: list[list]: encoded", "not used self.roi_feat_size = _pair(roi_feat_size) self.in_channels = in_channels self.conv_kernel_size = conv_kernel_size self.conv_out_channels =", "torch.clamp( boxes[:, 3].max().ceil() + 1, max=img_h).to(dtype=torch.int32) else: x0_int, y0_int = 0, 0 x1_int,", "= mask_pred.sigmoid() else: mask_pred = det_bboxes.new_tensor(mask_pred) device = mask_pred.device cls_segms = [[] for", "self.upsample_cfg.copy() if self.upsample_method is None: self.upsample = None elif self.upsample_method == 'deconv': upsample_cfg_.update(", "4 img_h (int): Height of the image to be pasted. img_w (int): Width", "tuple. If skip_empty == True, only area around the mask will be pasted.", "Compared to pasting them one by one, # this has more operations but", "(x1 - x0) * 2 - 1 # img_x, img_y have shapes (N,", "else: if self.class_agnostic: loss_mask = self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels)) else: loss_mask = self.loss_mask(mask_pred, mask_targets,", "'accepted methods are \"deconv\", \"nearest\", \"bilinear\", ' '\"carafe\"') self.num_convs = num_convs # WARN:", "nn.ReLU(inplace=True) self.debug_imgs = None def init_weights(self): for m in [self.upsample, self.conv_logits]: if m", "range(self.num_convs): in_channels = ( self.in_channels if i == 0 else self.conv_out_channels) padding =", "image size Returns: list[list]: encoded masks \"\"\" if isinstance(mask_pred, torch.Tensor): mask_pred = mask_pred.sigmoid()", "config ori_shape: original image size Returns: list[list]: encoded masks \"\"\" if isinstance(mask_pred, torch.Tensor):", "= img_x[:, None, :].expand(N, img_y.size(1), img_x.size(1)) gy = img_y[:, :, None].expand(N, img_y.size(1), img_x.size(1))", "shape (N, h', w') and its start and end coordinates in the original", "image to be pasted. img_w (int): Width of the image to be pasted.", "nn import torch.nn.functional as F from mmcv.cnn import ConvModule, build_upsample_layer from mmcv.ops import", "it' chunks = torch.chunk(torch.arange(N, device=device), num_chunks) threshold = rcnn_test_cfg.mask_thr_binary im_mask = torch.zeros( N,", "from mmcv.runner import auto_fp16, force_fp32 from torch.nn.modules.utils import _pair from mmdet.core import mask_target", "from mmcv.cnn import ConvModule, build_upsample_layer from mmcv.ops import Conv2d from mmcv.ops.carafe import CARAFEPack", "have memory issue num_chunks = int( np.ceil(N * img_h * img_w * BYTES_PER_FLOAT", "one by one, # this has more operations but is faster on COCO-scale", "skip_empty=True, so that it performs minimal number of # operations. num_chunks = N", "* BYTES_PER_FLOAT / GPU_MEM_LIMIT)) assert (num_chunks <= N), 'Default GPU_MEM_LIMIT is too small;", "(dict): rcnn testing config ori_shape: original image size Returns: list[list]: encoded masks \"\"\"", "* scale_factor).astype(np.int32) img_w = np.round(ori_shape[1] * scale_factor).astype(np.int32) else: w_scale, h_scale = scale_factor[0], scale_factor[1]", "img_y = (img_y - y0) / (y1 - y0) * 2 - 1", "GPU benefits from parallelism for larger chunks, # but may have memory issue", "self.conv_out_channels if self.upsample_method == 'deconv' else upsample_in_channels) self.conv_logits = Conv2d(logits_in_channel, out_channels, 1) self.relu", "out_channels = 1 if self.class_agnostic else self.num_classes logits_in_channel = ( self.conv_out_channels if self.upsample_method", "is the direct output of model, whose type is Tensor, while for multi-scale", "self.num_classes = num_classes self.class_agnostic = class_agnostic self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled", "= np.round(ori_shape[0] * h_scale.item()).astype( np.int32) img_w = np.round(ori_shape[1] * w_scale.item()).astype( np.int32) scale_factor =", "else: nn.init.kaiming_normal_( m.weight, mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias, 0) @auto_fp16() def forward(self, x): for conv", "{self.upsample_cfg[\"type\"]}, ' 'accepted methods are \"deconv\", \"nearest\", \"bilinear\", ' '\"carafe\"') self.num_convs = num_convs", "mask tensor, the second one is the slice object. If skip_empty == False,", "( self.conv_out_channels if self.num_convs > 0 else in_channels) upsample_cfg_ = self.upsample_cfg.copy() if self.upsample_method", "[ res.pos_assigned_gt_inds for res in sampling_results ] mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks, rcnn_train_cfg)", "N, 4 img_h (int): Height of the image to be pasted. img_w (int):", "0 else: if self.class_agnostic: loss_mask = self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels)) else: loss_mask = self.loss_mask(mask_pred,", "'deconv': x = self.relu(x) mask_pred = self.conv_logits(x) return mask_pred def get_targets(self, sampling_results, gt_masks,", "if torch.isinf(img_x).any(): inds = torch.where(torch.isinf(img_x)) img_x[inds] = 0 if torch.isinf(img_y).any(): inds = torch.where(torch.isinf(img_y))", "rcnn_test_cfg (dict): rcnn testing config ori_shape: original image size Returns: list[list]: encoded masks", "isinstance(scale_factor, float): img_h = np.round(ori_shape[0] * scale_factor).astype(np.int32) img_w = np.round(ori_shape[1] * scale_factor).astype(np.int32) else:", "self.upsample_method == 'carafe': upsample_cfg_.update( channels=upsample_in_channels, scale_factor=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) else: # suppress warnings", "1024**3 # 1 GB memory limit @HEADS.register_module() class FCNMaskHead(nn.Module): def __init__(self, num_convs=4, roi_feat_size=14,", "not isinstance(scale_factor, (float, torch.Tensor)): scale_factor = bboxes.new_tensor(scale_factor) bboxes = bboxes / scale_factor N", "one with # skip_empty=True, so that it performs minimal number of # operations.", "im_mask = torch.zeros( N, img_h, img_w, device=device, dtype=torch.bool if threshold >= 0 else", "self.convs = nn.ModuleList() for i in range(self.num_convs): in_channels = ( self.in_channels if i", "f'Invalid upsample method {self.upsample_cfg[\"type\"]}, ' 'accepted methods are \"deconv\", \"nearest\", \"bilinear\", ' '\"carafe\"')", "self.conv_out_channels, self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels = ( self.conv_out_channels if self.num_convs > 0", "False) upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method, align_corners=align_corners) self.upsample = build_upsample_layer(upsample_cfg_) out_channels = 1 if self.class_agnostic", "will be pasted. A mask of shape (N, h', w') and its start", "loss_mask = self.loss_mask(mask_pred, mask_targets, labels) loss['loss_mask'] = loss_mask return loss def get_seg_masks(self, mask_pred,", "* scale_factor).astype(np.int32) else: w_scale, h_scale = scale_factor[0], scale_factor[1] img_h = np.round(ori_shape[0] * h_scale.item()).astype(", "labels) loss['loss_mask'] = loss_mask return loss def get_seg_masks(self, mask_pred, det_bboxes, det_labels, rcnn_test_cfg, ori_shape,", "dim=1) # each is Nx1 N = masks.shape[0] img_y = torch.arange( y0_int, y1_int,", "= F.grid_sample( masks.to(dtype=torch.float32), grid, align_corners=False) if skip_empty: return img_masks[:, 0], (slice(y0_int, y1_int), slice(x0_int,", "torch.clamp( boxes[:, 2].max().ceil() + 1, max=img_w).to(dtype=torch.int32) y1_int = torch.clamp( boxes[:, 3].max().ceil() + 1,", "is most efficient when they are pasted one by one with # skip_empty=True,", "det_bboxes[:, :4] labels = det_labels if rescale: img_h, img_w = ori_shape[:2] else: if", "= conv_out_channels self.upsample_method = self.upsample_cfg.get('type') self.scale_factor = self.upsample_cfg.pop('scale_factor', None) self.num_classes = num_classes self.class_agnostic", "self.convs: x = conv(x) if self.upsample is not None: x = self.upsample(x) if", "def get_targets(self, sampling_results, gt_masks, rcnn_train_cfg): pos_proposals = [res.pos_bboxes for res in sampling_results] pos_assigned_gt_inds", "1.0 if not isinstance(scale_factor, (float, torch.Tensor)): scale_factor = bboxes.new_tensor(scale_factor) bboxes = bboxes /", "GB memory limit @HEADS.register_module() class FCNMaskHead(nn.Module): def __init__(self, num_convs=4, roi_feat_size=14, in_channels=256, conv_kernel_size=3, conv_out_channels=256,", "else: # suppress warnings align_corners = (None if self.upsample_method == 'nearest' else False)", "An important optimization for CPU. Returns: tuple: (Tensor, tuple). The first item is", "@HEADS.register_module() class FCNMaskHead(nn.Module): def __init__(self, num_convs=4, roi_feat_size=14, in_channels=256, conv_kernel_size=3, conv_out_channels=256, num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv',", "= build_upsample_layer(upsample_cfg_) elif self.upsample_method == 'carafe': upsample_cfg_.update( channels=upsample_in_channels, scale_factor=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) else:", "(N, img_h, img_w) and an empty tuple. If skip_empty == True, only area", "ConvModule, build_upsample_layer from mmcv.ops import Conv2d from mmcv.ops.carafe import CARAFEPack from mmcv.runner import", "and an empty tuple. If skip_empty == True, only area around the mask", "has more operations but is faster on COCO-scale dataset. device = masks.device if", "img_h, img_w, skip_empty=True): \"\"\"Paste instance masks acoording to boxes. This implementation is modified", "\"bilinear\", ' '\"carafe\"') self.num_convs = num_convs # WARN: roi_feat_size is reserved and not", "= self.upsample_cfg.get('type') self.scale_factor = self.upsample_cfg.pop('scale_factor', None) self.num_classes = num_classes self.class_agnostic = class_agnostic self.conv_cfg", "or ndarray): shape (n, #class, h, w). For single-scale testing, mask_pred is the", ">= 0 else torch.uint8) if not self.class_agnostic: mask_pred = mask_pred[range(N), labels][:, None] for", "(None if self.upsample_method == 'nearest' else False) upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method, align_corners=align_corners) self.upsample =", "(up to chunk size) # by using the entire image to sample the", "grid, align_corners=False) if skip_empty: return img_masks[:, 0], (slice(y0_int, y1_int), slice(x0_int, x1_int)) else: return", "'deconv', 'nearest', 'bilinear', 'carafe' ]: raise ValueError( f'Invalid upsample method {self.upsample_cfg[\"type\"]}, ' 'accepted", "= None def init_weights(self): for m in [self.upsample, self.conv_logits]: if m is None:", "x0) * 2 - 1 # img_x, img_y have shapes (N, w), (N,", "torch.where(torch.isinf(img_y)) img_y[inds] = 0 gx = img_x[:, None, :].expand(N, img_y.size(1), img_x.size(1)) gy =", "inds = torch.where(torch.isinf(img_y)) img_y[inds] = 0 gx = img_x[:, None, :].expand(N, img_y.size(1), img_x.size(1))", "may be too much or too little. It would be better to #", "- x0) / (x1 - x0) * 2 - 1 # img_x, img_y", "available resources. GPU_MEM_LIMIT = 1024**3 # 1 GB memory limit @HEADS.register_module() class FCNMaskHead(nn.Module):", "img_w = np.round(ori_shape[1] * w_scale.item()).astype( np.int32) scale_factor = 1.0 if not isinstance(scale_factor, (float,", "# skip_empty=True, so that it performs minimal number of # operations. num_chunks =", "'Default GPU_MEM_LIMIT is too small; try increasing it' chunks = torch.chunk(torch.arange(N, device=device), num_chunks)", "upsample_in_channels = ( self.conv_out_channels if self.num_convs > 0 else in_channels) upsample_cfg_ = self.upsample_cfg.copy()", "may have memory issue num_chunks = int( np.ceil(N * img_h * img_w *", "out_channels, 1) self.relu = nn.ReLU(inplace=True) self.debug_imgs = None def init_weights(self): for m in", "x = self.upsample(x) if self.upsample_method == 'deconv': x = self.relu(x) mask_pred = self.conv_logits(x)", "None def init_weights(self): for m in [self.upsample, self.conv_logits]: if m is None: continue", "torch.chunk(torch.arange(N, device=device), num_chunks) threshold = rcnn_test_cfg.mask_thr_binary im_mask = torch.zeros( N, img_h, img_w, device=device,", "1) // 2 self.convs.append( ConvModule( in_channels, self.conv_out_channels, self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels =", "img_w) and an empty tuple. If skip_empty == True, only area around the", "/ (y1 - y0) * 2 - 1 img_x = (img_x - x0)", "try increasing it' chunks = torch.chunk(torch.arange(N, device=device), num_chunks) threshold = rcnn_test_cfg.mask_thr_binary im_mask =", "within the region that tightly bound all boxes, and returns the results this", "0 gx = img_x[:, None, :].expand(N, img_y.size(1), img_x.size(1)) gy = img_y[:, :, None].expand(N,", "(N, h', w') and its start and end coordinates in the original image", "2 self.convs.append( ConvModule( in_channels, self.conv_out_channels, self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels = ( self.conv_out_channels", "encoded masks \"\"\" if isinstance(mask_pred, torch.Tensor): mask_pred = mask_pred.sigmoid() else: mask_pred = det_bboxes.new_tensor(mask_pred)", "self.upsample(x) if self.upsample_method == 'deconv': x = self.relu(x) mask_pred = self.conv_logits(x) return mask_pred", "mmcv.cnn import ConvModule, build_upsample_layer from mmcv.ops import Conv2d from mmcv.ops.carafe import CARAFEPack from", "= mask_pred[range(N), labels][:, None] for inds in chunks: masks_chunk, spatial_inds = _do_paste_mask( mask_pred[inds],", "def init_weights(self): for m in [self.upsample, self.conv_logits]: if m is None: continue elif", "1) self.relu = nn.ReLU(inplace=True) self.debug_imgs = None def init_weights(self): for m in [self.upsample,", "dtype=torch.bool if threshold >= 0 else torch.uint8) if not self.class_agnostic: mask_pred = mask_pred[range(N),", "upsample_in_channels) self.conv_logits = Conv2d(logits_in_channel, out_channels, 1) self.relu = nn.ReLU(inplace=True) self.debug_imgs = None def", "masks from mask_pred and bboxes. Args: mask_pred (Tensor or ndarray): shape (n, #class,", "Tensor, while for multi-scale testing, it will be converted to numpy array outside", "1, max=img_w).to(dtype=torch.int32) y1_int = torch.clamp( boxes[:, 3].max().ceil() + 1, max=img_h).to(dtype=torch.int32) else: x0_int, y0_int", "= torch.clamp( boxes.min(dim=0).values.floor()[:2] - 1, min=0).to(dtype=torch.int32) x1_int = torch.clamp( boxes[:, 2].max().ceil() + 1,", "y1_int, device=device, dtype=torch.float32) + 0.5 img_x = torch.arange( x0_int, x1_int, device=device, dtype=torch.float32) +", "mmcv.runner import auto_fp16, force_fp32 from torch.nn.modules.utils import _pair from mmdet.core import mask_target from", "tensor, the second one is the slice object. If skip_empty == False, the", "min=0).to(dtype=torch.int32) x1_int = torch.clamp( boxes[:, 2].max().ceil() + 1, max=img_w).to(dtype=torch.int32) y1_int = torch.clamp( boxes[:,", "y0, x1, y1 = torch.split(boxes, 1, dim=1) # each is Nx1 N =", "# determine it based on available resources. GPU_MEM_LIMIT = 1024**3 # 1 GB", "_pair(roi_feat_size) self.in_channels = in_channels self.conv_kernel_size = conv_kernel_size self.conv_out_channels = conv_out_channels self.upsample_method = self.upsample_cfg.get('type')", "= self.upsample(x) if self.upsample_method == 'deconv': x = self.relu(x) mask_pred = self.conv_logits(x) return", "mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias, 0) @auto_fp16() def forward(self, x): for conv in self.convs: x", "and debugging masks_chunk = (masks_chunk * 255).to(dtype=torch.uint8) im_mask[(inds, ) + spatial_inds] = masks_chunk", "from mmdet.core import mask_target from mmdet.models.builder import HEADS, build_loss BYTES_PER_FLOAT = 4 #", "they are pasted one by one with # skip_empty=True, so that it performs", "forward(self, x): for conv in self.convs: x = conv(x) if self.upsample is not", "w') and its start and end coordinates in the original image will be", "in_channels, self.conv_out_channels, self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels = ( self.conv_out_channels if self.num_convs >", "for i in range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return cls_segms def _do_paste_mask(masks, boxes, img_h, img_w, skip_empty=True):", "1, min=0).to(dtype=torch.int32) x1_int = torch.clamp( boxes[:, 2].max().ceil() + 1, max=img_w).to(dtype=torch.int32) y1_int = torch.clamp(", "None elif self.upsample_method == 'deconv': upsample_cfg_.update( in_channels=upsample_in_channels, out_channels=self.conv_out_channels, kernel_size=self.scale_factor, stride=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_)", "class_agnostic self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled = False self.loss_mask = build_loss(loss_mask)", "testing, mask_pred is the direct output of model, whose type is Tensor, while", "img_shape (Tensor): shape (3, ) rcnn_test_cfg (dict): rcnn testing config ori_shape: original image", "from mmcv.ops import Conv2d from mmcv.ops.carafe import CARAFEPack from mmcv.runner import auto_fp16, force_fp32", "init_weights(self): for m in [self.upsample, self.conv_logits]: if m is None: continue elif isinstance(m,", "(Tensor): shape (n, ) img_shape (Tensor): shape (3, ) rcnn_test_cfg (dict): rcnn testing", "bboxes = bboxes / scale_factor N = len(mask_pred) # The actual implementation split", "None: x = self.upsample(x) if self.upsample_method == 'deconv': x = self.relu(x) mask_pred =", "= torch.where(torch.isinf(img_x)) img_x[inds] = 0 if torch.isinf(img_y).any(): inds = torch.where(torch.isinf(img_y)) img_y[inds] = 0", "None, :].expand(N, img_y.size(1), img_x.size(1)) gy = img_y[:, :, None].expand(N, img_y.size(1), img_x.size(1)) grid =", "scale_factor).astype(np.int32) else: w_scale, h_scale = scale_factor[0], scale_factor[1] img_h = np.round(ori_shape[0] * h_scale.item()).astype( np.int32)", "is the slice object. If skip_empty == False, the whole image will be", "gy = img_y[:, :, None].expand(N, img_y.size(1), img_x.size(1)) grid = torch.stack([gx, gy], dim=3) img_masks", "* img_w * BYTES_PER_FLOAT / GPU_MEM_LIMIT)) assert (num_chunks <= N), 'Default GPU_MEM_LIMIT is", "= norm_cfg self.fp16_enabled = False self.loss_mask = build_loss(loss_mask) self.convs = nn.ModuleList() for i", "num_chunks = N else: # GPU benefits from parallelism for larger chunks, #", "if self.upsample_method == 'deconv' else upsample_in_channels) self.conv_logits = Conv2d(logits_in_channel, out_channels, 1) self.relu =", "chunk by chunk. if device.type == 'cpu': # CPU is most efficient when", "and its start and end coordinates in the original image will be returned.", "self.upsample is not None: x = self.upsample(x) if self.upsample_method == 'deconv': x =", "only area around the mask will be pasted. A mask of shape (N,", "2].max().ceil() + 1, max=img_w).to(dtype=torch.int32) y1_int = torch.clamp( boxes[:, 3].max().ceil() + 1, max=img_h).to(dtype=torch.int32) else:", "Conv2d(logits_in_channel, out_channels, 1) self.relu = nn.ReLU(inplace=True) self.debug_imgs = None def init_weights(self): for m", "for res in sampling_results] pos_assigned_gt_inds = [ res.pos_assigned_gt_inds for res in sampling_results ]", "mask_pred[range(N), labels][:, None] for inds in chunks: masks_chunk, spatial_inds = _do_paste_mask( mask_pred[inds], bboxes[inds],", "scale_factor, rescale): \"\"\"Get segmentation masks from mask_pred and bboxes. Args: mask_pred (Tensor or", "def __init__(self, num_convs=4, roi_feat_size=14, in_channels=256, conv_kernel_size=3, conv_out_channels=256, num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None, norm_cfg=None,", "= conv_kernel_size self.conv_out_channels = conv_out_channels self.upsample_method = self.upsample_cfg.get('type') self.scale_factor = self.upsample_cfg.pop('scale_factor', None) self.num_classes", "pos_assigned_gt_inds, gt_masks, rcnn_train_cfg) return mask_targets @force_fp32(apply_to=('mask_pred', )) def loss(self, mask_pred, mask_targets, labels): loss", "if self.upsample is not None: x = self.upsample(x) if self.upsample_method == 'deconv': x", "if self.class_agnostic else self.num_classes logits_in_channel = ( self.conv_out_channels if self.upsample_method == 'deconv' else", "conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels = ( self.conv_out_channels if self.num_convs > 0 else in_channels) upsample_cfg_", "w). For single-scale testing, mask_pred is the direct output of model, whose type", "raise ValueError( f'Invalid upsample method {self.upsample_cfg[\"type\"]}, ' 'accepted methods are \"deconv\", \"nearest\", \"bilinear\",", "for m in [self.upsample, self.conv_logits]: if m is None: continue elif isinstance(m, CARAFEPack):", "w_scale.item()).astype( np.int32) scale_factor = 1.0 if not isinstance(scale_factor, (float, torch.Tensor)): scale_factor = bboxes.new_tensor(scale_factor)", "assert (num_chunks <= N), 'Default GPU_MEM_LIMIT is too small; try increasing it' chunks", "padding = (self.conv_kernel_size - 1) // 2 self.convs.append( ConvModule( in_channels, self.conv_out_channels, self.conv_kernel_size, padding=padding,", "spatial_inds = _do_paste_mask( mask_pred[inds], bboxes[inds], img_h, img_w, skip_empty=device.type == 'cpu') if threshold >=", "bound all boxes, and returns the results this region only. An important optimization", "self.upsample_method = self.upsample_cfg.get('type') self.scale_factor = self.upsample_cfg.pop('scale_factor', None) self.num_classes = num_classes self.class_agnostic = class_agnostic", "upsample_cfg_ = self.upsample_cfg.copy() if self.upsample_method is None: self.upsample = None elif self.upsample_method ==", "if mask_pred.size(0) == 0: loss_mask = mask_pred.sum() * 0 else: if self.class_agnostic: loss_mask", "be pasted. It will return a mask of shape (N, img_h, img_w) and", "if i == 0 else self.conv_out_channels) padding = (self.conv_kernel_size - 1) // 2", "by chunk. if device.type == 'cpu': # CPU is most efficient when they", "(int): Width of the image to be pasted. skip_empty (bool): Only paste masks", "np.round(ori_shape[1] * w_scale.item()).astype( np.int32) scale_factor = 1.0 if not isinstance(scale_factor, (float, torch.Tensor)): scale_factor", "y0_int, y1_int, device=device, dtype=torch.float32) + 0.5 img_x = torch.arange( x0_int, x1_int, device=device, dtype=torch.float32)", "res in sampling_results ] mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks, rcnn_train_cfg) return mask_targets @force_fp32(apply_to=('mask_pred',", "from mmdet.models.builder import HEADS, build_loss BYTES_PER_FLOAT = 4 # TODO: This memory limit", "= self.loss_mask(mask_pred, mask_targets, labels) loss['loss_mask'] = loss_mask return loss def get_seg_masks(self, mask_pred, det_bboxes,", "import Conv2d from mmcv.ops.carafe import CARAFEPack from mmcv.runner import auto_fp16, force_fp32 from torch.nn.modules.utils", "mask_pred and bboxes. Args: mask_pred (Tensor or ndarray): shape (n, #class, h, w).", "_do_paste_mask( mask_pred[inds], bboxes[inds], img_h, img_w, skip_empty=device.type == 'cpu') if threshold >= 0: masks_chunk", "= torch.where(torch.isinf(img_y)) img_y[inds] = 0 gx = img_x[:, None, :].expand(N, img_y.size(1), img_x.size(1)) gy", ")) def loss(self, mask_pred, mask_targets, labels): loss = dict() if mask_pred.size(0) == 0:", "mask_pred.device cls_segms = [[] for _ in range(self.num_classes) ] # BG is not", "Args: masks (Tensor): N, 1, H, W boxes (Tensor): N, 4 img_h (int):", "det_labels if rescale: img_h, img_w = ori_shape[:2] else: if isinstance(scale_factor, float): img_h =", "# CPU is most efficient when they are pasted one by one with", "= rcnn_test_cfg.mask_thr_binary im_mask = torch.zeros( N, img_h, img_w, device=device, dtype=torch.bool if threshold >=", "self.class_agnostic: mask_pred = mask_pred[range(N), labels][:, None] for inds in chunks: masks_chunk, spatial_inds =", "+ spatial_inds] = masks_chunk for i in range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return cls_segms def _do_paste_mask(masks,", "= mask_pred.device cls_segms = [[] for _ in range(self.num_classes) ] # BG is", "img_x[inds] = 0 if torch.isinf(img_y).any(): inds = torch.where(torch.isinf(img_y)) img_y[inds] = 0 gx =", "little. It would be better to # determine it based on available resources.", "resources. GPU_MEM_LIMIT = 1024**3 # 1 GB memory limit @HEADS.register_module() class FCNMaskHead(nn.Module): def", "one by one with # skip_empty=True, so that it performs minimal number of", "skip_empty == False, the whole image will be pasted. It will return a", "range(self.num_classes) ] # BG is not included in num_classes bboxes = det_bboxes[:, :4]", "end coordinates in the original image will be returned. \"\"\" # On GPU,", "cls_segms = [[] for _ in range(self.num_classes) ] # BG is not included", "masks.device if skip_empty: x0_int, y0_int = torch.clamp( boxes.min(dim=0).values.floor()[:2] - 1, min=0).to(dtype=torch.int32) x1_int =", "limit may be too much or too little. It would be better to", "int( np.ceil(N * img_h * img_w * BYTES_PER_FLOAT / GPU_MEM_LIMIT)) assert (num_chunks <=", "(3, ) rcnn_test_cfg (dict): rcnn testing config ori_shape: original image size Returns: list[list]:", "= False self.loss_mask = build_loss(loss_mask) self.convs = nn.ModuleList() for i in range(self.num_convs): in_channels", "import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import ConvModule, build_upsample_layer", "from parallelism for larger chunks, # but may have memory issue num_chunks =", "= (masks_chunk * 255).to(dtype=torch.uint8) im_mask[(inds, ) + spatial_inds] = masks_chunk for i in", "self.class_agnostic: loss_mask = self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels)) else: loss_mask = self.loss_mask(mask_pred, mask_targets, labels) loss['loss_mask']", "by one, # this has more operations but is faster on COCO-scale dataset.", "one is the slice object. If skip_empty == False, the whole image will", "import auto_fp16, force_fp32 from torch.nn.modules.utils import _pair from mmdet.core import mask_target from mmdet.models.builder", "on available resources. GPU_MEM_LIMIT = 1024**3 # 1 GB memory limit @HEADS.register_module() class", "img_y[:, :, None].expand(N, img_y.size(1), img_x.size(1)) grid = torch.stack([gx, gy], dim=3) img_masks = F.grid_sample(", "else in_channels) upsample_cfg_ = self.upsample_cfg.copy() if self.upsample_method is None: self.upsample = None elif", "= self.relu(x) mask_pred = self.conv_logits(x) return mask_pred def get_targets(self, sampling_results, gt_masks, rcnn_train_cfg): pos_proposals", "# suppress warnings align_corners = (None if self.upsample_method == 'nearest' else False) upsample_cfg_.update(", "torch.uint8) if not self.class_agnostic: mask_pred = mask_pred[range(N), labels][:, None] for inds in chunks:", "( self.conv_out_channels if self.upsample_method == 'deconv' else upsample_in_channels) self.conv_logits = Conv2d(logits_in_channel, out_channels, 1)", "0: loss_mask = mask_pred.sum() * 0 else: if self.class_agnostic: loss_mask = self.loss_mask(mask_pred, mask_targets,", "testing config ori_shape: original image size Returns: list[list]: encoded masks \"\"\" if isinstance(mask_pred,", "None) self.num_classes = num_classes self.class_agnostic = class_agnostic self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg", "det_bboxes (Tensor): shape (n, 4/5) det_labels (Tensor): shape (n, ) img_shape (Tensor): shape", "= torch.stack([gx, gy], dim=3) img_masks = F.grid_sample( masks.to(dtype=torch.float32), grid, align_corners=False) if skip_empty: return", "mask_pred.sum() * 0 else: if self.class_agnostic: loss_mask = self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels)) else: loss_mask", "det_bboxes.new_tensor(mask_pred) device = mask_pred.device cls_segms = [[] for _ in range(self.num_classes) ] #", "upsample_cfg_.update( in_channels=upsample_in_channels, out_channels=self.conv_out_channels, kernel_size=self.scale_factor, stride=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) elif self.upsample_method == 'carafe': upsample_cfg_.update(", "= img_y[:, :, None].expand(N, img_y.size(1), img_x.size(1)) grid = torch.stack([gx, gy], dim=3) img_masks =", "align_corners=False) if skip_empty: return img_masks[:, 0], (slice(y0_int, y1_int), slice(x0_int, x1_int)) else: return img_masks[:,", "item is mask tensor, the second one is the slice object. If skip_empty", "and paste them chunk by chunk. if device.type == 'cpu': # CPU is", "shape (n, #class, h, w). For single-scale testing, mask_pred is the direct output", "by one with # skip_empty=True, so that it performs minimal number of #", "chunks: masks_chunk, spatial_inds = _do_paste_mask( mask_pred[inds], bboxes[inds], img_h, img_w, skip_empty=device.type == 'cpu') if", "# this has more operations but is faster on COCO-scale dataset. device =", "loss_weight=1.0)): super(FCNMaskHead, self).__init__() self.upsample_cfg = upsample_cfg.copy() if self.upsample_cfg['type'] not in [ None, 'deconv',", "torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import ConvModule,", "'carafe': upsample_cfg_.update( channels=upsample_in_channels, scale_factor=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) else: # suppress warnings align_corners =", "import CARAFEPack from mmcv.runner import auto_fp16, force_fp32 from torch.nn.modules.utils import _pair from mmdet.core", "the image to be pasted. img_w (int): Width of the image to be", "parallelism for larger chunks, # but may have memory issue num_chunks = int(", "= ( self.in_channels if i == 0 else self.conv_out_channels) padding = (self.conv_kernel_size -", "will return a mask of shape (N, img_h, img_w) and an empty tuple.", "True, only area around the mask will be pasted. A mask of shape", "rcnn testing config ori_shape: original image size Returns: list[list]: encoded masks \"\"\" if", "img_w, device=device, dtype=torch.bool if threshold >= 0 else torch.uint8) if not self.class_agnostic: mask_pred", "HEADS, build_loss BYTES_PER_FLOAT = 4 # TODO: This memory limit may be too", "shape (N, img_h, img_w) and an empty tuple. If skip_empty == True, only", "* img_h * img_w * BYTES_PER_FLOAT / GPU_MEM_LIMIT)) assert (num_chunks <= N), 'Default", "_ in range(self.num_classes) ] # BG is not included in num_classes bboxes =", "np.round(ori_shape[0] * scale_factor).astype(np.int32) img_w = np.round(ori_shape[1] * scale_factor).astype(np.int32) else: w_scale, h_scale = scale_factor[0],", "converted to numpy array outside of this method. det_bboxes (Tensor): shape (n, 4/5)", "torch.Tensor): mask_pred = mask_pred.sigmoid() else: mask_pred = det_bboxes.new_tensor(mask_pred) device = mask_pred.device cls_segms =", "self.upsample_method == 'deconv' else upsample_in_channels) self.conv_logits = Conv2d(logits_in_channel, out_channels, 1) self.relu = nn.ReLU(inplace=True)", "self.upsample_method == 'deconv': upsample_cfg_.update( in_channels=upsample_in_channels, out_channels=self.conv_out_channels, kernel_size=self.scale_factor, stride=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) elif self.upsample_method", "h_scale = scale_factor[0], scale_factor[1] img_h = np.round(ori_shape[0] * h_scale.item()).astype( np.int32) img_w = np.round(ori_shape[1]", "import HEADS, build_loss BYTES_PER_FLOAT = 4 # TODO: This memory limit may be", "roi_feat_size is reserved and not used self.roi_feat_size = _pair(roi_feat_size) self.in_channels = in_channels self.conv_kernel_size", "conv in self.convs: x = conv(x) if self.upsample is not None: x =", "\"\"\"Paste instance masks acoording to boxes. This implementation is modified from https://github.com/facebookresearch/detectron2/ Args:", "type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)): super(FCNMaskHead, self).__init__() self.upsample_cfg = upsample_cfg.copy() if self.upsample_cfg['type'] not in [", "= N else: # GPU benefits from parallelism for larger chunks, # but", "mask_pred, mask_targets, labels): loss = dict() if mask_pred.size(0) == 0: loss_mask = mask_pred.sum()", "be converted to numpy array outside of this method. det_bboxes (Tensor): shape (n,", "self.class_agnostic else self.num_classes logits_in_channel = ( self.conv_out_channels if self.upsample_method == 'deconv' else upsample_in_channels)", "num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None, norm_cfg=None, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)): super(FCNMaskHead, self).__init__() self.upsample_cfg", "self.upsample_method == 'nearest' else False) upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method, align_corners=align_corners) self.upsample = build_upsample_layer(upsample_cfg_) out_channels", "= det_labels if rescale: img_h, img_w = ori_shape[:2] else: if isinstance(scale_factor, float): img_h", "masks_chunk, spatial_inds = _do_paste_mask( mask_pred[inds], bboxes[inds], img_h, img_w, skip_empty=device.type == 'cpu') if threshold", "inds in chunks: masks_chunk, spatial_inds = _do_paste_mask( mask_pred[inds], bboxes[inds], img_h, img_w, skip_empty=device.type ==", "This memory limit may be too much or too little. It would be", "img_x.size(1)) grid = torch.stack([gx, gy], dim=3) img_masks = F.grid_sample( masks.to(dtype=torch.float32), grid, align_corners=False) if", "build_loss BYTES_PER_FLOAT = 4 # TODO: This memory limit may be too much", "it based on available resources. GPU_MEM_LIMIT = 1024**3 # 1 GB memory limit", "= Conv2d(logits_in_channel, out_channels, 1) self.relu = nn.ReLU(inplace=True) self.debug_imgs = None def init_weights(self): for", "Args: mask_pred (Tensor or ndarray): shape (n, #class, h, w). For single-scale testing,", "but may have memory issue num_chunks = int( np.ceil(N * img_h * img_w", "channels=upsample_in_channels, scale_factor=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) else: # suppress warnings align_corners = (None if", "from mask_pred and bboxes. Args: mask_pred (Tensor or ndarray): shape (n, #class, h,", "h_scale.item()).astype( np.int32) img_w = np.round(ori_shape[1] * w_scale.item()).astype( np.int32) scale_factor = 1.0 if not", ">= 0: masks_chunk = (masks_chunk >= threshold).to(dtype=torch.bool) else: # for visualization and debugging", "to be pasted. img_w (int): Width of the image to be pasted. skip_empty", "its start and end coordinates in the original image will be returned. \"\"\"", "None: self.upsample = None elif self.upsample_method == 'deconv': upsample_cfg_.update( in_channels=upsample_in_channels, out_channels=self.conv_out_channels, kernel_size=self.scale_factor, stride=self.scale_factor)", "rescale): \"\"\"Get segmentation masks from mask_pred and bboxes. Args: mask_pred (Tensor or ndarray):", "image to be pasted. skip_empty (bool): Only paste masks within the region that", "else torch.uint8) if not self.class_agnostic: mask_pred = mask_pred[range(N), labels][:, None] for inds in", "= loss_mask return loss def get_seg_masks(self, mask_pred, det_bboxes, det_labels, rcnn_test_cfg, ori_shape, scale_factor, rescale):", "to # determine it based on available resources. GPU_MEM_LIMIT = 1024**3 # 1", "self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels = ( self.conv_out_channels if self.num_convs > 0 else", "too little. It would be better to # determine it based on available", "* w_scale.item()).astype( np.int32) scale_factor = 1.0 if not isinstance(scale_factor, (float, torch.Tensor)): scale_factor =", "get_seg_masks(self, mask_pred, det_bboxes, det_labels, rcnn_test_cfg, ori_shape, scale_factor, rescale): \"\"\"Get segmentation masks from mask_pred", "0 else in_channels) upsample_cfg_ = self.upsample_cfg.copy() if self.upsample_method is None: self.upsample = None", "scale_factor=2), conv_cfg=None, norm_cfg=None, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)): super(FCNMaskHead, self).__init__() self.upsample_cfg = upsample_cfg.copy() if", "self.in_channels if i == 0 else self.conv_out_channels) padding = (self.conv_kernel_size - 1) //", "https://github.com/facebookresearch/detectron2/ Args: masks (Tensor): N, 1, H, W boxes (Tensor): N, 4 img_h", "pasting them one by one, # this has more operations but is faster", "norm_cfg self.fp16_enabled = False self.loss_mask = build_loss(loss_mask) self.convs = nn.ModuleList() for i in", "tuple: (Tensor, tuple). The first item is mask tensor, the second one is", "img_y.size(1), img_x.size(1)) grid = torch.stack([gx, gy], dim=3) img_masks = F.grid_sample( masks.to(dtype=torch.float32), grid, align_corners=False)", "for larger chunks, # but may have memory issue num_chunks = int( np.ceil(N", "method {self.upsample_cfg[\"type\"]}, ' 'accepted methods are \"deconv\", \"nearest\", \"bilinear\", ' '\"carafe\"') self.num_convs =", "is reserved and not used self.roi_feat_size = _pair(roi_feat_size) self.in_channels = in_channels self.conv_kernel_size =", "img_x.size(1)) gy = img_y[:, :, None].expand(N, img_y.size(1), img_x.size(1)) grid = torch.stack([gx, gy], dim=3)", "most efficient when they are pasted one by one with # skip_empty=True, so", "m in [self.upsample, self.conv_logits]: if m is None: continue elif isinstance(m, CARAFEPack): m.init_weights()", "from https://github.com/facebookresearch/detectron2/ Args: masks (Tensor): N, 1, H, W boxes (Tensor): N, 4", "CPU is most efficient when they are pasted one by one with #", "threshold).to(dtype=torch.bool) else: # for visualization and debugging masks_chunk = (masks_chunk * 255).to(dtype=torch.uint8) im_mask[(inds,", "res.pos_assigned_gt_inds for res in sampling_results ] mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks, rcnn_train_cfg) return", "the input into chunks, # and paste them chunk by chunk. if device.type", "chunk size) # by using the entire image to sample the masks #", "larger chunks, # but may have memory issue num_chunks = int( np.ceil(N *", "skip_empty=True): \"\"\"Paste instance masks acoording to boxes. This implementation is modified from https://github.com/facebookresearch/detectron2/", "x = self.relu(x) mask_pred = self.conv_logits(x) return mask_pred def get_targets(self, sampling_results, gt_masks, rcnn_train_cfg):", "img_h, img_w, skip_empty=device.type == 'cpu') if threshold >= 0: masks_chunk = (masks_chunk >=", "(N, h) if torch.isinf(img_x).any(): inds = torch.where(torch.isinf(img_x)) img_x[inds] = 0 if torch.isinf(img_y).any(): inds", "all masks together (up to chunk size) # by using the entire image", "for conv in self.convs: x = conv(x) if self.upsample is not None: x", "np.round(ori_shape[1] * scale_factor).astype(np.int32) else: w_scale, h_scale = scale_factor[0], scale_factor[1] img_h = np.round(ori_shape[0] *", "]: raise ValueError( f'Invalid upsample method {self.upsample_cfg[\"type\"]}, ' 'accepted methods are \"deconv\", \"nearest\",", "return mask_targets @force_fp32(apply_to=('mask_pred', )) def loss(self, mask_pred, mask_targets, labels): loss = dict() if", "BG is not included in num_classes bboxes = det_bboxes[:, :4] labels = det_labels", "y0) * 2 - 1 img_x = (img_x - x0) / (x1 -", "= _do_paste_mask( mask_pred[inds], bboxes[inds], img_h, img_w, skip_empty=device.type == 'cpu') if threshold >= 0:", "mmdet.models.builder import HEADS, build_loss BYTES_PER_FLOAT = 4 # TODO: This memory limit may", "N, 1, H, W boxes (Tensor): N, 4 img_h (int): Height of the", "np.int32) scale_factor = 1.0 if not isinstance(scale_factor, (float, torch.Tensor)): scale_factor = bboxes.new_tensor(scale_factor) bboxes", "better to # determine it based on available resources. GPU_MEM_LIMIT = 1024**3 #", "in the original image will be returned. \"\"\" # On GPU, paste all", "scale_factor[0], scale_factor[1] img_h = np.round(ori_shape[0] * h_scale.item()).astype( np.int32) img_w = np.round(ori_shape[1] * w_scale.item()).astype(", "return cls_segms def _do_paste_mask(masks, boxes, img_h, img_w, skip_empty=True): \"\"\"Paste instance masks acoording to", "1 if self.class_agnostic else self.num_classes logits_in_channel = ( self.conv_out_channels if self.upsample_method == 'deconv'", "2 - 1 img_x = (img_x - x0) / (x1 - x0) *", "import torch.nn.functional as F from mmcv.cnn import ConvModule, build_upsample_layer from mmcv.ops import Conv2d", "self.in_channels = in_channels self.conv_kernel_size = conv_kernel_size self.conv_out_channels = conv_out_channels self.upsample_method = self.upsample_cfg.get('type') self.scale_factor", "x1_int, y1_int = img_w, img_h x0, y0, x1, y1 = torch.split(boxes, 1, dim=1)", "as F from mmcv.cnn import ConvModule, build_upsample_layer from mmcv.ops import Conv2d from mmcv.ops.carafe", "On GPU, paste all masks together (up to chunk size) # by using", "x1, y1 = torch.split(boxes, 1, dim=1) # each is Nx1 N = masks.shape[0]", "build_upsample_layer from mmcv.ops import Conv2d from mmcv.ops.carafe import CARAFEPack from mmcv.runner import auto_fp16,", "conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled = False self.loss_mask = build_loss(loss_mask) self.convs = nn.ModuleList()", "the slice object. If skip_empty == False, the whole image will be pasted.", "mask of shape (N, h', w') and its start and end coordinates in", "0 else torch.uint8) if not self.class_agnostic: mask_pred = mask_pred[range(N), labels][:, None] for inds", "gt_masks, rcnn_train_cfg): pos_proposals = [res.pos_bboxes for res in sampling_results] pos_assigned_gt_inds = [ res.pos_assigned_gt_inds", "if not isinstance(scale_factor, (float, torch.Tensor)): scale_factor = bboxes.new_tensor(scale_factor) bboxes = bboxes / scale_factor", "] # BG is not included in num_classes bboxes = det_bboxes[:, :4] labels", "= 0 if torch.isinf(img_y).any(): inds = torch.where(torch.isinf(img_y)) img_y[inds] = 0 gx = img_x[:,", "if self.upsample_method is None: self.upsample = None elif self.upsample_method == 'deconv': upsample_cfg_.update( in_channels=upsample_in_channels,", "num_chunks) threshold = rcnn_test_cfg.mask_thr_binary im_mask = torch.zeros( N, img_h, img_w, device=device, dtype=torch.bool if", "(Tensor, tuple). The first item is mask tensor, the second one is the", "0.5 img_x = torch.arange( x0_int, x1_int, device=device, dtype=torch.float32) + 0.5 img_y = (img_y", "(n, 4/5) det_labels (Tensor): shape (n, ) img_shape (Tensor): shape (3, ) rcnn_test_cfg", "It will return a mask of shape (N, img_h, img_w) and an empty", "= torch.clamp( boxes[:, 3].max().ceil() + 1, max=img_h).to(dtype=torch.int32) else: x0_int, y0_int = 0, 0", "= ( self.conv_out_channels if self.num_convs > 0 else in_channels) upsample_cfg_ = self.upsample_cfg.copy() if", "whose type is Tensor, while for multi-scale testing, it will be converted to", "torch.zeros( N, img_h, img_w, device=device, dtype=torch.bool if threshold >= 0 else torch.uint8) if", "def loss(self, mask_pred, mask_targets, labels): loss = dict() if mask_pred.size(0) == 0: loss_mask", "float): img_h = np.round(ori_shape[0] * scale_factor).astype(np.int32) img_w = np.round(ori_shape[1] * scale_factor).astype(np.int32) else: w_scale,", "bboxes[inds], img_h, img_w, skip_empty=device.type == 'cpu') if threshold >= 0: masks_chunk = (masks_chunk", "all boxes, and returns the results this region only. An important optimization for", "# Compared to pasting them one by one, # this has more operations", "It would be better to # determine it based on available resources. GPU_MEM_LIMIT", "a mask of shape (N, img_h, img_w) and an empty tuple. If skip_empty", "but is faster on COCO-scale dataset. device = masks.device if skip_empty: x0_int, y0_int", "device=device, dtype=torch.bool if threshold >= 0 else torch.uint8) if not self.class_agnostic: mask_pred =", "if skip_empty: return img_masks[:, 0], (slice(y0_int, y1_int), slice(x0_int, x1_int)) else: return img_masks[:, 0],", "from mmcv.ops.carafe import CARAFEPack from mmcv.runner import auto_fp16, force_fp32 from torch.nn.modules.utils import _pair", "is too small; try increasing it' chunks = torch.chunk(torch.arange(N, device=device), num_chunks) threshold =", "= ori_shape[:2] else: if isinstance(scale_factor, float): img_h = np.round(ori_shape[0] * scale_factor).astype(np.int32) img_w =", "results this region only. An important optimization for CPU. Returns: tuple: (Tensor, tuple).", "not None: x = self.upsample(x) if self.upsample_method == 'deconv': x = self.relu(x) mask_pred", "0 x1_int, y1_int = img_w, img_h x0, y0, x1, y1 = torch.split(boxes, 1,", "self.conv_kernel_size = conv_kernel_size self.conv_out_channels = conv_out_channels self.upsample_method = self.upsample_cfg.get('type') self.scale_factor = self.upsample_cfg.pop('scale_factor', None)", "skip_empty (bool): Only paste masks within the region that tightly bound all boxes,", "this has more operations but is faster on COCO-scale dataset. device = masks.device", "'bilinear', 'carafe' ]: raise ValueError( f'Invalid upsample method {self.upsample_cfg[\"type\"]}, ' 'accepted methods are", "is Nx1 N = masks.shape[0] img_y = torch.arange( y0_int, y1_int, device=device, dtype=torch.float32) +", "to boxes. This implementation is modified from https://github.com/facebookresearch/detectron2/ Args: masks (Tensor): N, 1,", "(float, torch.Tensor)): scale_factor = bboxes.new_tensor(scale_factor) bboxes = bboxes / scale_factor N = len(mask_pred)", ">= threshold).to(dtype=torch.bool) else: # for visualization and debugging masks_chunk = (masks_chunk * 255).to(dtype=torch.uint8)", "the original image will be returned. \"\"\" # On GPU, paste all masks", "else upsample_in_channels) self.conv_logits = Conv2d(logits_in_channel, out_channels, 1) self.relu = nn.ReLU(inplace=True) self.debug_imgs = None", "device=device, dtype=torch.float32) + 0.5 img_y = (img_y - y0) / (y1 - y0)", "WARN: roi_feat_size is reserved and not used self.roi_feat_size = _pair(roi_feat_size) self.in_channels = in_channels", "continue elif isinstance(m, CARAFEPack): m.init_weights() else: nn.init.kaiming_normal_( m.weight, mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias, 0) @auto_fp16()", "the direct output of model, whose type is Tensor, while for multi-scale testing,", "= [[] for _ in range(self.num_classes) ] # BG is not included in", "torch.stack([gx, gy], dim=3) img_masks = F.grid_sample( masks.to(dtype=torch.float32), grid, align_corners=False) if skip_empty: return img_masks[:,", "are \"deconv\", \"nearest\", \"bilinear\", ' '\"carafe\"') self.num_convs = num_convs # WARN: roi_feat_size is", "False self.loss_mask = build_loss(loss_mask) self.convs = nn.ModuleList() for i in range(self.num_convs): in_channels =", "if m is None: continue elif isinstance(m, CARAFEPack): m.init_weights() else: nn.init.kaiming_normal_( m.weight, mode='fan_out',", "* 0 else: if self.class_agnostic: loss_mask = self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels)) else: loss_mask =", "bboxes. Args: mask_pred (Tensor or ndarray): shape (n, #class, h, w). For single-scale", "= dict() if mask_pred.size(0) == 0: loss_mask = mask_pred.sum() * 0 else: if", "of # operations. num_chunks = N else: # GPU benefits from parallelism for", "mode=self.upsample_method, align_corners=align_corners) self.upsample = build_upsample_layer(upsample_cfg_) out_channels = 1 if self.class_agnostic else self.num_classes logits_in_channel", "for visualization and debugging masks_chunk = (masks_chunk * 255).to(dtype=torch.uint8) im_mask[(inds, ) + spatial_inds]", "(Tensor): N, 1, H, W boxes (Tensor): N, 4 img_h (int): Height of", "GPU_MEM_LIMIT is too small; try increasing it' chunks = torch.chunk(torch.arange(N, device=device), num_chunks) threshold", "in_channels) upsample_cfg_ = self.upsample_cfg.copy() if self.upsample_method is None: self.upsample = None elif self.upsample_method", "(Tensor): shape (3, ) rcnn_test_cfg (dict): rcnn testing config ori_shape: original image size", "in_channels self.conv_kernel_size = conv_kernel_size self.conv_out_channels = conv_out_channels self.upsample_method = self.upsample_cfg.get('type') self.scale_factor = self.upsample_cfg.pop('scale_factor',", "align_corners = (None if self.upsample_method == 'nearest' else False) upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method, align_corners=align_corners)", "original image size Returns: list[list]: encoded masks \"\"\" if isinstance(mask_pred, torch.Tensor): mask_pred =", "# The actual implementation split the input into chunks, # and paste them", "threshold >= 0: masks_chunk = (masks_chunk >= threshold).to(dtype=torch.bool) else: # for visualization and", "norm_cfg=norm_cfg)) upsample_in_channels = ( self.conv_out_channels if self.num_convs > 0 else in_channels) upsample_cfg_ =", "issue num_chunks = int( np.ceil(N * img_h * img_w * BYTES_PER_FLOAT / GPU_MEM_LIMIT))", "3].max().ceil() + 1, max=img_h).to(dtype=torch.int32) else: x0_int, y0_int = 0, 0 x1_int, y1_int =", "for multi-scale testing, it will be converted to numpy array outside of this", "/ GPU_MEM_LIMIT)) assert (num_chunks <= N), 'Default GPU_MEM_LIMIT is too small; try increasing", "= _pair(roi_feat_size) self.in_channels = in_channels self.conv_kernel_size = conv_kernel_size self.conv_out_channels = conv_out_channels self.upsample_method =", "res in sampling_results] pos_assigned_gt_inds = [ res.pos_assigned_gt_inds for res in sampling_results ] mask_targets", "will be converted to numpy array outside of this method. det_bboxes (Tensor): shape", "x0) / (x1 - x0) * 2 - 1 # img_x, img_y have", "else: # for visualization and debugging masks_chunk = (masks_chunk * 255).to(dtype=torch.uint8) im_mask[(inds, )", "# On GPU, paste all masks together (up to chunk size) # by", "x0, y0, x1, y1 = torch.split(boxes, 1, dim=1) # each is Nx1 N", "= int( np.ceil(N * img_h * img_w * BYTES_PER_FLOAT / GPU_MEM_LIMIT)) assert (num_chunks", "the region that tightly bound all boxes, and returns the results this region", "much or too little. It would be better to # determine it based", "(self.conv_kernel_size - 1) // 2 self.convs.append( ConvModule( in_channels, self.conv_out_channels, self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg))", "if skip_empty: x0_int, y0_int = torch.clamp( boxes.min(dim=0).values.floor()[:2] - 1, min=0).to(dtype=torch.int32) x1_int = torch.clamp(", "conv_out_channels=256, num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None, norm_cfg=None, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)): super(FCNMaskHead, self).__init__()", "self.upsample_method == 'deconv': x = self.relu(x) mask_pred = self.conv_logits(x) return mask_pred def get_targets(self,", "important optimization for CPU. Returns: tuple: (Tensor, tuple). The first item is mask", "self.upsample = None elif self.upsample_method == 'deconv': upsample_cfg_.update( in_channels=upsample_in_channels, out_channels=self.conv_out_channels, kernel_size=self.scale_factor, stride=self.scale_factor) self.upsample", "the masks # Compared to pasting them one by one, # this has", "labels][:, None] for inds in chunks: masks_chunk, spatial_inds = _do_paste_mask( mask_pred[inds], bboxes[inds], img_h,", "else: if isinstance(scale_factor, float): img_h = np.round(ori_shape[0] * scale_factor).astype(np.int32) img_w = np.round(ori_shape[1] *", "(n, #class, h, w). For single-scale testing, mask_pred is the direct output of", "loss_mask = self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels)) else: loss_mask = self.loss_mask(mask_pred, mask_targets, labels) loss['loss_mask'] =", "get_targets(self, sampling_results, gt_masks, rcnn_train_cfg): pos_proposals = [res.pos_bboxes for res in sampling_results] pos_assigned_gt_inds =", "of model, whose type is Tensor, while for multi-scale testing, it will be", "masks \"\"\" if isinstance(mask_pred, torch.Tensor): mask_pred = mask_pred.sigmoid() else: mask_pred = det_bboxes.new_tensor(mask_pred) device", "masks_chunk = (masks_chunk * 255).to(dtype=torch.uint8) im_mask[(inds, ) + spatial_inds] = masks_chunk for i", "around the mask will be pasted. A mask of shape (N, h', w')", "class FCNMaskHead(nn.Module): def __init__(self, num_convs=4, roi_feat_size=14, in_channels=256, conv_kernel_size=3, conv_out_channels=256, num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2),", "'cpu': # CPU is most efficient when they are pasted one by one", "visualization and debugging masks_chunk = (masks_chunk * 255).to(dtype=torch.uint8) im_mask[(inds, ) + spatial_inds] =", "torch.clamp( boxes.min(dim=0).values.floor()[:2] - 1, min=0).to(dtype=torch.int32) x1_int = torch.clamp( boxes[:, 2].max().ceil() + 1, max=img_w).to(dtype=torch.int32)", "is mask tensor, the second one is the slice object. If skip_empty ==", "1, max=img_h).to(dtype=torch.int32) else: x0_int, y0_int = 0, 0 x1_int, y1_int = img_w, img_h", "padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels = ( self.conv_out_channels if self.num_convs > 0 else in_channels)", "] mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks, rcnn_train_cfg) return mask_targets @force_fp32(apply_to=('mask_pred', )) def loss(self,", "mmcv.ops import Conv2d from mmcv.ops.carafe import CARAFEPack from mmcv.runner import auto_fp16, force_fp32 from", "num_classes self.class_agnostic = class_agnostic self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled = False", "= (img_y - y0) / (y1 - y0) * 2 - 1 img_x", "img_x = (img_x - x0) / (x1 - x0) * 2 - 1", "conv_kernel_size self.conv_out_channels = conv_out_channels self.upsample_method = self.upsample_cfg.get('type') self.scale_factor = self.upsample_cfg.pop('scale_factor', None) self.num_classes =", "num_convs # WARN: roi_feat_size is reserved and not used self.roi_feat_size = _pair(roi_feat_size) self.in_channels", "mask_pred = mask_pred[range(N), labels][:, None] for inds in chunks: masks_chunk, spatial_inds = _do_paste_mask(", "masks together (up to chunk size) # by using the entire image to", "threshold = rcnn_test_cfg.mask_thr_binary im_mask = torch.zeros( N, img_h, img_w, device=device, dtype=torch.bool if threshold", "is not included in num_classes bboxes = det_bboxes[:, :4] labels = det_labels if", "if self.num_convs > 0 else in_channels) upsample_cfg_ = self.upsample_cfg.copy() if self.upsample_method is None:", "loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)): super(FCNMaskHead, self).__init__() self.upsample_cfg = upsample_cfg.copy() if self.upsample_cfg['type'] not in", "single-scale testing, mask_pred is the direct output of model, whose type is Tensor,", "boxes[:, 3].max().ceil() + 1, max=img_h).to(dtype=torch.int32) else: x0_int, y0_int = 0, 0 x1_int, y1_int", "else: x0_int, y0_int = 0, 0 x1_int, y1_int = img_w, img_h x0, y0,", "model, whose type is Tensor, while for multi-scale testing, it will be converted", "sampling_results] pos_assigned_gt_inds = [ res.pos_assigned_gt_inds for res in sampling_results ] mask_targets = mask_target(pos_proposals,", "Nx1 N = masks.shape[0] img_y = torch.arange( y0_int, y1_int, device=device, dtype=torch.float32) + 0.5", "[self.upsample, self.conv_logits]: if m is None: continue elif isinstance(m, CARAFEPack): m.init_weights() else: nn.init.kaiming_normal_(", "mask_pred def get_targets(self, sampling_results, gt_masks, rcnn_train_cfg): pos_proposals = [res.pos_bboxes for res in sampling_results]", "self.upsample = build_upsample_layer(upsample_cfg_) else: # suppress warnings align_corners = (None if self.upsample_method ==", "= build_upsample_layer(upsample_cfg_) else: # suppress warnings align_corners = (None if self.upsample_method == 'nearest'", "and returns the results this region only. An important optimization for CPU. Returns:", "y0) / (y1 - y0) * 2 - 1 img_x = (img_x -", "img_h * img_w * BYTES_PER_FLOAT / GPU_MEM_LIMIT)) assert (num_chunks <= N), 'Default GPU_MEM_LIMIT", "reserved and not used self.roi_feat_size = _pair(roi_feat_size) self.in_channels = in_channels self.conv_kernel_size = conv_kernel_size", "_pair from mmdet.core import mask_target from mmdet.models.builder import HEADS, build_loss BYTES_PER_FLOAT = 4", "skip_empty: return img_masks[:, 0], (slice(y0_int, y1_int), slice(x0_int, x1_int)) else: return img_masks[:, 0], ()", "in sampling_results ] mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks, rcnn_train_cfg) return mask_targets @force_fp32(apply_to=('mask_pred', ))", "boxes, img_h, img_w, skip_empty=True): \"\"\"Paste instance masks acoording to boxes. This implementation is", "kernel_size=self.scale_factor, stride=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) elif self.upsample_method == 'carafe': upsample_cfg_.update( channels=upsample_in_channels, scale_factor=self.scale_factor) self.upsample", "= class_agnostic self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled = False self.loss_mask =", "self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels)) else: loss_mask = self.loss_mask(mask_pred, mask_targets, labels) loss['loss_mask'] = loss_mask return", "= np.round(ori_shape[0] * scale_factor).astype(np.int32) img_w = np.round(ori_shape[1] * scale_factor).astype(np.int32) else: w_scale, h_scale =", "/ (x1 - x0) * 2 - 1 # img_x, img_y have shapes", "self.upsample_method is None: self.upsample = None elif self.upsample_method == 'deconv': upsample_cfg_.update( in_channels=upsample_in_channels, out_channels=self.conv_out_channels,", "image will be pasted. It will return a mask of shape (N, img_h,", "efficient when they are pasted one by one with # skip_empty=True, so that", "0.5 img_y = (img_y - y0) / (y1 - y0) * 2 -", "while for multi-scale testing, it will be converted to numpy array outside of", "object. If skip_empty == False, the whole image will be pasted. It will", "be pasted. A mask of shape (N, h', w') and its start and", "= upsample_cfg.copy() if self.upsample_cfg['type'] not in [ None, 'deconv', 'nearest', 'bilinear', 'carafe' ]:", "ValueError( f'Invalid upsample method {self.upsample_cfg[\"type\"]}, ' 'accepted methods are \"deconv\", \"nearest\", \"bilinear\", '", "img_w, img_h x0, y0, x1, y1 = torch.split(boxes, 1, dim=1) # each is", "testing, it will be converted to numpy array outside of this method. det_bboxes", "def get_seg_masks(self, mask_pred, det_bboxes, det_labels, rcnn_test_cfg, ori_shape, scale_factor, rescale): \"\"\"Get segmentation masks from", "auto_fp16, force_fp32 from torch.nn.modules.utils import _pair from mmdet.core import mask_target from mmdet.models.builder import", "ori_shape: original image size Returns: list[list]: encoded masks \"\"\" if isinstance(mask_pred, torch.Tensor): mask_pred", "# img_x, img_y have shapes (N, w), (N, h) if torch.isinf(img_x).any(): inds =", "self.upsample_cfg['type'] not in [ None, 'deconv', 'nearest', 'bilinear', 'carafe' ]: raise ValueError( f'Invalid", "'nearest', 'bilinear', 'carafe' ]: raise ValueError( f'Invalid upsample method {self.upsample_cfg[\"type\"]}, ' 'accepted methods", "boxes[:, 2].max().ceil() + 1, max=img_w).to(dtype=torch.int32) y1_int = torch.clamp( boxes[:, 3].max().ceil() + 1, max=img_h).to(dtype=torch.int32)", "= conv(x) if self.upsample is not None: x = self.upsample(x) if self.upsample_method ==", "1, H, W boxes (Tensor): N, 4 img_h (int): Height of the image", "1, dim=1) # each is Nx1 N = masks.shape[0] img_y = torch.arange( y0_int,", "returned. \"\"\" # On GPU, paste all masks together (up to chunk size)", "dtype=torch.float32) + 0.5 img_y = (img_y - y0) / (y1 - y0) *", "or too little. It would be better to # determine it based on", "and not used self.roi_feat_size = _pair(roi_feat_size) self.in_channels = in_channels self.conv_kernel_size = conv_kernel_size self.conv_out_channels", "torch.arange( x0_int, x1_int, device=device, dtype=torch.float32) + 0.5 img_y = (img_y - y0) /", "in sampling_results] pos_assigned_gt_inds = [ res.pos_assigned_gt_inds for res in sampling_results ] mask_targets =", "dtype=torch.float32) + 0.5 img_x = torch.arange( x0_int, x1_int, device=device, dtype=torch.float32) + 0.5 img_y", "'deconv' else upsample_in_channels) self.conv_logits = Conv2d(logits_in_channel, out_channels, 1) self.relu = nn.ReLU(inplace=True) self.debug_imgs =", "i in range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return cls_segms def _do_paste_mask(masks, boxes, img_h, img_w, skip_empty=True): \"\"\"Paste", "an empty tuple. If skip_empty == True, only area around the mask will", "y1_int = img_w, img_h x0, y0, x1, y1 = torch.split(boxes, 1, dim=1) #", "for _ in range(self.num_classes) ] # BG is not included in num_classes bboxes", "faster on COCO-scale dataset. device = masks.device if skip_empty: x0_int, y0_int = torch.clamp(", "super(FCNMaskHead, self).__init__() self.upsample_cfg = upsample_cfg.copy() if self.upsample_cfg['type'] not in [ None, 'deconv', 'nearest',", "2 - 1 # img_x, img_y have shapes (N, w), (N, h) if", "based on available resources. GPU_MEM_LIMIT = 1024**3 # 1 GB memory limit @HEADS.register_module()", "methods are \"deconv\", \"nearest\", \"bilinear\", ' '\"carafe\"') self.num_convs = num_convs # WARN: roi_feat_size", "= conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled = False self.loss_mask = build_loss(loss_mask) self.convs =", "elif self.upsample_method == 'deconv': upsample_cfg_.update( in_channels=upsample_in_channels, out_channels=self.conv_out_channels, kernel_size=self.scale_factor, stride=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) elif", "norm_cfg=None, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)): super(FCNMaskHead, self).__init__() self.upsample_cfg = upsample_cfg.copy() if self.upsample_cfg['type'] not", "range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return cls_segms def _do_paste_mask(masks, boxes, img_h, img_w, skip_empty=True): \"\"\"Paste instance masks", "to be pasted. skip_empty (bool): Only paste masks within the region that tightly", "= det_bboxes[:, :4] labels = det_labels if rescale: img_h, img_w = ori_shape[:2] else:", "pasted. skip_empty (bool): Only paste masks within the region that tightly bound all", "region only. An important optimization for CPU. Returns: tuple: (Tensor, tuple). The first", "have shapes (N, w), (N, h) if torch.isinf(img_x).any(): inds = torch.where(torch.isinf(img_x)) img_x[inds] =", "= 0, 0 x1_int, y1_int = img_w, img_h x0, y0, x1, y1 =", "img_y.size(1), img_x.size(1)) gy = img_y[:, :, None].expand(N, img_y.size(1), img_x.size(1)) grid = torch.stack([gx, gy],", "ndarray): shape (n, #class, h, w). For single-scale testing, mask_pred is the direct", "= 4 # TODO: This memory limit may be too much or too", "only. An important optimization for CPU. Returns: tuple: (Tensor, tuple). The first item", "loss_mask return loss def get_seg_masks(self, mask_pred, det_bboxes, det_labels, rcnn_test_cfg, ori_shape, scale_factor, rescale): \"\"\"Get", "(n, ) img_shape (Tensor): shape (3, ) rcnn_test_cfg (dict): rcnn testing config ori_shape:", "# and paste them chunk by chunk. if device.type == 'cpu': # CPU", "CARAFEPack from mmcv.runner import auto_fp16, force_fp32 from torch.nn.modules.utils import _pair from mmdet.core import", "in range(self.num_convs): in_channels = ( self.in_channels if i == 0 else self.conv_out_channels) padding", "- 1) // 2 self.convs.append( ConvModule( in_channels, self.conv_out_channels, self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels", "would be better to # determine it based on available resources. GPU_MEM_LIMIT =", "them chunk by chunk. if device.type == 'cpu': # CPU is most efficient", "<reponame>jstzwjr/mmdetection<gh_stars>1-10 import numpy as np import torch import torch.nn as nn import torch.nn.functional", "the second one is the slice object. If skip_empty == False, the whole", "img_x = torch.arange( x0_int, x1_int, device=device, dtype=torch.float32) + 0.5 img_y = (img_y -", "* h_scale.item()).astype( np.int32) img_w = np.round(ori_shape[1] * w_scale.item()).astype( np.int32) scale_factor = 1.0 if", "chunk. if device.type == 'cpu': # CPU is most efficient when they are", "minimal number of # operations. num_chunks = N else: # GPU benefits from", "operations. num_chunks = N else: # GPU benefits from parallelism for larger chunks,", "mask_pred, det_bboxes, det_labels, rcnn_test_cfg, ori_shape, scale_factor, rescale): \"\"\"Get segmentation masks from mask_pred and", "= ( self.conv_out_channels if self.upsample_method == 'deconv' else upsample_in_channels) self.conv_logits = Conv2d(logits_in_channel, out_channels,", ":4] labels = det_labels if rescale: img_h, img_w = ori_shape[:2] else: if isinstance(scale_factor,", "increasing it' chunks = torch.chunk(torch.arange(N, device=device), num_chunks) threshold = rcnn_test_cfg.mask_thr_binary im_mask = torch.zeros(", "pasted. It will return a mask of shape (N, img_h, img_w) and an", "= torch.zeros( N, img_h, img_w, device=device, dtype=torch.bool if threshold >= 0 else torch.uint8)", "paste masks within the region that tightly bound all boxes, and returns the", "GPU_MEM_LIMIT)) assert (num_chunks <= N), 'Default GPU_MEM_LIMIT is too small; try increasing it'", "sampling_results ] mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks, rcnn_train_cfg) return mask_targets @force_fp32(apply_to=('mask_pred', )) def", "original image will be returned. \"\"\" # On GPU, paste all masks together", "small; try increasing it' chunks = torch.chunk(torch.arange(N, device=device), num_chunks) threshold = rcnn_test_cfg.mask_thr_binary im_mask", "masks within the region that tightly bound all boxes, and returns the results", "is faster on COCO-scale dataset. device = masks.device if skip_empty: x0_int, y0_int =", "self).__init__() self.upsample_cfg = upsample_cfg.copy() if self.upsample_cfg['type'] not in [ None, 'deconv', 'nearest', 'bilinear',", "self.conv_out_channels) padding = (self.conv_kernel_size - 1) // 2 self.convs.append( ConvModule( in_channels, self.conv_out_channels, self.conv_kernel_size,", "elif self.upsample_method == 'carafe': upsample_cfg_.update( channels=upsample_in_channels, scale_factor=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) else: # suppress", "device = mask_pred.device cls_segms = [[] for _ in range(self.num_classes) ] # BG", "len(mask_pred) # The actual implementation split the input into chunks, # and paste", "memory issue num_chunks = int( np.ceil(N * img_h * img_w * BYTES_PER_FLOAT /", "BYTES_PER_FLOAT / GPU_MEM_LIMIT)) assert (num_chunks <= N), 'Default GPU_MEM_LIMIT is too small; try", "y0_int = torch.clamp( boxes.min(dim=0).values.floor()[:2] - 1, min=0).to(dtype=torch.int32) x1_int = torch.clamp( boxes[:, 2].max().ceil() +", "pos_proposals = [res.pos_bboxes for res in sampling_results] pos_assigned_gt_inds = [ res.pos_assigned_gt_inds for res", "be returned. \"\"\" # On GPU, paste all masks together (up to chunk", "torch.arange( y0_int, y1_int, device=device, dtype=torch.float32) + 0.5 img_x = torch.arange( x0_int, x1_int, device=device,", "__init__(self, num_convs=4, roi_feat_size=14, in_channels=256, conv_kernel_size=3, conv_out_channels=256, num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None, norm_cfg=None, loss_mask=dict(", "If skip_empty == True, only area around the mask will be pasted. A", "0 else self.conv_out_channels) padding = (self.conv_kernel_size - 1) // 2 self.convs.append( ConvModule( in_channels,", "img_w = np.round(ori_shape[1] * scale_factor).astype(np.int32) else: w_scale, h_scale = scale_factor[0], scale_factor[1] img_h =", "TODO: This memory limit may be too much or too little. It would", "= in_channels self.conv_kernel_size = conv_kernel_size self.conv_out_channels = conv_out_channels self.upsample_method = self.upsample_cfg.get('type') self.scale_factor =", "multi-scale testing, it will be converted to numpy array outside of this method.", "will be returned. \"\"\" # On GPU, paste all masks together (up to", "num_chunks = int( np.ceil(N * img_h * img_w * BYTES_PER_FLOAT / GPU_MEM_LIMIT)) assert", "0) @auto_fp16() def forward(self, x): for conv in self.convs: x = conv(x) if", "skip_empty: x0_int, y0_int = torch.clamp( boxes.min(dim=0).values.floor()[:2] - 1, min=0).to(dtype=torch.int32) x1_int = torch.clamp( boxes[:,", "self.upsample = build_upsample_layer(upsample_cfg_) out_channels = 1 if self.class_agnostic else self.num_classes logits_in_channel = (", "N = len(mask_pred) # The actual implementation split the input into chunks, #", "x0_int, y0_int = torch.clamp( boxes.min(dim=0).values.floor()[:2] - 1, min=0).to(dtype=torch.int32) x1_int = torch.clamp( boxes[:, 2].max().ceil()", "= len(mask_pred) # The actual implementation split the input into chunks, # and", "boxes (Tensor): N, 4 img_h (int): Height of the image to be pasted.", "loss def get_seg_masks(self, mask_pred, det_bboxes, det_labels, rcnn_test_cfg, ori_shape, scale_factor, rescale): \"\"\"Get segmentation masks", "self.class_agnostic = class_agnostic self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled = False self.loss_mask", "x): for conv in self.convs: x = conv(x) if self.upsample is not None:", "Only paste masks within the region that tightly bound all boxes, and returns", "isinstance(m, CARAFEPack): m.init_weights() else: nn.init.kaiming_normal_( m.weight, mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias, 0) @auto_fp16() def forward(self,", "bboxes = det_bboxes[:, :4] labels = det_labels if rescale: img_h, img_w = ori_shape[:2]", "rescale: img_h, img_w = ori_shape[:2] else: if isinstance(scale_factor, float): img_h = np.round(ori_shape[0] *", "self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled = False self.loss_mask = build_loss(loss_mask) self.convs", "tightly bound all boxes, and returns the results this region only. An important", "GPU, paste all masks together (up to chunk size) # by using the", "img_h x0, y0, x1, y1 = torch.split(boxes, 1, dim=1) # each is Nx1", "gy], dim=3) img_masks = F.grid_sample( masks.to(dtype=torch.float32), grid, align_corners=False) if skip_empty: return img_masks[:, 0],", "= 1 if self.class_agnostic else self.num_classes logits_in_channel = ( self.conv_out_channels if self.upsample_method ==", "region that tightly bound all boxes, and returns the results this region only.", "COCO-scale dataset. device = masks.device if skip_empty: x0_int, y0_int = torch.clamp( boxes.min(dim=0).values.floor()[:2] -", "= None elif self.upsample_method == 'deconv': upsample_cfg_.update( in_channels=upsample_in_channels, out_channels=self.conv_out_channels, kernel_size=self.scale_factor, stride=self.scale_factor) self.upsample =", ") img_shape (Tensor): shape (3, ) rcnn_test_cfg (dict): rcnn testing config ori_shape: original", "== 'deconv': x = self.relu(x) mask_pred = self.conv_logits(x) return mask_pred def get_targets(self, sampling_results,", "# for visualization and debugging masks_chunk = (masks_chunk * 255).to(dtype=torch.uint8) im_mask[(inds, ) +", "scale_factor=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) else: # suppress warnings align_corners = (None if self.upsample_method", "ConvModule( in_channels, self.conv_out_channels, self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels = ( self.conv_out_channels if self.num_convs", "together (up to chunk size) # by using the entire image to sample", "with # skip_empty=True, so that it performs minimal number of # operations. num_chunks", "of the image to be pasted. img_w (int): Width of the image to", "to pasting them one by one, # this has more operations but is", "boxes. This implementation is modified from https://github.com/facebookresearch/detectron2/ Args: masks (Tensor): N, 1, H,", "nonlinearity='relu') nn.init.constant_(m.bias, 0) @auto_fp16() def forward(self, x): for conv in self.convs: x =", "w), (N, h) if torch.isinf(img_x).any(): inds = torch.where(torch.isinf(img_x)) img_x[inds] = 0 if torch.isinf(img_y).any():", "- 1 # img_x, img_y have shapes (N, w), (N, h) if torch.isinf(img_x).any():", "+ 1, max=img_h).to(dtype=torch.int32) else: x0_int, y0_int = 0, 0 x1_int, y1_int = img_w,", "max=img_h).to(dtype=torch.int32) else: x0_int, y0_int = 0, 0 x1_int, y1_int = img_w, img_h x0,", "masks_chunk for i in range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return cls_segms def _do_paste_mask(masks, boxes, img_h, img_w,", "False, the whole image will be pasted. It will return a mask of", "det_labels (Tensor): shape (n, ) img_shape (Tensor): shape (3, ) rcnn_test_cfg (dict): rcnn", "nn.ModuleList() for i in range(self.num_convs): in_channels = ( self.in_channels if i == 0", "not included in num_classes bboxes = det_bboxes[:, :4] labels = det_labels if rescale:", "using the entire image to sample the masks # Compared to pasting them", "labels = det_labels if rescale: img_h, img_w = ori_shape[:2] else: if isinstance(scale_factor, float):", "self.fp16_enabled = False self.loss_mask = build_loss(loss_mask) self.convs = nn.ModuleList() for i in range(self.num_convs):", "img_h = np.round(ori_shape[0] * h_scale.item()).astype( np.int32) img_w = np.round(ori_shape[1] * w_scale.item()).astype( np.int32) scale_factor", "in_channels=256, conv_kernel_size=3, conv_out_channels=256, num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None, norm_cfg=None, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)):", "nn.init.constant_(m.bias, 0) @auto_fp16() def forward(self, x): for conv in self.convs: x = conv(x)", "suppress warnings align_corners = (None if self.upsample_method == 'nearest' else False) upsample_cfg_.update( scale_factor=self.scale_factor,", "self.roi_feat_size = _pair(roi_feat_size) self.in_channels = in_channels self.conv_kernel_size = conv_kernel_size self.conv_out_channels = conv_out_channels self.upsample_method", "actual implementation split the input into chunks, # and paste them chunk by", "from torch.nn.modules.utils import _pair from mmdet.core import mask_target from mmdet.models.builder import HEADS, build_loss", "== 0 else self.conv_out_channels) padding = (self.conv_kernel_size - 1) // 2 self.convs.append( ConvModule(", "= 1.0 if not isinstance(scale_factor, (float, torch.Tensor)): scale_factor = bboxes.new_tensor(scale_factor) bboxes = bboxes", "numpy array outside of this method. det_bboxes (Tensor): shape (n, 4/5) det_labels (Tensor):", "np.int32) img_w = np.round(ori_shape[1] * w_scale.item()).astype( np.int32) scale_factor = 1.0 if not isinstance(scale_factor,", "x1_int, device=device, dtype=torch.float32) + 0.5 img_y = (img_y - y0) / (y1 -", "slice object. If skip_empty == False, the whole image will be pasted. It", "= torch.arange( x0_int, x1_int, device=device, dtype=torch.float32) + 0.5 img_y = (img_y - y0)", "= nn.ModuleList() for i in range(self.num_convs): in_channels = ( self.in_channels if i ==", "too much or too little. It would be better to # determine it", "of this method. det_bboxes (Tensor): shape (n, 4/5) det_labels (Tensor): shape (n, )", "The first item is mask tensor, the second one is the slice object.", "and end coordinates in the original image will be returned. \"\"\" # On", "mask_target from mmdet.models.builder import HEADS, build_loss BYTES_PER_FLOAT = 4 # TODO: This memory", "= 1024**3 # 1 GB memory limit @HEADS.register_module() class FCNMaskHead(nn.Module): def __init__(self, num_convs=4,", "= build_loss(loss_mask) self.convs = nn.ModuleList() for i in range(self.num_convs): in_channels = ( self.in_channels", "for i in range(self.num_convs): in_channels = ( self.in_channels if i == 0 else", "to numpy array outside of this method. det_bboxes (Tensor): shape (n, 4/5) det_labels", "* 2 - 1 # img_x, img_y have shapes (N, w), (N, h)", "img_x[:, None, :].expand(N, img_y.size(1), img_x.size(1)) gy = img_y[:, :, None].expand(N, img_y.size(1), img_x.size(1)) grid", "# GPU benefits from parallelism for larger chunks, # but may have memory", "one, # this has more operations but is faster on COCO-scale dataset. device", "img_masks = F.grid_sample( masks.to(dtype=torch.float32), grid, align_corners=False) if skip_empty: return img_masks[:, 0], (slice(y0_int, y1_int),", "to sample the masks # Compared to pasting them one by one, #", "for inds in chunks: masks_chunk, spatial_inds = _do_paste_mask( mask_pred[inds], bboxes[inds], img_h, img_w, skip_empty=device.type", "force_fp32 from torch.nn.modules.utils import _pair from mmdet.core import mask_target from mmdet.models.builder import HEADS,", "conv_kernel_size=3, conv_out_channels=256, num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None, norm_cfg=None, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)): super(FCNMaskHead,", "= build_upsample_layer(upsample_cfg_) out_channels = 1 if self.class_agnostic else self.num_classes logits_in_channel = ( self.conv_out_channels", "scale_factor[1] img_h = np.round(ori_shape[0] * h_scale.item()).astype( np.int32) img_w = np.round(ori_shape[1] * w_scale.item()).astype( np.int32)", "tuple). The first item is mask tensor, the second one is the slice", "them one by one, # this has more operations but is faster on", "mask_targets, labels) loss['loss_mask'] = loss_mask return loss def get_seg_masks(self, mask_pred, det_bboxes, det_labels, rcnn_test_cfg,", "max=img_w).to(dtype=torch.int32) y1_int = torch.clamp( boxes[:, 3].max().ceil() + 1, max=img_h).to(dtype=torch.int32) else: x0_int, y0_int =", "in self.convs: x = conv(x) if self.upsample is not None: x = self.upsample(x)", "N, img_h, img_w, device=device, dtype=torch.bool if threshold >= 0 else torch.uint8) if not", "= masks.device if skip_empty: x0_int, y0_int = torch.clamp( boxes.min(dim=0).values.floor()[:2] - 1, min=0).to(dtype=torch.int32) x1_int", "determine it based on available resources. GPU_MEM_LIMIT = 1024**3 # 1 GB memory", "img_w (int): Width of the image to be pasted. skip_empty (bool): Only paste", "CARAFEPack): m.init_weights() else: nn.init.kaiming_normal_( m.weight, mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias, 0) @auto_fp16() def forward(self, x):", "h) if torch.isinf(img_x).any(): inds = torch.where(torch.isinf(img_x)) img_x[inds] = 0 if torch.isinf(img_y).any(): inds =", "m.weight, mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias, 0) @auto_fp16() def forward(self, x): for conv in self.convs:", "skip_empty == True, only area around the mask will be pasted. A mask", ":].expand(N, img_y.size(1), img_x.size(1)) gy = img_y[:, :, None].expand(N, img_y.size(1), img_x.size(1)) grid = torch.stack([gx,", "N else: # GPU benefits from parallelism for larger chunks, # but may", "det_bboxes, det_labels, rcnn_test_cfg, ori_shape, scale_factor, rescale): \"\"\"Get segmentation masks from mask_pred and bboxes.", "chunks, # and paste them chunk by chunk. if device.type == 'cpu': #", "= bboxes / scale_factor N = len(mask_pred) # The actual implementation split the", "else self.conv_out_channels) padding = (self.conv_kernel_size - 1) // 2 self.convs.append( ConvModule( in_channels, self.conv_out_channels,", "upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method, align_corners=align_corners) self.upsample = build_upsample_layer(upsample_cfg_) out_channels = 1 if self.class_agnostic else", "(masks_chunk * 255).to(dtype=torch.uint8) im_mask[(inds, ) + spatial_inds] = masks_chunk for i in range(N):", "if self.upsample_method == 'nearest' else False) upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method, align_corners=align_corners) self.upsample = build_upsample_layer(upsample_cfg_)", "self.upsample = build_upsample_layer(upsample_cfg_) elif self.upsample_method == 'carafe': upsample_cfg_.update( channels=upsample_in_channels, scale_factor=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_)", "@force_fp32(apply_to=('mask_pred', )) def loss(self, mask_pred, mask_targets, labels): loss = dict() if mask_pred.size(0) ==", "mask_pred is the direct output of model, whose type is Tensor, while for", "== 'cpu': # CPU is most efficient when they are pasted one by", "255).to(dtype=torch.uint8) im_mask[(inds, ) + spatial_inds] = masks_chunk for i in range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return", "area around the mask will be pasted. A mask of shape (N, h',", "of the image to be pasted. skip_empty (bool): Only paste masks within the", "mask will be pasted. A mask of shape (N, h', w') and its", "boxes, and returns the results this region only. An important optimization for CPU.", "Returns: list[list]: encoded masks \"\"\" if isinstance(mask_pred, torch.Tensor): mask_pred = mask_pred.sigmoid() else: mask_pred", "N = masks.shape[0] img_y = torch.arange( y0_int, y1_int, device=device, dtype=torch.float32) + 0.5 img_x", "'deconv': upsample_cfg_.update( in_channels=upsample_in_channels, out_channels=self.conv_out_channels, kernel_size=self.scale_factor, stride=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) elif self.upsample_method == 'carafe':", "= [res.pos_bboxes for res in sampling_results] pos_assigned_gt_inds = [ res.pos_assigned_gt_inds for res in", "if rescale: img_h, img_w = ori_shape[:2] else: if isinstance(scale_factor, float): img_h = np.round(ori_shape[0]", "debugging masks_chunk = (masks_chunk * 255).to(dtype=torch.uint8) im_mask[(inds, ) + spatial_inds] = masks_chunk for", "* 2 - 1 img_x = (img_x - x0) / (x1 - x0)", "self.num_convs = num_convs # WARN: roi_feat_size is reserved and not used self.roi_feat_size =", "[[] for _ in range(self.num_classes) ] # BG is not included in num_classes", "'carafe' ]: raise ValueError( f'Invalid upsample method {self.upsample_cfg[\"type\"]}, ' 'accepted methods are \"deconv\",", "used self.roi_feat_size = _pair(roi_feat_size) self.in_channels = in_channels self.conv_kernel_size = conv_kernel_size self.conv_out_channels = conv_out_channels", "self.upsample_cfg = upsample_cfg.copy() if self.upsample_cfg['type'] not in [ None, 'deconv', 'nearest', 'bilinear', 'carafe'", "the entire image to sample the masks # Compared to pasting them one", "the mask will be pasted. A mask of shape (N, h', w') and", "is None: self.upsample = None elif self.upsample_method == 'deconv': upsample_cfg_.update( in_channels=upsample_in_channels, out_channels=self.conv_out_channels, kernel_size=self.scale_factor,", "mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks, rcnn_train_cfg) return mask_targets @force_fp32(apply_to=('mask_pred', )) def loss(self, mask_pred, mask_targets, labels):", "(img_x - x0) / (x1 - x0) * 2 - 1 # img_x,", "i in range(self.num_convs): in_channels = ( self.in_channels if i == 0 else self.conv_out_channels)", "device=device, dtype=torch.float32) + 0.5 img_x = torch.arange( x0_int, x1_int, device=device, dtype=torch.float32) + 0.5", "pasted one by one with # skip_empty=True, so that it performs minimal number", "i == 0 else self.conv_out_channels) padding = (self.conv_kernel_size - 1) // 2 self.convs.append(", "the image to be pasted. skip_empty (bool): Only paste masks within the region", "isinstance(mask_pred, torch.Tensor): mask_pred = mask_pred.sigmoid() else: mask_pred = det_bboxes.new_tensor(mask_pred) device = mask_pred.device cls_segms", "img_w = ori_shape[:2] else: if isinstance(scale_factor, float): img_h = np.round(ori_shape[0] * scale_factor).astype(np.int32) img_w", "loss_mask = mask_pred.sum() * 0 else: if self.class_agnostic: loss_mask = self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels))", "performs minimal number of # operations. num_chunks = N else: # GPU benefits", "isinstance(scale_factor, (float, torch.Tensor)): scale_factor = bboxes.new_tensor(scale_factor) bboxes = bboxes / scale_factor N =", "self.upsample_cfg.pop('scale_factor', None) self.num_classes = num_classes self.class_agnostic = class_agnostic self.conv_cfg = conv_cfg self.norm_cfg =", "align_corners=align_corners) self.upsample = build_upsample_layer(upsample_cfg_) out_channels = 1 if self.class_agnostic else self.num_classes logits_in_channel =", "dim=3) img_masks = F.grid_sample( masks.to(dtype=torch.float32), grid, align_corners=False) if skip_empty: return img_masks[:, 0], (slice(y0_int,", "N), 'Default GPU_MEM_LIMIT is too small; try increasing it' chunks = torch.chunk(torch.arange(N, device=device),", "masks_chunk = (masks_chunk >= threshold).to(dtype=torch.bool) else: # for visualization and debugging masks_chunk =", "img_h, img_w = ori_shape[:2] else: if isinstance(scale_factor, float): img_h = np.round(ori_shape[0] * scale_factor).astype(np.int32)", "this method. det_bboxes (Tensor): shape (n, 4/5) det_labels (Tensor): shape (n, ) img_shape", "so that it performs minimal number of # operations. num_chunks = N else:", "masks (Tensor): N, 1, H, W boxes (Tensor): N, 4 img_h (int): Height", "x = conv(x) if self.upsample is not None: x = self.upsample(x) if self.upsample_method", "conv_cfg=None, norm_cfg=None, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)): super(FCNMaskHead, self).__init__() self.upsample_cfg = upsample_cfg.copy() if self.upsample_cfg['type']", "[res.pos_bboxes for res in sampling_results] pos_assigned_gt_inds = [ res.pos_assigned_gt_inds for res in sampling_results", "0, 0 x1_int, y1_int = img_w, img_h x0, y0, x1, y1 = torch.split(boxes,", "== 'carafe': upsample_cfg_.update( channels=upsample_in_channels, scale_factor=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) else: # suppress warnings align_corners", "= mask_pred.sum() * 0 else: if self.class_agnostic: loss_mask = self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels)) else:", "mask_pred (Tensor or ndarray): shape (n, #class, h, w). For single-scale testing, mask_pred", "is not None: x = self.upsample(x) if self.upsample_method == 'deconv': x = self.relu(x)", "self.scale_factor = self.upsample_cfg.pop('scale_factor', None) self.num_classes = num_classes self.class_agnostic = class_agnostic self.conv_cfg = conv_cfg", "scale_factor).astype(np.int32) img_w = np.round(ori_shape[1] * scale_factor).astype(np.int32) else: w_scale, h_scale = scale_factor[0], scale_factor[1] img_h", "(masks_chunk >= threshold).to(dtype=torch.bool) else: # for visualization and debugging masks_chunk = (masks_chunk *", "mask of shape (N, img_h, img_w) and an empty tuple. If skip_empty ==", "self.relu(x) mask_pred = self.conv_logits(x) return mask_pred def get_targets(self, sampling_results, gt_masks, rcnn_train_cfg): pos_proposals =", "modified from https://github.com/facebookresearch/detectron2/ Args: masks (Tensor): N, 1, H, W boxes (Tensor): N,", "# each is Nx1 N = masks.shape[0] img_y = torch.arange( y0_int, y1_int, device=device,", "= (None if self.upsample_method == 'nearest' else False) upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method, align_corners=align_corners) self.upsample", "boxes.min(dim=0).values.floor()[:2] - 1, min=0).to(dtype=torch.int32) x1_int = torch.clamp( boxes[:, 2].max().ceil() + 1, max=img_w).to(dtype=torch.int32) y1_int", "masks.shape[0] img_y = torch.arange( y0_int, y1_int, device=device, dtype=torch.float32) + 0.5 img_x = torch.arange(", "\"\"\" # On GPU, paste all masks together (up to chunk size) #", "this region only. An important optimization for CPU. Returns: tuple: (Tensor, tuple). The", "list[list]: encoded masks \"\"\" if isinstance(mask_pred, torch.Tensor): mask_pred = mask_pred.sigmoid() else: mask_pred =", "bboxes.new_tensor(scale_factor) bboxes = bboxes / scale_factor N = len(mask_pred) # The actual implementation", "= [ res.pos_assigned_gt_inds for res in sampling_results ] mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks,", "scale_factor N = len(mask_pred) # The actual implementation split the input into chunks,", "= torch.clamp( boxes[:, 2].max().ceil() + 1, max=img_w).to(dtype=torch.int32) y1_int = torch.clamp( boxes[:, 3].max().ceil() +", "= masks_chunk for i in range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return cls_segms def _do_paste_mask(masks, boxes, img_h,", "labels): loss = dict() if mask_pred.size(0) == 0: loss_mask = mask_pred.sum() * 0", "if threshold >= 0 else torch.uint8) if not self.class_agnostic: mask_pred = mask_pred[range(N), labels][:,", "in range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return cls_segms def _do_paste_mask(masks, boxes, img_h, img_w, skip_empty=True): \"\"\"Paste instance", "* 255).to(dtype=torch.uint8) im_mask[(inds, ) + spatial_inds] = masks_chunk for i in range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy())", "is Tensor, while for multi-scale testing, it will be converted to numpy array", "dataset. device = masks.device if skip_empty: x0_int, y0_int = torch.clamp( boxes.min(dim=0).values.floor()[:2] - 1,", "for CPU. Returns: tuple: (Tensor, tuple). The first item is mask tensor, the", "self.conv_logits = Conv2d(logits_in_channel, out_channels, 1) self.relu = nn.ReLU(inplace=True) self.debug_imgs = None def init_weights(self):", "it performs minimal number of # operations. num_chunks = N else: # GPU", "be better to # determine it based on available resources. GPU_MEM_LIMIT = 1024**3", "limit @HEADS.register_module() class FCNMaskHead(nn.Module): def __init__(self, num_convs=4, roi_feat_size=14, in_channels=256, conv_kernel_size=3, conv_out_channels=256, num_classes=80, class_agnostic=False,", "memory limit @HEADS.register_module() class FCNMaskHead(nn.Module): def __init__(self, num_convs=4, roi_feat_size=14, in_channels=256, conv_kernel_size=3, conv_out_channels=256, num_classes=80,", "\"nearest\", \"bilinear\", ' '\"carafe\"') self.num_convs = num_convs # WARN: roi_feat_size is reserved and", "in chunks: masks_chunk, spatial_inds = _do_paste_mask( mask_pred[inds], bboxes[inds], img_h, img_w, skip_empty=device.type == 'cpu')", "None: continue elif isinstance(m, CARAFEPack): m.init_weights() else: nn.init.kaiming_normal_( m.weight, mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias, 0)", "included in num_classes bboxes = det_bboxes[:, :4] labels = det_labels if rescale: img_h,", "( self.in_channels if i == 0 else self.conv_out_channels) padding = (self.conv_kernel_size - 1)", "entire image to sample the masks # Compared to pasting them one by", "np import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn", "// 2 self.convs.append( ConvModule( in_channels, self.conv_out_channels, self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels = (", "self.conv_logits]: if m is None: continue elif isinstance(m, CARAFEPack): m.init_weights() else: nn.init.kaiming_normal_( m.weight,", "each is Nx1 N = masks.shape[0] img_y = torch.arange( y0_int, y1_int, device=device, dtype=torch.float32)", "build_upsample_layer(upsample_cfg_) elif self.upsample_method == 'carafe': upsample_cfg_.update( channels=upsample_in_channels, scale_factor=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) else: #", "Height of the image to be pasted. img_w (int): Width of the image", "in_channels = ( self.in_channels if i == 0 else self.conv_out_channels) padding = (self.conv_kernel_size", "self.norm_cfg = norm_cfg self.fp16_enabled = False self.loss_mask = build_loss(loss_mask) self.convs = nn.ModuleList() for", "if self.upsample_cfg['type'] not in [ None, 'deconv', 'nearest', 'bilinear', 'carafe' ]: raise ValueError(", "This implementation is modified from https://github.com/facebookresearch/detectron2/ Args: masks (Tensor): N, 1, H, W", "'nearest' else False) upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method, align_corners=align_corners) self.upsample = build_upsample_layer(upsample_cfg_) out_channels = 1", "= (img_x - x0) / (x1 - x0) * 2 - 1 #", "loss(self, mask_pred, mask_targets, labels): loss = dict() if mask_pred.size(0) == 0: loss_mask =", "\"\"\" if isinstance(mask_pred, torch.Tensor): mask_pred = mask_pred.sigmoid() else: mask_pred = det_bboxes.new_tensor(mask_pred) device =", "split the input into chunks, # and paste them chunk by chunk. if", "' '\"carafe\"') self.num_convs = num_convs # WARN: roi_feat_size is reserved and not used", "img_w, skip_empty=device.type == 'cpu') if threshold >= 0: masks_chunk = (masks_chunk >= threshold).to(dtype=torch.bool)", "def _do_paste_mask(masks, boxes, img_h, img_w, skip_empty=True): \"\"\"Paste instance masks acoording to boxes. This", "1 # img_x, img_y have shapes (N, w), (N, h) if torch.isinf(img_x).any(): inds", "img_x, img_y have shapes (N, w), (N, h) if torch.isinf(img_x).any(): inds = torch.where(torch.isinf(img_x))", "m is None: continue elif isinstance(m, CARAFEPack): m.init_weights() else: nn.init.kaiming_normal_( m.weight, mode='fan_out', nonlinearity='relu')", "img_y have shapes (N, w), (N, h) if torch.isinf(img_x).any(): inds = torch.where(torch.isinf(img_x)) img_x[inds]", "image to sample the masks # Compared to pasting them one by one,", "y1_int = torch.clamp( boxes[:, 3].max().ceil() + 1, max=img_h).to(dtype=torch.int32) else: x0_int, y0_int = 0,", "= torch.arange( y0_int, y1_int, device=device, dtype=torch.float32) + 0.5 img_x = torch.arange( x0_int, x1_int,", "= 0 gx = img_x[:, None, :].expand(N, img_y.size(1), img_x.size(1)) gy = img_y[:, :,", "chunks = torch.chunk(torch.arange(N, device=device), num_chunks) threshold = rcnn_test_cfg.mask_thr_binary im_mask = torch.zeros( N, img_h,", "spatial_inds] = masks_chunk for i in range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return cls_segms def _do_paste_mask(masks, boxes,", "torch.where(torch.isinf(img_x)) img_x[inds] = 0 if torch.isinf(img_y).any(): inds = torch.where(torch.isinf(img_y)) img_y[inds] = 0 gx", "it will be converted to numpy array outside of this method. det_bboxes (Tensor):", "else self.num_classes logits_in_channel = ( self.conv_out_channels if self.upsample_method == 'deconv' else upsample_in_channels) self.conv_logits", "image will be returned. \"\"\" # On GPU, paste all masks together (up", "== 'nearest' else False) upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method, align_corners=align_corners) self.upsample = build_upsample_layer(upsample_cfg_) out_channels =", "shapes (N, w), (N, h) if torch.isinf(img_x).any(): inds = torch.where(torch.isinf(img_x)) img_x[inds] = 0", "self.conv_logits(x) return mask_pred def get_targets(self, sampling_results, gt_masks, rcnn_train_cfg): pos_proposals = [res.pos_bboxes for res", "pos_assigned_gt_inds = [ res.pos_assigned_gt_inds for res in sampling_results ] mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds,", "h, w). For single-scale testing, mask_pred is the direct output of model, whose", "'\"carafe\"') self.num_convs = num_convs # WARN: roi_feat_size is reserved and not used self.roi_feat_size", "mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks, rcnn_train_cfg) return mask_targets @force_fp32(apply_to=('mask_pred', )) def loss(self, mask_pred,", "memory limit may be too much or too little. It would be better", "not in [ None, 'deconv', 'nearest', 'bilinear', 'carafe' ]: raise ValueError( f'Invalid upsample", "(Tensor or ndarray): shape (n, #class, h, w). For single-scale testing, mask_pred is", "that tightly bound all boxes, and returns the results this region only. An", "torch.nn.functional as F from mmcv.cnn import ConvModule, build_upsample_layer from mmcv.ops import Conv2d from", "mask_pred.sigmoid() else: mask_pred = det_bboxes.new_tensor(mask_pred) device = mask_pred.device cls_segms = [[] for _", "paste all masks together (up to chunk size) # by using the entire", "== 'cpu') if threshold >= 0: masks_chunk = (masks_chunk >= threshold).to(dtype=torch.bool) else: #", "direct output of model, whose type is Tensor, while for multi-scale testing, it", "if not self.class_agnostic: mask_pred = mask_pred[range(N), labels][:, None] for inds in chunks: masks_chunk,", "upsample_cfg_.update( channels=upsample_in_channels, scale_factor=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) else: # suppress warnings align_corners = (None", "whole image will be pasted. It will return a mask of shape (N,", "coordinates in the original image will be returned. \"\"\" # On GPU, paste", "torch.isinf(img_x).any(): inds = torch.where(torch.isinf(img_x)) img_x[inds] = 0 if torch.isinf(img_y).any(): inds = torch.where(torch.isinf(img_y)) img_y[inds]", "number of # operations. num_chunks = N else: # GPU benefits from parallelism", "torch.isinf(img_y).any(): inds = torch.where(torch.isinf(img_y)) img_y[inds] = 0 gx = img_x[:, None, :].expand(N, img_y.size(1),", "= torch.split(boxes, 1, dim=1) # each is Nx1 N = masks.shape[0] img_y =", "if device.type == 'cpu': # CPU is most efficient when they are pasted", "(Tensor): shape (n, 4/5) det_labels (Tensor): shape (n, ) img_shape (Tensor): shape (3,", "mask_pred[inds], bboxes[inds], img_h, img_w, skip_empty=device.type == 'cpu') if threshold >= 0: masks_chunk =", "= (self.conv_kernel_size - 1) // 2 self.convs.append( ConvModule( in_channels, self.conv_out_channels, self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg,", "size) # by using the entire image to sample the masks # Compared", "the results this region only. An important optimization for CPU. Returns: tuple: (Tensor,", "too small; try increasing it' chunks = torch.chunk(torch.arange(N, device=device), num_chunks) threshold = rcnn_test_cfg.mask_thr_binary", "returns the results this region only. An important optimization for CPU. Returns: tuple:" ]
[ "= Config() #params for text detector cfg.det_algorithm = \"DB\" cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len", "1.6 cfg.use_dilation = False # #EAST parmas # cfg.det_east_score_thresh = 0.8 # cfg.det_east_cover_thresh", "cfg.det_db_unclip_ratio = 1.6 cfg.use_dilation = False # #EAST parmas # cfg.det_east_score_thresh = 0.8", "cfg.det_east_score_thresh = 0.8 # cfg.det_east_cover_thresh = 0.1 # cfg.det_east_nms_thresh = 0.2 cfg.use_pdserving =", "import division from __future__ import print_function class Config(object): pass def read_params(): cfg =", "# -*- coding:utf-8 -*- from __future__ import absolute_import from __future__ import division from", "pass def read_params(): cfg = Config() #params for text detector cfg.det_algorithm = \"DB\"", "Config() #params for text detector cfg.det_algorithm = \"DB\" cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len =", "False # #EAST parmas # cfg.det_east_score_thresh = 0.8 # cfg.det_east_cover_thresh = 0.1 #", "#params for text detector cfg.det_algorithm = \"DB\" cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len = 960", "cfg.det_limit_side_len = 960 cfg.det_limit_type = 'max' #DB parmas cfg.det_db_thresh = 0.3 cfg.det_db_box_thresh =", "0.1 # cfg.det_east_nms_thresh = 0.2 cfg.use_pdserving = False cfg.use_tensorrt = False return cfg", "0.5 cfg.det_db_unclip_ratio = 1.6 cfg.use_dilation = False # #EAST parmas # cfg.det_east_score_thresh =", "__future__ import absolute_import from __future__ import division from __future__ import print_function class Config(object):", "cfg = Config() #params for text detector cfg.det_algorithm = \"DB\" cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\"", "= 0.3 cfg.det_db_box_thresh = 0.5 cfg.det_db_unclip_ratio = 1.6 cfg.use_dilation = False # #EAST", "from __future__ import absolute_import from __future__ import division from __future__ import print_function class", "read_params(): cfg = Config() #params for text detector cfg.det_algorithm = \"DB\" cfg.det_model_dir =", "detector cfg.det_algorithm = \"DB\" cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len = 960 cfg.det_limit_type = 'max'", "-*- from __future__ import absolute_import from __future__ import division from __future__ import print_function", "\"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len = 960 cfg.det_limit_type = 'max' #DB parmas cfg.det_db_thresh = 0.3 cfg.det_db_box_thresh", "0.3 cfg.det_db_box_thresh = 0.5 cfg.det_db_unclip_ratio = 1.6 cfg.use_dilation = False # #EAST parmas", "division from __future__ import print_function class Config(object): pass def read_params(): cfg = Config()", "import absolute_import from __future__ import division from __future__ import print_function class Config(object): pass", "def read_params(): cfg = Config() #params for text detector cfg.det_algorithm = \"DB\" cfg.det_model_dir", "cfg.use_dilation = False # #EAST parmas # cfg.det_east_score_thresh = 0.8 # cfg.det_east_cover_thresh =", "'max' #DB parmas cfg.det_db_thresh = 0.3 cfg.det_db_box_thresh = 0.5 cfg.det_db_unclip_ratio = 1.6 cfg.use_dilation", "= False # #EAST parmas # cfg.det_east_score_thresh = 0.8 # cfg.det_east_cover_thresh = 0.1", "class Config(object): pass def read_params(): cfg = Config() #params for text detector cfg.det_algorithm", "= 'max' #DB parmas cfg.det_db_thresh = 0.3 cfg.det_db_box_thresh = 0.5 cfg.det_db_unclip_ratio = 1.6", "= \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len = 960 cfg.det_limit_type = 'max' #DB parmas cfg.det_db_thresh = 0.3", "= 0.8 # cfg.det_east_cover_thresh = 0.1 # cfg.det_east_nms_thresh = 0.2 cfg.use_pdserving = False", "cfg.det_db_box_thresh = 0.5 cfg.det_db_unclip_ratio = 1.6 cfg.use_dilation = False # #EAST parmas #", "#EAST parmas # cfg.det_east_score_thresh = 0.8 # cfg.det_east_cover_thresh = 0.1 # cfg.det_east_nms_thresh =", "print_function class Config(object): pass def read_params(): cfg = Config() #params for text detector", "__future__ import print_function class Config(object): pass def read_params(): cfg = Config() #params for", "#DB parmas cfg.det_db_thresh = 0.3 cfg.det_db_box_thresh = 0.5 cfg.det_db_unclip_ratio = 1.6 cfg.use_dilation =", "text detector cfg.det_algorithm = \"DB\" cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len = 960 cfg.det_limit_type =", "= \"DB\" cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len = 960 cfg.det_limit_type = 'max' #DB parmas", "cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len = 960 cfg.det_limit_type = 'max' #DB parmas cfg.det_db_thresh =", "absolute_import from __future__ import division from __future__ import print_function class Config(object): pass def", "cfg.det_limit_type = 'max' #DB parmas cfg.det_db_thresh = 0.3 cfg.det_db_box_thresh = 0.5 cfg.det_db_unclip_ratio =", "cfg.det_east_cover_thresh = 0.1 # cfg.det_east_nms_thresh = 0.2 cfg.use_pdserving = False cfg.use_tensorrt = False", "Config(object): pass def read_params(): cfg = Config() #params for text detector cfg.det_algorithm =", "= 0.5 cfg.det_db_unclip_ratio = 1.6 cfg.use_dilation = False # #EAST parmas # cfg.det_east_score_thresh", "# #EAST parmas # cfg.det_east_score_thresh = 0.8 # cfg.det_east_cover_thresh = 0.1 # cfg.det_east_nms_thresh", "parmas # cfg.det_east_score_thresh = 0.8 # cfg.det_east_cover_thresh = 0.1 # cfg.det_east_nms_thresh = 0.2", "0.8 # cfg.det_east_cover_thresh = 0.1 # cfg.det_east_nms_thresh = 0.2 cfg.use_pdserving = False cfg.use_tensorrt", "__future__ import division from __future__ import print_function class Config(object): pass def read_params(): cfg", "cfg.det_algorithm = \"DB\" cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len = 960 cfg.det_limit_type = 'max' #DB", "# cfg.det_east_score_thresh = 0.8 # cfg.det_east_cover_thresh = 0.1 # cfg.det_east_nms_thresh = 0.2 cfg.use_pdserving", "-*- coding:utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__", "for text detector cfg.det_algorithm = \"DB\" cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len = 960 cfg.det_limit_type", "= 1.6 cfg.use_dilation = False # #EAST parmas # cfg.det_east_score_thresh = 0.8 #", "import print_function class Config(object): pass def read_params(): cfg = Config() #params for text", "parmas cfg.det_db_thresh = 0.3 cfg.det_db_box_thresh = 0.5 cfg.det_db_unclip_ratio = 1.6 cfg.use_dilation = False", "from __future__ import division from __future__ import print_function class Config(object): pass def read_params():", "= 0.1 # cfg.det_east_nms_thresh = 0.2 cfg.use_pdserving = False cfg.use_tensorrt = False return", "cfg.det_db_thresh = 0.3 cfg.det_db_box_thresh = 0.5 cfg.det_db_unclip_ratio = 1.6 cfg.use_dilation = False #", "# cfg.det_east_cover_thresh = 0.1 # cfg.det_east_nms_thresh = 0.2 cfg.use_pdserving = False cfg.use_tensorrt =", "coding:utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import", "= 960 cfg.det_limit_type = 'max' #DB parmas cfg.det_db_thresh = 0.3 cfg.det_db_box_thresh = 0.5", "from __future__ import print_function class Config(object): pass def read_params(): cfg = Config() #params", "960 cfg.det_limit_type = 'max' #DB parmas cfg.det_db_thresh = 0.3 cfg.det_db_box_thresh = 0.5 cfg.det_db_unclip_ratio", "\"DB\" cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len = 960 cfg.det_limit_type = 'max' #DB parmas cfg.det_db_thresh" ]
[ ") self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x): out = self.deconv(x,output_size=skip_x.size()) # concat skip connections", "self.inplanes, kernel_size=7, stride=1, padding=3, bias=True) # initial conv layer self.bn1 = nn.BatchNorm2d(self.inplanes) self.relu1", "self.enc_layer3(x2) x4 = self.enc_layer4(x3) x5 = self.enc_layer5(x4) if self._showsizes: print \"after encoding: \"", "\",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x", "self.enc_layer5 = self._make_encoding_layer( self.inplanes*16, self.inplanes*32, stride=2) # 256->512 # decoding flow #self.num_final_flow_features =", "\"input: \",x.size(),\" is_cuda=\",x.is_cuda src_encode, s0, s1, s2, s3, s4 = self.encode(src) target_encode, t0,", "self.inplanes*8 ) # 256->128 self.visi_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) #", "self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.flow_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2,", "self.visi_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.inplanes ) # 32->16 # 1x1 conv", "is not None: outbp = self.bypass(x) out += outbp else: out += x", "outbp else: out += x out = self.relu(out) return out class Bottleneck(nn.Module): def", "DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x): out = self.deconv(x,output_size=skip_x.size()) # concat skip connections out = torch.cat(", "inplanes, planes, stride=2): return DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def _make_decoding_layer(self, inplanes, skipplanes, deconvplanes, resnetplanes ): return", "# U-net witih ResNet modules # # Semantic segmentation network used by MicroBooNE", "nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True)", "flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\" x = self.flow_dec_layer5(merged_encode,x4) if self._showsizes: print", "layer self.bn1 = nn.BatchNorm2d(self.inplanes) self.relu1 = nn.ReLU(inplace=True) self.pool1 = nn.MaxPool2d( 3, stride=2, padding=1", "math import torch.utils.model_zoo as model_zoo ########################################################### # # U-ResNet # U-net witih ResNet", "<filename>networks/larflow/models/larflow_uresnet.py import torch.nn as nn import torch as torch import math import torch.utils.model_zoo", "nn.BatchNorm2d(planes) self.relu2 = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) #", "= nn.BatchNorm2d(planes) self.stride = stride self.bypass = None if inplanes!=planes or stride>1: self.bypass", "self.inplanes, self.inplanes, self.inplanes ) # 32->16 # 1x1 conv for flow self.flow_conv =", "def __init__(self, num_classes=3, input_channels=3, inplanes=16, showsizes=False, use_visi=True): self.inplanes =inplanes super(LArFlowUResNet, self).__init__() self._showsizes =", "32->16 # 1x1 conv for flow self.flow_conv = nn.Conv2d( self.num_final_flow_features, 1, kernel_size=1, stride=1,", ") # 32->16 # 1x1 conv for flow self.flow_conv = nn.Conv2d( self.num_final_flow_features, 1,", "def __init__(self, inplanes, planes, stride=1 ): super(Preactivation, self).__init__() # residual path self.bn1 =", "showsizes # print size at each layer self.use_visi = use_visi # Encoder #", "s3, s4 ) if self.use_visi: visiout = self.visibility( merged_encode, t0, t1, t2, t3,", "self).__init__() # residual path self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes)", "#self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes ) # 32->16 self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2,", "else: bypass = self.shortcut(x) residual = self.conv1(x) residual = self.bn1(residual) residual = self.relu(residual)", "self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes ) # 32->16 self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes,", "return out class Bottleneck(nn.Module): def __init__(self, inplanes, planes, stride=1 ): super(Bottleneck, self).__init__() #", "self.inplanes*32, stride=2) # 256->512 # decoding flow #self.num_final_flow_features = self.inplanes self.num_final_flow_features = self.inplanes", "flow_predict = self.flow_conv( flowout ) if self.use_visi: visi_predict = self.visi_conv( visiout ) visi_predict", "torch import math import torch.utils.model_zoo as model_zoo ########################################################### # # U-ResNet # U-net", "self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.num_final_flow_features ) # 32->200 # decoding matchability", "class ConvTransposeLayer(nn.Module): def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__() self.deconv = nn.ConvTranspose2d( deconv_inplanes, deconv_outplanes, kernel_size=4, stride=2, padding=1,", "* m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_()", "x5 = self.enc_layer5(x4) if self._showsizes: print \"after encoding: \" print \" x1: \",x1.size()", "kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.stride = stride # if", "[target_encode,src_encode], 1 ) flowout = self.flow( merged_encode, s0, s1, s2, s3, s4 )", "self.shortcut is None: bypass = x else: bypass = self.shortcut(x) residual = self.conv1(x)", "= nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) # if stride >1, then we", "None: bypass = x else: bypass = self.shortcut(x) class DoubleResNet(nn.Module): def __init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__()", "self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 self.visi_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.inplanes", "size at each layer self.use_visi = use_visi # Encoder # stem # one", "inplanes!=planes or stride>1: self.bypass = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, padding=0, bias=False) self.relu =", "256->128 self.visi_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.visi_dec_layer2 =", "self.bypass is not None: outbp = self.bypass(x) out += outbp else: out +=", "if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def forward(self, src, target):", "is None: bypass = x else: bypass = self.shortcut(x) class DoubleResNet(nn.Module): def __init__(self,Block,inplanes,planes,stride=1):", ") if self.use_visi: visi_predict = self.visi_conv( visiout ) visi_predict = self.visi_softmax(visi_predict) else: visi_predict", "print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer2(x,x1) if self._showsizes: print \" dec2:", "bias=True ) # 2 classes, 0=not vis, 1=vis self.visi_softmax = nn.LogSoftmax(dim=1) # initialization", "out_planes, kernel_size=3, stride=stride,padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes,", "we need to subsamble the input if stride>1: self.shortcut = nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else: self.shortcut", "\" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def forward(self, src, target): if self._showsizes: print", "t2, t3, t4 = self.encode(target) merged_encode = torch.cat( [target_encode,src_encode], 1 ) flowout =", "\"\"\" decoding to flow prediction \"\"\" x = self.visi_dec_layer5(merged_encode,x4) if self._showsizes: print \"after", "prediction \"\"\" x = self.flow_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print \" dec5:", "self._showsizes: print \"after encoding: \" print \" x1: \",x1.size() print \" x2: \",x2.size()", ") # 64->32 self.visi_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.inplanes ) # 32->16", "outbp = self.bypass(x) out += outbp else: out += x out = self.relu(out)", "# concat skip connections out = torch.cat( [out,skip_x], 1 ) out = self.res(out)", "print \" x3: \",x3.size() print \" x4: \",x4.size() print \" x5: \",x5.size() return", "print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer2(x,x1) if self._showsizes: print \" dec2:", "\"after decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer4(x,x3) if self._showsizes: print", "nn.Conv2d) or isinstance(m,nn.ConvTranspose2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. /", "self.conv2(residual) residual = self.bn2(residual) residual = self.relu(residual) residual = self.conv3(residual) residual = self.bn3(residual)", "= self.flow_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer1(x,x0) if", "planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1,", "super(LArFlowUResNet, self).__init__() self._showsizes = showsizes # print size at each layer self.use_visi =", "ConvTransposeLayer(nn.Module): def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__() self.deconv = nn.ConvTranspose2d( deconv_inplanes, deconv_outplanes, kernel_size=4, stride=2, padding=1, bias=False", "self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.flow_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4", "self.inplanes*2, self.inplanes, self.inplanes, self.num_final_flow_features ) # 32->200 # decoding matchability if self.use_visi: self.visi_dec_layer5", "self.relu = nn.ReLU(inplace=True) def forward(self, x): out = self.conv1(x) out = self.bn1(out) out", "self.visi_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer3(x,x2) if self._showsizes:", "forward(self, x): out = self.res1(x) out = self.res2(out) return out class ConvTransposeLayer(nn.Module): def", "out_planes, stride=1): \"\"\"3x3 convolution with padding\"\"\" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1, bias=False) class", "1 ) flowout = self.flow( merged_encode, s0, s1, s2, s3, s4 ) if", "self.inplanes*4, self.inplanes*4 ) # 128->64 self.visi_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 )", "# 32->16 # 1x1 conv for flow self.flow_conv = nn.Conv2d( self.num_final_flow_features, 1, kernel_size=1,", "deconvplanes, resnetplanes ) def encode(self,x): # stem x = self.conv1(x) x = self.bn1(x)", "if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer3(x,x2) if self._showsizes: print", "else: self.shortcut = None def forward(self, x): if self.shortcut is None: bypass =", "flowout = self.flow( merged_encode, s0, s1, s2, s3, s4 ) if self.use_visi: visiout", "nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes,", "__init__(self, inplanes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 =", "resnetplanes ): return ConvTransposeLayer( inplanes, skipplanes, deconvplanes, resnetplanes ) def encode(self,x): # stem", "bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes)", "stride >1, then we need to subsamble the input if stride>1: self.shortcut =", "self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.flow_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2", "input_channels=3, inplanes=16, showsizes=False, use_visi=True): self.inplanes =inplanes super(LArFlowUResNet, self).__init__() self._showsizes = showsizes # print", "= nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes)", "= x else: bypass = self.shortcut(x) class DoubleResNet(nn.Module): def __init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__() self.res1 =", "planes, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.stride = stride #", "bypass = self.shortcut(x) residual = self.conv1(x) residual = self.bn1(residual) residual = self.relu(residual) residual", "nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) # if stride >1,", "\" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\"", "= self.conv1(x) residual = self.bn1(residual) residual = self.relu(residual) residual = self.conv2(residual) residual =", "self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.relu2 = nn.ReLU(inplace=True) self.conv2", "# 64->32 #self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes ) # 32->16 self.flow_dec_layer1 =", "def conv3x3(in_planes, out_planes, stride=1): \"\"\"3x3 convolution with padding\"\"\" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1,", "x5,x0,x1,x2,x3,x4 def flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\" x = self.flow_dec_layer5(merged_encode,x4) if", "x = self.flow_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer1(x,x0)", "src_encode, s0, s1, s2, s3, s4 = self.encode(src) target_encode, t0, t1, t2, t3,", "return DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def _make_decoding_layer(self, inplanes, skipplanes, deconvplanes, resnetplanes ): return ConvTransposeLayer( inplanes, skipplanes,", "deconv_outplanes, kernel_size=4, stride=2, padding=1, bias=False ) self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x): out =", "\"\"\" x = self.flow_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print \" dec5: \",x.size(),\"", "t0, t1, t2, t3, t4 = self.encode(target) merged_encode = torch.cat( [target_encode,src_encode], 1 )", "self.inplanes*1, self.inplanes*2, stride=1) # 16->32 self.enc_layer2 = self._make_encoding_layer( self.inplanes*2, self.inplanes*4, stride=2) # 32->64", "= self.conv1(x) out = self.bn1(out) out = self.relu1(out) out = self.conv2(out) out =", "self.conv1(x) x = self.bn1(x) x0 = self.relu1(x) x = self.pool1(x0) x1 = self.enc_layer1(x)", "# one big stem self.conv1 = nn.Conv2d(input_channels, self.inplanes, kernel_size=7, stride=1, padding=3, bias=True) #", "self._make_encoding_layer( self.inplanes*2, self.inplanes*4, stride=2) # 32->64 self.enc_layer3 = self._make_encoding_layer( self.inplanes*4, self.inplanes*8, stride=2) #", "self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.visi_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2,", "/ n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_encoding_layer(self, inplanes, planes, stride=2): return", "print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer4(x,x3) if self._showsizes: print \" dec4:", "64->128 self.enc_layer4 = self._make_encoding_layer( self.inplanes*8, self.inplanes*16, stride=2) # 128->256 self.enc_layer5 = self._make_encoding_layer( self.inplanes*16,", "stride=stride, padding=1, bias=False) # if stride >1, then we need to subsamble the", "self.flow_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\"", "# 128->64 self.flow_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 #self.flow_dec_layer1", "256->128 self.flow_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.flow_dec_layer2 =", "nn.Conv2d(input_channels, self.inplanes, kernel_size=7, stride=1, padding=3, bias=True) # initial conv layer self.bn1 = nn.BatchNorm2d(self.inplanes)", "self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.visi_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4", "self.pool1(x0) x1 = self.enc_layer1(x) x2 = self.enc_layer2(x1) x3 = self.enc_layer3(x2) x4 = self.enc_layer4(x3)", "None: bypass = x else: bypass = self.shortcut(x) residual = self.conv1(x) residual =", "out = self.relu1(out) out = self.conv2(out) out = self.bn2(out) if self.bypass is not", "Block( planes,planes, 1) def forward(self, x): out = self.res1(x) out = self.res2(out) return", "return out class LArFlowUResNet(nn.Module): def __init__(self, num_classes=3, input_channels=3, inplanes=16, showsizes=False, use_visi=True): self.inplanes =inplanes", "m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_encoding_layer(self, inplanes, planes,", "self.shortcut = nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else: self.shortcut = None def forward(self, x): if self.shortcut is", "import torch as torch import math import torch.utils.model_zoo as model_zoo ########################################################### # #", "dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda", "residual = self.conv3(residual) residual = self.bn3(residual) out = bypass+residual out = self.relu(out) return", "= self.visi_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer2(x,x1) if", "= nn.BatchNorm2d(planes) self.relu2 = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)", "nn.Conv2d( self.inplanes, 2, kernel_size=1, stride=1, padding=0, bias=True ) # 2 classes, 0=not vis,", "x out = self.relu(out) return out class Bottleneck(nn.Module): def __init__(self, inplanes, planes, stride=1", "= self.conv1(x) x = self.bn1(x) x0 = self.relu1(x) x = self.pool1(x0) x1 =", "= self.shortcut(x) class DoubleResNet(nn.Module): def __init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__() self.res1 = Block(inplanes,planes,stride) self.res2 = Block(", "ResNet modules # # Semantic segmentation network used by MicroBooNE # to label", "= nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else: self.shortcut = None def forward(self, x): if self.shortcut is None:", "= nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.relu2 =", "\" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\"", "self.deconv(x,output_size=skip_x.size()) # concat skip connections out = torch.cat( [out,skip_x], 1 ) out =", "self.enc_layer2(x1) x3 = self.enc_layer3(x2) x4 = self.enc_layer4(x3) x5 = self.enc_layer5(x4) if self._showsizes: print", "+= outbp else: out += x out = self.relu(out) return out class Bottleneck(nn.Module):", "class LArFlowUResNet(nn.Module): def __init__(self, num_classes=3, input_channels=3, inplanes=16, showsizes=False, use_visi=True): self.inplanes =inplanes super(LArFlowUResNet, self).__init__()", "[out,skip_x], 1 ) out = self.res(out) return out class LArFlowUResNet(nn.Module): def __init__(self, num_classes=3,", "self._make_encoding_layer( self.inplanes*4, self.inplanes*8, stride=2) # 64->128 self.enc_layer4 = self._make_encoding_layer( self.inplanes*8, self.inplanes*16, stride=2) #", "nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes,", "nn.BatchNorm2d(self.inplanes) self.relu1 = nn.ReLU(inplace=True) self.pool1 = nn.MaxPool2d( 3, stride=2, padding=1 ) self.enc_layer1 =", "for flow self.flow_conv = nn.Conv2d( self.num_final_flow_features, 1, kernel_size=1, stride=1, padding=0, bias=True ) #", "# 32->200 # decoding matchability if self.use_visi: self.visi_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16,", "= self.res1(x) out = self.res2(out) return out class ConvTransposeLayer(nn.Module): def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__() self.deconv", "self.inplanes, self.inplanes ) # 32->16 self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.num_final_flow_features )", "self.conv2(out) out = self.bn2(out) if self.bypass is not None: outbp = self.bypass(x) out", "1, kernel_size=1, stride=1, padding=0, bias=True ) # 1x1 conv for mathability if self.use_visi:", "self.inplanes*2, self.inplanes*2 ) # 64->32 #self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes ) #", "s2, s3, s4 ) if self.use_visi: visiout = self.visibility( merged_encode, t0, t1, t2,", ") def encode(self,x): # stem x = self.conv1(x) x = self.bn1(x) x0 =", ") # 256->128 self.visi_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64", "# # U-ResNet # U-net witih ResNet modules # # Semantic segmentation network", "self.shortcut is None: bypass = x else: bypass = self.shortcut(x) class DoubleResNet(nn.Module): def", "out = self.deconv(x,output_size=skip_x.size()) # concat skip connections out = torch.cat( [out,skip_x], 1 )", "padding=1, bias=False) # if stride >1, then we need to subsamble the input", ") if self.use_visi: visiout = self.visibility( merged_encode, t0, t1, t2, t3, t4 )", "print \" x5: \",x5.size() return x5,x0,x1,x2,x3,x4 def flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction", "): return ConvTransposeLayer( inplanes, skipplanes, deconvplanes, resnetplanes ) def encode(self,x): # stem x", "stride=2, padding=1 ) self.enc_layer1 = self._make_encoding_layer( self.inplanes*1, self.inplanes*2, stride=1) # 16->32 self.enc_layer2 =", "# decoding matchability if self.use_visi: self.visi_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 )", "self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer1(x,x0) if self._showsizes: print \"", "x = self.flow_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer3(x,x2)", "stride=1, padding=0, bias=True ) # 2 classes, 0=not vis, 1=vis self.visi_softmax = nn.LogSoftmax(dim=1)", "n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_encoding_layer(self, inplanes, planes, stride=2): return DoubleResNet(BasicBlock,inplanes,planes,stride=stride)", "nn import torch as torch import math import torch.utils.model_zoo as model_zoo ########################################################### #", "# 128->256 self.enc_layer5 = self._make_encoding_layer( self.inplanes*16, self.inplanes*32, stride=2) # 256->512 # decoding flow", "vis, 1=vis self.visi_softmax = nn.LogSoftmax(dim=1) # initialization for m in self.modules(): if isinstance(m,", "iscuda=\",x.is_cuda x = self.visi_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x =", "self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.flow_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8", "return ConvTransposeLayer( inplanes, skipplanes, deconvplanes, resnetplanes ) def encode(self,x): # stem x =", ") out = self.res(out) return out class LArFlowUResNet(nn.Module): def __init__(self, num_classes=3, input_channels=3, inplanes=16,", "= bypass+residual out = self.relu(out) return out class PreactivationBlock(nn.Module): def __init__(self, inplanes, planes,", "# 256->128 self.visi_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.visi_dec_layer2", "= nn.ReLU(inplace=True) def forward(self, x): out = self.conv1(x) out = self.bn1(out) out =", "PreactivationBlock(nn.Module): def __init__(self, inplanes, planes, stride=1 ): super(Preactivation, self).__init__() # residual path self.bn1", "for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m,nn.ConvTranspose2d): n = m.kernel_size[0] *", "stride=stride,padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1): super(BasicBlock,", "def forward(self, x): if self.shortcut is None: bypass = x else: bypass =", "stem x = self.conv1(x) x = self.bn1(x) x0 = self.relu1(x) x = self.pool1(x0)", "print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow", "mathability if self.use_visi: self.visi_conv = nn.Conv2d( self.inplanes, 2, kernel_size=1, stride=1, padding=0, bias=True )", "# 32->64 self.enc_layer3 = self._make_encoding_layer( self.inplanes*4, self.inplanes*8, stride=2) # 64->128 self.enc_layer4 = self._make_encoding_layer(", "if self.shortcut is None: bypass = x else: bypass = self.shortcut(x) residual =", "to flow prediction \"\"\" x = self.flow_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print", "to be copy of caffe version # ########################################################### def conv3x3(in_planes, out_planes, stride=1): \"\"\"3x3", "planes, kernel_size=3, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.relu2 = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(planes, planes,", "to subsamble the input if stride>1: self.shortcut = nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else: self.shortcut = None", "self.inplanes*2, stride=1) # 16->32 self.enc_layer2 = self._make_encoding_layer( self.inplanes*2, self.inplanes*4, stride=2) # 32->64 self.enc_layer3", "64->32 self.visi_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.inplanes ) # 32->16 # 1x1", "stride=stride, padding=0, bias=False) self.relu = nn.ReLU(inplace=True) def forward(self, x): out = self.conv1(x) out", "nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,", "= self.bn2(out) if self.bypass is not None: outbp = self.bypass(x) out += outbp", "1x1 conv for flow self.flow_conv = nn.Conv2d( self.num_final_flow_features, 1, kernel_size=1, stride=1, padding=0, bias=True", "else: bypass = self.shortcut(x) class DoubleResNet(nn.Module): def __init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__() self.res1 = Block(inplanes,planes,stride) self.res2", "padding=1 ) self.enc_layer1 = self._make_encoding_layer( self.inplanes*1, self.inplanes*2, stride=1) # 16->32 self.enc_layer2 = self._make_encoding_layer(", "nn.BatchNorm2d(planes) self.relu1 = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.stride =", "t2, t3, t4 ) flow_predict = self.flow_conv( flowout ) if self.use_visi: visi_predict =", "pixels # # resnet implementation from pytorch.torchvision module # U-net from (cite) #", "stride self.bypass = None if inplanes!=planes or stride>1: self.bypass = nn.Conv2d(inplanes, planes, kernel_size=1,", "self.bn2(out) if self.bypass is not None: outbp = self.bypass(x) out += outbp else:", "bypass+residual out = self.relu(out) return out class PreactivationBlock(nn.Module): def __init__(self, inplanes, planes, stride=1", "self).__init__() # residual path self.bn1 = nn.BatchNorm2d(inplanes) self.relu1 = nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(inplanes,", "__init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__() self.deconv = nn.ConvTranspose2d( deconv_inplanes, deconv_outplanes, kernel_size=4, stride=2, padding=1, bias=False ) self.res", "DoubleResNet(nn.Module): def __init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__() self.res1 = Block(inplanes,planes,stride) self.res2 = Block( planes,planes, 1) def", "concat skip connections out = torch.cat( [out,skip_x], 1 ) out = self.res(out) return", "self._make_encoding_layer( self.inplanes*1, self.inplanes*2, stride=1) # 16->32 self.enc_layer2 = self._make_encoding_layer( self.inplanes*2, self.inplanes*4, stride=2) #", "decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer4(x,x3) if self._showsizes: print \"", "iscuda=\",x.is_cuda x = self.flow_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x =", "= self._make_encoding_layer( self.inplanes*16, self.inplanes*32, stride=2) # 256->512 # decoding flow #self.num_final_flow_features = self.inplanes", "# 2 classes, 0=not vis, 1=vis self.visi_softmax = nn.LogSoftmax(dim=1) # initialization for m", "= nn.Conv2d(inplanes, planes, kernel_size=3, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.relu2 = nn.ReLU(inplace=True) self.conv2 =", "128->64 self.visi_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 self.visi_dec_layer1 =", "# initial conv layer self.bn1 = nn.BatchNorm2d(self.inplanes) self.relu1 = nn.ReLU(inplace=True) self.pool1 = nn.MaxPool2d(", "self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.flow_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8,", "bypass = x else: bypass = self.shortcut(x) class DoubleResNet(nn.Module): def __init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__() self.res1", "planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes, kernel_size=1,", "self.visi_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 self.visi_dec_layer1 = self._make_decoding_layer(", "residual = self.conv1(x) residual = self.bn1(residual) residual = self.relu(residual) residual = self.conv2(residual) residual", "kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes, kernel_size=1, bias=False)", "# 64->32 self.visi_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.inplanes ) # 32->16 #", "if self._showsizes: print \"input: \",x.size(),\" is_cuda=\",x.is_cuda src_encode, s0, s1, s2, s3, s4 =", "caffe version # ########################################################### def conv3x3(in_planes, out_planes, stride=1): \"\"\"3x3 convolution with padding\"\"\" return", "iscuda=\",x.is_cuda x = self.visi_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x =", "connections out = torch.cat( [out,skip_x], 1 ) out = self.res(out) return out class", "kernel_size=7, stride=1, padding=3, bias=True) # initial conv layer self.bn1 = nn.BatchNorm2d(self.inplanes) self.relu1 =", "self.inplanes*8, self.inplanes*8 ) # 256->128 self.visi_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 )", "U-ResNet # U-net witih ResNet modules # # Semantic segmentation network used by", "= self.bn3(residual) out = bypass+residual out = self.relu(out) return out class PreactivationBlock(nn.Module): def", "if inplanes!=planes or stride>1: self.bypass = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, padding=0, bias=False) self.relu", "planes, kernel_size=3, stride=stride, padding=1, bias=False) # if stride >1, then we need to", "self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.flow_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4,", "= self.deconv(x,output_size=skip_x.size()) # concat skip connections out = torch.cat( [out,skip_x], 1 ) out", "s3, s4 = self.encode(src) target_encode, t0, t1, t2, t3, t4 = self.encode(target) merged_encode", "+= x out = self.relu(out) return out class Bottleneck(nn.Module): def __init__(self, inplanes, planes,", "t4 ) flow_predict = self.flow_conv( flowout ) if self.use_visi: visi_predict = self.visi_conv( visiout", "inplanes, planes, stride=1 ): super(Preactivation, self).__init__() # residual path self.bn1 = nn.BatchNorm2d(inplanes) self.relu1", "out = self.conv1(x) out = self.bn1(out) out = self.relu1(out) out = self.conv2(out) out", "kernel_size=4, stride=2, padding=1, bias=False ) self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x): out = self.deconv(x,output_size=skip_x.size())", "out class Bottleneck(nn.Module): def __init__(self, inplanes, planes, stride=1 ): super(Bottleneck, self).__init__() # residual", "def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__() self.deconv = nn.ConvTranspose2d( deconv_inplanes, deconv_outplanes, kernel_size=4, stride=2, padding=1, bias=False )", "\"\"\"3x3 convolution with padding\"\"\" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1, bias=False) class BasicBlock(nn.Module): expansion", "# 256->128 self.flow_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.flow_dec_layer2", "self.inplanes*2 ) # 64->32 self.visi_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.inplanes ) #", "= nn.Conv2d( self.inplanes, 2, kernel_size=1, stride=1, padding=0, bias=True ) # 2 classes, 0=not", "initialization for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m,nn.ConvTranspose2d): n = m.kernel_size[0]", "dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda", "\" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\"", "= nn.BatchNorm2d(self.inplanes) self.relu1 = nn.ReLU(inplace=True) self.pool1 = nn.MaxPool2d( 3, stride=2, padding=1 ) self.enc_layer1", "network used by MicroBooNE # to label track/shower pixels # # resnet implementation", "dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda", "# Semantic segmentation network used by MicroBooNE # to label track/shower pixels #", "# decoding flow #self.num_final_flow_features = self.inplanes self.num_final_flow_features = self.inplanes self.flow_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2,", "isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_encoding_layer(self, inplanes, planes, stride=2): return DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def _make_decoding_layer(self,", "None if inplanes!=planes or stride>1: self.bypass = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, padding=0, bias=False)", "iscuda=\",x.is_cuda x = self.flow_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x =", "# # Semantic segmentation network used by MicroBooNE # to label track/shower pixels", "= self._make_encoding_layer( self.inplanes*1, self.inplanes*2, stride=1) # 16->32 self.enc_layer2 = self._make_encoding_layer( self.inplanes*2, self.inplanes*4, stride=2)", "self.res2(out) return out class ConvTransposeLayer(nn.Module): def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__() self.deconv = nn.ConvTranspose2d( deconv_inplanes, deconv_outplanes,", "self.relu1(out) out = self.conv2(out) out = self.bn2(out) if self.bypass is not None: outbp", "bias=False) self.bn2 = nn.BatchNorm2d(planes) self.relu2 = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,", "out = bypass+residual out = self.relu(out) return out class PreactivationBlock(nn.Module): def __init__(self, inplanes,", "as nn import torch as torch import math import torch.utils.model_zoo as model_zoo ###########################################################", ") visi_predict = self.visi_softmax(visi_predict) else: visi_predict = None if self._showsizes: print \" softmax:", "stride=2) # 256->512 # decoding flow #self.num_final_flow_features = self.inplanes self.num_final_flow_features = self.inplanes self.flow_dec_layer5", "stride=1) # 16->32 self.enc_layer2 = self._make_encoding_layer( self.inplanes*2, self.inplanes*4, stride=2) # 32->64 self.enc_layer3 =", "deconvplanes, resnetplanes ): return ConvTransposeLayer( inplanes, skipplanes, deconvplanes, resnetplanes ) def encode(self,x): #", "= self.flow_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x", "self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.visi_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2,", "to label track/shower pixels # # resnet implementation from pytorch.torchvision module # U-net", "from pytorch.torchvision module # U-net from (cite) # # meant to be copy", "self._showsizes: print \"input: \",x.size(),\" is_cuda=\",x.is_cuda src_encode, s0, s1, s2, s3, s4 = self.encode(src)", "out = self.res1(x) out = self.res2(out) return out class ConvTransposeLayer(nn.Module): def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__()", "inplanes=16, showsizes=False, use_visi=True): self.inplanes =inplanes super(LArFlowUResNet, self).__init__() self._showsizes = showsizes # print size", "bias=False) self.bn3 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.stride = stride # if stride", "self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.stride = stride self.bypass = None", "residual = self.bn1(residual) residual = self.relu(residual) residual = self.conv2(residual) residual = self.bn2(residual) residual", "\" x4: \",x4.size() print \" x5: \",x5.size() return x5,x0,x1,x2,x3,x4 def flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding", "self.visi_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x =", "self._showsizes: print \"after decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer4(x,x3) if", "return out class ConvTransposeLayer(nn.Module): def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__() self.deconv = nn.ConvTranspose2d( deconv_inplanes, deconv_outplanes, kernel_size=4,", "import torch.nn as nn import torch as torch import math import torch.utils.model_zoo as", "nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_encoding_layer(self, inplanes, planes, stride=2): return DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def _make_decoding_layer(self, inplanes,", "modules # # Semantic segmentation network used by MicroBooNE # to label track/shower", "kernel_size=3, stride=stride,padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1):", "= self.res2(out) return out class ConvTransposeLayer(nn.Module): def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__() self.deconv = nn.ConvTranspose2d( deconv_inplanes,", "m.bias.data.zero_() def _make_encoding_layer(self, inplanes, planes, stride=2): return DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def _make_decoding_layer(self, inplanes, skipplanes, deconvplanes,", "bias=True) # initial conv layer self.bn1 = nn.BatchNorm2d(self.inplanes) self.relu1 = nn.ReLU(inplace=True) self.pool1 =", "kernel_size=1, stride=stride, padding=0, bias=False) self.relu = nn.ReLU(inplace=True) def forward(self, x): out = self.conv1(x)", "t4 = self.encode(target) merged_encode = torch.cat( [target_encode,src_encode], 1 ) flowout = self.flow( merged_encode,", "math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_encoding_layer(self, inplanes, planes, stride=2):", "self.bypass = None if inplanes!=planes or stride>1: self.bypass = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride,", "print \" x1: \",x1.size() print \" x2: \",x2.size() print \" x3: \",x3.size() print", "path self.bn1 = nn.BatchNorm2d(inplanes) self.relu1 = nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, bias=False)", "out = self.res2(out) return out class ConvTransposeLayer(nn.Module): def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__() self.deconv = nn.ConvTranspose2d(", "# 128->64 self.visi_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 self.visi_dec_layer1", "residual path self.bn1 = nn.BatchNorm2d(inplanes) self.relu1 = nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3,", "self.inplanes*8, self.inplanes*16, stride=2) # 128->256 self.enc_layer5 = self._make_encoding_layer( self.inplanes*16, self.inplanes*32, stride=2) # 256->512", "= self.enc_layer5(x4) if self._showsizes: print \"after encoding: \" print \" x1: \",x1.size() print", "stride=2) # 128->256 self.enc_layer5 = self._make_encoding_layer( self.inplanes*16, self.inplanes*32, stride=2) # 256->512 # decoding", "self.shortcut(x) residual = self.conv1(x) residual = self.bn1(residual) residual = self.relu(residual) residual = self.conv2(residual)", "conv layer self.bn1 = nn.BatchNorm2d(self.inplanes) self.relu1 = nn.ReLU(inplace=True) self.pool1 = nn.MaxPool2d( 3, stride=2,", "# 16->32 self.enc_layer2 = self._make_encoding_layer( self.inplanes*2, self.inplanes*4, stride=2) # 32->64 self.enc_layer3 = self._make_encoding_layer(", "self.inplanes*2, self.inplanes, self.inplanes, self.inplanes ) # 32->16 # 1x1 conv for flow self.flow_conv", "1=vis self.visi_softmax = nn.LogSoftmax(dim=1) # initialization for m in self.modules(): if isinstance(m, nn.Conv2d)", "self.visi_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def forward(self, src,", "__init__(self, inplanes, planes, stride=1 ): super(Bottleneck, self).__init__() # residual path self.conv1 = nn.Conv2d(inplanes,", "else: out += x out = self.relu(out) return out class Bottleneck(nn.Module): def __init__(self,", "self.visibility( merged_encode, t0, t1, t2, t3, t4 ) flow_predict = self.flow_conv( flowout )", "super(ConvTransposeLayer,self).__init__() self.deconv = nn.ConvTranspose2d( deconv_inplanes, deconv_outplanes, kernel_size=4, stride=2, padding=1, bias=False ) self.res =", "\",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x", "isinstance(m, nn.Conv2d) or isinstance(m,nn.ConvTranspose2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2.", "torch.utils.model_zoo as model_zoo ########################################################### # # U-ResNet # U-net witih ResNet modules #", "self.bn2 = nn.BatchNorm2d(planes) self.stride = stride self.bypass = None if inplanes!=planes or stride>1:", "U-net from (cite) # # meant to be copy of caffe version #", "if self._showsizes: print \"after decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer4(x,x3)", "self.inplanes*4, self.inplanes*4 ) # 128->64 self.flow_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 )", "self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes) self.relu", "= nn.Conv2d(planes, planes, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.stride =", "\",x3.size() print \" x4: \",x4.size() print \" x5: \",x5.size() return x5,x0,x1,x2,x3,x4 def flow(self,merged_encode,x0,x1,x2,x3,x4):", "flow prediction \"\"\" x = self.flow_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print \"", "__init__(self, inplanes, planes, stride=1 ): super(Preactivation, self).__init__() # residual path self.bn1 = nn.BatchNorm2d(inplanes)", "self.inplanes*8, stride=2) # 64->128 self.enc_layer4 = self._make_encoding_layer( self.inplanes*8, self.inplanes*16, stride=2) # 128->256 self.enc_layer5", "x): if self.shortcut is None: bypass = x else: bypass = self.shortcut(x) class", "stride # if stride >1, then we need to subsamble the input if", "flowout ) if self.use_visi: visi_predict = self.visi_conv( visiout ) visi_predict = self.visi_softmax(visi_predict) else:", "= self.enc_layer2(x1) x3 = self.enc_layer3(x2) x4 = self.enc_layer4(x3) x5 = self.enc_layer5(x4) if self._showsizes:", "print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer1(x,x0) if self._showsizes: print \" dec1:", "_make_decoding_layer(self, inplanes, skipplanes, deconvplanes, resnetplanes ): return ConvTransposeLayer( inplanes, skipplanes, deconvplanes, resnetplanes )", "self.flow_conv( flowout ) if self.use_visi: visi_predict = self.visi_conv( visiout ) visi_predict = self.visi_softmax(visi_predict)", "self.enc_layer1 = self._make_encoding_layer( self.inplanes*1, self.inplanes*2, stride=1) # 16->32 self.enc_layer2 = self._make_encoding_layer( self.inplanes*2, self.inplanes*4,", "self.inplanes, self.inplanes, self.num_final_flow_features ) # 32->200 # decoding matchability if self.use_visi: self.visi_dec_layer5 =", "super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu1 = nn.ReLU(inplace=True)", "= None def forward(self, x): if self.shortcut is None: bypass = x else:", "self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.visi_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4,", "= self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.inplanes ) # 32->16 # 1x1 conv for", "x2 = self.enc_layer2(x1) x3 = self.enc_layer3(x2) x4 = self.enc_layer4(x3) x5 = self.enc_layer5(x4) if", "each layer self.use_visi = use_visi # Encoder # stem # one big stem", "padding=0, bias=True ) # 2 classes, 0=not vis, 1=vis self.visi_softmax = nn.LogSoftmax(dim=1) #", "= self.relu(out) return out class Bottleneck(nn.Module): def __init__(self, inplanes, planes, stride=1 ): super(Bottleneck,", "elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_encoding_layer(self, inplanes, planes, stride=2): return DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def", "decoding matchability if self.use_visi: self.visi_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) #", "= Block(inplanes,planes,stride) self.res2 = Block( planes,planes, 1) def forward(self, x): out = self.res1(x)", "s1, s2, s3, s4 = self.encode(src) target_encode, t0, t1, t2, t3, t4 =", "self.use_visi = use_visi # Encoder # stem # one big stem self.conv1 =", "\"\"\" x = self.visi_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print \" dec5: \",x.size(),\"", "64->32 #self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes ) # 32->16 self.flow_dec_layer1 = self._make_decoding_layer(", "\",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x", "stride=2): return DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def _make_decoding_layer(self, inplanes, skipplanes, deconvplanes, resnetplanes ): return ConvTransposeLayer( inplanes,", "torch.nn as nn import torch as torch import math import torch.utils.model_zoo as model_zoo", "resnetplanes ) def encode(self,x): # stem x = self.conv1(x) x = self.bn1(x) x0", "16->32 self.enc_layer2 = self._make_encoding_layer( self.inplanes*2, self.inplanes*4, stride=2) # 32->64 self.enc_layer3 = self._make_encoding_layer( self.inplanes*4,", "if self.use_visi: visi_predict = self.visi_conv( visiout ) visi_predict = self.visi_softmax(visi_predict) else: visi_predict =", "planes, kernel_size=1, stride=stride, padding=0, bias=False) self.relu = nn.ReLU(inplace=True) def forward(self, x): out =", "x = self.flow_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda", "nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3", "label track/shower pixels # # resnet implementation from pytorch.torchvision module # U-net from", "by MicroBooNE # to label track/shower pixels # # resnet implementation from pytorch.torchvision", "\",x.size(),\" is_cuda=\",x.is_cuda src_encode, s0, s1, s2, s3, s4 = self.encode(src) target_encode, t0, t1,", "if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer2(x,x1) if self._showsizes: print", "self.inplanes ) # 32->16 # 1x1 conv for flow self.flow_conv = nn.Conv2d( self.num_final_flow_features,", "nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else: self.shortcut = None def forward(self, x): if self.shortcut is None: bypass", "def flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\" x = self.flow_dec_layer5(merged_encode,x4) if self._showsizes:", "stride) self.bn1 = nn.BatchNorm2d(planes) self.relu1 = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 =", "\",x.size(),\" iscuda=\",x.is_cuda return x def visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\" x", "bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2", "# 1x1 conv for mathability if self.use_visi: self.visi_conv = nn.Conv2d( self.inplanes, 2, kernel_size=1,", "if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer1(x,x0) if self._showsizes: print", "self.visi_conv = nn.Conv2d( self.inplanes, 2, kernel_size=1, stride=1, padding=0, bias=True ) # 2 classes,", ") # 2 classes, 0=not vis, 1=vis self.visi_softmax = nn.LogSoftmax(dim=1) # initialization for", "# ########################################################### def conv3x3(in_planes, out_planes, stride=1): \"\"\"3x3 convolution with padding\"\"\" return nn.Conv2d(in_planes, out_planes,", "out = self.relu(out) return out class Bottleneck(nn.Module): def __init__(self, inplanes, planes, stride=1 ):", "= self._make_encoding_layer( self.inplanes*2, self.inplanes*4, stride=2) # 32->64 self.enc_layer3 = self._make_encoding_layer( self.inplanes*4, self.inplanes*8, stride=2)", "128->256 self.enc_layer5 = self._make_encoding_layer( self.inplanes*16, self.inplanes*32, stride=2) # 256->512 # decoding flow #self.num_final_flow_features", "= self.flow_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def visibility(self,merged_encode,x0,x1,x2,x3,x4):", "self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes,", "256->512 # decoding flow #self.num_final_flow_features = self.inplanes self.num_final_flow_features = self.inplanes self.flow_dec_layer5 = self._make_decoding_layer(", "self.bn1(residual) residual = self.relu(residual) residual = self.conv2(residual) residual = self.bn2(residual) residual = self.relu(residual)", "x = self.bn1(x) x0 = self.relu1(x) x = self.pool1(x0) x1 = self.enc_layer1(x) x2", "=inplanes super(LArFlowUResNet, self).__init__() self._showsizes = showsizes # print size at each layer self.use_visi", "x = self.visi_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer2(x,x1)", "bias=True ) # 1x1 conv for mathability if self.use_visi: self.visi_conv = nn.Conv2d( self.inplanes,", "bias=False) class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1): super(BasicBlock, self).__init__()", "kernel_size=1, stride=1, padding=0, bias=True ) # 2 classes, 0=not vis, 1=vis self.visi_softmax =", "nn.MaxPool2d( 3, stride=2, padding=1 ) self.enc_layer1 = self._make_encoding_layer( self.inplanes*1, self.inplanes*2, stride=1) # 16->32", "self.bn1(x) x0 = self.relu1(x) x = self.pool1(x0) x1 = self.enc_layer1(x) x2 = self.enc_layer2(x1)", "\",x5.size() return x5,x0,x1,x2,x3,x4 def flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\" x =", "\",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x", "self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) # if stride >1, then", "self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer2(x,x1) if self._showsizes: print \"", "out += x out = self.relu(out) return out class Bottleneck(nn.Module): def __init__(self, inplanes,", "# # meant to be copy of caffe version # ########################################################### def conv3x3(in_planes,", "= self.enc_layer1(x) x2 = self.enc_layer2(x1) x3 = self.enc_layer3(x2) x4 = self.enc_layer4(x3) x5 =", "print \" x2: \",x2.size() print \" x3: \",x3.size() print \" x4: \",x4.size() print", "self.enc_layer4(x3) x5 = self.enc_layer5(x4) if self._showsizes: print \"after encoding: \" print \" x1:", "self._showsizes: print \"after decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer4(x,x3) if", "= self.visi_softmax(visi_predict) else: visi_predict = None if self._showsizes: print \" softmax: \",x.size() return", "subsamble the input if stride>1: self.shortcut = nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else: self.shortcut = None def", "self.relu(out) return out class PreactivationBlock(nn.Module): def __init__(self, inplanes, planes, stride=1 ): super(Preactivation, self).__init__()", "planes, stride=2): return DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def _make_decoding_layer(self, inplanes, skipplanes, deconvplanes, resnetplanes ): return ConvTransposeLayer(", "implementation from pytorch.torchvision module # U-net from (cite) # # meant to be", "self.inplanes, 2, kernel_size=1, stride=1, padding=0, bias=True ) # 2 classes, 0=not vis, 1=vis", "skipplanes, deconvplanes, resnetplanes ): return ConvTransposeLayer( inplanes, skipplanes, deconvplanes, resnetplanes ) def encode(self,x):", "= self.relu(residual) residual = self.conv3(residual) residual = self.bn3(residual) out = bypass+residual out =", "= self.inplanes self.flow_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.flow_dec_layer4", "def visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\" x = self.visi_dec_layer5(merged_encode,x4) if self._showsizes:", "self._showsizes = showsizes # print size at each layer self.use_visi = use_visi #", "stride=1 ): super(Bottleneck, self).__init__() # residual path self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)", "\" x3: \",x3.size() print \" x4: \",x4.size() print \" x5: \",x5.size() return x5,x0,x1,x2,x3,x4", "= nn.ConvTranspose2d( deconv_inplanes, deconv_outplanes, kernel_size=4, stride=2, padding=1, bias=False ) self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def", "= stride # if stride >1, then we need to subsamble the input", "iscuda=\",x.is_cuda return x def forward(self, src, target): if self._showsizes: print \"input: \",x.size(),\" is_cuda=\",x.is_cuda", "self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.inplanes ) # 32->16 # 1x1 conv for flow", "dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda", "self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.visi_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8", "skipplanes, deconvplanes, resnetplanes ) def encode(self,x): # stem x = self.conv1(x) x =", "return x5,x0,x1,x2,x3,x4 def flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\" x = self.flow_dec_layer5(merged_encode,x4)", "out class PreactivationBlock(nn.Module): def __init__(self, inplanes, planes, stride=1 ): super(Preactivation, self).__init__() # residual", "src, target): if self._showsizes: print \"input: \",x.size(),\" is_cuda=\",x.is_cuda src_encode, s0, s1, s2, s3,", "= self.conv2(out) out = self.bn2(out) if self.bypass is not None: outbp = self.bypass(x)", "= self.visi_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer3(x,x2) if", "self.conv1(x) residual = self.bn1(residual) residual = self.relu(residual) residual = self.conv2(residual) residual = self.bn2(residual)", "self.inplanes*16, self.inplanes*32, stride=2) # 256->512 # decoding flow #self.num_final_flow_features = self.inplanes self.num_final_flow_features =", "= self.shortcut(x) residual = self.conv1(x) residual = self.bn1(residual) residual = self.relu(residual) residual =", "self.inplanes*16, self.inplanes*16 ) # 512->256 self.flow_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 )", "flow self.flow_conv = nn.Conv2d( self.num_final_flow_features, 1, kernel_size=1, stride=1, padding=0, bias=True ) # 1x1", "import math import torch.utils.model_zoo as model_zoo ########################################################### # # U-ResNet # U-net witih", "def encode(self,x): # stem x = self.conv1(x) x = self.bn1(x) x0 = self.relu1(x)", "self.bn3(residual) out = bypass+residual out = self.relu(out) return out class PreactivationBlock(nn.Module): def __init__(self,", "# to label track/shower pixels # # resnet implementation from pytorch.torchvision module #", "= self.relu(out) return out class PreactivationBlock(nn.Module): def __init__(self, inplanes, planes, stride=1 ): super(Preactivation,", "stride=1, padding=3, bias=True) # initial conv layer self.bn1 = nn.BatchNorm2d(self.inplanes) self.relu1 = nn.ReLU(inplace=True)", "classes, 0=not vis, 1=vis self.visi_softmax = nn.LogSoftmax(dim=1) # initialization for m in self.modules():", "self.res(out) return out class LArFlowUResNet(nn.Module): def __init__(self, num_classes=3, input_channels=3, inplanes=16, showsizes=False, use_visi=True): self.inplanes", "used by MicroBooNE # to label track/shower pixels # # resnet implementation from", "self.encode(src) target_encode, t0, t1, t2, t3, t4 = self.encode(target) merged_encode = torch.cat( [target_encode,src_encode],", "self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.flow_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4,", "big stem self.conv1 = nn.Conv2d(input_channels, self.inplanes, kernel_size=7, stride=1, padding=3, bias=True) # initial conv", "32->200 # decoding matchability if self.use_visi: self.visi_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16", "Bottleneck(nn.Module): def __init__(self, inplanes, planes, stride=1 ): super(Bottleneck, self).__init__() # residual path self.conv1", "the input if stride>1: self.shortcut = nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else: self.shortcut = None def forward(self,", "self.flow_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.flow_dec_layer4 = self._make_decoding_layer(", "= self._make_encoding_layer( self.inplanes*4, self.inplanes*8, stride=2) # 64->128 self.enc_layer4 = self._make_encoding_layer( self.inplanes*8, self.inplanes*16, stride=2)", "self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu1 = nn.ReLU(inplace=True) self.conv2 =", ">1, then we need to subsamble the input if stride>1: self.shortcut = nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False)", "input if stride>1: self.shortcut = nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else: self.shortcut = None def forward(self, x):", "skip connections out = torch.cat( [out,skip_x], 1 ) out = self.res(out) return out", "self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.visi_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8,", "inplanes, skipplanes, deconvplanes, resnetplanes ): return ConvTransposeLayer( inplanes, skipplanes, deconvplanes, resnetplanes ) def", "padding=0, bias=True ) # 1x1 conv for mathability if self.use_visi: self.visi_conv = nn.Conv2d(", "stride=2, padding=1, bias=False ) self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x): out = self.deconv(x,output_size=skip_x.size()) #", "= None if inplanes!=planes or stride>1: self.bypass = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, padding=0,", "stem self.conv1 = nn.Conv2d(input_channels, self.inplanes, kernel_size=7, stride=1, padding=3, bias=True) # initial conv layer", "= self.encode(src) target_encode, t0, t1, t2, t3, t4 = self.encode(target) merged_encode = torch.cat(", "self.conv3 = nn.Conv2d(planes, planes, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.stride", "of caffe version # ########################################################### def conv3x3(in_planes, out_planes, stride=1): \"\"\"3x3 convolution with padding\"\"\"", "padding=0, bias=False) self.relu = nn.ReLU(inplace=True) def forward(self, x): out = self.conv1(x) out =", ") self.enc_layer1 = self._make_encoding_layer( self.inplanes*1, self.inplanes*2, stride=1) # 16->32 self.enc_layer2 = self._make_encoding_layer( self.inplanes*2,", "if stride >1, then we need to subsamble the input if stride>1: self.shortcut", "merged_encode, s0, s1, s2, s3, s4 ) if self.use_visi: visiout = self.visibility( merged_encode,", "= nn.BatchNorm2d(planes) self.relu1 = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.stride", "def __init__(self, inplanes, planes, stride=1 ): super(Bottleneck, self).__init__() # residual path self.conv1 =", "= nn.ReLU(inplace=True) self.stride = stride # if stride >1, then we need to", "self.relu1 = nn.ReLU(inplace=True) self.pool1 = nn.MaxPool2d( 3, stride=2, padding=1 ) self.enc_layer1 = self._make_encoding_layer(", "super(Preactivation, self).__init__() # residual path self.bn1 = nn.BatchNorm2d(inplanes) self.relu1 = nn.ReLU(inplace=True) self.conv1 =", "= self.visibility( merged_encode, t0, t1, t2, t3, t4 ) flow_predict = self.flow_conv( flowout", "target): if self._showsizes: print \"input: \",x.size(),\" is_cuda=\",x.is_cuda src_encode, s0, s1, s2, s3, s4", "planes, stride=1 ): super(Bottleneck, self).__init__() # residual path self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1,", "nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, padding=0, bias=False) self.relu = nn.ReLU(inplace=True) def forward(self, x): out", "path self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes,", "initial conv layer self.bn1 = nn.BatchNorm2d(self.inplanes) self.relu1 = nn.ReLU(inplace=True) self.pool1 = nn.MaxPool2d( 3,", "= self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 #self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2,", "self.inplanes*4, stride=2) # 32->64 self.enc_layer3 = self._make_encoding_layer( self.inplanes*4, self.inplanes*8, stride=2) # 64->128 self.enc_layer4", "= nn.LogSoftmax(dim=1) # initialization for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m,nn.ConvTranspose2d):", "if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding", "target_encode, t0, t1, t2, t3, t4 = self.encode(target) merged_encode = torch.cat( [target_encode,src_encode], 1", "# if stride >1, then we need to subsamble the input if stride>1:", "def forward(self,x,skip_x): out = self.deconv(x,output_size=skip_x.size()) # concat skip connections out = torch.cat( [out,skip_x],", "bypass = self.shortcut(x) class DoubleResNet(nn.Module): def __init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__() self.res1 = Block(inplanes,planes,stride) self.res2 =", "= self.bn1(x) x0 = self.relu1(x) x = self.pool1(x0) x1 = self.enc_layer1(x) x2 =", "self.bn2 = nn.BatchNorm2d(planes) self.relu2 = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1,", "iscuda=\",x.is_cuda return x def visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\" x =", "nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.relu2 = nn.ReLU(inplace=True)", "iscuda=\",x.is_cuda x = self.flow_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x =", "= nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes) self.relu =", "Encoder # stem # one big stem self.conv1 = nn.Conv2d(input_channels, self.inplanes, kernel_size=7, stride=1,", "= self.conv2(residual) residual = self.bn2(residual) residual = self.relu(residual) residual = self.conv3(residual) residual =", "= self.enc_layer3(x2) x4 = self.enc_layer4(x3) x5 = self.enc_layer5(x4) if self._showsizes: print \"after encoding:", "\" x2: \",x2.size() print \" x3: \",x3.size() print \" x4: \",x4.size() print \"", "pytorch.torchvision module # U-net from (cite) # # meant to be copy of", "self.inplanes*16, self.inplanes*16 ) # 512->256 self.visi_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 )", "forward(self,x,skip_x): out = self.deconv(x,output_size=skip_x.size()) # concat skip connections out = torch.cat( [out,skip_x], 1", "encoding: \" print \" x1: \",x1.size() print \" x2: \",x2.size() print \" x3:", "= nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.stride = stride self.bypass", "self.use_visi: visi_predict = self.visi_conv( visiout ) visi_predict = self.visi_softmax(visi_predict) else: visi_predict = None", "x1: \",x1.size() print \" x2: \",x2.size() print \" x3: \",x3.size() print \" x4:", "= self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.visi_dec_layer3 = self._make_decoding_layer( self.inplanes*8,", "x3: \",x3.size() print \" x4: \",x4.size() print \" x5: \",x5.size() return x5,x0,x1,x2,x3,x4 def", "x = self.visi_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def", "out = torch.cat( [out,skip_x], 1 ) out = self.res(out) return out class LArFlowUResNet(nn.Module):", "planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu1 = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2", "\" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\"", "self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x): out = self.deconv(x,output_size=skip_x.size()) # concat skip connections out", "self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.visi_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4,", "self.flow_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer2(x,x1) if self._showsizes:", "not None: outbp = self.bypass(x) out += outbp else: out += x out", "conv for mathability if self.use_visi: self.visi_conv = nn.Conv2d( self.inplanes, 2, kernel_size=1, stride=1, padding=0,", "residual path self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 =", "padding=1, bias=False ) self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x): out = self.deconv(x,output_size=skip_x.size()) # concat", "stem # one big stem self.conv1 = nn.Conv2d(input_channels, self.inplanes, kernel_size=7, stride=1, padding=3, bias=True)", "self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 self.visi_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes,", "self.inplanes*2, self.inplanes, self.inplanes ) # 32->16 self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.num_final_flow_features", "= self.visi_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x", "x1 = self.enc_layer1(x) x2 = self.enc_layer2(x1) x3 = self.enc_layer3(x2) x4 = self.enc_layer4(x3) x5", "planes,planes, 1) def forward(self, x): out = self.res1(x) out = self.res2(out) return out", "= self.relu(residual) residual = self.conv2(residual) residual = self.bn2(residual) residual = self.relu(residual) residual =", "def forward(self, x): out = self.res1(x) out = self.res2(out) return out class ConvTransposeLayer(nn.Module):", "x = self.visi_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda", "= self.visi_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def forward(self,", "from (cite) # # meant to be copy of caffe version # ###########################################################", "self.deconv = nn.ConvTranspose2d( deconv_inplanes, deconv_outplanes, kernel_size=4, stride=2, padding=1, bias=False ) self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1)", "self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 #self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes", "if self.use_visi: self.visi_conv = nn.Conv2d( self.inplanes, 2, kernel_size=1, stride=1, padding=0, bias=True ) #", "= torch.cat( [target_encode,src_encode], 1 ) flowout = self.flow( merged_encode, s0, s1, s2, s3,", "\",x2.size() print \" x3: \",x3.size() print \" x4: \",x4.size() print \" x5: \",x5.size()", ") # 1x1 conv for mathability if self.use_visi: self.visi_conv = nn.Conv2d( self.inplanes, 2,", "inplanes, skipplanes, deconvplanes, resnetplanes ) def encode(self,x): # stem x = self.conv1(x) x", ") # 512->256 self.visi_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128", "= nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.stride = stride # if stride >1, then", "self.use_visi: self.visi_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.visi_dec_layer4 =", "= m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d):", "print \"after decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer4(x,x3) if self._showsizes:", "= self.res(out) return out class LArFlowUResNet(nn.Module): def __init__(self, num_classes=3, input_channels=3, inplanes=16, showsizes=False, use_visi=True):", "as model_zoo ########################################################### # # U-ResNet # U-net witih ResNet modules # #", "merged_encode = torch.cat( [target_encode,src_encode], 1 ) flowout = self.flow( merged_encode, s0, s1, s2,", "# 1x1 conv for flow self.flow_conv = nn.Conv2d( self.num_final_flow_features, 1, kernel_size=1, stride=1, padding=0,", "as torch import math import torch.utils.model_zoo as model_zoo ########################################################### # # U-ResNet #", "# residual path self.bn1 = nn.BatchNorm2d(inplanes) self.relu1 = nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(inplanes, planes,", "\",x1.size() print \" x2: \",x2.size() print \" x3: \",x3.size() print \" x4: \",x4.size()", ") flow_predict = self.flow_conv( flowout ) if self.use_visi: visi_predict = self.visi_conv( visiout )", "\",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x", "# resnet implementation from pytorch.torchvision module # U-net from (cite) # # meant", "nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.stride = stride # if stride >1, then we", "nn.BatchNorm2d(planes) self.stride = stride self.bypass = None if inplanes!=planes or stride>1: self.bypass =", "out class ConvTransposeLayer(nn.Module): def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__() self.deconv = nn.ConvTranspose2d( deconv_inplanes, deconv_outplanes, kernel_size=4, stride=2,", "self.bn1 = nn.BatchNorm2d(self.inplanes) self.relu1 = nn.ReLU(inplace=True) self.pool1 = nn.MaxPool2d( 3, stride=2, padding=1 )", "self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 #self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes )", "be copy of caffe version # ########################################################### def conv3x3(in_planes, out_planes, stride=1): \"\"\"3x3 convolution", "visiout = self.visibility( merged_encode, t0, t1, t2, t3, t4 ) flow_predict = self.flow_conv(", "self.relu(residual) residual = self.conv2(residual) residual = self.bn2(residual) residual = self.relu(residual) residual = self.conv3(residual)", "= self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.num_final_flow_features ) # 32->200 # decoding matchability if", "= nn.Conv2d( self.num_final_flow_features, 1, kernel_size=1, stride=1, padding=0, bias=True ) # 1x1 conv for", "self.inplanes*4 ) # 128->64 self.visi_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) #", "iscuda=\",x.is_cuda x = self.visi_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x", "residual = self.relu(residual) residual = self.conv3(residual) residual = self.bn3(residual) out = bypass+residual out", "3, stride=2, padding=1 ) self.enc_layer1 = self._make_encoding_layer( self.inplanes*1, self.inplanes*2, stride=1) # 16->32 self.enc_layer2", "bias=False ) self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x): out = self.deconv(x,output_size=skip_x.size()) # concat skip", "x = self.visi_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer3(x,x2)", "print \"input: \",x.size(),\" is_cuda=\",x.is_cuda src_encode, s0, s1, s2, s3, s4 = self.encode(src) target_encode,", "self.res1(x) out = self.res2(out) return out class ConvTransposeLayer(nn.Module): def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__() self.deconv =", "visiout ) visi_predict = self.visi_softmax(visi_predict) else: visi_predict = None if self._showsizes: print \"", "= use_visi # Encoder # stem # one big stem self.conv1 = nn.Conv2d(input_channels,", "\" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\"", "torch as torch import math import torch.utils.model_zoo as model_zoo ########################################################### # # U-ResNet", "if self.bypass is not None: outbp = self.bypass(x) out += outbp else: out", "x0 = self.relu1(x) x = self.pool1(x0) x1 = self.enc_layer1(x) x2 = self.enc_layer2(x1) x3", "512->256 self.visi_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.visi_dec_layer3 =", "if self.use_visi: visiout = self.visibility( merged_encode, t0, t1, t2, t3, t4 ) flow_predict", "self.inplanes*2 ) # 64->32 #self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes ) # 32->16", "residual = self.relu(residual) residual = self.conv2(residual) residual = self.bn2(residual) residual = self.relu(residual) residual", "if self._showsizes: print \"after encoding: \" print \" x1: \",x1.size() print \" x2:", "return out class PreactivationBlock(nn.Module): def __init__(self, inplanes, planes, stride=1 ): super(Preactivation, self).__init__() #", "conv for flow self.flow_conv = nn.Conv2d( self.num_final_flow_features, 1, kernel_size=1, stride=1, padding=0, bias=True )", "if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer1(x,x0) if self._showsizes: print", "self.pool1 = nn.MaxPool2d( 3, stride=2, padding=1 ) self.enc_layer1 = self._make_encoding_layer( self.inplanes*1, self.inplanes*2, stride=1)", "self.bypass(x) out += outbp else: out += x out = self.relu(out) return out", "nn.Conv2d(planes, planes, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.stride = stride", "# 64->128 self.enc_layer4 = self._make_encoding_layer( self.inplanes*8, self.inplanes*16, stride=2) # 128->256 self.enc_layer5 = self._make_encoding_layer(", "decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer4(x,x3) if self._showsizes: print \"", "\",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return", "forward(self, x): out = self.conv1(x) out = self.bn1(out) out = self.relu1(out) out =", "self.num_final_flow_features = self.inplanes self.flow_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256", "DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def _make_decoding_layer(self, inplanes, skipplanes, deconvplanes, resnetplanes ): return ConvTransposeLayer( inplanes, skipplanes, deconvplanes,", "): super(Preactivation, self).__init__() # residual path self.bn1 = nn.BatchNorm2d(inplanes) self.relu1 = nn.ReLU(inplace=True) self.conv1", "out = self.bn2(out) if self.bypass is not None: outbp = self.bypass(x) out +=", "= self.enc_layer4(x3) x5 = self.enc_layer5(x4) if self._showsizes: print \"after encoding: \" print \"", "print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer3(x,x2) if self._showsizes: print \" dec3:", "dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda", "module # U-net from (cite) # # meant to be copy of caffe", "= conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.stride = stride self.bypass = None if", "self.relu2 = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) # if", "= self.bypass(x) out += outbp else: out += x out = self.relu(out) return", "self.num_final_flow_features ) # 32->200 # decoding matchability if self.use_visi: self.visi_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2,", "self.flow_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer3(x,x2) if self._showsizes:", "Semantic segmentation network used by MicroBooNE # to label track/shower pixels # #", "class Bottleneck(nn.Module): def __init__(self, inplanes, planes, stride=1 ): super(Bottleneck, self).__init__() # residual path", "): super(Bottleneck, self).__init__() # residual path self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1", "print \"after encoding: \" print \" x1: \",x1.size() print \" x2: \",x2.size() print", "self.stride = stride # if stride >1, then we need to subsamble the", "stride=2) # 64->128 self.enc_layer4 = self._make_encoding_layer( self.inplanes*8, self.inplanes*16, stride=2) # 128->256 self.enc_layer5 =", "copy of caffe version # ########################################################### def conv3x3(in_planes, out_planes, stride=1): \"\"\"3x3 convolution with", "= x else: bypass = self.shortcut(x) residual = self.conv1(x) residual = self.bn1(residual) residual", "import torch.utils.model_zoo as model_zoo ########################################################### # # U-ResNet # U-net witih ResNet modules", "if self.use_visi: self.visi_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.visi_dec_layer4", "self.inplanes*8, self.inplanes*8 ) # 256->128 self.flow_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 )", "x = self.conv1(x) x = self.bn1(x) x0 = self.relu1(x) x = self.pool1(x0) x1", "\" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\"", "s0, s1, s2, s3, s4 = self.encode(src) target_encode, t0, t1, t2, t3, t4", "nn.ReLU(inplace=True) def forward(self, x): out = self.conv1(x) out = self.bn1(out) out = self.relu1(out)", "self.enc_layer4 = self._make_encoding_layer( self.inplanes*8, self.inplanes*16, stride=2) # 128->256 self.enc_layer5 = self._make_encoding_layer( self.inplanes*16, self.inplanes*32,", "stride>1: self.shortcut = nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else: self.shortcut = None def forward(self, x): if self.shortcut", "Block(inplanes,planes,stride) self.res2 = Block( planes,planes, 1) def forward(self, x): out = self.res1(x) out", "m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_encoding_layer(self, inplanes,", "bias=False) # if stride >1, then we need to subsamble the input if", "1 def __init__(self, inplanes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride)", "encode(self,x): # stem x = self.conv1(x) x = self.bn1(x) x0 = self.relu1(x) x", "s2, s3, s4 = self.encode(src) target_encode, t0, t1, t2, t3, t4 = self.encode(target)", "self.visi_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer1(x,x0) if self._showsizes:", "planes, stride=1 ): super(Preactivation, self).__init__() # residual path self.bn1 = nn.BatchNorm2d(inplanes) self.relu1 =", "def __init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__() self.res1 = Block(inplanes,planes,stride) self.res2 = Block( planes,planes, 1) def forward(self,", "dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda", "decoding to flow prediction \"\"\" x = self.flow_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\"", "t1, t2, t3, t4 = self.encode(target) merged_encode = torch.cat( [target_encode,src_encode], 1 ) flowout", "m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m,nn.ConvTranspose2d): n = m.kernel_size[0] * m.kernel_size[1]", "inplanes, planes, stride=1 ): super(Bottleneck, self).__init__() # residual path self.conv1 = nn.Conv2d(inplanes, planes,", "planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu1", "n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m,", "= Block( planes,planes, 1) def forward(self, x): out = self.res1(x) out = self.res2(out)", "stride=2) # 32->64 self.enc_layer3 = self._make_encoding_layer( self.inplanes*4, self.inplanes*8, stride=2) # 64->128 self.enc_layer4 =", "resnet implementation from pytorch.torchvision module # U-net from (cite) # # meant to", "self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer1(x,x0) if self._showsizes: print \"", "stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes, kernel_size=1, bias=False) self.bn3", "nn.LogSoftmax(dim=1) # initialization for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m,nn.ConvTranspose2d): n", "x = self.pool1(x0) x1 = self.enc_layer1(x) x2 = self.enc_layer2(x1) x3 = self.enc_layer3(x2) x4", "to flow prediction \"\"\" x = self.visi_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print", "self.flow_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.flow_dec_layer3 = self._make_decoding_layer(", "if self.shortcut is None: bypass = x else: bypass = self.shortcut(x) class DoubleResNet(nn.Module):", "= self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.flow_dec_layer3 = self._make_decoding_layer( self.inplanes*8,", "self.bn1(out) out = self.relu1(out) out = self.conv2(out) out = self.bn2(out) if self.bypass is", "class PreactivationBlock(nn.Module): def __init__(self, inplanes, planes, stride=1 ): super(Preactivation, self).__init__() # residual path", "kernel_size=1, stride=1, padding=0, bias=True ) # 1x1 conv for mathability if self.use_visi: self.visi_conv", "self.inplanes*16, stride=2) # 128->256 self.enc_layer5 = self._make_encoding_layer( self.inplanes*16, self.inplanes*32, stride=2) # 256->512 #", "__init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__() self.res1 = Block(inplanes,planes,stride) self.res2 = Block( planes,planes, 1) def forward(self, x):", "then we need to subsamble the input if stride>1: self.shortcut = nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else:", "self.inplanes, self.inplanes ) # 32->16 # 1x1 conv for flow self.flow_conv = nn.Conv2d(", "\" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction", "= self._make_encoding_layer( self.inplanes*8, self.inplanes*16, stride=2) # 128->256 self.enc_layer5 = self._make_encoding_layer( self.inplanes*16, self.inplanes*32, stride=2)", "dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def forward(self, src, target): if self._showsizes: print \"input:", "kernel_size=3, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.relu2 = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,", "x def forward(self, src, target): if self._showsizes: print \"input: \",x.size(),\" is_cuda=\",x.is_cuda src_encode, s0,", "showsizes=False, use_visi=True): self.inplanes =inplanes super(LArFlowUResNet, self).__init__() self._showsizes = showsizes # print size at", "self.enc_layer3 = self._make_encoding_layer( self.inplanes*4, self.inplanes*8, stride=2) # 64->128 self.enc_layer4 = self._make_encoding_layer( self.inplanes*8, self.inplanes*16,", "# U-net from (cite) # # meant to be copy of caffe version", "self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to", "= showsizes # print size at each layer self.use_visi = use_visi # Encoder", "#self.num_final_flow_features = self.inplanes self.num_final_flow_features = self.inplanes self.flow_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16", "self.enc_layer5(x4) if self._showsizes: print \"after encoding: \" print \" x1: \",x1.size() print \"", "with padding\"\"\" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1", "= stride self.bypass = None if inplanes!=planes or stride>1: self.bypass = nn.Conv2d(inplanes, planes,", "padding\"\"\" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1 def", "= nn.ReLU(inplace=True) self.pool1 = nn.MaxPool2d( 3, stride=2, padding=1 ) self.enc_layer1 = self._make_encoding_layer( self.inplanes*1,", "self.bn3 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.stride = stride # if stride >1,", "# initialization for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m,nn.ConvTranspose2d): n =", "if stride>1: self.shortcut = nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else: self.shortcut = None def forward(self, x): if", "class DoubleResNet(nn.Module): def __init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__() self.res1 = Block(inplanes,planes,stride) self.res2 = Block( planes,planes, 1)", "self.inplanes, self.num_final_flow_features ) # 32->200 # decoding matchability if self.use_visi: self.visi_dec_layer5 = self._make_decoding_layer(", "out = self.bn1(out) out = self.relu1(out) out = self.conv2(out) out = self.bn2(out) if", "nn.ReLU(inplace=True) self.stride = stride # if stride >1, then we need to subsamble", "self.shortcut = None def forward(self, x): if self.shortcut is None: bypass = x", "########################################################### # # U-ResNet # U-net witih ResNet modules # # Semantic segmentation", "self.relu1 = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.stride = stride", "self.relu = nn.ReLU(inplace=True) self.stride = stride # if stride >1, then we need", "= 1 def __init__(self, inplanes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes,", "x else: bypass = self.shortcut(x) residual = self.conv1(x) residual = self.bn1(residual) residual =", "for mathability if self.use_visi: self.visi_conv = nn.Conv2d( self.inplanes, 2, kernel_size=1, stride=1, padding=0, bias=True", "decoding to flow prediction \"\"\" x = self.visi_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\"", "self.bn2(residual) residual = self.relu(residual) residual = self.conv3(residual) residual = self.bn3(residual) out = bypass+residual", "s1, s2, s3, s4 ) if self.use_visi: visiout = self.visibility( merged_encode, t0, t1,", "= self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes ) # 32->16 self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes,", "s4 ) if self.use_visi: visiout = self.visibility( merged_encode, t0, t1, t2, t3, t4", "x = self.visi_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer1(x,x0)", "nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.stride = stride self.bypass =", "= nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,", "self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu1 = nn.ReLU(inplace=True) self.conv2", "self.stride = stride self.bypass = None if inplanes!=planes or stride>1: self.bypass = nn.Conv2d(inplanes,", "self.visi_conv( visiout ) visi_predict = self.visi_softmax(visi_predict) else: visi_predict = None if self._showsizes: print", "print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer4(x,x3) if self._showsizes: print \" dec4:", "= nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) # if stride", "self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.visi_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8,", "self.visi_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer2(x,x1) if self._showsizes:", "expansion = 1 def __init__(self, inplanes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes,", "padding=3, bias=True) # initial conv layer self.bn1 = nn.BatchNorm2d(self.inplanes) self.relu1 = nn.ReLU(inplace=True) self.pool1", "= nn.Conv2d(input_channels, self.inplanes, kernel_size=7, stride=1, padding=3, bias=True) # initial conv layer self.bn1 =", "stride=1, padding=0, bias=True ) # 1x1 conv for mathability if self.use_visi: self.visi_conv =", "out = self.conv2(out) out = self.bn2(out) if self.bypass is not None: outbp =", "self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.flow_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8,", "= self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.visi_dec_layer2 = self._make_decoding_layer( self.inplanes*4,", "self.relu(residual) residual = self.conv3(residual) residual = self.bn3(residual) out = bypass+residual out = self.relu(out)", "32->64 self.enc_layer3 = self._make_encoding_layer( self.inplanes*4, self.inplanes*8, stride=2) # 64->128 self.enc_layer4 = self._make_encoding_layer( self.inplanes*8,", "self.inplanes self.num_final_flow_features = self.inplanes self.flow_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) #", "\" print \" x1: \",x1.size() print \" x2: \",x2.size() print \" x3: \",x3.size()", "self.visi_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.visi_dec_layer4 = self._make_decoding_layer(", "x): out = self.res1(x) out = self.res2(out) return out class ConvTransposeLayer(nn.Module): def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes):", "stride=1 ): super(Preactivation, self).__init__() # residual path self.bn1 = nn.BatchNorm2d(inplanes) self.relu1 = nn.ReLU(inplace=True)", "self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 =", "_make_encoding_layer(self, inplanes, planes, stride=2): return DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def _make_decoding_layer(self, inplanes, skipplanes, deconvplanes, resnetplanes ):", "in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m,nn.ConvTranspose2d): n = m.kernel_size[0] * m.kernel_size[1] *", "def forward(self, x): out = self.conv1(x) out = self.bn1(out) out = self.relu1(out) out", "128->64 self.flow_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 #self.flow_dec_layer1 =", "self.shortcut(x) class DoubleResNet(nn.Module): def __init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__() self.res1 = Block(inplanes,planes,stride) self.res2 = Block( planes,planes,", "32->16 self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.num_final_flow_features ) # 32->200 # decoding", "kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)", "self.inplanes*4 ) # 128->64 self.flow_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) #", "self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.visi_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2", "out += outbp else: out += x out = self.relu(out) return out class", "self.num_final_flow_features, 1, kernel_size=1, stride=1, padding=0, bias=True ) # 1x1 conv for mathability if", "if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer3(x,x2) if self._showsizes: print", "isinstance(m,nn.ConvTranspose2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif", "print \"after decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer4(x,x3) if self._showsizes:", "if self._showsizes: print \"after decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer4(x,x3)", "= self.flow_conv( flowout ) if self.use_visi: visi_predict = self.visi_conv( visiout ) visi_predict =", "padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes, kernel_size=1, bias=False) self.bn3 =", "1 ) out = self.res(out) return out class LArFlowUResNet(nn.Module): def __init__(self, num_classes=3, input_channels=3,", "self.inplanes ) # 32->16 self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.num_final_flow_features ) #", "ConvTransposeLayer( inplanes, skipplanes, deconvplanes, resnetplanes ) def encode(self,x): # stem x = self.conv1(x)", "t3, t4 = self.encode(target) merged_encode = torch.cat( [target_encode,src_encode], 1 ) flowout = self.flow(", "nn.ConvTranspose2d( deconv_inplanes, deconv_outplanes, kernel_size=4, stride=2, padding=1, bias=False ) self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x):", "self.relu1 = nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.relu2", "self.visi_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.visi_dec_layer3 = self._make_decoding_layer(", "self.inplanes*2, self.inplanes*2 ) # 64->32 self.visi_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.inplanes )", "self.bypass = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, padding=0, bias=False) self.relu = nn.ReLU(inplace=True) def forward(self,", "dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\"", "prediction \"\"\" x = self.visi_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print \" dec5:", "\" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\"", "self.inplanes self.flow_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.flow_dec_layer4 =", "def _make_decoding_layer(self, inplanes, skipplanes, deconvplanes, resnetplanes ): return ConvTransposeLayer( inplanes, skipplanes, deconvplanes, resnetplanes", "x): if self.shortcut is None: bypass = x else: bypass = self.shortcut(x) residual", "# print size at each layer self.use_visi = use_visi # Encoder # stem", "self.use_visi: visiout = self.visibility( merged_encode, t0, t1, t2, t3, t4 ) flow_predict =", "= self.conv3(residual) residual = self.bn3(residual) out = bypass+residual out = self.relu(out) return out", "self.inplanes*16 ) # 512->256 self.flow_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) #", "stride=1): \"\"\"3x3 convolution with padding\"\"\" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1, bias=False) class BasicBlock(nn.Module):", "self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer2(x,x1) if self._showsizes: print \"", "1x1 conv for mathability if self.use_visi: self.visi_conv = nn.Conv2d( self.inplanes, 2, kernel_size=1, stride=1,", "self.res2 = Block( planes,planes, 1) def forward(self, x): out = self.res1(x) out =", "self.use_visi: self.visi_conv = nn.Conv2d( self.inplanes, 2, kernel_size=1, stride=1, padding=0, bias=True ) # 2", "forward(self, src, target): if self._showsizes: print \"input: \",x.size(),\" is_cuda=\",x.is_cuda src_encode, s0, s1, s2,", "t3, t4 ) flow_predict = self.flow_conv( flowout ) if self.use_visi: visi_predict = self.visi_conv(", "s0, s1, s2, s3, s4 ) if self.use_visi: visiout = self.visibility( merged_encode, t0,", "x5: \",x5.size() return x5,x0,x1,x2,x3,x4 def flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\" x", "* m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_encoding_layer(self,", "self._make_encoding_layer( self.inplanes*8, self.inplanes*16, stride=2) # 128->256 self.enc_layer5 = self._make_encoding_layer( self.inplanes*16, self.inplanes*32, stride=2) #", "= nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes,", "self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 #self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes,", "self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 self.visi_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes,", "bias=False) self.relu = nn.ReLU(inplace=True) def forward(self, x): out = self.conv1(x) out = self.bn1(out)", "(cite) # # meant to be copy of caffe version # ########################################################### def", "= nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, padding=0, bias=False) self.relu = nn.ReLU(inplace=True) def forward(self, x):", "nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) # if stride >1, then we need", "self.flow_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 #self.flow_dec_layer1 = self._make_decoding_layer(", ") # 64->32 #self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes ) # 32->16 self.flow_dec_layer1", "iscuda=\",x.is_cuda x = self.flow_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x", "convolution with padding\"\"\" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1, bias=False) class BasicBlock(nn.Module): expansion =", "stride=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu1 =", "one big stem self.conv1 = nn.Conv2d(input_channels, self.inplanes, kernel_size=7, stride=1, padding=3, bias=True) # initial", "512->256 self.flow_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.flow_dec_layer3 =", "# U-ResNet # U-net witih ResNet modules # # Semantic segmentation network used", "= conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu1 = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes,", "x): out = self.conv1(x) out = self.bn1(out) out = self.relu1(out) out = self.conv2(out)", "conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.stride = stride self.bypass = None if inplanes!=planes", "LArFlowUResNet(nn.Module): def __init__(self, num_classes=3, input_channels=3, inplanes=16, showsizes=False, use_visi=True): self.inplanes =inplanes super(LArFlowUResNet, self).__init__() self._showsizes", "self).__init__() self._showsizes = showsizes # print size at each layer self.use_visi = use_visi", "super(DoubleResNet,self).__init__() self.res1 = Block(inplanes,planes,stride) self.res2 = Block( planes,planes, 1) def forward(self, x): out", "out = self.relu(out) return out class PreactivationBlock(nn.Module): def __init__(self, inplanes, planes, stride=1 ):", "def _make_encoding_layer(self, inplanes, planes, stride=2): return DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def _make_decoding_layer(self, inplanes, skipplanes, deconvplanes, resnetplanes", ") # 32->16 self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.num_final_flow_features ) # 32->200", "self.flow_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer1(x,x0) if self._showsizes:", "# residual path self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2", "self.bn1 = nn.BatchNorm2d(planes) self.relu1 = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes)", "dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda", "segmentation network used by MicroBooNE # to label track/shower pixels # # resnet", "= self.bn1(out) out = self.relu1(out) out = self.conv2(out) out = self.bn2(out) if self.bypass", "kernel_size=3, stride=stride, padding=1, bias=False) # if stride >1, then we need to subsamble", "x4 = self.enc_layer4(x3) x5 = self.enc_layer5(x4) if self._showsizes: print \"after encoding: \" print", "stride>1: self.bypass = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, padding=0, bias=False) self.relu = nn.ReLU(inplace=True) def", "version # ########################################################### def conv3x3(in_planes, out_planes, stride=1): \"\"\"3x3 convolution with padding\"\"\" return nn.Conv2d(in_planes,", "self._make_encoding_layer( self.inplanes*16, self.inplanes*32, stride=2) # 256->512 # decoding flow #self.num_final_flow_features = self.inplanes self.num_final_flow_features", "= self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.flow_dec_layer4 = self._make_decoding_layer( self.inplanes*16,", "2 classes, 0=not vis, 1=vis self.visi_softmax = nn.LogSoftmax(dim=1) # initialization for m in", "model_zoo ########################################################### # # U-ResNet # U-net witih ResNet modules # # Semantic", "None def forward(self, x): if self.shortcut is None: bypass = x else: bypass", "if isinstance(m, nn.Conv2d) or isinstance(m,nn.ConvTranspose2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0,", "self.flow_conv = nn.Conv2d( self.num_final_flow_features, 1, kernel_size=1, stride=1, padding=0, bias=True ) # 1x1 conv", "self.visi_softmax = nn.LogSoftmax(dim=1) # initialization for m in self.modules(): if isinstance(m, nn.Conv2d) or", "\",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x", "s4 = self.encode(src) target_encode, t0, t1, t2, t3, t4 = self.encode(target) merged_encode =", "self.enc_layer1(x) x2 = self.enc_layer2(x1) x3 = self.enc_layer3(x2) x4 = self.enc_layer4(x3) x5 = self.enc_layer5(x4)", "print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer1(x,x0) if self._showsizes: print \" dec1:", "x = self.flow_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer2(x,x1)", "need to subsamble the input if stride>1: self.shortcut = nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else: self.shortcut =", "is None: bypass = x else: bypass = self.shortcut(x) residual = self.conv1(x) residual", "return x def forward(self, src, target): if self._showsizes: print \"input: \",x.size(),\" is_cuda=\",x.is_cuda src_encode,", "return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1 def __init__(self,", "merged_encode, t0, t1, t2, t3, t4 ) flow_predict = self.flow_conv( flowout ) if", "= self.pool1(x0) x1 = self.enc_layer1(x) x2 = self.enc_layer2(x1) x3 = self.enc_layer3(x2) x4 =", "torch.cat( [target_encode,src_encode], 1 ) flowout = self.flow( merged_encode, s0, s1, s2, s3, s4", "\"after decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer4(x,x3) if self._showsizes: print", "= self.inplanes self.num_final_flow_features = self.inplanes self.flow_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 )", "x2: \",x2.size() print \" x3: \",x3.size() print \" x4: \",x4.size() print \" x5:", "MicroBooNE # to label track/shower pixels # # resnet implementation from pytorch.torchvision module", "residual = self.bn2(residual) residual = self.relu(residual) residual = self.conv3(residual) residual = self.bn3(residual) out", "print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def forward(self, src, target): if self._showsizes:", "deconv_inplanes, deconv_outplanes, kernel_size=4, stride=2, padding=1, bias=False ) self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x): out", "self.relu(out) return out class Bottleneck(nn.Module): def __init__(self, inplanes, planes, stride=1 ): super(Bottleneck, self).__init__()", "self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.num_final_flow_features ) # 32->200 # decoding matchability if self.use_visi:", "forward(self, x): if self.shortcut is None: bypass = x else: bypass = self.shortcut(x)", "= self.bn2(residual) residual = self.relu(residual) residual = self.conv3(residual) residual = self.bn3(residual) out =", "bypass = x else: bypass = self.shortcut(x) residual = self.conv1(x) residual = self.bn1(residual)", "layer self.use_visi = use_visi # Encoder # stem # one big stem self.conv1", "# stem x = self.conv1(x) x = self.bn1(x) x0 = self.relu1(x) x =", "planes) self.bn2 = nn.BatchNorm2d(planes) self.stride = stride self.bypass = None if inplanes!=planes or", "out class LArFlowUResNet(nn.Module): def __init__(self, num_classes=3, input_channels=3, inplanes=16, showsizes=False, use_visi=True): self.inplanes =inplanes super(LArFlowUResNet,", "or stride>1: self.bypass = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, padding=0, bias=False) self.relu = nn.ReLU(inplace=True)", "visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\" x = self.visi_dec_layer5(merged_encode,x4) if self._showsizes: print", ") flowout = self.flow( merged_encode, s0, s1, s2, s3, s4 ) if self.use_visi:", "= self.flow( merged_encode, s0, s1, s2, s3, s4 ) if self.use_visi: visiout =", "########################################################### def conv3x3(in_planes, out_planes, stride=1): \"\"\"3x3 convolution with padding\"\"\" return nn.Conv2d(in_planes, out_planes, kernel_size=3,", ") # 512->256 self.flow_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128", "self.inplanes*2, self.inplanes*4, stride=2) # 32->64 self.enc_layer3 = self._make_encoding_layer( self.inplanes*4, self.inplanes*8, stride=2) # 64->128", "x else: bypass = self.shortcut(x) class DoubleResNet(nn.Module): def __init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__() self.res1 = Block(inplanes,planes,stride)", "# meant to be copy of caffe version # ########################################################### def conv3x3(in_planes, out_planes,", "m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1)", "self.encode(target) merged_encode = torch.cat( [target_encode,src_encode], 1 ) flowout = self.flow( merged_encode, s0, s1,", "self.inplanes =inplanes super(LArFlowUResNet, self).__init__() self._showsizes = showsizes # print size at each layer", "\",x4.size() print \" x5: \",x5.size() return x5,x0,x1,x2,x3,x4 def flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow", "t0, t1, t2, t3, t4 ) flow_predict = self.flow_conv( flowout ) if self.use_visi:", "witih ResNet modules # # Semantic segmentation network used by MicroBooNE # to", "m.weight.data.fill_(1) m.bias.data.zero_() def _make_encoding_layer(self, inplanes, planes, stride=2): return DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def _make_decoding_layer(self, inplanes, skipplanes,", "\",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return", "def __init__(self, inplanes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1", "\",x.size(),\" iscuda=\",x.is_cuda return x def forward(self, src, target): if self._showsizes: print \"input: \",x.size(),\"", "self.visi_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.visi_dec_layer2 = self._make_decoding_layer(", "m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def", "torch.cat( [out,skip_x], 1 ) out = self.res(out) return out class LArFlowUResNet(nn.Module): def __init__(self,", "\" x1: \",x1.size() print \" x2: \",x2.size() print \" x3: \",x3.size() print \"", "= self.flow_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer2(x,x1) if", "or isinstance(m,nn.ConvTranspose2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n))", "self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer3(x,x2) if self._showsizes: print \"", "nn.ReLU(inplace=True) self.pool1 = nn.MaxPool2d( 3, stride=2, padding=1 ) self.enc_layer1 = self._make_encoding_layer( self.inplanes*1, self.inplanes*2,", "2, kernel_size=1, stride=1, padding=0, bias=True ) # 2 classes, 0=not vis, 1=vis self.visi_softmax", "x def visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\" x = self.visi_dec_layer5(merged_encode,x4) if", "= nn.BatchNorm2d(inplanes) self.relu1 = nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, bias=False) self.bn2 =", "use_visi=True): self.inplanes =inplanes super(LArFlowUResNet, self).__init__() self._showsizes = showsizes # print size at each", "super(Bottleneck, self).__init__() # residual path self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 =", "num_classes=3, input_channels=3, inplanes=16, showsizes=False, use_visi=True): self.inplanes =inplanes super(LArFlowUResNet, self).__init__() self._showsizes = showsizes #", "= self.visi_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer1(x,x0) if", "matchability if self.use_visi: self.visi_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256", "= DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x): out = self.deconv(x,output_size=skip_x.size()) # concat skip connections out =", "= self.flow_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer3(x,x2) if", "= self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.visi_dec_layer4 = self._make_decoding_layer( self.inplanes*16,", "# stem # one big stem self.conv1 = nn.Conv2d(input_channels, self.inplanes, kernel_size=7, stride=1, padding=3,", "nn.Conv2d( self.num_final_flow_features, 1, kernel_size=1, stride=1, padding=0, bias=True ) # 1x1 conv for mathability", "# 256->512 # decoding flow #self.num_final_flow_features = self.inplanes self.num_final_flow_features = self.inplanes self.flow_dec_layer5 =", "= self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.flow_dec_layer2 = self._make_decoding_layer( self.inplanes*4,", "iscuda=\",x.is_cuda x = self.visi_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x =", "visi_predict = self.visi_conv( visiout ) visi_predict = self.visi_softmax(visi_predict) else: visi_predict = None if", "at each layer self.use_visi = use_visi # Encoder # stem # one big", "\"\"\" decoding to flow prediction \"\"\" x = self.flow_dec_layer5(merged_encode,x4) if self._showsizes: print \"after", "self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 =", "if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer2(x,x1) if self._showsizes: print", "self.conv1(x) out = self.bn1(out) out = self.relu1(out) out = self.conv2(out) out = self.bn2(out)", "print size at each layer self.use_visi = use_visi # Encoder # stem #", "self.conv3(residual) residual = self.bn3(residual) out = bypass+residual out = self.relu(out) return out class", "self.flow_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x =", "t1, t2, t3, t4 ) flow_predict = self.flow_conv( flowout ) if self.use_visi: visi_predict", "= self.bn1(residual) residual = self.relu(residual) residual = self.conv2(residual) residual = self.bn2(residual) residual =", "flow prediction \"\"\" x = self.visi_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print \"", "= self.visi_conv( visiout ) visi_predict = self.visi_softmax(visi_predict) else: visi_predict = None if self._showsizes:", "return x def visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\" x = self.visi_dec_layer5(merged_encode,x4)", "\" x5: \",x5.size() return x5,x0,x1,x2,x3,x4 def flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\"", "conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu1 = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes)", "residual = self.bn3(residual) out = bypass+residual out = self.relu(out) return out class PreactivationBlock(nn.Module):", "nn.Conv2d(inplanes, planes, kernel_size=3, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.relu2 = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(planes,", "out = self.res(out) return out class LArFlowUResNet(nn.Module): def __init__(self, num_classes=3, input_channels=3, inplanes=16, showsizes=False,", "= self.encode(target) merged_encode = torch.cat( [target_encode,src_encode], 1 ) flowout = self.flow( merged_encode, s0,", "= torch.cat( [out,skip_x], 1 ) out = self.res(out) return out class LArFlowUResNet(nn.Module): def", "0=not vis, 1=vis self.visi_softmax = nn.LogSoftmax(dim=1) # initialization for m in self.modules(): if", "__init__(self, num_classes=3, input_channels=3, inplanes=16, showsizes=False, use_visi=True): self.inplanes =inplanes super(LArFlowUResNet, self).__init__() self._showsizes = showsizes", "use_visi # Encoder # stem # one big stem self.conv1 = nn.Conv2d(input_channels, self.inplanes,", "decoding flow #self.num_final_flow_features = self.inplanes self.num_final_flow_features = self.inplanes self.flow_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16,", "self.inplanes*16 ) # 512->256 self.visi_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) #", "self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m,nn.ConvTranspose2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels", "x = self.flow_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def", "self.res1 = Block(inplanes,planes,stride) self.res2 = Block( planes,planes, 1) def forward(self, x): out =", "self.relu1(x) x = self.pool1(x0) x1 = self.enc_layer1(x) x2 = self.enc_layer2(x1) x3 = self.enc_layer3(x2)", "print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer3(x,x2) if self._showsizes: print \" dec3:", "is_cuda=\",x.is_cuda src_encode, s0, s1, s2, s3, s4 = self.encode(src) target_encode, t0, t1, t2,", "self.flow( merged_encode, s0, s1, s2, s3, s4 ) if self.use_visi: visiout = self.visibility(", "self.bn1 = nn.BatchNorm2d(inplanes) self.relu1 = nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, bias=False) self.bn2", "self.visi_softmax(visi_predict) else: visi_predict = None if self._showsizes: print \" softmax: \",x.size() return flow_predict,visi_predict", "= self.relu1(x) x = self.pool1(x0) x1 = self.enc_layer1(x) x2 = self.enc_layer2(x1) x3 =", "BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 =", "self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.flow_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2,", ") # 32->200 # decoding matchability if self.use_visi: self.visi_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16,", "print \" x4: \",x4.size() print \" x5: \",x5.size() return x5,x0,x1,x2,x3,x4 def flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\"", "self.conv1 = nn.Conv2d(input_channels, self.inplanes, kernel_size=7, stride=1, padding=3, bias=True) # initial conv layer self.bn1", "conv3x3(in_planes, out_planes, stride=1): \"\"\"3x3 convolution with padding\"\"\" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1, bias=False)", "# 512->256 self.visi_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.visi_dec_layer3", "= self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 self.visi_dec_layer1 = self._make_decoding_layer( self.inplanes*2,", "self.inplanes*4, self.inplanes*8, stride=2) # 64->128 self.enc_layer4 = self._make_encoding_layer( self.inplanes*8, self.inplanes*16, stride=2) # 128->256", "dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda", "visi_predict = self.visi_softmax(visi_predict) else: visi_predict = None if self._showsizes: print \" softmax: \",x.size()", "# # resnet implementation from pytorch.torchvision module # U-net from (cite) # #", "# Encoder # stem # one big stem self.conv1 = nn.Conv2d(input_channels, self.inplanes, kernel_size=7,", ") # 128->64 self.flow_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32", "\" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\"", "x4: \",x4.size() print \" x5: \",x5.size() return x5,x0,x1,x2,x3,x4 def flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to", "track/shower pixels # # resnet implementation from pytorch.torchvision module # U-net from (cite)", "None: outbp = self.bypass(x) out += outbp else: out += x out =", "= self.relu1(out) out = self.conv2(out) out = self.bn2(out) if self.bypass is not None:", "meant to be copy of caffe version # ########################################################### def conv3x3(in_planes, out_planes, stride=1):", "nn.BatchNorm2d(inplanes) self.relu1 = nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, bias=False) self.bn2 = nn.BatchNorm2d(planes)", "= nn.MaxPool2d( 3, stride=2, padding=1 ) self.enc_layer1 = self._make_encoding_layer( self.inplanes*1, self.inplanes*2, stride=1) #", "self.enc_layer2 = self._make_encoding_layer( self.inplanes*2, self.inplanes*4, stride=2) # 32->64 self.enc_layer3 = self._make_encoding_layer( self.inplanes*4, self.inplanes*8,", "U-net witih ResNet modules # # Semantic segmentation network used by MicroBooNE #", "# 32->16 self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.num_final_flow_features ) # 32->200 #", ") # 128->64 self.visi_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32", "class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1", ") # 256->128 self.flow_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64", "self.flow_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.flow_dec_layer2 = self._make_decoding_layer(", "self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def forward(self, src, target): if", "self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer3(x,x2) if self._showsizes: print \"", "inplanes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes)", "self.inplanes*8 ) # 256->128 self.flow_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) #", "residual = self.conv2(residual) residual = self.bn2(residual) residual = self.relu(residual) residual = self.conv3(residual) residual", "def forward(self, src, target): if self._showsizes: print \"input: \",x.size(),\" is_cuda=\",x.is_cuda src_encode, s0, s1,", "flow #self.num_final_flow_features = self.inplanes self.num_final_flow_features = self.inplanes self.flow_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16,", "# 512->256 self.flow_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.flow_dec_layer3", "1) def forward(self, x): out = self.res1(x) out = self.res2(out) return out class", "\"after encoding: \" print \" x1: \",x1.size() print \" x2: \",x2.size() print \"", "x3 = self.enc_layer3(x2) x4 = self.enc_layer4(x3) x5 = self.enc_layer5(x4) if self._showsizes: print \"after" ]
[ "in range(len(examples))] questions = [examples[i]['question'] for i in range(len(examples))] tokenized_examples = tokenizer( questions,", "import paddle from paddle.io import DataLoader from args import parse_args import paddlenlp as", "Stack(dtype=\"int64\") }): fn(samples) train_data_loader = DataLoader( dataset=train_ds, batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn, return_list=True) num_training_steps = args.max_steps", "KIND, either express or implied. # See the License for the specific language", "the overflows using a stride. This results # in one example possible giving", "Unless required by applicable law or agreed to in writing, software # distributed", "sequence_ids[k] == 1 else None) for k, o in enumerate(tokenized_example[\"offset_mapping\"]) ] return tokenized_examples", "paddlenlp as ppnlp from paddlenlp.data import Pad, Stack, Tuple, Dict from paddlenlp.transformers import", "The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0", "time.time() - tic_eval) tic_eval = time.time() all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions, _, _ = compute_prediction(", "= args.max_steps if args.max_steps > 0 else len( train_data_loader) * args.num_train_epochs num_train_epochs =", "len(all_start_logits): print(\"Processing example: %d\" % len(all_start_logits)) print('time per 1000:', time.time() - tic_eval) tic_eval", "tic_train))) tic_train = time.time() loss.backward() optimizer.step() lr_scheduler.step() optimizer.clear_grad() if global_step % args.save_steps ==", "while offsets[token_end_index][1] >= end_char: token_end_index -= 1 tokenized_examples[i][\"end_positions\"] = token_end_index + 1 return", "tic_eval = time.time() all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions, _, _ = compute_prediction( data_loader.dataset.data, data_loader.dataset.new_data, (all_start_logits,", "in the text. token_start_index = 0 while sequence_ids[token_start_index] != 1: token_start_index += 1", "loss: %f, speed: %.2f step/s\" % (global_step, epoch + 1, step + 1,", "Note: we could go after the last offset if the answer is the", "ErnieGramForQuestionAnswering, ErnieGramTokenizer from paddlenlp.transformers import RobertaForQuestionAnswering, RobertaTokenizer from paddlenlp.transformers import LinearDecayWithWarmup from paddlenlp.metrics.squad", "Stack(dtype=\"int64\"), \"end_positions\": Stack(dtype=\"int64\") }): fn(samples) train_data_loader = DataLoader( dataset=train_ds, batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn, return_list=True) num_training_steps", "context so it's easy to determine if a token # position is part", "positions for i, tokenized_example in enumerate(tokenized_examples): # Grab the sequence corresponding to that", "= paddle.DataParallel(model) def prepare_train_features(examples): # Tokenize our examples with truncation and maybe padding,", "start_logits_tensor, end_logits_tensor = model(input_ids, token_type_ids) for idx in range(start_logits_tensor.shape[0]): if len(all_start_logits) % 1000", "dev_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id) }): fn(samples)", "label impossible answers with the index of the CLS token. input_ids = tokenized_example[\"input_ids\"]", "the current span in the text. token_end_index = len(input_ids) - 1 while sequence_ids[token_end_index]", "move the token_start_index and token_end_index to the two ends of the answer. #", "the answer is out of the span (in which case this feature is", "bias and LayerNorm parameters are excluded. decay_params = [ p.name for n, p", "results # in one example possible giving several features when a context is", "json import math from functools import partial import numpy as np import paddle", "len(answers[0]) # Start token index of the current span in the text. token_start_index", "-= 1 # Detect if the answer is out of the span (in", "answer is out of the span (in which case this feature is labeled", "- tic_train))) tic_train = time.time() loss.backward() optimizer.step() lr_scheduler.step() optimizer.clear_grad() if global_step % args.save_steps", "args.learning_rate, num_training_steps, args.warmup_proportion) # Generate parameter names needed to perform weight decay. #", "the offset_mapping that are not part of the context so it's easy to", "this file except in compliance with the License. # You may obtain a", "n, p in model.named_parameters() if not any(nd in n for nd in [\"bias\",", "if paddle.distributed.get_world_size() > 1: model = paddle.DataParallel(model) def prepare_train_features(examples): # Tokenize our examples", "no need to compute start and end positions for i, tokenized_example in enumerate(tokenized_examples):", "self).__init__() def forward(self, y, label): start_logits, end_logits = y start_position, end_position = label", "of the example containing this span of text. sample_index = tokenized_example['overflow_to_sample'] answers =", "for i in range(len(examples))] tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # Let's", "examples with truncation and maybe padding, but keep the overflows using a stride.", "writer: writer.write( json.dumps( all_predictions, ensure_ascii=False, indent=4) + \"\\n\") squad_evaluate( examples=data_loader.dataset.data, preds=all_predictions, is_whitespace_splited=False) model.train()", "feature is labeled with the CLS index). if not (offsets[token_start_index][0] <= start_char and", "from paddlenlp.metrics.squad import squad_evaluate, compute_prediction from paddlenlp.datasets import load_dataset MODEL_CLASSES = { \"bert\":", "criterion(logits, (start_positions, end_positions)) if global_step % args.logging_steps == 0: print( \"global step %d,", "there is no need to compute start and end positions for i, tokenized_example", "batched=True) dev_batch_sampler = paddle.io.BatchSampler( dev_ds, batch_size=args.batch_size, shuffle=False) dev_batchify_fn = lambda samples, fn=Dict({ \"input_ids\":", "paddlenlp.transformers import LinearDecayWithWarmup from paddlenlp.metrics.squad import squad_evaluate, compute_prediction from paddlenlp.datasets import load_dataset MODEL_CLASSES", "task_name = args.task_name.lower() args.model_type = args.model_type.lower() model_class, tokenizer_class = MODEL_CLASSES[args.model_type] tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path)", "those examples! for i, tokenized_example in enumerate(tokenized_examples): # We will label impossible answers", "or global_step == num_training_steps: if rank == 0: output_dir = os.path.join(args.output_dir, \"model_%d\" %", "token_end_index + 1 return tokenized_examples if args.do_train: if args.train_file: train_ds = load_dataset(task_name, data_files=args.train_file)", "ANY KIND, either express or implied. # See the License for the specific", "need better way to get inner model of DataParallel model_to_save = model._layers if", "is_whitespace_splited=False) model.train() class CrossEntropyLossForSQuAD(paddle.nn.Layer): def __init__(self): super(CrossEntropyLossForSQuAD, self).__init__() def forward(self, y, label): start_logits,", "import json import math from functools import partial import numpy as np import", "basic data structure, while we use list of dictionary instead. contexts = [examples[i]['context']", "with truncation and maybe padding, but keep the overflows using a stride. This", "contexts = [examples[i]['context'] for i in range(len(examples))] questions = [examples[i]['question'] for i in", "i in range(len(examples))] questions = [examples[i]['question'] for i in range(len(examples))] tokenized_examples = tokenizer(", "will label impossible answers with the index of the CLS token. input_ids =", "are not part of the context so it's easy to determine if a", "License. import os import random import time import json import math from functools", "num_training_steps: if rank == 0: output_dir = os.path.join(args.output_dir, \"model_%d\" % global_step) if not", "write all_nbest_json and scores_diff_json files if needed with open('prediction.json', \"w\", encoding='utf-8') as writer:", "# Copyright 2018 The HuggingFace Inc. team. # # Licensed under the Apache", "several features when a context is long, each of those features having a", "enumerate(train_data_loader): global_step += 1 input_ids, token_type_ids, start_positions, end_positions = batch logits = model(", "train_ds = load_dataset(task_name, splits='train') train_ds.map(prepare_train_features, batched=True) train_batch_sampler = paddle.io.DistributedBatchSampler( train_ds, batch_size=args.batch_size, shuffle=True) train_batchify_fn", "= paddle.unsqueeze(start_position, axis=-1) end_position = paddle.unsqueeze(end_position, axis=-1) start_loss = paddle.nn.functional.cross_entropy( input=start_logits, label=start_position) end_loss", "_ = compute_prediction( data_loader.dataset.data, data_loader.dataset.new_data, (all_start_logits, all_end_logits), False, args.n_best_size, args.max_answer_length) # Can also", "for i, tokenized_example in enumerate(tokenized_examples): # Grab the sequence corresponding to that example", "truncation and maybe padding, but keep the overflows using a stride. This results", "class CrossEntropyLossForSQuAD(paddle.nn.Layer): def __init__(self): super(CrossEntropyLossForSQuAD, self).__init__() def forward(self, y, label): start_logits, end_logits =", "text. token_end_index = len(input_ids) - 1 while sequence_ids[token_end_index] != 1: token_end_index -= 1", "rank == 0: output_dir = os.path.join(args.output_dir, \"model_%d\" % global_step) if not os.path.exists(output_dir): os.makedirs(output_dir)", "of the answer. # Note: we could go after the last offset if", "index of the current span in the text. token_end_index = len(input_ids) - 1", "else len( train_data_loader) * args.num_train_epochs num_train_epochs = math.ceil(num_training_steps / len(train_data_loader)) lr_scheduler = LinearDecayWithWarmup(", "/ len(train_data_loader)) lr_scheduler = LinearDecayWithWarmup( args.learning_rate, num_training_steps, args.warmup_proportion) # Generate parameter names needed", "tokenized_examples[i][\"offset_mapping\"] = [ (o if sequence_ids[k] == 1 else None) for k, o", "if rank == 0: output_dir = os.path.join(args.output_dir, \"model_%d\" % global_step) if not os.path.exists(output_dir):", "all_predictions, ensure_ascii=False, indent=4) + \"\\n\") squad_evaluate( examples=data_loader.dataset.data, preds=all_predictions, is_whitespace_splited=False) model.train() class CrossEntropyLossForSQuAD(paddle.nn.Layer): def", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # For validation, there is no need to", "def forward(self, y, label): start_logits, end_logits = y start_position, end_position = label start_position", "for k, o in enumerate(tokenized_example[\"offset_mapping\"]) ] return tokenized_examples if args.do_predict and rank ==", "<= start_char: token_start_index += 1 tokenized_examples[i][\"start_positions\"] = token_start_index - 1 while offsets[token_end_index][1] >=", "if global_step == num_training_steps: break def prepare_validation_features(examples): # Tokenize our examples with truncation", "global_step) if not os.path.exists(output_dir): os.makedirs(output_dir) # need better way to get inner model", "sample_index = tokenized_example['overflow_to_sample'] answers = examples[sample_index]['answers'] answer_starts = examples[sample_index]['answer_starts'] # Start/end character index", "and rank == 0: if args.predict_file: dev_ds = load_dataset(task_name, data_files=args.predict_file) else: dev_ds =", "of text. sample_index = tokenized_example['overflow_to_sample'] answers = examples[sample_index]['answers'] answer_starts = examples[sample_index]['answer_starts'] # Start/end", "if not os.path.exists(output_dir): os.makedirs(output_dir) # need better way to get inner model of", "DataLoader( dataset=train_ds, batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn, return_list=True) num_training_steps = args.max_steps if args.max_steps > 0 else", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "run(args): paddle.set_device(args.device) if paddle.distributed.get_world_size() > 1: paddle.distributed.init_parallel_env() rank = paddle.distributed.get_rank() task_name = args.task_name.lower()", "n for nd in [\"bias\", \"norm\"]) ] optimizer = paddle.optimizer.AdamW( learning_rate=lr_scheduler, epsilon=args.adam_epsilon, parameters=model.parameters(),", "contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # Let's label those examples! for i, tokenized_example in enumerate(tokenized_examples):", "start_char + len(answers[0]) # Start token index of the current span in the", "= label start_position = paddle.unsqueeze(start_position, axis=-1) end_position = paddle.unsqueeze(end_position, axis=-1) start_loss = paddle.nn.functional.cross_entropy(", "the last word (edge case). while token_start_index < len(offsets) and offsets[ token_start_index][0] <=", "# context that overlaps a bit the context of the previous feature. #", "# Start token index of the current span in the text. token_start_index =", "batch: %d, loss: %f, speed: %.2f step/s\" % (global_step, epoch + 1, step", "RobertaTokenizer from paddlenlp.transformers import LinearDecayWithWarmup from paddlenlp.metrics.squad import squad_evaluate, compute_prediction from paddlenlp.datasets import", "containing this span of text. sample_index = tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"] = examples[sample_index]['id'] # Set", "train_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id), \"start_positions\": Stack(dtype=\"int64\"),", "import ErnieForQuestionAnswering, ErnieTokenizer from paddlenlp.transformers import ErnieGramForQuestionAnswering, ErnieGramTokenizer from paddlenlp.transformers import RobertaForQuestionAnswering, RobertaTokenizer", "shuffle=False) dev_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id) }):", "OF ANY KIND, either express or implied. # See the License for the", "paddlenlp.data import Pad, Stack, Tuple, Dict from paddlenlp.transformers import BertForQuestionAnswering, BertTokenizer from paddlenlp.transformers", "random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed) @paddle.no_grad() def evaluate(model, data_loader, args): model.eval() all_start_logits = [] all_end_logits", "len( train_data_loader) * args.num_train_epochs num_train_epochs = math.ceil(num_training_steps / len(train_data_loader)) lr_scheduler = LinearDecayWithWarmup( args.learning_rate,", "the example containing this span of text. sample_index = tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"] = examples[sample_index]['id']", "is the last word (edge case). while token_start_index < len(offsets) and offsets[ token_start_index][0]", "not (offsets[token_start_index][0] <= start_char and offsets[token_end_index][1] >= end_char): tokenized_examples[i][\"start_positions\"] = cls_index tokenized_examples[i][\"end_positions\"] =", "main difference is # that HugggingFace uses ArrowTable as basic data structure, while", "of text. sample_index = tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"] = examples[sample_index]['id'] # Set to None the", "us compute the start_positions and end_positions. offsets = tokenized_example['offset_mapping'] # Grab the sequence", "ErnieForQuestionAnswering, ErnieTokenizer from paddlenlp.transformers import ErnieGramForQuestionAnswering, ErnieGramTokenizer from paddlenlp.transformers import RobertaForQuestionAnswering, RobertaTokenizer from", "context is long, each of those features having a # context that overlaps", "\"roberta\": (RobertaForQuestionAnswering, RobertaTokenizer) } def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed) @paddle.no_grad() def evaluate(model, data_loader,", "batched=True) train_batch_sampler = paddle.io.DistributedBatchSampler( train_ds, batch_size=args.batch_size, shuffle=True) train_batchify_fn = lambda samples, fn=Dict({ \"input_ids\":", "to:', output_dir) if global_step == num_training_steps: break def prepare_validation_features(examples): # Tokenize our examples", "Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id) }): fn(samples) dev_data_loader = DataLoader( dataset=dev_ds, batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn,", "of dictionary instead. contexts = [examples[i]['context'] for i in range(len(examples))] questions = [examples[i]['question']", "(global_step, epoch + 1, step + 1, loss, args.logging_steps / (time.time() - tic_train)))", "if os.path.exists(args.model_name_or_path): print(\"init checkpoint from %s\" % args.model_name_or_path) model = model_class.from_pretrained(args.model_name_or_path) if paddle.distributed.get_world_size()", "= model_class.from_pretrained(args.model_name_or_path) if paddle.distributed.get_world_size() > 1: model = paddle.DataParallel(model) def prepare_train_features(examples): # Tokenize", "span in the text. token_end_index = len(input_ids) - 1 while sequence_ids[token_end_index] != 1:", "x: x in decay_params) criterion = CrossEntropyLossForSQuAD() global_step = 0 tic_train = time.time()", "tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args) if rank == 0: if os.path.exists(args.model_name_or_path): print(\"init checkpoint from %s\" %", "- 1 while sequence_ids[token_end_index] != 1: token_end_index -= 1 # Minus one more", "global_step % args.logging_steps == 0: print( \"global step %d, epoch: %d, batch: %d,", "epoch + 1, step + 1, loss, args.logging_steps / (time.time() - tic_train))) tic_train", "keep the overflows using a stride. This results # in one example possible", "\"model_%d\" % global_step) if not os.path.exists(output_dir): os.makedirs(output_dir) # need better way to get", "data structure, while we use list of dictionary instead. contexts = [examples[i]['context'] for", "paddle.io import DataLoader from args import parse_args import paddlenlp as ppnlp from paddlenlp.data", "if rank == 0: if os.path.exists(args.model_name_or_path): print(\"init checkpoint from %s\" % args.model_name_or_path) model", "the context so it's easy to determine if a token # position is", "to the two ends of the answer. # Note: we could go after", "two ends of the answer. # Note: we could go after the last", "if the answer is the last word (edge case). while token_start_index < len(offsets)", "range(len(examples))] tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # Let's label those examples!", "(ErnieGramForQuestionAnswering, ErnieGramTokenizer), \"roberta\": (RobertaForQuestionAnswering, RobertaTokenizer) } def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed) @paddle.no_grad() def", "MODEL_CLASSES = { \"bert\": (BertForQuestionAnswering, BertTokenizer), \"ernie\": (ErnieForQuestionAnswering, ErnieTokenizer), \"ernie_gram\": (ErnieGramForQuestionAnswering, ErnieGramTokenizer), \"roberta\":", "global_step += 1 input_ids, token_type_ids, start_positions, end_positions = batch logits = model( input_ids=input_ids,", "text. sample_index = tokenized_example['overflow_to_sample'] answers = examples[sample_index]['answers'] answer_starts = examples[sample_index]['answer_starts'] # Start/end character", "open('prediction.json', \"w\", encoding='utf-8') as writer: writer.write( json.dumps( all_predictions, ensure_ascii=False, indent=4) + \"\\n\") squad_evaluate(", "original context. This will # help us compute the start_positions and end_positions. offsets", "if len(all_start_logits) % 1000 == 0 and len(all_start_logits): print(\"Processing example: %d\" % len(all_start_logits))", "input_ids.index(tokenizer.cls_token_id) # The offset mappings will give us a map from token to", "- 1 while offsets[token_end_index][1] >= end_char: token_end_index -= 1 tokenized_examples[i][\"end_positions\"] = token_end_index +", "prepare_validation_features(examples): # Tokenize our examples with truncation and maybe padding, but keep the", "instead. contexts = [examples[i]['context'] for i in range(len(examples))] questions = [examples[i]['question'] for i", "tic_eval = time.time() for batch in data_loader: input_ids, token_type_ids = batch start_logits_tensor, end_logits_tensor", "paddlenlp.transformers import RobertaForQuestionAnswering, RobertaTokenizer from paddlenlp.transformers import LinearDecayWithWarmup from paddlenlp.metrics.squad import squad_evaluate, compute_prediction", "all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions, _, _ = compute_prediction( data_loader.dataset.data, data_loader.dataset.new_data, (all_start_logits, all_end_logits), False, args.n_best_size, args.max_answer_length)", "def __init__(self): super(CrossEntropyLossForSQuAD, self).__init__() def forward(self, y, label): start_logits, end_logits = y start_position,", "to reach actual text token_end_index -= 1 # Detect if the answer is", "> 1: paddle.distributed.init_parallel_env() rank = paddle.distributed.get_rank() task_name = args.task_name.lower() args.model_type = args.model_type.lower() model_class,", "+= 1 tokenized_examples[i][\"start_positions\"] = token_start_index - 1 while offsets[token_end_index][1] >= end_char: token_end_index -=", "needed to perform weight decay. # All bias and LayerNorm parameters are excluded.", "0 or global_step == num_training_steps: if rank == 0: output_dir = os.path.join(args.output_dir, \"model_%d\"", "output_dir = os.path.join(args.output_dir, \"model_%d\" % global_step) if not os.path.exists(output_dir): os.makedirs(output_dir) # need better", "token index of the current span in the text. token_start_index = 0 while", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "is out of the span (in which case this feature is labeled with", "== 1 else None) for k, o in enumerate(tokenized_example[\"offset_mapping\"]) ] return tokenized_examples if", "load_dataset MODEL_CLASSES = { \"bert\": (BertForQuestionAnswering, BertTokenizer), \"ernie\": (ErnieForQuestionAnswering, ErnieTokenizer), \"ernie_gram\": (ErnieGramForQuestionAnswering, ErnieGramTokenizer),", "of DataParallel model_to_save = model._layers if isinstance( model, paddle.DataParallel) else model model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir)", "(edge case). while token_start_index < len(offsets) and offsets[ token_start_index][0] <= start_char: token_start_index +=", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "to get inner model of DataParallel model_to_save = model._layers if isinstance( model, paddle.DataParallel)", "paddlenlp.metrics.squad import squad_evaluate, compute_prediction from paddlenlp.datasets import load_dataset MODEL_CLASSES = { \"bert\": (BertForQuestionAnswering,", "this feature is labeled with the CLS index). if not (offsets[token_start_index][0] <= start_char", "enumerate(tokenized_example[\"offset_mapping\"]) ] return tokenized_examples if args.do_predict and rank == 0: if args.predict_file: dev_ds", "args.n_best_size, args.max_answer_length) # Can also write all_nbest_json and scores_diff_json files if needed with", "tic_train = time.time() for epoch in range(num_train_epochs): for step, batch in enumerate(train_data_loader): global_step", "tokenized_example in enumerate(tokenized_examples): # Grab the sequence corresponding to that example (to know", "tokenized_examples if args.do_predict and rank == 0: if args.predict_file: dev_ds = load_dataset(task_name, data_files=args.predict_file)", "under the License. import os import random import time import json import math", "squad_evaluate, compute_prediction from paddlenlp.datasets import load_dataset MODEL_CLASSES = { \"bert\": (BertForQuestionAnswering, BertTokenizer), \"ernie\":", "token_type_ids, start_positions, end_positions = batch logits = model( input_ids=input_ids, token_type_ids=token_type_ids) loss = criterion(logits,", "%d, batch: %d, loss: %f, speed: %.2f step/s\" % (global_step, epoch + 1,", "load_dataset(task_name, splits='dev') dev_ds.map(prepare_validation_features, batched=True) dev_batch_sampler = paddle.io.BatchSampler( dev_ds, batch_size=args.batch_size, shuffle=False) dev_batchify_fn = lambda", "data_loader.dataset.data, data_loader.dataset.new_data, (all_start_logits, all_end_logits), False, args.n_best_size, args.max_answer_length) # Can also write all_nbest_json and", "of the context or not. tokenized_examples[i][\"offset_mapping\"] = [ (o if sequence_ids[k] == 1", "from paddlenlp.transformers import ErnieGramForQuestionAnswering, ErnieGramTokenizer from paddlenlp.transformers import RobertaForQuestionAnswering, RobertaTokenizer from paddlenlp.transformers import", "else: train_ds = load_dataset(task_name, splits='train') train_ds.map(prepare_train_features, batched=True) train_batch_sampler = paddle.io.DistributedBatchSampler( train_ds, batch_size=args.batch_size, shuffle=True)", "# help us compute the start_positions and end_positions. offsets = tokenized_example['offset_mapping'] # Grab", "span in the text. token_start_index = 0 while sequence_ids[token_start_index] != 1: token_start_index +=", "epoch: %d, batch: %d, loss: %f, speed: %.2f step/s\" % (global_step, epoch +", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "== 0 or global_step == num_training_steps: if rank == 0: output_dir = os.path.join(args.output_dir,", "num_training_steps = args.max_steps if args.max_steps > 0 else len( train_data_loader) * args.num_train_epochs num_train_epochs", "= y start_position, end_position = label start_position = paddle.unsqueeze(start_position, axis=-1) end_position = paddle.unsqueeze(end_position,", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "token_end_index = len(input_ids) - 1 while sequence_ids[token_end_index] != 1: token_end_index -= 1 #", "== 0: if args.predict_file: dev_ds = load_dataset(task_name, data_files=args.predict_file) else: dev_ds = load_dataset(task_name, splits='dev')", "in one example possible giving several features when a context is long, each", "the start_positions and end_positions. offsets = tokenized_example['offset_mapping'] # Grab the sequence corresponding to", "# Detect if the answer is out of the span (in which case", "BertForQuestionAnswering, BertTokenizer from paddlenlp.transformers import ErnieForQuestionAnswering, ErnieTokenizer from paddlenlp.transformers import ErnieGramForQuestionAnswering, ErnieGramTokenizer from", "mappings will give us a map from token to character position in the", "num_training_steps: break def prepare_validation_features(examples): # Tokenize our examples with truncation and maybe padding,", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "%.2f step/s\" % (global_step, epoch + 1, step + 1, loss, args.logging_steps /", "of the context so it's easy to determine if a token # position", "range(len(examples))] tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # For validation, there is", "if not (offsets[token_start_index][0] <= start_char and offsets[token_end_index][1] >= end_char): tokenized_examples[i][\"start_positions\"] = cls_index tokenized_examples[i][\"end_positions\"]", "token_start_index = 0 while sequence_ids[token_start_index] != 1: token_start_index += 1 # End token", "long, each of those features having a # context that overlaps a bit", "print('time per 1000:', time.time() - tic_eval) tic_eval = time.time() all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions, _,", "end_position = label start_position = paddle.unsqueeze(start_position, axis=-1) end_position = paddle.unsqueeze(end_position, axis=-1) start_loss =", "the CLS index). if not (offsets[token_start_index][0] <= start_char and offsets[token_end_index][1] >= end_char): tokenized_examples[i][\"start_positions\"]", "required by applicable law or agreed to in writing, software # distributed under", "cls_index = input_ids.index(tokenizer.cls_token_id) # The offset mappings will give us a map from", "batch_size=args.batch_size, shuffle=False) dev_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id)", "applicable law or agreed to in writing, software # distributed under the License", "> 1: model = paddle.DataParallel(model) def prepare_train_features(examples): # Tokenize our examples with truncation", "the index of the example containing this span of text. sample_index = tokenized_example['overflow_to_sample']", "One example can give several spans, this is the index of the example", "args.predict_file: dev_ds = load_dataset(task_name, data_files=args.predict_file) else: dev_ds = load_dataset(task_name, splits='dev') dev_ds.map(prepare_validation_features, batched=True) dev_batch_sampler", "offset mappings will give us a map from token to character position in", "as writer: writer.write( json.dumps( all_predictions, ensure_ascii=False, indent=4) + \"\\n\") squad_evaluate( examples=data_loader.dataset.data, preds=all_predictions, is_whitespace_splited=False)", "the question). sequence_ids = tokenized_example['token_type_ids'] # One example can give several spans, this", "stride=args.doc_stride, max_seq_len=args.max_seq_length) # Let's label those examples! for i, tokenized_example in enumerate(tokenized_examples): #", "1: token_start_index += 1 # End token index of the current span in", "batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn, return_list=True) evaluate(model, dev_data_loader, args) if __name__ == \"__main__\": args = parse_args()", "= compute_prediction( data_loader.dataset.data, data_loader.dataset.new_data, (all_start_logits, all_end_logits), False, args.n_best_size, args.max_answer_length) # Can also write", "answer_starts = examples[sample_index]['answer_starts'] # Start/end character index of the answer in the text.", "are excluded. decay_params = [ p.name for n, p in model.named_parameters() if not", "or agreed to in writing, software # distributed under the License is distributed", "label): start_logits, end_logits = y start_position, end_position = label start_position = paddle.unsqueeze(start_position, axis=-1)", "from paddlenlp.transformers import LinearDecayWithWarmup from paddlenlp.metrics.squad import squad_evaluate, compute_prediction from paddlenlp.datasets import load_dataset", "import LinearDecayWithWarmup from paddlenlp.metrics.squad import squad_evaluate, compute_prediction from paddlenlp.datasets import load_dataset MODEL_CLASSES =", "import squad_evaluate, compute_prediction from paddlenlp.datasets import load_dataset MODEL_CLASSES = { \"bert\": (BertForQuestionAnswering, BertTokenizer),", "after the last offset if the answer is the last word (edge case).", "%d, epoch: %d, batch: %d, loss: %f, speed: %.2f step/s\" % (global_step, epoch", "is labeled with the CLS index). if not (offsets[token_start_index][0] <= start_char and offsets[token_end_index][1]", "sequence_ids[token_end_index] != 1: token_end_index -= 1 # Minus one more to reach actual", "+ 1, step + 1, loss, args.logging_steps / (time.time() - tic_train))) tic_train =", "Minus one more to reach actual text token_end_index -= 1 # Detect if", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "index of the current span in the text. token_start_index = 0 while sequence_ids[token_start_index]", "and offsets[ token_start_index][0] <= start_char: token_start_index += 1 tokenized_examples[i][\"start_positions\"] = token_start_index - 1", "= time.time() for batch in data_loader: input_ids, token_type_ids = batch start_logits_tensor, end_logits_tensor =", "answer_starts[0] end_char = start_char + len(answers[0]) # Start token index of the current", "label=start_position) end_loss = paddle.nn.functional.cross_entropy( input=end_logits, label=end_position) loss = (start_loss + end_loss) / 2", "the index of the CLS token. input_ids = tokenized_example[\"input_ids\"] cls_index = input_ids.index(tokenizer.cls_token_id) #", "for i, tokenized_example in enumerate(tokenized_examples): # We will label impossible answers with the", "tokenized_examples[i][\"start_positions\"] = token_start_index - 1 while offsets[token_end_index][1] >= end_char: token_end_index -= 1 tokenized_examples[i][\"end_positions\"]", "= paddle.nn.functional.cross_entropy( input=start_logits, label=start_position) end_loss = paddle.nn.functional.cross_entropy( input=end_logits, label=end_position) loss = (start_loss +", "span (in which case this feature is labeled with the CLS index). if", "it's easy to determine if a token # position is part of the", "examples! for i, tokenized_example in enumerate(tokenized_examples): # We will label impossible answers with", "tokenized_examples[i][\"example_id\"] = examples[sample_index]['id'] # Set to None the offset_mapping that are not part", "paddle.distributed.get_rank() task_name = args.task_name.lower() args.model_type = args.model_type.lower() model_class, tokenizer_class = MODEL_CLASSES[args.model_type] tokenizer =", "print(\"init checkpoint from %s\" % args.model_name_or_path) model = model_class.from_pretrained(args.model_name_or_path) if paddle.distributed.get_world_size() > 1:", "train_data_loader) * args.num_train_epochs num_train_epochs = math.ceil(num_training_steps / len(train_data_loader)) lr_scheduler = LinearDecayWithWarmup( args.learning_rate, num_training_steps,", "for epoch in range(num_train_epochs): for step, batch in enumerate(train_data_loader): global_step += 1 input_ids,", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "= examples[sample_index]['answer_starts'] # Start/end character index of the answer in the text. start_char", "encoding='utf-8') as writer: writer.write( json.dumps( all_predictions, ensure_ascii=False, indent=4) + \"\\n\") squad_evaluate( examples=data_loader.dataset.data, preds=all_predictions,", "perform weight decay. # All bias and LayerNorm parameters are excluded. decay_params =", "with the CLS index). if not (offsets[token_start_index][0] <= start_char and offsets[token_end_index][1] >= end_char):", "writing, software # distributed under the License is distributed on an \"AS IS\"", "context that overlaps a bit the context of the previous feature. # NOTE:", "in enumerate(train_data_loader): global_step += 1 input_ids, token_type_ids, start_positions, end_positions = batch logits =", "paddle.unsqueeze(start_position, axis=-1) end_position = paddle.unsqueeze(end_position, axis=-1) start_loss = paddle.nn.functional.cross_entropy( input=start_logits, label=start_position) end_loss =", "splits='train') train_ds.map(prepare_train_features, batched=True) train_batch_sampler = paddle.io.DistributedBatchSampler( train_ds, batch_size=args.batch_size, shuffle=True) train_batchify_fn = lambda samples,", "2018 The HuggingFace Inc. team. # # Licensed under the Apache License, Version", "Set to None the offset_mapping that are not part of the context so", "os.path.exists(args.model_name_or_path): print(\"init checkpoint from %s\" % args.model_name_or_path) model = model_class.from_pretrained(args.model_name_or_path) if paddle.distributed.get_world_size() >", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "from args import parse_args import paddlenlp as ppnlp from paddlenlp.data import Pad, Stack,", "len(input_ids) - 1 while sequence_ids[token_end_index] != 1: token_end_index -= 1 # Minus one", "= paddle.distributed.get_rank() task_name = args.task_name.lower() args.model_type = args.model_type.lower() model_class, tokenizer_class = MODEL_CLASSES[args.model_type] tokenizer", "License. # You may obtain a copy of the License at # #", "prepare_train_features(examples): # Tokenize our examples with truncation and maybe padding, but keep the", "= time.time() all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions, _, _ = compute_prediction( data_loader.dataset.data, data_loader.dataset.new_data, (all_start_logits, all_end_logits),", "if args.max_steps > 0 else len( train_data_loader) * args.num_train_epochs num_train_epochs = math.ceil(num_training_steps /", "num_train_epochs = math.ceil(num_training_steps / len(train_data_loader)) lr_scheduler = LinearDecayWithWarmup( args.learning_rate, num_training_steps, args.warmup_proportion) # Generate", "lr_scheduler.step() optimizer.clear_grad() if global_step % args.save_steps == 0 or global_step == num_training_steps: if", "= examples[sample_index]['answers'] answer_starts = examples[sample_index]['answer_starts'] # Start/end character index of the answer in", "import math from functools import partial import numpy as np import paddle from", "= { \"bert\": (BertForQuestionAnswering, BertTokenizer), \"ernie\": (ErnieForQuestionAnswering, ErnieTokenizer), \"ernie_gram\": (ErnieGramForQuestionAnswering, ErnieGramTokenizer), \"roberta\": (RobertaForQuestionAnswering,", "end_positions = batch logits = model( input_ids=input_ids, token_type_ids=token_type_ids) loss = criterion(logits, (start_positions, end_positions))", "else: # Otherwise move the token_start_index and token_end_index to the two ends of", "compliance with the License. # You may obtain a copy of the License", "token_end_index to the two ends of the answer. # Note: we could go", "answer is the last word (edge case). while token_start_index < len(offsets) and offsets[", "that HugggingFace uses ArrowTable as basic data structure, while we use list of", "MODEL_CLASSES[args.model_type] tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args) if rank == 0: if os.path.exists(args.model_name_or_path): print(\"init checkpoint", "to that example (to know what is the context and what is the", "the text. token_start_index = 0 while sequence_ids[token_start_index] != 1: token_start_index += 1 #", "previous feature. # NOTE: Almost the same functionality as HuggingFace's prepare_train_features function. The", "tokenized_examples[i][\"start_positions\"] = cls_index tokenized_examples[i][\"end_positions\"] = cls_index else: # Otherwise move the token_start_index and", "\"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id), \"start_positions\": Stack(dtype=\"int64\"), \"end_positions\": Stack(dtype=\"int64\") }): fn(samples) train_data_loader = DataLoader( dataset=train_ds,", "offset if the answer is the last word (edge case). while token_start_index <", "for the specific language governing permissions and # limitations under the License. import", "any(nd in n for nd in [\"bias\", \"norm\"]) ] optimizer = paddle.optimizer.AdamW( learning_rate=lr_scheduler,", "\"bert\": (BertForQuestionAnswering, BertTokenizer), \"ernie\": (ErnieForQuestionAnswering, ErnieTokenizer), \"ernie_gram\": (ErnieGramForQuestionAnswering, ErnieGramTokenizer), \"roberta\": (RobertaForQuestionAnswering, RobertaTokenizer) }", "examples=data_loader.dataset.data, preds=all_predictions, is_whitespace_splited=False) model.train() class CrossEntropyLossForSQuAD(paddle.nn.Layer): def __init__(self): super(CrossEntropyLossForSQuAD, self).__init__() def forward(self, y,", "answers = examples[sample_index]['answers'] answer_starts = examples[sample_index]['answer_starts'] # Start/end character index of the answer", "o in enumerate(tokenized_example[\"offset_mapping\"]) ] return tokenized_examples if args.do_predict and rank == 0: if", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "/ 2 return loss def run(args): paddle.set_device(args.device) if paddle.distributed.get_world_size() > 1: paddle.distributed.init_parallel_env() rank", "= [examples[i]['context'] for i in range(len(examples))] questions = [examples[i]['question'] for i in range(len(examples))]", "start_char: token_start_index += 1 tokenized_examples[i][\"start_positions\"] = token_start_index - 1 while offsets[token_end_index][1] >= end_char:", "step/s\" % (global_step, epoch + 1, step + 1, loss, args.logging_steps / (time.time()", "\"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id) }): fn(samples) dev_data_loader = DataLoader( dataset=dev_ds, batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn, return_list=True) evaluate(model,", "super(CrossEntropyLossForSQuAD, self).__init__() def forward(self, y, label): start_logits, end_logits = y start_position, end_position =", "CrossEntropyLossForSQuAD(paddle.nn.Layer): def __init__(self): super(CrossEntropyLossForSQuAD, self).__init__() def forward(self, y, label): start_logits, end_logits = y", "start_position = paddle.unsqueeze(start_position, axis=-1) end_position = paddle.unsqueeze(end_position, axis=-1) start_loss = paddle.nn.functional.cross_entropy( input=start_logits, label=start_position)", "questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # For validation, there is no need to compute", "and offsets[token_end_index][1] >= end_char): tokenized_examples[i][\"start_positions\"] = cls_index tokenized_examples[i][\"end_positions\"] = cls_index else: # Otherwise", "input=end_logits, label=end_position) loss = (start_loss + end_loss) / 2 return loss def run(args):", "structure, while we use list of dictionary instead. contexts = [examples[i]['context'] for i", "loss, args.logging_steps / (time.time() - tic_train))) tic_train = time.time() loss.backward() optimizer.step() lr_scheduler.step() optimizer.clear_grad()", "position is part of the context or not. tokenized_examples[i][\"offset_mapping\"] = [ (o if", "step %d, epoch: %d, batch: %d, loss: %f, speed: %.2f step/s\" % (global_step,", "= [] tic_eval = time.time() for batch in data_loader: input_ids, token_type_ids = batch", "in range(len(examples))] tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # For validation, there", "None the offset_mapping that are not part of the context so it's easy", "paddle.seed(args.seed) @paddle.no_grad() def evaluate(model, data_loader, args): model.eval() all_start_logits = [] all_end_logits = []", "having a # context that overlaps a bit the context of the previous", "end_char = start_char + len(answers[0]) # Start token index of the current span", "learning_rate=lr_scheduler, epsilon=args.adam_epsilon, parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda x: x in decay_params) criterion = CrossEntropyLossForSQuAD() global_step", "args.warmup_proportion) # Generate parameter names needed to perform weight decay. # All bias", "give us a map from token to character position in the original context.", "= paddle.io.DistributedBatchSampler( train_ds, batch_size=args.batch_size, shuffle=True) train_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id),", "sequence_ids[token_start_index] != 1: token_start_index += 1 # End token index of the current", "0 while sequence_ids[token_start_index] != 1: token_start_index += 1 # End token index of", "if args.predict_file: dev_ds = load_dataset(task_name, data_files=args.predict_file) else: dev_ds = load_dataset(task_name, splits='dev') dev_ds.map(prepare_validation_features, batched=True)", "Pad(axis=0, pad_val=tokenizer.pad_token_type_id), \"start_positions\": Stack(dtype=\"int64\"), \"end_positions\": Stack(dtype=\"int64\") }): fn(samples) train_data_loader = DataLoader( dataset=train_ds, batch_sampler=train_batch_sampler,", "splits='dev') dev_ds.map(prepare_validation_features, batched=True) dev_batch_sampler = paddle.io.BatchSampler( dev_ds, batch_size=args.batch_size, shuffle=False) dev_batchify_fn = lambda samples,", "tokenized_example['offset_mapping'] # Grab the sequence corresponding to that example (to know what is", "not use this file except in compliance with the License. # You may", "1 return tokenized_examples if args.do_train: if args.train_file: train_ds = load_dataset(task_name, data_files=args.train_file) else: train_ds", "(in which case this feature is labeled with the CLS index). if not", "for batch in data_loader: input_ids, token_type_ids = batch start_logits_tensor, end_logits_tensor = model(input_ids, token_type_ids)", "data_loader, args): model.eval() all_start_logits = [] all_end_logits = [] tic_eval = time.time() for", "len(offsets) and offsets[ token_start_index][0] <= start_char: token_start_index += 1 tokenized_examples[i][\"start_positions\"] = token_start_index -", "start_positions and end_positions. offsets = tokenized_example['offset_mapping'] # Grab the sequence corresponding to that", "args import parse_args import paddlenlp as ppnlp from paddlenlp.data import Pad, Stack, Tuple,", "sequence corresponding to that example (to know what is the context and what", "import DataLoader from args import parse_args import paddlenlp as ppnlp from paddlenlp.data import", "token_end_index -= 1 # Minus one more to reach actual text token_end_index -=", "Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id), \"start_positions\": Stack(dtype=\"int64\"), \"end_positions\": Stack(dtype=\"int64\") }): fn(samples) train_data_loader =", "License, Version 2.0 (the \"License\"); # you may not use this file except", "index of the example containing this span of text. sample_index = tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"]", "ErnieGramTokenizer from paddlenlp.transformers import RobertaForQuestionAnswering, RobertaTokenizer from paddlenlp.transformers import LinearDecayWithWarmup from paddlenlp.metrics.squad import", "(time.time() - tic_train))) tic_train = time.time() loss.backward() optimizer.step() lr_scheduler.step() optimizer.clear_grad() if global_step %", "}): fn(samples) dev_data_loader = DataLoader( dataset=dev_ds, batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn, return_list=True) evaluate(model, dev_data_loader, args) if", "set_seed(args): random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed) @paddle.no_grad() def evaluate(model, data_loader, args): model.eval() all_start_logits = []", "containing this span of text. sample_index = tokenized_example['overflow_to_sample'] answers = examples[sample_index]['answers'] answer_starts =", "examples[sample_index]['id'] # Set to None the offset_mapping that are not part of the", "paddle.io.BatchSampler( dev_ds, batch_size=args.batch_size, shuffle=False) dev_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\":", "LinearDecayWithWarmup from paddlenlp.metrics.squad import squad_evaluate, compute_prediction from paddlenlp.datasets import load_dataset MODEL_CLASSES = {", "return_list=True) num_training_steps = args.max_steps if args.max_steps > 0 else len( train_data_loader) * args.num_train_epochs", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "each of those features having a # context that overlaps a bit the", "example possible giving several features when a context is long, each of those", "example containing this span of text. sample_index = tokenized_example['overflow_to_sample'] answers = examples[sample_index]['answers'] answer_starts", "!= 1: token_start_index += 1 # End token index of the current span", "parameter names needed to perform weight decay. # All bias and LayerNorm parameters", "# All bias and LayerNorm parameters are excluded. decay_params = [ p.name for", "inner model of DataParallel model_to_save = model._layers if isinstance( model, paddle.DataParallel) else model", "input_ids=input_ids, token_type_ids=token_type_ids) loss = criterion(logits, (start_positions, end_positions)) if global_step % args.logging_steps == 0:", "paddle.nn.functional.cross_entropy( input=start_logits, label=start_position) end_loss = paddle.nn.functional.cross_entropy( input=end_logits, label=end_position) loss = (start_loss + end_loss)", "the CLS token. input_ids = tokenized_example[\"input_ids\"] cls_index = input_ids.index(tokenizer.cls_token_id) # The offset mappings", "= len(input_ids) - 1 while sequence_ids[token_end_index] != 1: token_end_index -= 1 # Minus", "in n for nd in [\"bias\", \"norm\"]) ] optimizer = paddle.optimizer.AdamW( learning_rate=lr_scheduler, epsilon=args.adam_epsilon,", "args.do_predict and rank == 0: if args.predict_file: dev_ds = load_dataset(task_name, data_files=args.predict_file) else: dev_ds", "os import random import time import json import math from functools import partial", "all_predictions, _, _ = compute_prediction( data_loader.dataset.data, data_loader.dataset.new_data, (all_start_logits, all_end_logits), False, args.n_best_size, args.max_answer_length) #", "idx in range(start_logits_tensor.shape[0]): if len(all_start_logits) % 1000 == 0 and len(all_start_logits): print(\"Processing example:", "bit the context of the previous feature. # NOTE: Almost the same functionality", "np.random.seed(args.seed) paddle.seed(args.seed) @paddle.no_grad() def evaluate(model, data_loader, args): model.eval() all_start_logits = [] all_end_logits =", "enumerate(tokenized_examples): # We will label impossible answers with the index of the CLS", "load_dataset(task_name, data_files=args.predict_file) else: dev_ds = load_dataset(task_name, splits='dev') dev_ds.map(prepare_validation_features, batched=True) dev_batch_sampler = paddle.io.BatchSampler( dev_ds,", "is # that HugggingFace uses ArrowTable as basic data structure, while we use", "\"norm\"]) ] optimizer = paddle.optimizer.AdamW( learning_rate=lr_scheduler, epsilon=args.adam_epsilon, parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda x: x in", "% args.logging_steps == 0: print( \"global step %d, epoch: %d, batch: %d, loss:", "all_start_logits = [] all_end_logits = [] tic_eval = time.time() for batch in data_loader:", "isinstance( model, paddle.DataParallel) else model model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) print('Saving checkpoint to:', output_dir) if global_step", "1: paddle.distributed.init_parallel_env() rank = paddle.distributed.get_rank() task_name = args.task_name.lower() args.model_type = args.model_type.lower() model_class, tokenizer_class", "# you may not use this file except in compliance with the License.", "args.num_train_epochs num_train_epochs = math.ceil(num_training_steps / len(train_data_loader)) lr_scheduler = LinearDecayWithWarmup( args.learning_rate, num_training_steps, args.warmup_proportion) #", "i in range(len(examples))] tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # For validation,", "example containing this span of text. sample_index = tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"] = examples[sample_index]['id'] #", "spans, this is the index of the example containing this span of text.", "agreed to in writing, software # distributed under the License is distributed on", "input=start_logits, label=start_position) end_loss = paddle.nn.functional.cross_entropy( input=end_logits, label=end_position) loss = (start_loss + end_loss) /", "(start_loss + end_loss) / 2 return loss def run(args): paddle.set_device(args.device) if paddle.distributed.get_world_size() >", "example: %d\" % len(all_start_logits)) print('time per 1000:', time.time() - tic_eval) tic_eval = time.time()", "and LayerNorm parameters are excluded. decay_params = [ p.name for n, p in", "all_nbest_json and scores_diff_json files if needed with open('prediction.json', \"w\", encoding='utf-8') as writer: writer.write(", "as np import paddle from paddle.io import DataLoader from args import parse_args import", "cls_index else: # Otherwise move the token_start_index and token_end_index to the two ends", "All Rights Reserved. # Copyright 2018 The HuggingFace Inc. team. # # Licensed", "question). sequence_ids = tokenized_example['token_type_ids'] # One example can give several spans, this is", "text. sample_index = tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"] = examples[sample_index]['id'] # Set to None the offset_mapping", "# position is part of the context or not. tokenized_examples[i][\"offset_mapping\"] = [ (o", "context of the previous feature. # NOTE: Almost the same functionality as HuggingFace's", "reach actual text token_end_index -= 1 # Detect if the answer is out", "0 else len( train_data_loader) * args.num_train_epochs num_train_epochs = math.ceil(num_training_steps / len(train_data_loader)) lr_scheduler =", "(the \"License\"); # you may not use this file except in compliance with", "data_loader: input_ids, token_type_ids = batch start_logits_tensor, end_logits_tensor = model(input_ids, token_type_ids) for idx in", "= MODEL_CLASSES[args.model_type] tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args) if rank == 0: if os.path.exists(args.model_name_or_path): print(\"init", "more to reach actual text token_end_index -= 1 # Detect if the answer", "and end_positions. offsets = tokenized_example['offset_mapping'] # Grab the sequence corresponding to that example", "import Pad, Stack, Tuple, Dict from paddlenlp.transformers import BertForQuestionAnswering, BertTokenizer from paddlenlp.transformers import", "functionality as HuggingFace's prepare_train_features function. The main difference is # that HugggingFace uses", "0 tic_train = time.time() for epoch in range(num_train_epochs): for step, batch in enumerate(train_data_loader):", "Generate parameter names needed to perform weight decay. # All bias and LayerNorm", "0: if os.path.exists(args.model_name_or_path): print(\"init checkpoint from %s\" % args.model_name_or_path) model = model_class.from_pretrained(args.model_name_or_path) if", "# Unless required by applicable law or agreed to in writing, software #", "dev_batch_sampler = paddle.io.BatchSampler( dev_ds, batch_size=args.batch_size, shuffle=False) dev_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0,", "overflows using a stride. This results # in one example possible giving several", "= criterion(logits, (start_positions, end_positions)) if global_step % args.logging_steps == 0: print( \"global step", "if global_step % args.save_steps == 0 or global_step == num_training_steps: if rank ==", "-= 1 # Minus one more to reach actual text token_end_index -= 1", "by applicable law or agreed to in writing, software # distributed under the", "from paddlenlp.transformers import BertForQuestionAnswering, BertTokenizer from paddlenlp.transformers import ErnieForQuestionAnswering, ErnieTokenizer from paddlenlp.transformers import", "for i in range(len(examples))] questions = [examples[i]['question'] for i in range(len(examples))] tokenized_examples =", "speed: %.2f step/s\" % (global_step, epoch + 1, step + 1, loss, args.logging_steps", "start and end positions for i, tokenized_example in enumerate(tokenized_examples): # Grab the sequence", "all_end_logits), False, args.n_best_size, args.max_answer_length) # Can also write all_nbest_json and scores_diff_json files if", "for i in range(len(examples))] tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # For", "[ (o if sequence_ids[k] == 1 else None) for k, o in enumerate(tokenized_example[\"offset_mapping\"])", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "span of text. sample_index = tokenized_example['overflow_to_sample'] answers = examples[sample_index]['answers'] answer_starts = examples[sample_index]['answer_starts'] #", "[] tic_eval = time.time() for batch in data_loader: input_ids, token_type_ids = batch start_logits_tensor,", "governing permissions and # limitations under the License. import os import random import", "the text. token_end_index = len(input_ids) - 1 while sequence_ids[token_end_index] != 1: token_end_index -=", "= paddle.nn.functional.cross_entropy( input=end_logits, label=end_position) loss = (start_loss + end_loss) / 2 return loss", "1: model = paddle.DataParallel(model) def prepare_train_features(examples): # Tokenize our examples with truncation and", "= model(input_ids, token_type_ids) for idx in range(start_logits_tensor.shape[0]): if len(all_start_logits) % 1000 == 0", "import load_dataset MODEL_CLASSES = { \"bert\": (BertForQuestionAnswering, BertTokenizer), \"ernie\": (ErnieForQuestionAnswering, ErnieTokenizer), \"ernie_gram\": (ErnieGramForQuestionAnswering,", "will # help us compute the start_positions and end_positions. offsets = tokenized_example['offset_mapping'] #", "preds=all_predictions, is_whitespace_splited=False) model.train() class CrossEntropyLossForSQuAD(paddle.nn.Layer): def __init__(self): super(CrossEntropyLossForSQuAD, self).__init__() def forward(self, y, label):", "offsets[token_end_index][1] >= end_char): tokenized_examples[i][\"start_positions\"] = cls_index tokenized_examples[i][\"end_positions\"] = cls_index else: # Otherwise move", "LinearDecayWithWarmup( args.learning_rate, num_training_steps, args.warmup_proportion) # Generate parameter names needed to perform weight decay.", "1 input_ids, token_type_ids, start_positions, end_positions = batch logits = model( input_ids=input_ids, token_type_ids=token_type_ids) loss", "batch logits = model( input_ids=input_ids, token_type_ids=token_type_ids) loss = criterion(logits, (start_positions, end_positions)) if global_step", "0: output_dir = os.path.join(args.output_dir, \"model_%d\" % global_step) if not os.path.exists(output_dir): os.makedirs(output_dir) # need", "need to compute start and end positions for i, tokenized_example in enumerate(tokenized_examples): #", "if global_step % args.logging_steps == 0: print( \"global step %d, epoch: %d, batch:", "parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda x: x in decay_params) criterion = CrossEntropyLossForSQuAD() global_step = 0", "to character position in the original context. This will # help us compute", "rank = paddle.distributed.get_rank() task_name = args.task_name.lower() args.model_type = args.model_type.lower() model_class, tokenizer_class = MODEL_CLASSES[args.model_type]", "weight decay. # All bias and LayerNorm parameters are excluded. decay_params = [", "token_start_index += 1 # End token index of the current span in the", "from token to character position in the original context. This will # help", "The offset mappings will give us a map from token to character position", "of the answer in the text. start_char = answer_starts[0] end_char = start_char +", "could go after the last offset if the answer is the last word", "answer in the text. start_char = answer_starts[0] end_char = start_char + len(answers[0]) #", "= [] all_end_logits = [] tic_eval = time.time() for batch in data_loader: input_ids,", "text. token_start_index = 0 while sequence_ids[token_start_index] != 1: token_start_index += 1 # End", "file except in compliance with the License. # You may obtain a copy", "train_batch_sampler = paddle.io.DistributedBatchSampler( train_ds, batch_size=args.batch_size, shuffle=True) train_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0,", "] optimizer = paddle.optimizer.AdamW( learning_rate=lr_scheduler, epsilon=args.adam_epsilon, parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda x: x in decay_params)", "of the span (in which case this feature is labeled with the CLS", "global_step = 0 tic_train = time.time() for epoch in range(num_train_epochs): for step, batch", "Start/end character index of the answer in the text. start_char = answer_starts[0] end_char", "% args.save_steps == 0 or global_step == num_training_steps: if rank == 0: output_dir", "stride. This results # in one example possible giving several features when a", "of those features having a # context that overlaps a bit the context", "use list of dictionary instead. contexts = [examples[i]['context'] for i in range(len(examples))] questions", "\"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id), \"start_positions\": Stack(dtype=\"int64\"), \"end_positions\": Stack(dtype=\"int64\") }): fn(samples) train_data_loader", "= [ p.name for n, p in model.named_parameters() if not any(nd in n", "model.named_parameters() if not any(nd in n for nd in [\"bias\", \"norm\"]) ] optimizer", "the context and what is the question). sequence_ids = tokenized_example['token_type_ids'] # One example", "Rights Reserved. # Copyright 2018 The HuggingFace Inc. team. # # Licensed under", "License for the specific language governing permissions and # limitations under the License.", "sequence_ids = tokenized_example['token_type_ids'] # One example can give several spans, this is the", "word (edge case). while token_start_index < len(offsets) and offsets[ token_start_index][0] <= start_char: token_start_index", "pad_val=tokenizer.pad_token_type_id) }): fn(samples) dev_data_loader = DataLoader( dataset=dev_ds, batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn, return_list=True) evaluate(model, dev_data_loader, args)", "from paddlenlp.transformers import ErnieForQuestionAnswering, ErnieTokenizer from paddlenlp.transformers import ErnieGramForQuestionAnswering, ErnieGramTokenizer from paddlenlp.transformers import", "= tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args) if rank == 0: if os.path.exists(args.model_name_or_path): print(\"init checkpoint from %s\"", "= [examples[i]['question'] for i in range(len(examples))] tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length)", "For validation, there is no need to compute start and end positions for", "to in writing, software # distributed under the License is distributed on an", "args.max_answer_length) # Can also write all_nbest_json and scores_diff_json files if needed with open('prediction.json',", "= args.task_name.lower() args.model_type = args.model_type.lower() model_class, tokenizer_class = MODEL_CLASSES[args.model_type] tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args)", "better way to get inner model of DataParallel model_to_save = model._layers if isinstance(", "using a stride. This results # in one example possible giving several features", "batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn, return_list=True) num_training_steps = args.max_steps if args.max_steps > 0 else len( train_data_loader)", "implied. # See the License for the specific language governing permissions and #", "input_ids = tokenized_example[\"input_ids\"] cls_index = input_ids.index(tokenizer.cls_token_id) # The offset mappings will give us", "\"License\"); # you may not use this file except in compliance with the", "is the context and what is the question). sequence_ids = tokenized_example['token_type_ids'] # One", "a stride. This results # in one example possible giving several features when", "token_end_index -= 1 tokenized_examples[i][\"end_positions\"] = token_end_index + 1 return tokenized_examples if args.do_train: if", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "while token_start_index < len(offsets) and offsets[ token_start_index][0] <= start_char: token_start_index += 1 tokenized_examples[i][\"start_positions\"]", "model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) print('Saving checkpoint to:', output_dir) if global_step == num_training_steps: break def prepare_validation_features(examples):", "index of the example containing this span of text. sample_index = tokenized_example['overflow_to_sample'] answers", "the current span in the text. token_start_index = 0 while sequence_ids[token_start_index] != 1:", "decay_params = [ p.name for n, p in model.named_parameters() if not any(nd in", "uses ArrowTable as basic data structure, while we use list of dictionary instead.", "y, label): start_logits, end_logits = y start_position, end_position = label start_position = paddle.unsqueeze(start_position,", "that overlaps a bit the context of the previous feature. # NOTE: Almost", "CLS index). if not (offsets[token_start_index][0] <= start_char and offsets[token_end_index][1] >= end_char): tokenized_examples[i][\"start_positions\"] =", "optimizer.clear_grad() if global_step % args.save_steps == 0 or global_step == num_training_steps: if rank", "model = model_class.from_pretrained(args.model_name_or_path) if paddle.distributed.get_world_size() > 1: model = paddle.DataParallel(model) def prepare_train_features(examples): #", "HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the", "tokenized_example[\"input_ids\"] cls_index = input_ids.index(tokenizer.cls_token_id) # The offset mappings will give us a map", "padding, but keep the overflows using a stride. This results # in one", "the example containing this span of text. sample_index = tokenized_example['overflow_to_sample'] answers = examples[sample_index]['answers']", "possible giving several features when a context is long, each of those features", "end_positions)) if global_step % args.logging_steps == 0: print( \"global step %d, epoch: %d,", "validation, there is no need to compute start and end positions for i,", "parse_args import paddlenlp as ppnlp from paddlenlp.data import Pad, Stack, Tuple, Dict from", "of the example containing this span of text. sample_index = tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"] =", "and scores_diff_json files if needed with open('prediction.json', \"w\", encoding='utf-8') as writer: writer.write( json.dumps(", "(o if sequence_ids[k] == 1 else None) for k, o in enumerate(tokenized_example[\"offset_mapping\"]) ]", "def run(args): paddle.set_device(args.device) if paddle.distributed.get_world_size() > 1: paddle.distributed.init_parallel_env() rank = paddle.distributed.get_rank() task_name =", "team. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "or implied. # See the License for the specific language governing permissions and", "the specific language governing permissions and # limitations under the License. import os", "def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed) @paddle.no_grad() def evaluate(model, data_loader, args): model.eval() all_start_logits =", "decay_params) criterion = CrossEntropyLossForSQuAD() global_step = 0 tic_train = time.time() for epoch in", "i, tokenized_example in enumerate(tokenized_examples): # We will label impossible answers with the index", "we could go after the last offset if the answer is the last", "BertTokenizer from paddlenlp.transformers import ErnieForQuestionAnswering, ErnieTokenizer from paddlenlp.transformers import ErnieGramForQuestionAnswering, ErnieGramTokenizer from paddlenlp.transformers", "batch in data_loader: input_ids, token_type_ids = batch start_logits_tensor, end_logits_tensor = model(input_ids, token_type_ids) for", "that are not part of the context so it's easy to determine if", "import partial import numpy as np import paddle from paddle.io import DataLoader from", "index of the CLS token. input_ids = tokenized_example[\"input_ids\"] cls_index = input_ids.index(tokenizer.cls_token_id) # The", "token. input_ids = tokenized_example[\"input_ids\"] cls_index = input_ids.index(tokenizer.cls_token_id) # The offset mappings will give", "offsets[ token_start_index][0] <= start_char: token_start_index += 1 tokenized_examples[i][\"start_positions\"] = token_start_index - 1 while", "= paddle.unsqueeze(end_position, axis=-1) start_loss = paddle.nn.functional.cross_entropy( input=start_logits, label=start_position) end_loss = paddle.nn.functional.cross_entropy( input=end_logits, label=end_position)", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "len(all_start_logits) % 1000 == 0 and len(all_start_logits): print(\"Processing example: %d\" % len(all_start_logits)) print('time", "cls_index tokenized_examples[i][\"end_positions\"] = cls_index else: # Otherwise move the token_start_index and token_end_index to", "= paddle.optimizer.AdamW( learning_rate=lr_scheduler, epsilon=args.adam_epsilon, parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda x: x in decay_params) criterion =", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "when a context is long, each of those features having a # context", "of the current span in the text. token_end_index = len(input_ids) - 1 while", "weight_decay=args.weight_decay, apply_decay_param_fun=lambda x: x in decay_params) criterion = CrossEntropyLossForSQuAD() global_step = 0 tic_train", "this span of text. sample_index = tokenized_example['overflow_to_sample'] answers = examples[sample_index]['answers'] answer_starts = examples[sample_index]['answer_starts']", "give several spans, this is the index of the example containing this span", "%s\" % args.model_name_or_path) model = model_class.from_pretrained(args.model_name_or_path) if paddle.distributed.get_world_size() > 1: model = paddle.DataParallel(model)", "(all_start_logits, all_end_logits), False, args.n_best_size, args.max_answer_length) # Can also write all_nbest_json and scores_diff_json files", "= start_char + len(answers[0]) # Start token index of the current span in", "model = paddle.DataParallel(model) def prepare_train_features(examples): # Tokenize our examples with truncation and maybe", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "of the CLS token. input_ids = tokenized_example[\"input_ids\"] cls_index = input_ids.index(tokenizer.cls_token_id) # The offset", "in writing, software # distributed under the License is distributed on an \"AS", "token_end_index -= 1 # Detect if the answer is out of the span", "import os import random import time import json import math from functools import", "start_char = answer_starts[0] end_char = start_char + len(answers[0]) # Start token index of", "= LinearDecayWithWarmup( args.learning_rate, num_training_steps, args.warmup_proportion) # Generate parameter names needed to perform weight", "Tuple, Dict from paddlenlp.transformers import BertForQuestionAnswering, BertTokenizer from paddlenlp.transformers import ErnieForQuestionAnswering, ErnieTokenizer from", "data_loader.dataset.new_data, (all_start_logits, all_end_logits), False, args.n_best_size, args.max_answer_length) # Can also write all_nbest_json and scores_diff_json", "<= start_char and offsets[token_end_index][1] >= end_char): tokenized_examples[i][\"start_positions\"] = cls_index tokenized_examples[i][\"end_positions\"] = cls_index else:", "train_ds, batch_size=args.batch_size, shuffle=True) train_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0,", "len(all_start_logits)) print('time per 1000:', time.time() - tic_eval) tic_eval = time.time() all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions,", "1 # End token index of the current span in the text. token_end_index", "= load_dataset(task_name, data_files=args.predict_file) else: dev_ds = load_dataset(task_name, splits='dev') dev_ds.map(prepare_validation_features, batched=True) dev_batch_sampler = paddle.io.BatchSampler(", "# Minus one more to reach actual text token_end_index -= 1 # Detect", "# One example can give several spans, this is the index of the", "= DataLoader( dataset=dev_ds, batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn, return_list=True) evaluate(model, dev_data_loader, args) if __name__ == \"__main__\":", "args.save_steps == 0 or global_step == num_training_steps: if rank == 0: output_dir =", "collate_fn=train_batchify_fn, return_list=True) num_training_steps = args.max_steps if args.max_steps > 0 else len( train_data_loader) *", "# See the License for the specific language governing permissions and # limitations", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "-= 1 tokenized_examples[i][\"end_positions\"] = token_end_index + 1 return tokenized_examples if args.do_train: if args.train_file:", "rank == 0: if args.predict_file: dev_ds = load_dataset(task_name, data_files=args.predict_file) else: dev_ds = load_dataset(task_name,", "this span of text. sample_index = tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"] = examples[sample_index]['id'] # Set to", "# Can also write all_nbest_json and scores_diff_json files if needed with open('prediction.json', \"w\",", "} def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed) @paddle.no_grad() def evaluate(model, data_loader, args): model.eval() all_start_logits", "%d, loss: %f, speed: %.2f step/s\" % (global_step, epoch + 1, step +", "parameters are excluded. decay_params = [ p.name for n, p in model.named_parameters() if", "model_class, tokenizer_class = MODEL_CLASSES[args.model_type] tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args) if rank == 0: if", "= batch logits = model( input_ids=input_ids, token_type_ids=token_type_ids) loss = criterion(logits, (start_positions, end_positions)) if", "os.makedirs(output_dir) # need better way to get inner model of DataParallel model_to_save =", "one more to reach actual text token_end_index -= 1 # Detect if the", "NOTE: Almost the same functionality as HuggingFace's prepare_train_features function. The main difference is", "example can give several spans, this is the index of the example containing", "optimizer.step() lr_scheduler.step() optimizer.clear_grad() if global_step % args.save_steps == 0 or global_step == num_training_steps:", "import RobertaForQuestionAnswering, RobertaTokenizer from paddlenlp.transformers import LinearDecayWithWarmup from paddlenlp.metrics.squad import squad_evaluate, compute_prediction from", "Detect if the answer is out of the span (in which case this", "global_step % args.save_steps == 0 or global_step == num_training_steps: if rank == 0:", "from paddlenlp.data import Pad, Stack, Tuple, Dict from paddlenlp.transformers import BertForQuestionAnswering, BertTokenizer from", "part of the context so it's easy to determine if a token #", "Reserved. # Copyright 2018 The HuggingFace Inc. team. # # Licensed under the", "paddlenlp.datasets import load_dataset MODEL_CLASSES = { \"bert\": (BertForQuestionAnswering, BertTokenizer), \"ernie\": (ErnieForQuestionAnswering, ErnieTokenizer), \"ernie_gram\":", "None) for k, o in enumerate(tokenized_example[\"offset_mapping\"]) ] return tokenized_examples if args.do_predict and rank", "range(len(examples))] questions = [examples[i]['question'] for i in range(len(examples))] tokenized_examples = tokenizer( questions, contexts,", "[ p.name for n, p in model.named_parameters() if not any(nd in n for", "+= 1 # End token index of the current span in the text.", "and maybe padding, but keep the overflows using a stride. This results #", "# need better way to get inner model of DataParallel model_to_save = model._layers", "step, batch in enumerate(train_data_loader): global_step += 1 input_ids, token_type_ids, start_positions, end_positions = batch", "= examples[sample_index]['id'] # Set to None the offset_mapping that are not part of", "of the previous feature. # NOTE: Almost the same functionality as HuggingFace's prepare_train_features", "model( input_ids=input_ids, token_type_ids=token_type_ids) loss = criterion(logits, (start_positions, end_positions)) if global_step % args.logging_steps ==", "determine if a token # position is part of the context or not.", "import paddlenlp as ppnlp from paddlenlp.data import Pad, Stack, Tuple, Dict from paddlenlp.transformers", "return loss def run(args): paddle.set_device(args.device) if paddle.distributed.get_world_size() > 1: paddle.distributed.init_parallel_env() rank = paddle.distributed.get_rank()", "the sequence corresponding to that example (to know what is the context and", "giving several features when a context is long, each of those features having", "[\"bias\", \"norm\"]) ] optimizer = paddle.optimizer.AdamW( learning_rate=lr_scheduler, epsilon=args.adam_epsilon, parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda x: x", "lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id) }): fn(samples) dev_data_loader =", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "# We will label impossible answers with the index of the CLS token.", "lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id), \"start_positions\": Stack(dtype=\"int64\"), \"end_positions\": Stack(dtype=\"int64\")", "tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # Let's label those examples! for i, tokenized_example", "(start_positions, end_positions)) if global_step % args.logging_steps == 0: print( \"global step %d, epoch:", "you may not use this file except in compliance with the License. #", "token_start_index][0] <= start_char: token_start_index += 1 tokenized_examples[i][\"start_positions\"] = token_start_index - 1 while offsets[token_end_index][1]", "not. tokenized_examples[i][\"offset_mapping\"] = [ (o if sequence_ids[k] == 1 else None) for k,", "def prepare_train_features(examples): # Tokenize our examples with truncation and maybe padding, but keep", "is no need to compute start and end positions for i, tokenized_example in", ">= end_char: token_end_index -= 1 tokenized_examples[i][\"end_positions\"] = token_end_index + 1 return tokenized_examples if", "Inc. team. # # Licensed under the Apache License, Version 2.0 (the \"License\");", "difference is # that HugggingFace uses ArrowTable as basic data structure, while we", "in enumerate(tokenized_example[\"offset_mapping\"]) ] return tokenized_examples if args.do_predict and rank == 0: if args.predict_file:", "token_start_index and token_end_index to the two ends of the answer. # Note: we", "1: token_end_index -= 1 # Minus one more to reach actual text token_end_index", "time.time() for batch in data_loader: input_ids, token_type_ids = batch start_logits_tensor, end_logits_tensor = model(input_ids,", "args.train_file: train_ds = load_dataset(task_name, data_files=args.train_file) else: train_ds = load_dataset(task_name, splits='train') train_ds.map(prepare_train_features, batched=True) train_batch_sampler", "Start token index of the current span in the text. token_start_index = 0", "token_start_index += 1 tokenized_examples[i][\"start_positions\"] = token_start_index - 1 while offsets[token_end_index][1] >= end_char: token_end_index", "args.logging_steps / (time.time() - tic_train))) tic_train = time.time() loss.backward() optimizer.step() lr_scheduler.step() optimizer.clear_grad() if", "= token_start_index - 1 while offsets[token_end_index][1] >= end_char: token_end_index -= 1 tokenized_examples[i][\"end_positions\"] =", "= token_end_index + 1 return tokenized_examples if args.do_train: if args.train_file: train_ds = load_dataset(task_name,", "is part of the context or not. tokenized_examples[i][\"offset_mapping\"] = [ (o if sequence_ids[k]", "ends of the answer. # Note: we could go after the last offset", "also write all_nbest_json and scores_diff_json files if needed with open('prediction.json', \"w\", encoding='utf-8') as", "tokenized_example in enumerate(tokenized_examples): # We will label impossible answers with the index of", "language governing permissions and # limitations under the License. import os import random", "the text. start_char = answer_starts[0] end_char = start_char + len(answers[0]) # Start token", "a map from token to character position in the original context. This will", "BertTokenizer), \"ernie\": (ErnieForQuestionAnswering, ErnieTokenizer), \"ernie_gram\": (ErnieGramForQuestionAnswering, ErnieGramTokenizer), \"roberta\": (RobertaForQuestionAnswering, RobertaTokenizer) } def set_seed(args):", "one example possible giving several features when a context is long, each of", "collate_fn=dev_batchify_fn, return_list=True) evaluate(model, dev_data_loader, args) if __name__ == \"__main__\": args = parse_args() run(args)", "_, _ = compute_prediction( data_loader.dataset.data, data_loader.dataset.new_data, (all_start_logits, all_end_logits), False, args.n_best_size, args.max_answer_length) # Can", "False, args.n_best_size, args.max_answer_length) # Can also write all_nbest_json and scores_diff_json files if needed", "and len(all_start_logits): print(\"Processing example: %d\" % len(all_start_logits)) print('time per 1000:', time.time() - tic_eval)", "answers with the index of the CLS token. input_ids = tokenized_example[\"input_ids\"] cls_index =", "train_ds = load_dataset(task_name, data_files=args.train_file) else: train_ds = load_dataset(task_name, splits='train') train_ds.map(prepare_train_features, batched=True) train_batch_sampler =", "# Grab the sequence corresponding to that example (to know what is the", "if not any(nd in n for nd in [\"bias\", \"norm\"]) ] optimizer =", "# NOTE: Almost the same functionality as HuggingFace's prepare_train_features function. The main difference", "function. The main difference is # that HugggingFace uses ArrowTable as basic data", "pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id) }): fn(samples) dev_data_loader = DataLoader( dataset=dev_ds, batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn, return_list=True)", "questions = [examples[i]['question'] for i in range(len(examples))] tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride,", "Copyright 2018 The HuggingFace Inc. team. # # Licensed under the Apache License,", "use this file except in compliance with the License. # You may obtain", "the License. import os import random import time import json import math from", "\"end_positions\": Stack(dtype=\"int64\") }): fn(samples) train_data_loader = DataLoader( dataset=train_ds, batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn, return_list=True) num_training_steps =", "batch start_logits_tensor, end_logits_tensor = model(input_ids, token_type_ids) for idx in range(start_logits_tensor.shape[0]): if len(all_start_logits) %", "] return tokenized_examples if args.do_predict and rank == 0: if args.predict_file: dev_ds =", "from paddlenlp.datasets import load_dataset MODEL_CLASSES = { \"bert\": (BertForQuestionAnswering, BertTokenizer), \"ernie\": (ErnieForQuestionAnswering, ErnieTokenizer),", "epsilon=args.adam_epsilon, parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda x: x in decay_params) criterion = CrossEntropyLossForSQuAD() global_step =", "in the text. token_end_index = len(input_ids) - 1 while sequence_ids[token_end_index] != 1: token_end_index", "which case this feature is labeled with the CLS index). if not (offsets[token_start_index][0]", "span of text. sample_index = tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"] = examples[sample_index]['id'] # Set to None", "numpy as np import paddle from paddle.io import DataLoader from args import parse_args", "end_loss = paddle.nn.functional.cross_entropy( input=end_logits, label=end_position) loss = (start_loss + end_loss) / 2 return", "= args.model_type.lower() model_class, tokenizer_class = MODEL_CLASSES[args.model_type] tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args) if rank ==", "% (global_step, epoch + 1, step + 1, loss, args.logging_steps / (time.time() -", "paddle.nn.functional.cross_entropy( input=end_logits, label=end_position) loss = (start_loss + end_loss) / 2 return loss def", "axis=-1) end_position = paddle.unsqueeze(end_position, axis=-1) start_loss = paddle.nn.functional.cross_entropy( input=start_logits, label=start_position) end_loss = paddle.nn.functional.cross_entropy(", "fn(samples) dev_data_loader = DataLoader( dataset=dev_ds, batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn, return_list=True) evaluate(model, dev_data_loader, args) if __name__", "paddle.io.DistributedBatchSampler( train_ds, batch_size=args.batch_size, shuffle=True) train_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\":", "fn(samples) train_data_loader = DataLoader( dataset=train_ds, batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn, return_list=True) num_training_steps = args.max_steps if args.max_steps", "Authors. All Rights Reserved. # Copyright 2018 The HuggingFace Inc. team. # #", "# The offset mappings will give us a map from token to character", "optimizer = paddle.optimizer.AdamW( learning_rate=lr_scheduler, epsilon=args.adam_epsilon, parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda x: x in decay_params) criterion", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "paddle.distributed.get_world_size() > 1: model = paddle.DataParallel(model) def prepare_train_features(examples): # Tokenize our examples with", "\"start_positions\": Stack(dtype=\"int64\"), \"end_positions\": Stack(dtype=\"int64\") }): fn(samples) train_data_loader = DataLoader( dataset=train_ds, batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn, return_list=True)", "# Tokenize our examples with truncation and maybe padding, but keep the overflows", "token_start_index < len(offsets) and offsets[ token_start_index][0] <= start_char: token_start_index += 1 tokenized_examples[i][\"start_positions\"] =", "__init__(self): super(CrossEntropyLossForSQuAD, self).__init__() def forward(self, y, label): start_logits, end_logits = y start_position, end_position", "labeled with the CLS index). if not (offsets[token_start_index][0] <= start_char and offsets[token_end_index][1] >=", "= load_dataset(task_name, data_files=args.train_file) else: train_ds = load_dataset(task_name, splits='train') train_ds.map(prepare_train_features, batched=True) train_batch_sampler = paddle.io.DistributedBatchSampler(", "# limitations under the License. import os import random import time import json", "character index of the answer in the text. start_char = answer_starts[0] end_char =", "Pad, Stack, Tuple, Dict from paddlenlp.transformers import BertForQuestionAnswering, BertTokenizer from paddlenlp.transformers import ErnieForQuestionAnswering,", "{ \"bert\": (BertForQuestionAnswering, BertTokenizer), \"ernie\": (ErnieForQuestionAnswering, ErnieTokenizer), \"ernie_gram\": (ErnieGramForQuestionAnswering, ErnieGramTokenizer), \"roberta\": (RobertaForQuestionAnswering, RobertaTokenizer)", "tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # Let's label those examples! for", "start_position, end_position = label start_position = paddle.unsqueeze(start_position, axis=-1) end_position = paddle.unsqueeze(end_position, axis=-1) start_loss", "paddle.unsqueeze(end_position, axis=-1) start_loss = paddle.nn.functional.cross_entropy( input=start_logits, label=start_position) end_loss = paddle.nn.functional.cross_entropy( input=end_logits, label=end_position) loss", "\"ernie\": (ErnieForQuestionAnswering, ErnieTokenizer), \"ernie_gram\": (ErnieGramForQuestionAnswering, ErnieGramTokenizer), \"roberta\": (RobertaForQuestionAnswering, RobertaTokenizer) } def set_seed(args): random.seed(args.seed)", "while we use list of dictionary instead. contexts = [examples[i]['context'] for i in", "Grab the sequence corresponding to that example (to know what is the context", "= (start_loss + end_loss) / 2 return loss def run(args): paddle.set_device(args.device) if paddle.distributed.get_world_size()", "text. start_char = answer_starts[0] end_char = start_char + len(answers[0]) # Start token index", "if needed with open('prediction.json', \"w\", encoding='utf-8') as writer: writer.write( json.dumps( all_predictions, ensure_ascii=False, indent=4)", "2.0 (the \"License\"); # you may not use this file except in compliance", "paddle.distributed.init_parallel_env() rank = paddle.distributed.get_rank() task_name = args.task_name.lower() args.model_type = args.model_type.lower() model_class, tokenizer_class =", "from paddlenlp.transformers import RobertaForQuestionAnswering, RobertaTokenizer from paddlenlp.transformers import LinearDecayWithWarmup from paddlenlp.metrics.squad import squad_evaluate,", "end_logits_tensor = model(input_ids, token_type_ids) for idx in range(start_logits_tensor.shape[0]): if len(all_start_logits) % 1000 ==", "\"w\", encoding='utf-8') as writer: writer.write( json.dumps( all_predictions, ensure_ascii=False, indent=4) + \"\\n\") squad_evaluate( examples=data_loader.dataset.data,", "global_step == num_training_steps: break def prepare_validation_features(examples): # Tokenize our examples with truncation and", "else None) for k, o in enumerate(tokenized_example[\"offset_mapping\"]) ] return tokenized_examples if args.do_predict and", "ppnlp from paddlenlp.data import Pad, Stack, Tuple, Dict from paddlenlp.transformers import BertForQuestionAnswering, BertTokenizer", "- tic_eval) tic_eval = time.time() all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions, _, _ = compute_prediction( data_loader.dataset.data,", "tokenized_example['token_type_ids'] # One example can give several spans, this is the index of", "the same functionality as HuggingFace's prepare_train_features function. The main difference is # that", "the span (in which case this feature is labeled with the CLS index).", "loss = (start_loss + end_loss) / 2 return loss def run(args): paddle.set_device(args.device) if", "in the text. start_char = answer_starts[0] end_char = start_char + len(answers[0]) # Start", "the token_start_index and token_end_index to the two ends of the answer. # Note:", "files if needed with open('prediction.json', \"w\", encoding='utf-8') as writer: writer.write( json.dumps( all_predictions, ensure_ascii=False,", "checkpoint from %s\" % args.model_name_or_path) model = model_class.from_pretrained(args.model_name_or_path) if paddle.distributed.get_world_size() > 1: model", "else: dev_ds = load_dataset(task_name, splits='dev') dev_ds.map(prepare_validation_features, batched=True) dev_batch_sampler = paddle.io.BatchSampler( dev_ds, batch_size=args.batch_size, shuffle=False)", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "args.logging_steps == 0: print( \"global step %d, epoch: %d, batch: %d, loss: %f,", "label start_position = paddle.unsqueeze(start_position, axis=-1) end_position = paddle.unsqueeze(end_position, axis=-1) start_loss = paddle.nn.functional.cross_entropy( input=start_logits,", "paddle.set_device(args.device) if paddle.distributed.get_world_size() > 1: paddle.distributed.init_parallel_env() rank = paddle.distributed.get_rank() task_name = args.task_name.lower() args.model_type", "same functionality as HuggingFace's prepare_train_features function. The main difference is # that HugggingFace", "examples[sample_index]['answer_starts'] # Start/end character index of the answer in the text. start_char =", "range(num_train_epochs): for step, batch in enumerate(train_data_loader): global_step += 1 input_ids, token_type_ids, start_positions, end_positions", "know what is the context and what is the question). sequence_ids = tokenized_example['token_type_ids']", "1 tokenized_examples[i][\"start_positions\"] = token_start_index - 1 while offsets[token_end_index][1] >= end_char: token_end_index -= 1", "checkpoint to:', output_dir) if global_step == num_training_steps: break def prepare_validation_features(examples): # Tokenize our", "max_seq_len=args.max_seq_length) # Let's label those examples! for i, tokenized_example in enumerate(tokenized_examples): # We", "sample_index = tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"] = examples[sample_index]['id'] # Set to None the offset_mapping that", "train_ds.map(prepare_train_features, batched=True) train_batch_sampler = paddle.io.DistributedBatchSampler( train_ds, batch_size=args.batch_size, shuffle=True) train_batchify_fn = lambda samples, fn=Dict({", "# # Unless required by applicable law or agreed to in writing, software", "in model.named_parameters() if not any(nd in n for nd in [\"bias\", \"norm\"]) ]", "not os.path.exists(output_dir): os.makedirs(output_dir) # need better way to get inner model of DataParallel", "if a token # position is part of the context or not. tokenized_examples[i][\"offset_mapping\"]", "express or implied. # See the License for the specific language governing permissions", "functools import partial import numpy as np import paddle from paddle.io import DataLoader", "Let's label those examples! for i, tokenized_example in enumerate(tokenized_examples): # We will label", "pad_val=tokenizer.pad_token_type_id), \"start_positions\": Stack(dtype=\"int64\"), \"end_positions\": Stack(dtype=\"int64\") }): fn(samples) train_data_loader = DataLoader( dataset=train_ds, batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn,", "start_positions, end_positions = batch logits = model( input_ids=input_ids, token_type_ids=token_type_ids) loss = criterion(logits, (start_positions,", "nd in [\"bias\", \"norm\"]) ] optimizer = paddle.optimizer.AdamW( learning_rate=lr_scheduler, epsilon=args.adam_epsilon, parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda", "dev_ds = load_dataset(task_name, data_files=args.predict_file) else: dev_ds = load_dataset(task_name, splits='dev') dev_ds.map(prepare_validation_features, batched=True) dev_batch_sampler =", "this is the index of the example containing this span of text. sample_index", "specific language governing permissions and # limitations under the License. import os import", "forward(self, y, label): start_logits, end_logits = y start_position, end_position = label start_position =", "All bias and LayerNorm parameters are excluded. decay_params = [ p.name for n,", "RobertaForQuestionAnswering, RobertaTokenizer from paddlenlp.transformers import LinearDecayWithWarmup from paddlenlp.metrics.squad import squad_evaluate, compute_prediction from paddlenlp.datasets", "loss def run(args): paddle.set_device(args.device) if paddle.distributed.get_world_size() > 1: paddle.distributed.init_parallel_env() rank = paddle.distributed.get_rank() task_name", "scores_diff_json files if needed with open('prediction.json', \"w\", encoding='utf-8') as writer: writer.write( json.dumps( all_predictions,", "decay. # All bias and LayerNorm parameters are excluded. decay_params = [ p.name", "to compute start and end positions for i, tokenized_example in enumerate(tokenized_examples): # Grab", "fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id), \"start_positions\": Stack(dtype=\"int64\"), \"end_positions\": Stack(dtype=\"int64\") }): fn(samples)", "token_type_ids=token_type_ids) loss = criterion(logits, (start_positions, end_positions)) if global_step % args.logging_steps == 0: print(", "context. This will # help us compute the start_positions and end_positions. offsets =", "else model model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) print('Saving checkpoint to:', output_dir) if global_step == num_training_steps: break", "index). if not (offsets[token_start_index][0] <= start_char and offsets[token_end_index][1] >= end_char): tokenized_examples[i][\"start_positions\"] = cls_index", ">= end_char): tokenized_examples[i][\"start_positions\"] = cls_index tokenized_examples[i][\"end_positions\"] = cls_index else: # Otherwise move the", "either express or implied. # See the License for the specific language governing", "in range(num_train_epochs): for step, batch in enumerate(train_data_loader): global_step += 1 input_ids, token_type_ids, start_positions,", "dev_ds.map(prepare_validation_features, batched=True) dev_batch_sampler = paddle.io.BatchSampler( dev_ds, batch_size=args.batch_size, shuffle=False) dev_batchify_fn = lambda samples, fn=Dict({", "= load_dataset(task_name, splits='train') train_ds.map(prepare_train_features, batched=True) train_batch_sampler = paddle.io.DistributedBatchSampler( train_ds, batch_size=args.batch_size, shuffle=True) train_batchify_fn =", "import ErnieGramForQuestionAnswering, ErnieGramTokenizer from paddlenlp.transformers import RobertaForQuestionAnswering, RobertaTokenizer from paddlenlp.transformers import LinearDecayWithWarmup from", "tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args) if rank == 0: if os.path.exists(args.model_name_or_path): print(\"init checkpoint from", "to None the offset_mapping that are not part of the context so it's", "}): fn(samples) train_data_loader = DataLoader( dataset=train_ds, batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn, return_list=True) num_training_steps = args.max_steps if", "tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # For validation, there is no", "axis=-1) start_loss = paddle.nn.functional.cross_entropy( input=start_logits, label=start_position) end_loss = paddle.nn.functional.cross_entropy( input=end_logits, label=end_position) loss =", "the context or not. tokenized_examples[i][\"offset_mapping\"] = [ (o if sequence_ids[k] == 1 else", "example (to know what is the context and what is the question). sequence_ids", "args.max_steps > 0 else len( train_data_loader) * args.num_train_epochs num_train_epochs = math.ceil(num_training_steps / len(train_data_loader))", "is the question). sequence_ids = tokenized_example['token_type_ids'] # One example can give several spans,", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "with the index of the CLS token. input_ids = tokenized_example[\"input_ids\"] cls_index = input_ids.index(tokenizer.cls_token_id)", "loss = criterion(logits, (start_positions, end_positions)) if global_step % args.logging_steps == 0: print( \"global", "model._layers if isinstance( model, paddle.DataParallel) else model model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) print('Saving checkpoint to:', output_dir)", "samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id) }): fn(samples) dev_data_loader = DataLoader(", "all_end_logits = [] tic_eval = time.time() for batch in data_loader: input_ids, token_type_ids =", "offsets = tokenized_example['offset_mapping'] # Grab the sequence corresponding to that example (to know", "# Start/end character index of the answer in the text. start_char = answer_starts[0]", "def evaluate(model, data_loader, args): model.eval() all_start_logits = [] all_end_logits = [] tic_eval =", "end_logits = y start_position, end_position = label start_position = paddle.unsqueeze(start_position, axis=-1) end_position =", "= tokenized_example['token_type_ids'] # One example can give several spans, this is the index", "load_dataset(task_name, splits='train') train_ds.map(prepare_train_features, batched=True) train_batch_sampler = paddle.io.DistributedBatchSampler( train_ds, batch_size=args.batch_size, shuffle=True) train_batchify_fn = lambda", "== 0 and len(all_start_logits): print(\"Processing example: %d\" % len(all_start_logits)) print('time per 1000:', time.time()", "math from functools import partial import numpy as np import paddle from paddle.io", "input_ids, token_type_ids = batch start_logits_tensor, end_logits_tensor = model(input_ids, token_type_ids) for idx in range(start_logits_tensor.shape[0]):", "# Let's label those examples! for i, tokenized_example in enumerate(tokenized_examples): # We will", "CrossEntropyLossForSQuAD() global_step = 0 tic_train = time.time() for epoch in range(num_train_epochs): for step,", "1 while offsets[token_end_index][1] >= end_char: token_end_index -= 1 tokenized_examples[i][\"end_positions\"] = token_end_index + 1", "and token_end_index to the two ends of the answer. # Note: we could", "token # position is part of the context or not. tokenized_examples[i][\"offset_mapping\"] = [", "print(\"Processing example: %d\" % len(all_start_logits)) print('time per 1000:', time.time() - tic_eval) tic_eval =", "output_dir) if global_step == num_training_steps: break def prepare_validation_features(examples): # Tokenize our examples with", "= tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"] = examples[sample_index]['id'] # Set to None the offset_mapping that are", "the License. # You may obtain a copy of the License at #", "step + 1, loss, args.logging_steps / (time.time() - tic_train))) tic_train = time.time() loss.backward()", "if args.do_train: if args.train_file: train_ds = load_dataset(task_name, data_files=args.train_file) else: train_ds = load_dataset(task_name, splits='train')", "batch in enumerate(train_data_loader): global_step += 1 input_ids, token_type_ids, start_positions, end_positions = batch logits", "tokenized_examples if args.do_train: if args.train_file: train_ds = load_dataset(task_name, data_files=args.train_file) else: train_ds = load_dataset(task_name,", "per 1000:', time.time() - tic_eval) tic_eval = time.time() all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions, _, _", "== 0: output_dir = os.path.join(args.output_dir, \"model_%d\" % global_step) if not os.path.exists(output_dir): os.makedirs(output_dir) #", "np import paddle from paddle.io import DataLoader from args import parse_args import paddlenlp", "not any(nd in n for nd in [\"bias\", \"norm\"]) ] optimizer = paddle.optimizer.AdamW(", "so it's easy to determine if a token # position is part of", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "batch_size=args.batch_size, shuffle=True) train_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id),", "model(input_ids, token_type_ids) for idx in range(start_logits_tensor.shape[0]): if len(all_start_logits) % 1000 == 0 and", "input_ids, token_type_ids, start_positions, end_positions = batch logits = model( input_ids=input_ids, token_type_ids=token_type_ids) loss =", "k, o in enumerate(tokenized_example[\"offset_mapping\"]) ] return tokenized_examples if args.do_predict and rank == 0:", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "paddle from paddle.io import DataLoader from args import parse_args import paddlenlp as ppnlp", "ArrowTable as basic data structure, while we use list of dictionary instead. contexts", "break def prepare_validation_features(examples): # Tokenize our examples with truncation and maybe padding, but", "context or not. tokenized_examples[i][\"offset_mapping\"] = [ (o if sequence_ids[k] == 1 else None)", "if sequence_ids[k] == 1 else None) for k, o in enumerate(tokenized_example[\"offset_mapping\"]) ] return", "or not. tokenized_examples[i][\"offset_mapping\"] = [ (o if sequence_ids[k] == 1 else None) for", "[examples[i]['question'] for i in range(len(examples))] tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) #", "we use list of dictionary instead. contexts = [examples[i]['context'] for i in range(len(examples))]", "tokenized_example['overflow_to_sample'] answers = examples[sample_index]['answers'] answer_starts = examples[sample_index]['answer_starts'] # Start/end character index of the", "1, step + 1, loss, args.logging_steps / (time.time() - tic_train))) tic_train = time.time()", "# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # Copyright 2018 The", "1 # Minus one more to reach actual text token_end_index -= 1 #", "time import json import math from functools import partial import numpy as np", "2020 PaddlePaddle Authors. All Rights Reserved. # Copyright 2018 The HuggingFace Inc. team.", "will give us a map from token to character position in the original", "while sequence_ids[token_end_index] != 1: token_end_index -= 1 # Minus one more to reach", "start_char and offsets[token_end_index][1] >= end_char): tokenized_examples[i][\"start_positions\"] = cls_index tokenized_examples[i][\"end_positions\"] = cls_index else: #", "case). while token_start_index < len(offsets) and offsets[ token_start_index][0] <= start_char: token_start_index += 1", "end_char: token_end_index -= 1 tokenized_examples[i][\"end_positions\"] = token_end_index + 1 return tokenized_examples if args.do_train:", "= tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # For validation, there is no need", "import parse_args import paddlenlp as ppnlp from paddlenlp.data import Pad, Stack, Tuple, Dict", "list of dictionary instead. contexts = [examples[i]['context'] for i in range(len(examples))] questions =", "way to get inner model of DataParallel model_to_save = model._layers if isinstance( model,", "def prepare_validation_features(examples): # Tokenize our examples with truncation and maybe padding, but keep", "num_training_steps, args.warmup_proportion) # Generate parameter names needed to perform weight decay. # All", "shuffle=True) train_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id), \"start_positions\":", "from paddle.io import DataLoader from args import parse_args import paddlenlp as ppnlp from", "args.model_type.lower() model_class, tokenizer_class = MODEL_CLASSES[args.model_type] tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args) if rank == 0:", "compute the start_positions and end_positions. offsets = tokenized_example['offset_mapping'] # Grab the sequence corresponding", "what is the question). sequence_ids = tokenized_example['token_type_ids'] # One example can give several", "(c) 2020 PaddlePaddle Authors. All Rights Reserved. # Copyright 2018 The HuggingFace Inc.", "label those examples! for i, tokenized_example in enumerate(tokenized_examples): # We will label impossible", "[examples[i]['context'] for i in range(len(examples))] questions = [examples[i]['question'] for i in range(len(examples))] tokenized_examples", "in enumerate(tokenized_examples): # Grab the sequence corresponding to that example (to know what", "tokenizer.save_pretrained(output_dir) print('Saving checkpoint to:', output_dir) if global_step == num_training_steps: break def prepare_validation_features(examples): #", "in enumerate(tokenized_examples): # We will label impossible answers with the index of the", "import time import json import math from functools import partial import numpy as", "tic_eval) tic_eval = time.time() all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions, _, _ = compute_prediction( data_loader.dataset.data, data_loader.dataset.new_data,", "a # context that overlaps a bit the context of the previous feature.", "lr_scheduler = LinearDecayWithWarmup( args.learning_rate, num_training_steps, args.warmup_proportion) # Generate parameter names needed to perform", "excluded. decay_params = [ p.name for n, p in model.named_parameters() if not any(nd", "our examples with truncation and maybe padding, but keep the overflows using a", "with the License. # You may obtain a copy of the License at", "%d\" % len(all_start_logits)) print('time per 1000:', time.time() - tic_eval) tic_eval = time.time() all_start_logits.append(start_logits_tensor.numpy()[idx])", "tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"] = examples[sample_index]['id'] # Set to None the offset_mapping that are not", "* args.num_train_epochs num_train_epochs = math.ceil(num_training_steps / len(train_data_loader)) lr_scheduler = LinearDecayWithWarmup( args.learning_rate, num_training_steps, args.warmup_proportion)", "for idx in range(start_logits_tensor.shape[0]): if len(all_start_logits) % 1000 == 0 and len(all_start_logits): print(\"Processing", "actual text token_end_index -= 1 # Detect if the answer is out of", "== num_training_steps: if rank == 0: output_dir = os.path.join(args.output_dir, \"model_%d\" % global_step) if", "is long, each of those features having a # context that overlaps a", "+ \"\\n\") squad_evaluate( examples=data_loader.dataset.data, preds=all_predictions, is_whitespace_splited=False) model.train() class CrossEntropyLossForSQuAD(paddle.nn.Layer): def __init__(self): super(CrossEntropyLossForSQuAD, self).__init__()", "args.max_steps if args.max_steps > 0 else len( train_data_loader) * args.num_train_epochs num_train_epochs = math.ceil(num_training_steps", "from functools import partial import numpy as np import paddle from paddle.io import", "logits = model( input_ids=input_ids, token_type_ids=token_type_ids) loss = criterion(logits, (start_positions, end_positions)) if global_step %", "@paddle.no_grad() def evaluate(model, data_loader, args): model.eval() all_start_logits = [] all_end_logits = [] tic_eval", "model model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) print('Saving checkpoint to:', output_dir) if global_step == num_training_steps: break def", "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "dev_ds = load_dataset(task_name, splits='dev') dev_ds.map(prepare_validation_features, batched=True) dev_batch_sampler = paddle.io.BatchSampler( dev_ds, batch_size=args.batch_size, shuffle=False) dev_batchify_fn", "\"ernie_gram\": (ErnieGramForQuestionAnswering, ErnieGramTokenizer), \"roberta\": (RobertaForQuestionAnswering, RobertaTokenizer) } def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed) @paddle.no_grad()", "features having a # context that overlaps a bit the context of the", "the original context. This will # help us compute the start_positions and end_positions.", "(to know what is the context and what is the question). sequence_ids =", "max_seq_len=args.max_seq_length) # For validation, there is no need to compute start and end", "maybe padding, but keep the overflows using a stride. This results # in", "as basic data structure, while we use list of dictionary instead. contexts =", "(ErnieForQuestionAnswering, ErnieTokenizer), \"ernie_gram\": (ErnieGramForQuestionAnswering, ErnieGramTokenizer), \"roberta\": (RobertaForQuestionAnswering, RobertaTokenizer) } def set_seed(args): random.seed(args.seed) np.random.seed(args.seed)", "go after the last offset if the answer is the last word (edge", "os.path.exists(output_dir): os.makedirs(output_dir) # need better way to get inner model of DataParallel model_to_save", "# Otherwise move the token_start_index and token_end_index to the two ends of the", "1, loss, args.logging_steps / (time.time() - tic_train))) tic_train = time.time() loss.backward() optimizer.step() lr_scheduler.step()", "pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id), \"start_positions\": Stack(dtype=\"int64\"), \"end_positions\": Stack(dtype=\"int64\") }): fn(samples) train_data_loader = DataLoader(", "% len(all_start_logits)) print('time per 1000:', time.time() - tic_eval) tic_eval = time.time() all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx])", "offset_mapping that are not part of the context so it's easy to determine", "as ppnlp from paddlenlp.data import Pad, Stack, Tuple, Dict from paddlenlp.transformers import BertForQuestionAnswering,", "(RobertaForQuestionAnswering, RobertaTokenizer) } def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed) @paddle.no_grad() def evaluate(model, data_loader, args):", "law or agreed to in writing, software # distributed under the License is", "in range(start_logits_tensor.shape[0]): if len(all_start_logits) % 1000 == 0 and len(all_start_logits): print(\"Processing example: %d\"", "label=end_position) loss = (start_loss + end_loss) / 2 return loss def run(args): paddle.set_device(args.device)", "the License for the specific language governing permissions and # limitations under the", "2 return loss def run(args): paddle.set_device(args.device) if paddle.distributed.get_world_size() > 1: paddle.distributed.init_parallel_env() rank =", "p in model.named_parameters() if not any(nd in n for nd in [\"bias\", \"norm\"])", "== 0: if os.path.exists(args.model_name_or_path): print(\"init checkpoint from %s\" % args.model_name_or_path) model = model_class.from_pretrained(args.model_name_or_path)", "paddle.optimizer.AdamW( learning_rate=lr_scheduler, epsilon=args.adam_epsilon, parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda x: x in decay_params) criterion = CrossEntropyLossForSQuAD()", "in decay_params) criterion = CrossEntropyLossForSQuAD() global_step = 0 tic_train = time.time() for epoch", "ensure_ascii=False, indent=4) + \"\\n\") squad_evaluate( examples=data_loader.dataset.data, preds=all_predictions, is_whitespace_splited=False) model.train() class CrossEntropyLossForSQuAD(paddle.nn.Layer): def __init__(self):", "is the index of the example containing this span of text. sample_index =", "the answer in the text. start_char = answer_starts[0] end_char = start_char + len(answers[0])", "to perform weight decay. # All bias and LayerNorm parameters are excluded. decay_params", "us a map from token to character position in the original context. This", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "for nd in [\"bias\", \"norm\"]) ] optimizer = paddle.optimizer.AdamW( learning_rate=lr_scheduler, epsilon=args.adam_epsilon, parameters=model.parameters(), weight_decay=args.weight_decay,", "can give several spans, this is the index of the example containing this", "Can also write all_nbest_json and scores_diff_json files if needed with open('prediction.json', \"w\", encoding='utf-8')", "model.eval() all_start_logits = [] all_end_logits = [] tic_eval = time.time() for batch in", "that example (to know what is the context and what is the question).", "= tokenized_example['overflow_to_sample'] answers = examples[sample_index]['answers'] answer_starts = examples[sample_index]['answer_starts'] # Start/end character index of", "if paddle.distributed.get_world_size() > 1: paddle.distributed.init_parallel_env() rank = paddle.distributed.get_rank() task_name = args.task_name.lower() args.model_type =", "range(start_logits_tensor.shape[0]): if len(all_start_logits) % 1000 == 0 and len(all_start_logits): print(\"Processing example: %d\" %", "if args.train_file: train_ds = load_dataset(task_name, data_files=args.train_file) else: train_ds = load_dataset(task_name, splits='train') train_ds.map(prepare_train_features, batched=True)", "current span in the text. token_end_index = len(input_ids) - 1 while sequence_ids[token_end_index] !=", "= model( input_ids=input_ids, token_type_ids=token_type_ids) loss = criterion(logits, (start_positions, end_positions)) if global_step % args.logging_steps", "epoch in range(num_train_epochs): for step, batch in enumerate(train_data_loader): global_step += 1 input_ids, token_type_ids,", "and what is the question). sequence_ids = tokenized_example['token_type_ids'] # One example can give", "time.time() all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions, _, _ = compute_prediction( data_loader.dataset.data, data_loader.dataset.new_data, (all_start_logits, all_end_logits), False,", "rank == 0: if os.path.exists(args.model_name_or_path): print(\"init checkpoint from %s\" % args.model_name_or_path) model =", "a context is long, each of those features having a # context that", "= tokenized_example['offset_mapping'] # Grab the sequence corresponding to that example (to know what", "model.train() class CrossEntropyLossForSQuAD(paddle.nn.Layer): def __init__(self): super(CrossEntropyLossForSQuAD, self).__init__() def forward(self, y, label): start_logits, end_logits", "out of the span (in which case this feature is labeled with the", "x in decay_params) criterion = CrossEntropyLossForSQuAD() global_step = 0 tic_train = time.time() for", "model_to_save = model._layers if isinstance( model, paddle.DataParallel) else model model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) print('Saving checkpoint", "last offset if the answer is the last word (edge case). while token_start_index", "end_positions. offsets = tokenized_example['offset_mapping'] # Grab the sequence corresponding to that example (to", "position in the original context. This will # help us compute the start_positions", "dictionary instead. contexts = [examples[i]['context'] for i in range(len(examples))] questions = [examples[i]['question'] for", "case this feature is labeled with the CLS index). if not (offsets[token_start_index][0] <=", "Tokenize our examples with truncation and maybe padding, but keep the overflows using", "in the original context. This will # help us compute the start_positions and", "(offsets[token_start_index][0] <= start_char and offsets[token_end_index][1] >= end_char): tokenized_examples[i][\"start_positions\"] = cls_index tokenized_examples[i][\"end_positions\"] = cls_index", "tic_train = time.time() loss.backward() optimizer.step() lr_scheduler.step() optimizer.clear_grad() if global_step % args.save_steps == 0", "args.model_name_or_path) model = model_class.from_pretrained(args.model_name_or_path) if paddle.distributed.get_world_size() > 1: model = paddle.DataParallel(model) def prepare_train_features(examples):", "args.do_train: if args.train_file: train_ds = load_dataset(task_name, data_files=args.train_file) else: train_ds = load_dataset(task_name, splits='train') train_ds.map(prepare_train_features,", "part of the context or not. tokenized_examples[i][\"offset_mapping\"] = [ (o if sequence_ids[k] ==", "DataLoader( dataset=dev_ds, batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn, return_list=True) evaluate(model, dev_data_loader, args) if __name__ == \"__main__\": args", "# in one example possible giving several features when a context is long,", "in range(len(examples))] tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # Let's label those", "# Generate parameter names needed to perform weight decay. # All bias and", "ErnieGramTokenizer), \"roberta\": (RobertaForQuestionAnswering, RobertaTokenizer) } def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed) @paddle.no_grad() def evaluate(model,", "CLS token. input_ids = tokenized_example[\"input_ids\"] cls_index = input_ids.index(tokenizer.cls_token_id) # The offset mappings will", "the answer. # Note: we could go after the last offset if the", "squad_evaluate( examples=data_loader.dataset.data, preds=all_predictions, is_whitespace_splited=False) model.train() class CrossEntropyLossForSQuAD(paddle.nn.Layer): def __init__(self): super(CrossEntropyLossForSQuAD, self).__init__() def forward(self,", "compute_prediction from paddlenlp.datasets import load_dataset MODEL_CLASSES = { \"bert\": (BertForQuestionAnswering, BertTokenizer), \"ernie\": (ErnieForQuestionAnswering,", "in compliance with the License. # You may obtain a copy of the", "0: if args.predict_file: dev_ds = load_dataset(task_name, data_files=args.predict_file) else: dev_ds = load_dataset(task_name, splits='dev') dev_ds.map(prepare_validation_features,", "len(train_data_loader)) lr_scheduler = LinearDecayWithWarmup( args.learning_rate, num_training_steps, args.warmup_proportion) # Generate parameter names needed to", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "= time.time() for epoch in range(num_train_epochs): for step, batch in enumerate(train_data_loader): global_step +=", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "LayerNorm parameters are excluded. decay_params = [ p.name for n, p in model.named_parameters()", "help us compute the start_positions and end_positions. offsets = tokenized_example['offset_mapping'] # Grab the", "what is the context and what is the question). sequence_ids = tokenized_example['token_type_ids'] #", "writer.write( json.dumps( all_predictions, ensure_ascii=False, indent=4) + \"\\n\") squad_evaluate( examples=data_loader.dataset.data, preds=all_predictions, is_whitespace_splited=False) model.train() class", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "1 tokenized_examples[i][\"end_positions\"] = token_end_index + 1 return tokenized_examples if args.do_train: if args.train_file: train_ds", "criterion = CrossEntropyLossForSQuAD() global_step = 0 tic_train = time.time() for epoch in range(num_train_epochs):", "paddlenlp.transformers import ErnieForQuestionAnswering, ErnieTokenizer from paddlenlp.transformers import ErnieGramForQuestionAnswering, ErnieGramTokenizer from paddlenlp.transformers import RobertaForQuestionAnswering,", "# Set to None the offset_mapping that are not part of the context", "HuggingFace's prepare_train_features function. The main difference is # that HugggingFace uses ArrowTable as", "and end positions for i, tokenized_example in enumerate(tokenized_examples): # Grab the sequence corresponding", "os.path.join(args.output_dir, \"model_%d\" % global_step) if not os.path.exists(output_dir): os.makedirs(output_dir) # need better way to", "RobertaTokenizer) } def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed) @paddle.no_grad() def evaluate(model, data_loader, args): model.eval()", "1 else None) for k, o in enumerate(tokenized_example[\"offset_mapping\"]) ] return tokenized_examples if args.do_predict", "end_char): tokenized_examples[i][\"start_positions\"] = cls_index tokenized_examples[i][\"end_positions\"] = cls_index else: # Otherwise move the token_start_index", "token index of the current span in the text. token_end_index = len(input_ids) -", "the answer is the last word (edge case). while token_start_index < len(offsets) and", "ErnieTokenizer), \"ernie_gram\": (ErnieGramForQuestionAnswering, ErnieGramTokenizer), \"roberta\": (RobertaForQuestionAnswering, RobertaTokenizer) } def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed)", "end_loss) / 2 return loss def run(args): paddle.set_device(args.device) if paddle.distributed.get_world_size() > 1: paddle.distributed.init_parallel_env()", "prepare_train_features function. The main difference is # that HugggingFace uses ArrowTable as basic", "needed with open('prediction.json', \"w\", encoding='utf-8') as writer: writer.write( json.dumps( all_predictions, ensure_ascii=False, indent=4) +", "See the License for the specific language governing permissions and # limitations under", "paddle.DataParallel) else model model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) print('Saving checkpoint to:', output_dir) if global_step == num_training_steps:", "= load_dataset(task_name, splits='dev') dev_ds.map(prepare_validation_features, batched=True) dev_batch_sampler = paddle.io.BatchSampler( dev_ds, batch_size=args.batch_size, shuffle=False) dev_batchify_fn =", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "y start_position, end_position = label start_position = paddle.unsqueeze(start_position, axis=-1) end_position = paddle.unsqueeze(end_position, axis=-1)", "character position in the original context. This will # help us compute the", "offsets[token_end_index][1] >= end_char: token_end_index -= 1 tokenized_examples[i][\"end_positions\"] = token_end_index + 1 return tokenized_examples", "DataParallel model_to_save = model._layers if isinstance( model, paddle.DataParallel) else model model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) print('Saving", "start_loss = paddle.nn.functional.cross_entropy( input=start_logits, label=start_position) end_loss = paddle.nn.functional.cross_entropy( input=end_logits, label=end_position) loss = (start_loss", "return tokenized_examples if args.do_predict and rank == 0: if args.predict_file: dev_ds = load_dataset(task_name,", "ErnieTokenizer from paddlenlp.transformers import ErnieGramForQuestionAnswering, ErnieGramTokenizer from paddlenlp.transformers import RobertaForQuestionAnswering, RobertaTokenizer from paddlenlp.transformers", "\"global step %d, epoch: %d, batch: %d, loss: %f, speed: %.2f step/s\" %", "train_data_loader = DataLoader( dataset=train_ds, batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn, return_list=True) num_training_steps = args.max_steps if args.max_steps >", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "model of DataParallel model_to_save = model._layers if isinstance( model, paddle.DataParallel) else model model_to_save.save_pretrained(output_dir)", "stride=args.doc_stride, max_seq_len=args.max_seq_length) # For validation, there is no need to compute start and", "from %s\" % args.model_name_or_path) model = model_class.from_pretrained(args.model_name_or_path) if paddle.distributed.get_world_size() > 1: model =", "and # limitations under the License. import os import random import time import", "a bit the context of the previous feature. # NOTE: Almost the same", "= cls_index tokenized_examples[i][\"end_positions\"] = cls_index else: # Otherwise move the token_start_index and token_end_index", "answer. # Note: we could go after the last offset if the answer", "This will # help us compute the start_positions and end_positions. offsets = tokenized_example['offset_mapping']", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "end positions for i, tokenized_example in enumerate(tokenized_examples): # Grab the sequence corresponding to", "import BertForQuestionAnswering, BertTokenizer from paddlenlp.transformers import ErnieForQuestionAnswering, ErnieTokenizer from paddlenlp.transformers import ErnieGramForQuestionAnswering, ErnieGramTokenizer", "compute_prediction( data_loader.dataset.data, data_loader.dataset.new_data, (all_start_logits, all_end_logits), False, args.n_best_size, args.max_answer_length) # Can also write all_nbest_json", "features when a context is long, each of those features having a #", "while sequence_ids[token_start_index] != 1: token_start_index += 1 # End token index of the", "as HuggingFace's prepare_train_features function. The main difference is # that HugggingFace uses ArrowTable", "if isinstance( model, paddle.DataParallel) else model model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) print('Saving checkpoint to:', output_dir) if", "load_dataset(task_name, data_files=args.train_file) else: train_ds = load_dataset(task_name, splits='train') train_ds.map(prepare_train_features, batched=True) train_batch_sampler = paddle.io.DistributedBatchSampler( train_ds,", "1000:', time.time() - tic_eval) tic_eval = time.time() all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions, _, _ =", "if args.do_predict and rank == 0: if args.predict_file: dev_ds = load_dataset(task_name, data_files=args.predict_file) else:", "+ len(answers[0]) # Start token index of the current span in the text.", "(BertForQuestionAnswering, BertTokenizer), \"ernie\": (ErnieForQuestionAnswering, ErnieTokenizer), \"ernie_gram\": (ErnieGramForQuestionAnswering, ErnieGramTokenizer), \"roberta\": (RobertaForQuestionAnswering, RobertaTokenizer) } def", "+ 1 return tokenized_examples if args.do_train: if args.train_file: train_ds = load_dataset(task_name, data_files=args.train_file) else:", "time.time() loss.backward() optimizer.step() lr_scheduler.step() optimizer.clear_grad() if global_step % args.save_steps == 0 or global_step", "loss.backward() optimizer.step() lr_scheduler.step() optimizer.clear_grad() if global_step % args.save_steps == 0 or global_step ==", "PaddlePaddle Authors. All Rights Reserved. # Copyright 2018 The HuggingFace Inc. team. #", "Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # Copyright 2018 The HuggingFace", "token_start_index - 1 while offsets[token_end_index][1] >= end_char: token_end_index -= 1 tokenized_examples[i][\"end_positions\"] = token_end_index", "!= 1: token_end_index -= 1 # Minus one more to reach actual text", "= paddle.io.BatchSampler( dev_ds, batch_size=args.batch_size, shuffle=False) dev_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id),", "feature. # NOTE: Almost the same functionality as HuggingFace's prepare_train_features function. The main", "corresponding to that example (to know what is the context and what is", "index of the answer in the text. start_char = answer_starts[0] end_char = start_char", "return tokenized_examples if args.do_train: if args.train_file: train_ds = load_dataset(task_name, data_files=args.train_file) else: train_ds =", "== num_training_steps: break def prepare_validation_features(examples): # Tokenize our examples with truncation and maybe", "+= 1 input_ids, token_type_ids, start_positions, end_positions = batch logits = model( input_ids=input_ids, token_type_ids=token_type_ids)", "names needed to perform weight decay. # All bias and LayerNorm parameters are", "p.name for n, p in model.named_parameters() if not any(nd in n for nd", "map from token to character position in the original context. This will #", "token_type_ids) for idx in range(start_logits_tensor.shape[0]): if len(all_start_logits) % 1000 == 0 and len(all_start_logits):", "= tokenized_example[\"input_ids\"] cls_index = input_ids.index(tokenizer.cls_token_id) # The offset mappings will give us a", "the two ends of the answer. # Note: we could go after the", "= input_ids.index(tokenizer.cls_token_id) # The offset mappings will give us a map from token", "current span in the text. token_start_index = 0 while sequence_ids[token_start_index] != 1: token_start_index", "Otherwise move the token_start_index and token_end_index to the two ends of the answer.", "the last offset if the answer is the last word (edge case). while", "args): model.eval() all_start_logits = [] all_end_logits = [] tic_eval = time.time() for batch", "import numpy as np import paddle from paddle.io import DataLoader from args import", "get inner model of DataParallel model_to_save = model._layers if isinstance( model, paddle.DataParallel) else", "The main difference is # that HugggingFace uses ArrowTable as basic data structure,", "end_position = paddle.unsqueeze(end_position, axis=-1) start_loss = paddle.nn.functional.cross_entropy( input=start_logits, label=start_position) end_loss = paddle.nn.functional.cross_entropy( input=end_logits,", "= math.ceil(num_training_steps / len(train_data_loader)) lr_scheduler = LinearDecayWithWarmup( args.learning_rate, num_training_steps, args.warmup_proportion) # Generate parameter", "= time.time() loss.backward() optimizer.step() lr_scheduler.step() optimizer.clear_grad() if global_step % args.save_steps == 0 or", "Version 2.0 (the \"License\"); # you may not use this file except in", "= os.path.join(args.output_dir, \"model_%d\" % global_step) if not os.path.exists(output_dir): os.makedirs(output_dir) # need better way", "except in compliance with the License. # You may obtain a copy of", "1 while sequence_ids[token_end_index] != 1: token_end_index -= 1 # Minus one more to", "overlaps a bit the context of the previous feature. # NOTE: Almost the", "data_files=args.train_file) else: train_ds = load_dataset(task_name, splits='train') train_ds.map(prepare_train_features, batched=True) train_batch_sampler = paddle.io.DistributedBatchSampler( train_ds, batch_size=args.batch_size,", "samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id), \"start_positions\": Stack(dtype=\"int64\"), \"end_positions\": Stack(dtype=\"int64\") }):", "in data_loader: input_ids, token_type_ids = batch start_logits_tensor, end_logits_tensor = model(input_ids, token_type_ids) for idx", "1 # Detect if the answer is out of the span (in which", "text token_end_index -= 1 # Detect if the answer is out of the", "permissions and # limitations under the License. import os import random import time", "+ 1, loss, args.logging_steps / (time.time() - tic_train))) tic_train = time.time() loss.backward() optimizer.step()", "apply_decay_param_fun=lambda x: x in decay_params) criterion = CrossEntropyLossForSQuAD() global_step = 0 tic_train =", "impossible answers with the index of the CLS token. input_ids = tokenized_example[\"input_ids\"] cls_index", "# End token index of the current span in the text. token_end_index =", "= 0 while sequence_ids[token_start_index] != 1: token_start_index += 1 # End token index", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "= DataLoader( dataset=train_ds, batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn, return_list=True) num_training_steps = args.max_steps if args.max_steps > 0", "+ end_loss) / 2 return loss def run(args): paddle.set_device(args.device) if paddle.distributed.get_world_size() > 1:", "% args.model_name_or_path) model = model_class.from_pretrained(args.model_name_or_path) if paddle.distributed.get_world_size() > 1: model = paddle.DataParallel(model) def", "if the answer is out of the span (in which case this feature", "dataset=train_ds, batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn, return_list=True) num_training_steps = args.max_steps if args.max_steps > 0 else len(", "tokenizer_class = MODEL_CLASSES[args.model_type] tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args) if rank == 0: if os.path.exists(args.model_name_or_path):", "print( \"global step %d, epoch: %d, batch: %d, loss: %f, speed: %.2f step/s\"", "= model._layers if isinstance( model, paddle.DataParallel) else model model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) print('Saving checkpoint to:',", "# Note: we could go after the last offset if the answer is", "with open('prediction.json', \"w\", encoding='utf-8') as writer: writer.write( json.dumps( all_predictions, ensure_ascii=False, indent=4) + \"\\n\")", "== 0: print( \"global step %d, epoch: %d, batch: %d, loss: %f, speed:", "= cls_index else: # Otherwise move the token_start_index and token_end_index to the two", "We will label impossible answers with the index of the CLS token. input_ids", "token to character position in the original context. This will # help us", "token_type_ids = batch start_logits_tensor, end_logits_tensor = model(input_ids, token_type_ids) for idx in range(start_logits_tensor.shape[0]): if", "context and what is the question). sequence_ids = tokenized_example['token_type_ids'] # One example can", "= batch start_logits_tensor, end_logits_tensor = model(input_ids, token_type_ids) for idx in range(start_logits_tensor.shape[0]): if len(all_start_logits)", "last word (edge case). while token_start_index < len(offsets) and offsets[ token_start_index][0] <= start_char:", "Stack, Tuple, Dict from paddlenlp.transformers import BertForQuestionAnswering, BertTokenizer from paddlenlp.transformers import ErnieForQuestionAnswering, ErnieTokenizer", "examples[sample_index]['answers'] answer_starts = examples[sample_index]['answer_starts'] # Start/end character index of the answer in the", "evaluate(model, data_loader, args): model.eval() all_start_logits = [] all_end_logits = [] tic_eval = time.time()", "a token # position is part of the context or not. tokenized_examples[i][\"offset_mapping\"] =", "1000 == 0 and len(all_start_logits): print(\"Processing example: %d\" % len(all_start_logits)) print('time per 1000:',", "time.time() for epoch in range(num_train_epochs): for step, batch in enumerate(train_data_loader): global_step += 1", "% 1000 == 0 and len(all_start_logits): print(\"Processing example: %d\" % len(all_start_logits)) print('time per", "paddle.distributed.get_world_size() > 1: paddle.distributed.init_parallel_env() rank = paddle.distributed.get_rank() task_name = args.task_name.lower() args.model_type = args.model_type.lower()", "% global_step) if not os.path.exists(output_dir): os.makedirs(output_dir) # need better way to get inner", "start_logits, end_logits = y start_position, end_position = label start_position = paddle.unsqueeze(start_position, axis=-1) end_position", "dev_ds, batch_size=args.batch_size, shuffle=False) dev_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0,", "/ (time.time() - tic_train))) tic_train = time.time() loss.backward() optimizer.step() lr_scheduler.step() optimizer.clear_grad() if global_step", "%f, speed: %.2f step/s\" % (global_step, epoch + 1, step + 1, loss,", "= lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id) }): fn(samples) dev_data_loader", "several spans, this is the index of the example containing this span of", "args.task_name.lower() args.model_type = args.model_type.lower() model_class, tokenizer_class = MODEL_CLASSES[args.model_type] tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args) if", "contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # For validation, there is no need to compute start", "dataset=dev_ds, batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn, return_list=True) evaluate(model, dev_data_loader, args) if __name__ == \"__main__\": args =", "# that HugggingFace uses ArrowTable as basic data structure, while we use list", "math.ceil(num_training_steps / len(train_data_loader)) lr_scheduler = LinearDecayWithWarmup( args.learning_rate, num_training_steps, args.warmup_proportion) # Generate parameter names", "enumerate(tokenized_examples): # Grab the sequence corresponding to that example (to know what is", "= 0 tic_train = time.time() for epoch in range(num_train_epochs): for step, batch in", "= [ (o if sequence_ids[k] == 1 else None) for k, o in", "print('Saving checkpoint to:', output_dir) if global_step == num_training_steps: break def prepare_validation_features(examples): # Tokenize", "random import time import json import math from functools import partial import numpy", "of the current span in the text. token_start_index = 0 while sequence_ids[token_start_index] !=", "= lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id), \"start_positions\": Stack(dtype=\"int64\"), \"end_positions\":", "\"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id) }): fn(samples) dev_data_loader = DataLoader( dataset=dev_ds, batch_sampler=dev_batch_sampler,", "for n, p in model.named_parameters() if not any(nd in n for nd in", "= CrossEntropyLossForSQuAD() global_step = 0 tic_train = time.time() for epoch in range(num_train_epochs): for", "This results # in one example possible giving several features when a context", "Dict from paddlenlp.transformers import BertForQuestionAnswering, BertTokenizer from paddlenlp.transformers import ErnieForQuestionAnswering, ErnieTokenizer from paddlenlp.transformers", "the context of the previous feature. # NOTE: Almost the same functionality as", "the previous feature. # NOTE: Almost the same functionality as HuggingFace's prepare_train_features function.", "Almost the same functionality as HuggingFace's prepare_train_features function. The main difference is #", "i in range(len(examples))] tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # Let's label", "paddlenlp.transformers import ErnieGramForQuestionAnswering, ErnieGramTokenizer from paddlenlp.transformers import RobertaForQuestionAnswering, RobertaTokenizer from paddlenlp.transformers import LinearDecayWithWarmup", "dev_data_loader = DataLoader( dataset=dev_ds, batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn, return_list=True) evaluate(model, dev_data_loader, args) if __name__ ==", "model_class.from_pretrained(args.model_name_or_path) if paddle.distributed.get_world_size() > 1: model = paddle.DataParallel(model) def prepare_train_features(examples): # Tokenize our", "not part of the context so it's easy to determine if a token", "tokenized_examples[i][\"end_positions\"] = cls_index else: # Otherwise move the token_start_index and token_end_index to the", "[] all_end_logits = [] tic_eval = time.time() for batch in data_loader: input_ids, token_type_ids", "= answer_starts[0] end_char = start_char + len(answers[0]) # Start token index of the", "import random import time import json import math from functools import partial import", "in [\"bias\", \"norm\"]) ] optimizer = paddle.optimizer.AdamW( learning_rate=lr_scheduler, epsilon=args.adam_epsilon, parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda x:", "for step, batch in enumerate(train_data_loader): global_step += 1 input_ids, token_type_ids, start_positions, end_positions =", "json.dumps( all_predictions, ensure_ascii=False, indent=4) + \"\\n\") squad_evaluate( examples=data_loader.dataset.data, preds=all_predictions, is_whitespace_splited=False) model.train() class CrossEntropyLossForSQuAD(paddle.nn.Layer):", "args.model_type = args.model_type.lower() model_class, tokenizer_class = MODEL_CLASSES[args.model_type] tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args) if rank", "compute start and end positions for i, tokenized_example in enumerate(tokenized_examples): # Grab the", "limitations under the License. import os import random import time import json import", "to determine if a token # position is part of the context or", "indent=4) + \"\\n\") squad_evaluate( examples=data_loader.dataset.data, preds=all_predictions, is_whitespace_splited=False) model.train() class CrossEntropyLossForSQuAD(paddle.nn.Layer): def __init__(self): super(CrossEntropyLossForSQuAD,", "fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id) }): fn(samples) dev_data_loader = DataLoader( dataset=dev_ds,", "easy to determine if a token # position is part of the context", "tokenized_examples[i][\"end_positions\"] = token_end_index + 1 return tokenized_examples if args.do_train: if args.train_file: train_ds =", "paddlenlp.transformers import BertForQuestionAnswering, BertTokenizer from paddlenlp.transformers import ErnieForQuestionAnswering, ErnieTokenizer from paddlenlp.transformers import ErnieGramForQuestionAnswering,", "0: print( \"global step %d, epoch: %d, batch: %d, loss: %f, speed: %.2f", "global_step == num_training_steps: if rank == 0: output_dir = os.path.join(args.output_dir, \"model_%d\" % global_step)", "questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # Let's label those examples! for i, tokenized_example in", "paddle.DataParallel(model) def prepare_train_features(examples): # Tokenize our examples with truncation and maybe padding, but", "DataLoader from args import parse_args import paddlenlp as ppnlp from paddlenlp.data import Pad,", "< len(offsets) and offsets[ token_start_index][0] <= start_char: token_start_index += 1 tokenized_examples[i][\"start_positions\"] = token_start_index", "End token index of the current span in the text. token_end_index = len(input_ids)", "HugggingFace uses ArrowTable as basic data structure, while we use list of dictionary", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "0 and len(all_start_logits): print(\"Processing example: %d\" % len(all_start_logits)) print('time per 1000:', time.time() -", "set_seed(args) if rank == 0: if os.path.exists(args.model_name_or_path): print(\"init checkpoint from %s\" % args.model_name_or_path)", "but keep the overflows using a stride. This results # in one example", "Pad(axis=0, pad_val=tokenizer.pad_token_type_id) }): fn(samples) dev_data_loader = DataLoader( dataset=dev_ds, batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn, return_list=True) evaluate(model, dev_data_loader,", "= tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # Let's label those examples! for i,", "all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions, _, _ = compute_prediction( data_loader.dataset.data, data_loader.dataset.new_data, (all_start_logits, all_end_logits), False, args.n_best_size,", "data_files=args.predict_file) else: dev_ds = load_dataset(task_name, splits='dev') dev_ds.map(prepare_validation_features, batched=True) dev_batch_sampler = paddle.io.BatchSampler( dev_ds, batch_size=args.batch_size,", "partial import numpy as np import paddle from paddle.io import DataLoader from args", "i, tokenized_example in enumerate(tokenized_examples): # Grab the sequence corresponding to that example (to", "# For validation, there is no need to compute start and end positions", "> 0 else len( train_data_loader) * args.num_train_epochs num_train_epochs = math.ceil(num_training_steps / len(train_data_loader)) lr_scheduler", "those features having a # context that overlaps a bit the context of", "model, paddle.DataParallel) else model model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) print('Saving checkpoint to:', output_dir) if global_step ==", "\"\\n\") squad_evaluate( examples=data_loader.dataset.data, preds=all_predictions, is_whitespace_splited=False) model.train() class CrossEntropyLossForSQuAD(paddle.nn.Layer): def __init__(self): super(CrossEntropyLossForSQuAD, self).__init__() def" ]
[ "# env.render() # # # Update Q table with new knowledge # Q[s,", "--> Identity s: s + 1: [[1. 0. 0. 0. 0. 0. 0.", "Q = np.zeros([env.observation_space.n, env.action_space.n]) # # # List of reward and steps per", "greedy # print(\"s = \", s,\" --> Identity s:s+1: \", np.identity(env.observation_space.n)[s:s+1]) # s", "tf.reset_default_graph() # Feature vector for current state representation input1 = tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32)", "+ lr * (r + y * np.max(Q[s1, :]) - Q[s, a]) #", "Credit to https://medium.com/emergent-future/simple-reinforcement-learning-with-tensorflow-part-0-q-learning-with-tables-and-neural-networks-d195264329d0 import gym import tensorflow as tf import numpy as np", "as tf import numpy as np import matplotlib.pyplot as plt env = gym.make('FrozenLake-v0')", "at a state predict = tf.argmax(Qout, axis=1) # Feature vector for next state", "0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]] #", "the noise, it is epsilon-greedy with epsilon decreasing over time # a =", "+= r # s = s1 # if d: # break # rList.append(rAll)", "Q value a, allQ = sess.run([predict, Qout], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]}) if np.random.rand(1) < e:", "plt.show() plt.figure() plt.plot(jList, label=\"Steps - Q Learning\") plt.show() # ------------------------------------------------------------------------- # TABULAR IMPLEMENTATION", "np.argmax(Q[s, :] + np.random.rand(1, env.action_space.n)*(1./(i + 1))) # s1, r, d, _ =", "# j = 0 # while j < 99: # j += 1", "W) # Greedy action at a state predict = tf.argmax(Qout, axis=1) # Feature", "= tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel = trainer.minimize(loss) # TRAIN THE NETWORK init = tf.global_variables_initializer() #", "as sess: sess.run(init) for i in range(number_episodes): print(\"Episode #{} is running!\".format(i)) # First", "Set learning parameters # lr = 0.8 # y = 0.95 # number_episodes", "Choose action by epsilon (e) greedy # print(\"s = \", s,\" --> Identity", "tf.reduce_sum(tf.square(Qout - nextQ)) trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel = trainer.minimize(loss) # TRAIN THE NETWORK", "0. 0. 0. 0.]] # Identity [s:s+1] is a one-hot vector # Therefore", "while j < 200: # or While not d: j += 1 #", "Weighting W vector in range 0 - 0.01 (like the way Andrew Ng", "Q1 = sess.run(Qout, feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1 = np.max(Q1) targetQ = allQ targetQ[0, a[0]]", "+ 1: [[0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.", "axis=1) # Feature vector for next state representation nextQ = tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32)", "0.1 number_episodes = 2000 # List to store total rewards and steps per", "plt.plot(rList, label=\"Return - Q Learning\") plt.show() plt.figure() plt.plot(jList, label=\"Steps - Q Learning\") plt.show()", "# Q[s, a] = Q[s, a] + lr * (r + y *", "tf.Variable(<initial-value>, name=<optional-name>) # tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None) # Weighting W vector", "the network Q1 = sess.run(Qout, feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1 = np.max(Q1) targetQ = allQ", "current state representation input1 = tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32) # tf.Variable(<initial-value>, name=<optional-name>) # tf.random_uniform(shape,", "dtype=tf.float32) # tf.Variable(<initial-value>, name=<optional-name>) # tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None) # Weighting", "updateModel = trainer.minimize(loss) # TRAIN THE NETWORK init = tf.global_variables_initializer() # Set learning", "Identity s:s+1: \", np.identity(env.observation_space.n)[s:s+1]) # s = 0 --> Identity s: s +", "env.step(a[0]) # Obtain next state Q value by feeding the new state throughout", "= 0 d = False j = 0 # Q network while j", "nextQ: targetQ}) rAll += r s = s1 if d: e = 1./((i/50)", "W vector in range 0 - 0.01 (like the way Andrew Ng did", "plt env = gym.make('FrozenLake-v0') # NEURAL NETWORK IMPLEMENTATION tf.reset_default_graph() # Feature vector for", "0. 0. 0. 0. 0.]] # s = 1 --> Identity s: s", "s = 1 --> Identity s: s + 1: [[0. 1. 0. 0.", "200: # or While not d: j += 1 # Choose action by", "tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32) # tf.Variable(<initial-value>, name=<optional-name>) # tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None)", "= np.argmax(Q[s, :] + np.random.rand(1, env.action_space.n)*(1./(i + 1))) # s1, r, d, _", "i in range(number_episodes): print(\"Episode #{} is running!\".format(i)) # First state s = env.reset()", "(number_episodes): # print(\"Episode #{} is running!\".format(i)) # s = env.reset() # rAll =", "# NEURAL NETWORK IMPLEMENTATION tf.reset_default_graph() # Feature vector for current state representation input1", "0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.", "parameters # lr = 0.8 # y = 0.95 # number_episodes = 20000", "Learning\") plt.show() plt.figure() plt.plot(jList, label=\"Steps - Q Learning\") plt.show() # ------------------------------------------------------------------------- # TABULAR", "W = tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n], 0, 0.01)) # Qout with shape [1, env.action_space.n] -", "all zeros # Q = np.zeros([env.observation_space.n, env.action_space.n]) # # # List of reward", "0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]] # Identity [s:s+1]", "with new knowledge # Q[s, a] = Q[s, a] + lr * (r", "Q Learning\") plt.show() # ------------------------------------------------------------------------- # TABULAR IMPLEMENTATION # # # Set learning", "= \", s,\" --> Identity s:s+1: \", np.identity(env.observation_space.n)[s:s+1]) # s = 0 -->", "label=\"Steps - Q Learning\") plt.show() # ------------------------------------------------------------------------- # TABULAR IMPLEMENTATION # # #", "= 20000 # # # Initial table with all zeros # Q =", "0 - 0.01 (like the way Andrew Ng did with *0.01 W =", "Choose an action by greedily (with noise) picking from Q table # #", "# Because of the noise, it is epsilon-greedy with epsilon decreasing over time", "epsilon (e) greedy # print(\"s = \", s,\" --> Identity s:s+1: \", np.identity(env.observation_space.n)[s:s+1])", "0. 0. 0. 0. 0.]] # Identity [s:s+1] is a one-hot vector #", "np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1 = np.max(Q1) targetQ = allQ targetQ[0, a[0]] = r + y", "0.]] # s = 1 --> Identity s: s + 1: [[0. 1.", "d = False j = 0 # Q network while j < 200:", "trainer.minimize(loss) # TRAIN THE NETWORK init = tf.global_variables_initializer() # Set learning parameters y", "decreasing over time # a = np.argmax(Q[s, :] + np.random.rand(1, env.action_space.n)*(1./(i + 1)))", "with epsilon decreasing over time # a = np.argmax(Q[s, :] + np.random.rand(1, env.action_space.n)*(1./(i", "# Therefore W is the actual Q value a, allQ = sess.run([predict, Qout],", "for i in range(number_episodes): print(\"Episode #{} is running!\".format(i)) # First state s =", "target and predicted Q values _, W1 = sess.run([updateModel, W], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1], nextQ:", "number_episodes = 2000 # List to store total rewards and steps per episode", "Identity s: s + 1: [[0. 1. 0. 0. 0. 0. 0. 0.", "env.action_space.n], dtype=tf.float32) # Entropy loss loss = tf.reduce_sum(tf.square(Qout - nextQ)) trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1)", "# Q = np.zeros([env.observation_space.n, env.action_space.n]) # # # List of reward and steps", "= env.reset() # rAll = 0 # d = False # j =", "0 --> Identity s: s + 1: [[1. 0. 0. 0. 0. 0.", "state s = env.reset() rAll = 0 d = False j = 0", "--> Identity s: s + 1: [[0. 1. 0. 0. 0. 0. 0.", "Identity [s:s+1] is a one-hot vector # Therefore W is the actual Q", "_, W1 = sess.run([updateModel, W], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1], nextQ: targetQ}) rAll += r s", "= env.step(a[0]) # Obtain next state Q value by feeding the new state", "W is the actual Q value a, allQ = sess.run([predict, Qout], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]})", "20000 # # # Initial table with all zeros # Q = np.zeros([env.observation_space.n,", "available at a state Qout = tf.matmul(input1, W) # Greedy action at a", "rList.append(rAll) env.close() plt.figure() plt.plot(rList, label=\"Return - Q Learning\") plt.show() plt.figure() plt.plot(jList, label=\"Steps -", "0, 0.01)) # Qout with shape [1, env.action_space.n] - Action state value for", "env.action_space.sample() s1, r, d, _ = env.step(a[0]) # Obtain next state Q value", "state value for Q[s, a] with every a available at a state Qout", "# j += 1 # # Choose an action by greedily (with noise)", "s + 1: [[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.", "# d = False # j = 0 # while j < 99:", "- Q[s, a]) # rAll += r # s = s1 # if", "tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel = trainer.minimize(loss) # TRAIN THE NETWORK init = tf.global_variables_initializer() # Set", "feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]}) if np.random.rand(1) < e: a[0] = env.action_space.sample() s1, r, d, _", "using target and predicted Q values _, W1 = sess.run([updateModel, W], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1],", "= [] # for i in range (number_episodes): # print(\"Episode #{} is running!\".format(i))", "value by feeding the new state throughout the network Q1 = sess.run(Qout, feed_dict={input1:", "s = 0 --> Identity s: s + 1: [[1. 0. 0. 0.", "0. 0. 0. 0. 0. 0. 0.]] # s = 1 --> Identity", "steps per episode jList = [] rList = [] with tf.Session() as sess:", "episode jList = [] rList = [] with tf.Session() as sess: sess.run(init) for", "vector for current state representation input1 = tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32) # tf.Variable(<initial-value>, name=<optional-name>)", "in range(number_episodes): print(\"Episode #{} is running!\".format(i)) # First state s = env.reset() rAll", "# Q network while j < 200: # or While not d: j", ":] + np.random.rand(1, env.action_space.n)*(1./(i + 1))) # s1, r, d, _ = env.step(a)", "tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n], 0, 0.01)) # Qout with shape [1, env.action_space.n] - Action state", "rList = [] with tf.Session() as sess: sess.run(init) for i in range(number_episodes): print(\"Episode", "Q[s, a] with every a available at a state Qout = tf.matmul(input1, W)", "0. 0.]] # s = 1 --> Identity s: s + 1: [[0.", "# s = 0 --> Identity s: s + 1: [[1. 0. 0.", "for next state representation nextQ = tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32) # Entropy loss loss", "# for i in range (number_episodes): # print(\"Episode #{} is running!\".format(i)) # s", "\", s,\" --> Identity s:s+1: \", np.identity(env.observation_space.n)[s:s+1]) # s = 0 --> Identity", "reward and steps per episode # rList = [] # for i in", "representation nextQ = tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32) # Entropy loss loss = tf.reduce_sum(tf.square(Qout -", "+ 10) break jList.append(j) rList.append(rAll) env.close() plt.figure() plt.plot(rList, label=\"Return - Q Learning\") plt.show()", "= 1./((i/50) + 10) break jList.append(j) rList.append(rAll) env.close() plt.figure() plt.plot(rList, label=\"Return - Q", "plt.plot(jList, label=\"Steps - Q Learning\") plt.show() # ------------------------------------------------------------------------- # TABULAR IMPLEMENTATION # #", "# Set learning parameters y = 0.99 e = 0.1 number_episodes = 2000", "Identity s: s + 1: [[1. 0. 0. 0. 0. 0. 0. 0.", "Learning\") plt.show() # ------------------------------------------------------------------------- # TABULAR IMPLEMENTATION # # # Set learning parameters", "e = 1./((i/50) + 10) break jList.append(j) rList.append(rAll) env.close() plt.figure() plt.plot(rList, label=\"Return -", "1: [[0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.", "range 0 - 0.01 (like the way Andrew Ng did with *0.01 W", "While not d: j += 1 # Choose action by epsilon (e) greedy", "range(number_episodes): print(\"Episode #{} is running!\".format(i)) # First state s = env.reset() rAll =", "0. 0. 0. 0. 0. 0. 0. 0. 0.]] # s = 1", "zeros # Q = np.zeros([env.observation_space.n, env.action_space.n]) # # # List of reward and", "(r + y * np.max(Q[s1, :]) - Q[s, a]) # rAll += r", "learning parameters y = 0.99 e = 0.1 number_episodes = 2000 # List", "= 2000 # List to store total rewards and steps per episode jList", "e: a[0] = env.action_space.sample() s1, r, d, _ = env.step(a[0]) # Obtain next", "0 # while j < 99: # j += 1 # # Choose", "a available at a state Qout = tf.matmul(input1, W) # Greedy action at", "d, _ = env.step(a[0]) # Obtain next state Q value by feeding the", "# # Set learning parameters # lr = 0.8 # y = 0.95", "Obtain next state Q value by feeding the new state throughout the network", "from Q table # # Because of the noise, it is epsilon-greedy with", "new state throughout the network Q1 = sess.run(Qout, feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1 = np.max(Q1)", "targetQ = allQ targetQ[0, a[0]] = r + y * maxQ1 # Train", "= np.max(Q1) targetQ = allQ targetQ[0, a[0]] = r + y * maxQ1", "dtype=tf.float32, seed=None, name=None) # Weighting W vector in range 0 - 0.01 (like", "= Q[s, a] + lr * (r + y * np.max(Q[s1, :]) -", "learning parameters # lr = 0.8 # y = 0.95 # number_episodes =", "Therefore W is the actual Q value a, allQ = sess.run([predict, Qout], feed_dict={input1:", "vector # Therefore W is the actual Q value a, allQ = sess.run([predict,", "Set learning parameters y = 0.99 e = 0.1 number_episodes = 2000 #", "a, allQ = sess.run([predict, Qout], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]}) if np.random.rand(1) < e: a[0] =", "= s1 if d: e = 1./((i/50) + 10) break jList.append(j) rList.append(rAll) env.close()", "= 1 --> Identity s: s + 1: [[0. 1. 0. 0. 0.", "TABULAR IMPLEMENTATION # # # Set learning parameters # lr = 0.8 #", "matplotlib.pyplot as plt env = gym.make('FrozenLake-v0') # NEURAL NETWORK IMPLEMENTATION tf.reset_default_graph() # Feature", "0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]", "name=<optional-name>) # tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None) # Weighting W vector in", "- nextQ)) trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel = trainer.minimize(loss) # TRAIN THE NETWORK init", "rList = [] # for i in range (number_episodes): # print(\"Episode #{} is", "# List of reward and steps per episode # rList = [] #", "table # # Because of the noise, it is epsilon-greedy with epsilon decreasing", "Q[s, a] = Q[s, a] + lr * (r + y * np.max(Q[s1,", "99: # j += 1 # # Choose an action by greedily (with", "False j = 0 # Q network while j < 200: # or", "Qout], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]}) if np.random.rand(1) < e: a[0] = env.action_space.sample() s1, r, d,", "steps per episode # rList = [] # for i in range (number_episodes):", "next state Q value by feeding the new state throughout the network Q1", "_ = env.step(a[0]) # Obtain next state Q value by feeding the new", "= [] with tf.Session() as sess: sess.run(init) for i in range(number_episodes): print(\"Episode #{}", "+= r s = s1 if d: e = 1./((i/50) + 10) break", ":]) - Q[s, a]) # rAll += r # s = s1 #", "# Weighting W vector in range 0 - 0.01 (like the way Andrew", "= 0.8 # y = 0.95 # number_episodes = 20000 # # #", "parameters y = 0.99 e = 0.1 number_episodes = 2000 # List to", "0. 0. 0. 0. 0. 0. 0. 0.]] # Identity [s:s+1] is a", "= 0 # while j < 99: # j += 1 # #", "s1, r, d, _ = env.step(a) # # env.render() # # # Update", "# lr = 0.8 # y = 0.95 # number_episodes = 20000 #", "s = env.reset() rAll = 0 d = False j = 0 #", "# or While not d: j += 1 # Choose action by epsilon", "#{} is running!\".format(i)) # First state s = env.reset() rAll = 0 d", "state Qout = tf.matmul(input1, W) # Greedy action at a state predict =", "s: s + 1: [[0. 1. 0. 0. 0. 0. 0. 0. 0.", "to store total rewards and steps per episode jList = [] rList =", "lr = 0.8 # y = 0.95 # number_episodes = 20000 # #", "+ np.random.rand(1, env.action_space.n)*(1./(i + 1))) # s1, r, d, _ = env.step(a) #", "store total rewards and steps per episode jList = [] rList = []", "with tf.Session() as sess: sess.run(init) for i in range(number_episodes): print(\"Episode #{} is running!\".format(i))", "Q table # # Because of the noise, it is epsilon-greedy with epsilon", "First state s = env.reset() rAll = 0 d = False j =", "env.render() # # # Update Q table with new knowledge # Q[s, a]", "a] + lr * (r + y * np.max(Q[s1, :]) - Q[s, a])", "every a available at a state Qout = tf.matmul(input1, W) # Greedy action", "0. 0. 0.]] # s = 1 --> Identity s: s + 1:", "# # Because of the noise, it is epsilon-greedy with epsilon decreasing over", "over time # a = np.argmax(Q[s, :] + np.random.rand(1, env.action_space.n)*(1./(i + 1))) #", "vector for next state representation nextQ = tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32) # Entropy loss", "is running!\".format(i)) # s = env.reset() # rAll = 0 # d =", "# print(\"Episode #{} is running!\".format(i)) # s = env.reset() # rAll = 0", "new knowledge # Q[s, a] = Q[s, a] + lr * (r +", "by feeding the new state throughout the network Q1 = sess.run(Qout, feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]})", "rAll += r s = s1 if d: e = 1./((i/50) + 10)", "+ y * maxQ1 # Train our network using target and predicted Q", "np.random.rand(1) < e: a[0] = env.action_space.sample() s1, r, d, _ = env.step(a[0]) #", "(like the way Andrew Ng did with *0.01 W = tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n], 0,", "= 0 # d = False # j = 0 # while j", "# First state s = env.reset() rAll = 0 d = False j", "a] with every a available at a state Qout = tf.matmul(input1, W) #", "not d: j += 1 # Choose action by epsilon (e) greedy #", "1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.", "0. 0.]] # Identity [s:s+1] is a one-hot vector # Therefore W is", "# Choose action by epsilon (e) greedy # print(\"s = \", s,\" -->", "j += 1 # # Choose an action by greedily (with noise) picking", "= env.reset() rAll = 0 d = False j = 0 # Q", "and steps per episode # rList = [] # for i in range", "# Update Q table with new knowledge # Q[s, a] = Q[s, a]", "did with *0.01 W = tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n], 0, 0.01)) # Qout with shape", "if np.random.rand(1) < e: a[0] = env.action_space.sample() s1, r, d, _ = env.step(a[0])", "[[1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.", "= 0.99 e = 0.1 number_episodes = 2000 # List to store total", "epsilon decreasing over time # a = np.argmax(Q[s, :] + np.random.rand(1, env.action_space.n)*(1./(i +", "\", np.identity(env.observation_space.n)[s:s+1]) # s = 0 --> Identity s: s + 1: [[1.", "way Andrew Ng did with *0.01 W = tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n], 0, 0.01)) #", "network while j < 200: # or While not d: j += 1", "# # Initial table with all zeros # Q = np.zeros([env.observation_space.n, env.action_space.n]) #", "with every a available at a state Qout = tf.matmul(input1, W) # Greedy", "Ng did with *0.01 W = tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n], 0, 0.01)) # Qout with", "of the noise, it is epsilon-greedy with epsilon decreasing over time # a", "# Feature vector for next state representation nextQ = tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32) #", "# Credit to https://medium.com/emergent-future/simple-reinforcement-learning-with-tensorflow-part-0-q-learning-with-tables-and-neural-networks-d195264329d0 import gym import tensorflow as tf import numpy as", "Andrew Ng did with *0.01 W = tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n], 0, 0.01)) # Qout", "1: [[1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.", "per episode jList = [] rList = [] with tf.Session() as sess: sess.run(init)", "representation input1 = tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32) # tf.Variable(<initial-value>, name=<optional-name>) # tf.random_uniform(shape, minval=0, maxval=None,", "# # env.render() # # # Update Q table with new knowledge #", "Q[s, a]) # rAll += r # s = s1 # if d:", "greedily (with noise) picking from Q table # # Because of the noise,", "# Train our network using target and predicted Q values _, W1 =", "init = tf.global_variables_initializer() # Set learning parameters y = 0.99 e = 0.1", "np.identity(env.observation_space.n)[s:s+1], nextQ: targetQ}) rAll += r s = s1 if d: e =", "# Set learning parameters # lr = 0.8 # y = 0.95 #", "0.01 (like the way Andrew Ng did with *0.01 W = tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n],", "False # j = 0 # while j < 99: # j +=", "= sess.run([predict, Qout], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]}) if np.random.rand(1) < e: a[0] = env.action_space.sample() s1,", "np.identity(env.observation_space.n)[s:s+1]) # s = 0 --> Identity s: s + 1: [[1. 0.", "0 # Q network while j < 200: # or While not d:", "Entropy loss loss = tf.reduce_sum(tf.square(Qout - nextQ)) trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel = trainer.minimize(loss)", "noise, it is epsilon-greedy with epsilon decreasing over time # a = np.argmax(Q[s,", "and steps per episode jList = [] rList = [] with tf.Session() as", "IMPLEMENTATION # # # Set learning parameters # lr = 0.8 # y", "print(\"Episode #{} is running!\".format(i)) # s = env.reset() # rAll = 0 #", "*0.01 W = tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n], 0, 0.01)) # Qout with shape [1, env.action_space.n]", "Qout = tf.matmul(input1, W) # Greedy action at a state predict = tf.argmax(Qout,", "import matplotlib.pyplot as plt env = gym.make('FrozenLake-v0') # NEURAL NETWORK IMPLEMENTATION tf.reset_default_graph() #", "= False j = 0 # Q network while j < 200: #", "e = 0.1 number_episodes = 2000 # List to store total rewards and", "r, d, _ = env.step(a[0]) # Obtain next state Q value by feeding", "is the actual Q value a, allQ = sess.run([predict, Qout], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]}) if", "------------------------------------------------------------------------- # TABULAR IMPLEMENTATION # # # Set learning parameters # lr =", "tf.Session() as sess: sess.run(init) for i in range(number_episodes): print(\"Episode #{} is running!\".format(i)) #", "knowledge # Q[s, a] = Q[s, a] + lr * (r + y", "https://medium.com/emergent-future/simple-reinforcement-learning-with-tensorflow-part-0-q-learning-with-tables-and-neural-networks-d195264329d0 import gym import tensorflow as tf import numpy as np import matplotlib.pyplot", "# # Update Q table with new knowledge # Q[s, a] = Q[s,", "np.zeros([env.observation_space.n, env.action_space.n]) # # # List of reward and steps per episode #", "maxQ1 = np.max(Q1) targetQ = allQ targetQ[0, a[0]] = r + y *", "[] with tf.Session() as sess: sess.run(init) for i in range(number_episodes): print(\"Episode #{} is", "1 # Choose action by epsilon (e) greedy # print(\"s = \", s,\"", "< e: a[0] = env.action_space.sample() s1, r, d, _ = env.step(a[0]) # Obtain", "the way Andrew Ng did with *0.01 W = tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n], 0, 0.01))", "maxQ1 # Train our network using target and predicted Q values _, W1", "s + 1: [[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.", "* maxQ1 # Train our network using target and predicted Q values _,", "to https://medium.com/emergent-future/simple-reinforcement-learning-with-tensorflow-part-0-q-learning-with-tables-and-neural-networks-d195264329d0 import gym import tensorflow as tf import numpy as np import", "feeding the new state throughout the network Q1 = sess.run(Qout, feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1", "range (number_episodes): # print(\"Episode #{} is running!\".format(i)) # s = env.reset() # rAll", "the new state throughout the network Q1 = sess.run(Qout, feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1 =", "[[0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.", "epsilon-greedy with epsilon decreasing over time # a = np.argmax(Q[s, :] + np.random.rand(1,", "- Q Learning\") plt.show() # ------------------------------------------------------------------------- # TABULAR IMPLEMENTATION # # # Set", "trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel = trainer.minimize(loss) # TRAIN THE NETWORK init = tf.global_variables_initializer()", "Q value by feeding the new state throughout the network Q1 = sess.run(Qout,", "rAll += r # s = s1 # if d: # break #", "a state Qout = tf.matmul(input1, W) # Greedy action at a state predict", "(with noise) picking from Q table # # Because of the noise, it", "i in range (number_episodes): # print(\"Episode #{} is running!\".format(i)) # s = env.reset()", "--> Identity s:s+1: \", np.identity(env.observation_space.n)[s:s+1]) # s = 0 --> Identity s: s", "rewards and steps per episode jList = [] rList = [] with tf.Session()", "# Greedy action at a state predict = tf.argmax(Qout, axis=1) # Feature vector", "+= 1 # Choose action by epsilon (e) greedy # print(\"s = \",", "running!\".format(i)) # s = env.reset() # rAll = 0 # d = False", "# Qout with shape [1, env.action_space.n] - Action state value for Q[s, a]", "predict = tf.argmax(Qout, axis=1) # Feature vector for next state representation nextQ =", "throughout the network Q1 = sess.run(Qout, feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1 = np.max(Q1) targetQ =", "break jList.append(j) rList.append(rAll) env.close() plt.figure() plt.plot(rList, label=\"Return - Q Learning\") plt.show() plt.figure() plt.plot(jList,", "input1 = tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32) # tf.Variable(<initial-value>, name=<optional-name>) # tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32,", "Q Learning\") plt.show() plt.figure() plt.plot(jList, label=\"Steps - Q Learning\") plt.show() # ------------------------------------------------------------------------- #", "# TABULAR IMPLEMENTATION # # # Set learning parameters # lr = 0.8", "as plt env = gym.make('FrozenLake-v0') # NEURAL NETWORK IMPLEMENTATION tf.reset_default_graph() # Feature vector", "or While not d: j += 1 # Choose action by epsilon (e)", "= 0.95 # number_episodes = 20000 # # # Initial table with all", "tf.global_variables_initializer() # Set learning parameters y = 0.99 e = 0.1 number_episodes =", "with *0.01 W = tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n], 0, 0.01)) # Qout with shape [1,", "r + y * maxQ1 # Train our network using target and predicted", "state representation nextQ = tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32) # Entropy loss loss = tf.reduce_sum(tf.square(Qout", "np.max(Q[s1, :]) - Q[s, a]) # rAll += r # s = s1", "NETWORK init = tf.global_variables_initializer() # Set learning parameters y = 0.99 e =", "with shape [1, env.action_space.n] - Action state value for Q[s, a] with every", "Q[s, a] + lr * (r + y * np.max(Q[s1, :]) - Q[s,", "nextQ = tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32) # Entropy loss loss = tf.reduce_sum(tf.square(Qout - nextQ))", "0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]] # s", "a[0] = env.action_space.sample() s1, r, d, _ = env.step(a[0]) # Obtain next state", "allQ targetQ[0, a[0]] = r + y * maxQ1 # Train our network", "# # # Set learning parameters # lr = 0.8 # y =", "W], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1], nextQ: targetQ}) rAll += r s = s1 if d:", "tf.matmul(input1, W) # Greedy action at a state predict = tf.argmax(Qout, axis=1) #", "sess.run([updateModel, W], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1], nextQ: targetQ}) rAll += r s = s1 if", "y = 0.95 # number_episodes = 20000 # # # Initial table with", "j = 0 # Q network while j < 200: # or While", "< 200: # or While not d: j += 1 # Choose action", "# Identity [s:s+1] is a one-hot vector # Therefore W is the actual", "#{} is running!\".format(i)) # s = env.reset() # rAll = 0 # d", "= tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32) # Entropy loss loss = tf.reduce_sum(tf.square(Qout - nextQ)) trainer", "j += 1 # Choose action by epsilon (e) greedy # print(\"s =", "0. 0. 0. 0. 0. 0. 0. 0.]] # s = 1 -->", "d, _ = env.step(a) # # env.render() # # # Update Q table", "= r + y * maxQ1 # Train our network using target and", "state predict = tf.argmax(Qout, axis=1) # Feature vector for next state representation nextQ", "in range (number_episodes): # print(\"Episode #{} is running!\".format(i)) # s = env.reset() #", "+= 1 # # Choose an action by greedily (with noise) picking from", "1))) # s1, r, d, _ = env.step(a) # # env.render() # #", "nextQ)) trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel = trainer.minimize(loss) # TRAIN THE NETWORK init =", "sess.run(init) for i in range(number_episodes): print(\"Episode #{} is running!\".format(i)) # First state s", "Action state value for Q[s, a] with every a available at a state", "action by epsilon (e) greedy # print(\"s = \", s,\" --> Identity s:s+1:", "table with all zeros # Q = np.zeros([env.observation_space.n, env.action_space.n]) # # # List", "# tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None) # Weighting W vector in range", "# # # Update Q table with new knowledge # Q[s, a] =", "Feature vector for current state representation input1 = tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32) # tf.Variable(<initial-value>,", "it is epsilon-greedy with epsilon decreasing over time # a = np.argmax(Q[s, :]", "at a state Qout = tf.matmul(input1, W) # Greedy action at a state", "# number_episodes = 20000 # # # Initial table with all zeros #", "action by greedily (with noise) picking from Q table # # Because of", "env.step(a) # # env.render() # # # Update Q table with new knowledge", "# # # List of reward and steps per episode # rList =", "# rAll = 0 # d = False # j = 0 #", "0. 0. 0. 0. 0. 0. 0.]] # Identity [s:s+1] is a one-hot", "# List to store total rewards and steps per episode jList = []", "sess.run([predict, Qout], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]}) if np.random.rand(1) < e: a[0] = env.action_space.sample() s1, r,", "- Action state value for Q[s, a] with every a available at a", "List to store total rewards and steps per episode jList = [] rList", "number_episodes = 20000 # # # Initial table with all zeros # Q", "Q values _, W1 = sess.run([updateModel, W], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1], nextQ: targetQ}) rAll +=", "if d: e = 1./((i/50) + 10) break jList.append(j) rList.append(rAll) env.close() plt.figure() plt.plot(rList,", "y * maxQ1 # Train our network using target and predicted Q values", "targetQ}) rAll += r s = s1 if d: e = 1./((i/50) +", "0.]] # Identity [s:s+1] is a one-hot vector # Therefore W is the", "= env.action_space.sample() s1, r, d, _ = env.step(a[0]) # Obtain next state Q", "r s = s1 if d: e = 1./((i/50) + 10) break jList.append(j)", "a = np.argmax(Q[s, :] + np.random.rand(1, env.action_space.n)*(1./(i + 1))) # s1, r, d,", "= np.zeros([env.observation_space.n, env.action_space.n]) # # # List of reward and steps per episode", "value for Q[s, a] with every a available at a state Qout =", "+ 1: [[1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.", "values _, W1 = sess.run([updateModel, W], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1], nextQ: targetQ}) rAll += r", "time # a = np.argmax(Q[s, :] + np.random.rand(1, env.action_space.n)*(1./(i + 1))) # s1,", "0. 0. 0.]] # Identity [s:s+1] is a one-hot vector # Therefore W", "1./((i/50) + 10) break jList.append(j) rList.append(rAll) env.close() plt.figure() plt.plot(rList, label=\"Return - Q Learning\")", "import gym import tensorflow as tf import numpy as np import matplotlib.pyplot as", "feed_dict={input1: np.identity(env.observation_space.n)[s:s+1], nextQ: targetQ}) rAll += r s = s1 if d: e", "Update Q table with new knowledge # Q[s, a] = Q[s, a] +", "# tf.Variable(<initial-value>, name=<optional-name>) # tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None) # Weighting W", "[] # for i in range (number_episodes): # print(\"Episode #{} is running!\".format(i)) #", "* np.max(Q[s1, :]) - Q[s, a]) # rAll += r # s =", "label=\"Return - Q Learning\") plt.show() plt.figure() plt.plot(jList, label=\"Steps - Q Learning\") plt.show() #", "= tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32) # tf.Variable(<initial-value>, name=<optional-name>) # tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None,", "loss = tf.reduce_sum(tf.square(Qout - nextQ)) trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel = trainer.minimize(loss) # TRAIN", "1 --> Identity s: s + 1: [[0. 1. 0. 0. 0. 0.", "state throughout the network Q1 = sess.run(Qout, feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1 = np.max(Q1) targetQ", "of reward and steps per episode # rList = [] # for i", "value a, allQ = sess.run([predict, Qout], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]}) if np.random.rand(1) < e: a[0]", "allQ = sess.run([predict, Qout], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]}) if np.random.rand(1) < e: a[0] = env.action_space.sample()", "s = s1 if d: e = 1./((i/50) + 10) break jList.append(j) rList.append(rAll)", "while j < 99: # j += 1 # # Choose an action", "import tensorflow as tf import numpy as np import matplotlib.pyplot as plt env", "- Q Learning\") plt.show() plt.figure() plt.plot(jList, label=\"Steps - Q Learning\") plt.show() # -------------------------------------------------------------------------", "= allQ targetQ[0, a[0]] = r + y * maxQ1 # Train our", "0 # d = False # j = 0 # while j <", "0. 0. 0. 0. 0. 0. 0. 0. 0.]] # Identity [s:s+1] is", "[s:s+1] is a one-hot vector # Therefore W is the actual Q value", "# # # Initial table with all zeros # Q = np.zeros([env.observation_space.n, env.action_space.n])", "j < 99: # j += 1 # # Choose an action by", "the actual Q value a, allQ = sess.run([predict, Qout], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]}) if np.random.rand(1)", "as np import matplotlib.pyplot as plt env = gym.make('FrozenLake-v0') # NEURAL NETWORK IMPLEMENTATION", "W1 = sess.run([updateModel, W], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1], nextQ: targetQ}) rAll += r s =", "import numpy as np import matplotlib.pyplot as plt env = gym.make('FrozenLake-v0') # NEURAL", "# ------------------------------------------------------------------------- # TABULAR IMPLEMENTATION # # # Set learning parameters # lr", "episode # rList = [] # for i in range (number_episodes): # print(\"Episode", "env.reset() rAll = 0 d = False j = 0 # Q network", "0.95 # number_episodes = 20000 # # # Initial table with all zeros", "env.action_space.n]) # # # List of reward and steps per episode # rList", "= 0 # Q network while j < 200: # or While not", "env.close() plt.figure() plt.plot(rList, label=\"Return - Q Learning\") plt.show() plt.figure() plt.plot(jList, label=\"Steps - Q", "0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]] # Identity", "# TRAIN THE NETWORK init = tf.global_variables_initializer() # Set learning parameters y =", "= trainer.minimize(loss) # TRAIN THE NETWORK init = tf.global_variables_initializer() # Set learning parameters", "gym.make('FrozenLake-v0') # NEURAL NETWORK IMPLEMENTATION tf.reset_default_graph() # Feature vector for current state representation", "env.observation_space.n], dtype=tf.float32) # tf.Variable(<initial-value>, name=<optional-name>) # tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None) #", "y * np.max(Q[s1, :]) - Q[s, a]) # rAll += r # s", "feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1 = np.max(Q1) targetQ = allQ targetQ[0, a[0]] = r +", "np import matplotlib.pyplot as plt env = gym.make('FrozenLake-v0') # NEURAL NETWORK IMPLEMENTATION tf.reset_default_graph()", "List of reward and steps per episode # rList = [] # for", "# while j < 99: # j += 1 # # Choose an", "actual Q value a, allQ = sess.run([predict, Qout], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]}) if np.random.rand(1) <", "NEURAL NETWORK IMPLEMENTATION tf.reset_default_graph() # Feature vector for current state representation input1 =", "np.max(Q1) targetQ = allQ targetQ[0, a[0]] = r + y * maxQ1 #", "env.action_space.n], 0, 0.01)) # Qout with shape [1, env.action_space.n] - Action state value", "plt.figure() plt.plot(jList, label=\"Steps - Q Learning\") plt.show() # ------------------------------------------------------------------------- # TABULAR IMPLEMENTATION #", "+ y * np.max(Q[s1, :]) - Q[s, a]) # rAll += r #", "targetQ[0, a[0]] = r + y * maxQ1 # Train our network using", "next state representation nextQ = tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32) # Entropy loss loss =", "tf.argmax(Qout, axis=1) # Feature vector for next state representation nextQ = tf.placeholder(shape=[1, env.action_space.n],", "# s = 1 --> Identity s: s + 1: [[0. 1. 0.", "# y = 0.95 # number_episodes = 20000 # # # Initial table", "in range 0 - 0.01 (like the way Andrew Ng did with *0.01", "s,\" --> Identity s:s+1: \", np.identity(env.observation_space.n)[s:s+1]) # s = 0 --> Identity s:", "s1, r, d, _ = env.step(a[0]) # Obtain next state Q value by", "# s = env.reset() # rAll = 0 # d = False #", "gym import tensorflow as tf import numpy as np import matplotlib.pyplot as plt", "np.identity(env.observation_space.n)[s:s+1]}) if np.random.rand(1) < e: a[0] = env.action_space.sample() s1, r, d, _ =", "rAll = 0 # d = False # j = 0 # while", "Q table with new knowledge # Q[s, a] = Q[s, a] + lr", "for current state representation input1 = tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32) # tf.Variable(<initial-value>, name=<optional-name>) #", "jList = [] rList = [] with tf.Session() as sess: sess.run(init) for i", "0 d = False j = 0 # Q network while j <", "for i in range (number_episodes): # print(\"Episode #{} is running!\".format(i)) # s =", "maxval=None, dtype=tf.float32, seed=None, name=None) # Weighting W vector in range 0 - 0.01", "0.99 e = 0.1 number_episodes = 2000 # List to store total rewards", "# rAll += r # s = s1 # if d: # break", "y = 0.99 e = 0.1 number_episodes = 2000 # List to store", "d: e = 1./((i/50) + 10) break jList.append(j) rList.append(rAll) env.close() plt.figure() plt.plot(rList, label=\"Return", "IMPLEMENTATION tf.reset_default_graph() # Feature vector for current state representation input1 = tf.placeholder(shape=[1, env.observation_space.n],", "= 0.1 number_episodes = 2000 # List to store total rewards and steps", "Greedy action at a state predict = tf.argmax(Qout, axis=1) # Feature vector for", "0. 0. 0. 0. 0. 0.]] # Identity [s:s+1] is a one-hot vector", "plt.figure() plt.plot(rList, label=\"Return - Q Learning\") plt.show() plt.figure() plt.plot(jList, label=\"Steps - Q Learning\")", "d: j += 1 # Choose action by epsilon (e) greedy # print(\"s", "NETWORK IMPLEMENTATION tf.reset_default_graph() # Feature vector for current state representation input1 = tf.placeholder(shape=[1,", "total rewards and steps per episode jList = [] rList = [] with", "env.action_space.n)*(1./(i + 1))) # s1, r, d, _ = env.step(a) # # env.render()", "* (r + y * np.max(Q[s1, :]) - Q[s, a]) # rAll +=", "a]) # rAll += r # s = s1 # if d: #", "state representation input1 = tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32) # tf.Variable(<initial-value>, name=<optional-name>) # tf.random_uniform(shape, minval=0,", "= gym.make('FrozenLake-v0') # NEURAL NETWORK IMPLEMENTATION tf.reset_default_graph() # Feature vector for current state", "- 0.01 (like the way Andrew Ng did with *0.01 W = tf.Variable(tf.random_uniform([env.observation_space.n,", "tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None) # Weighting W vector in range 0", "sess.run(Qout, feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1 = np.max(Q1) targetQ = allQ targetQ[0, a[0]] = r", "our network using target and predicted Q values _, W1 = sess.run([updateModel, W],", "is running!\".format(i)) # First state s = env.reset() rAll = 0 d =", "action at a state predict = tf.argmax(Qout, axis=1) # Feature vector for next", "# rList = [] # for i in range (number_episodes): # print(\"Episode #{}", "for Q[s, a] with every a available at a state Qout = tf.matmul(input1,", "network using target and predicted Q values _, W1 = sess.run([updateModel, W], feed_dict={input1:", "lr * (r + y * np.max(Q[s1, :]) - Q[s, a]) # rAll", "a state predict = tf.argmax(Qout, axis=1) # Feature vector for next state representation", "one-hot vector # Therefore W is the actual Q value a, allQ =", "with all zeros # Q = np.zeros([env.observation_space.n, env.action_space.n]) # # # List of", "= 0 --> Identity s: s + 1: [[1. 0. 0. 0. 0.", "name=None) # Weighting W vector in range 0 - 0.01 (like the way", "j < 200: # or While not d: j += 1 # Choose", "env.action_space.n] - Action state value for Q[s, a] with every a available at", "tf import numpy as np import matplotlib.pyplot as plt env = gym.make('FrozenLake-v0') #", "by epsilon (e) greedy # print(\"s = \", s,\" --> Identity s:s+1: \",", "a[0]] = r + y * maxQ1 # Train our network using target", "Initial table with all zeros # Q = np.zeros([env.observation_space.n, env.action_space.n]) # # #", "= sess.run([updateModel, W], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1], nextQ: targetQ}) rAll += r s = s1", "s = env.reset() # rAll = 0 # d = False # j", "Train our network using target and predicted Q values _, W1 = sess.run([updateModel,", "env.reset() # rAll = 0 # d = False # j = 0", "is epsilon-greedy with epsilon decreasing over time # a = np.argmax(Q[s, :] +", "s1 if d: e = 1./((i/50) + 10) break jList.append(j) rList.append(rAll) env.close() plt.figure()", "a one-hot vector # Therefore W is the actual Q value a, allQ", "running!\".format(i)) # First state s = env.reset() rAll = 0 d = False", "1 # # Choose an action by greedily (with noise) picking from Q", "TRAIN THE NETWORK init = tf.global_variables_initializer() # Set learning parameters y = 0.99", "= tf.reduce_sum(tf.square(Qout - nextQ)) trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel = trainer.minimize(loss) # TRAIN THE", "print(\"s = \", s,\" --> Identity s:s+1: \", np.identity(env.observation_space.n)[s:s+1]) # s = 0", "0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]] # s =", "0.01)) # Qout with shape [1, env.action_space.n] - Action state value for Q[s,", "+ 1))) # s1, r, d, _ = env.step(a) # # env.render() #", "state Q value by feeding the new state throughout the network Q1 =", "picking from Q table # # Because of the noise, it is epsilon-greedy", "noise) picking from Q table # # Because of the noise, it is", "= [] rList = [] with tf.Session() as sess: sess.run(init) for i in", "sess: sess.run(init) for i in range(number_episodes): print(\"Episode #{} is running!\".format(i)) # First state", "per episode # rList = [] # for i in range (number_episodes): #", "= env.step(a) # # env.render() # # # Update Q table with new", "Q network while j < 200: # or While not d: j +=", "seed=None, name=None) # Weighting W vector in range 0 - 0.01 (like the", "Feature vector for next state representation nextQ = tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32) # Entropy", "THE NETWORK init = tf.global_variables_initializer() # Set learning parameters y = 0.99 e", "an action by greedily (with noise) picking from Q table # # Because", "= tf.global_variables_initializer() # Set learning parameters y = 0.99 e = 0.1 number_episodes", "tensorflow as tf import numpy as np import matplotlib.pyplot as plt env =", "print(\"Episode #{} is running!\".format(i)) # First state s = env.reset() rAll = 0", "jList.append(j) rList.append(rAll) env.close() plt.figure() plt.plot(rList, label=\"Return - Q Learning\") plt.show() plt.figure() plt.plot(jList, label=\"Steps", "a] = Q[s, a] + lr * (r + y * np.max(Q[s1, :])", "# s1, r, d, _ = env.step(a) # # env.render() # # #", "and predicted Q values _, W1 = sess.run([updateModel, W], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1], nextQ: targetQ})", "2000 # List to store total rewards and steps per episode jList =", "is a one-hot vector # Therefore W is the actual Q value a,", "# Choose an action by greedily (with noise) picking from Q table #", "[] rList = [] with tf.Session() as sess: sess.run(init) for i in range(number_episodes):", "plt.show() # ------------------------------------------------------------------------- # TABULAR IMPLEMENTATION # # # Set learning parameters #", "Because of the noise, it is epsilon-greedy with epsilon decreasing over time #", "dtype=tf.float32) # Entropy loss loss = tf.reduce_sum(tf.square(Qout - nextQ)) trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel", "numpy as np import matplotlib.pyplot as plt env = gym.make('FrozenLake-v0') # NEURAL NETWORK", "0. 0. 0. 0.]] # s = 1 --> Identity s: s +", "10) break jList.append(j) rList.append(rAll) env.close() plt.figure() plt.plot(rList, label=\"Return - Q Learning\") plt.show() plt.figure()", "np.random.rand(1, env.action_space.n)*(1./(i + 1))) # s1, r, d, _ = env.step(a) # #", "Qout with shape [1, env.action_space.n] - Action state value for Q[s, a] with", "network Q1 = sess.run(Qout, feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1 = np.max(Q1) targetQ = allQ targetQ[0,", "s: s + 1: [[1. 0. 0. 0. 0. 0. 0. 0. 0.", "0.8 # y = 0.95 # number_episodes = 20000 # # # Initial", "shape [1, env.action_space.n] - Action state value for Q[s, a] with every a", "# Obtain next state Q value by feeding the new state throughout the", "[1, env.action_space.n] - Action state value for Q[s, a] with every a available", "= False # j = 0 # while j < 99: # j", "# # List of reward and steps per episode # rList = []", "# a = np.argmax(Q[s, :] + np.random.rand(1, env.action_space.n)*(1./(i + 1))) # s1, r,", "r, d, _ = env.step(a) # # env.render() # # # Update Q", "_ = env.step(a) # # env.render() # # # Update Q table with", "by greedily (with noise) picking from Q table # # Because of the", "< 99: # j += 1 # # Choose an action by greedily", "= sess.run(Qout, feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1 = np.max(Q1) targetQ = allQ targetQ[0, a[0]] =", "loss loss = tf.reduce_sum(tf.square(Qout - nextQ)) trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel = trainer.minimize(loss) #", "# Entropy loss loss = tf.reduce_sum(tf.square(Qout - nextQ)) trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel =", "minval=0, maxval=None, dtype=tf.float32, seed=None, name=None) # Weighting W vector in range 0 -", "# Initial table with all zeros # Q = np.zeros([env.observation_space.n, env.action_space.n]) # #", "# Feature vector for current state representation input1 = tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32) #", "tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32) # Entropy loss loss = tf.reduce_sum(tf.square(Qout - nextQ)) trainer =", "s:s+1: \", np.identity(env.observation_space.n)[s:s+1]) # s = 0 --> Identity s: s + 1:", "(e) greedy # print(\"s = \", s,\" --> Identity s:s+1: \", np.identity(env.observation_space.n)[s:s+1]) #", "vector in range 0 - 0.01 (like the way Andrew Ng did with", "predicted Q values _, W1 = sess.run([updateModel, W], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1], nextQ: targetQ}) rAll", "env = gym.make('FrozenLake-v0') # NEURAL NETWORK IMPLEMENTATION tf.reset_default_graph() # Feature vector for current", "= tf.matmul(input1, W) # Greedy action at a state predict = tf.argmax(Qout, axis=1)", "table with new knowledge # Q[s, a] = Q[s, a] + lr *", "= tf.argmax(Qout, axis=1) # Feature vector for next state representation nextQ = tf.placeholder(shape=[1,", "rAll = 0 d = False j = 0 # Q network while", "0. 0. 0. 0. 0. 0.]] # s = 1 --> Identity s:", "= tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n], 0, 0.01)) # Qout with shape [1, env.action_space.n] - Action", "d = False # j = 0 # while j < 99: #", "# print(\"s = \", s,\" --> Identity s:s+1: \", np.identity(env.observation_space.n)[s:s+1]) # s =", "# # Choose an action by greedily (with noise) picking from Q table", "j = 0 # while j < 99: # j += 1 #" ]
[ "'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey':", "'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519': signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4':", "KIND, either express or implied. # See the License for the specific language", "by a KeyType SUPPORTED_LANGUAGES = { 'AesEaxKey': ['cc', 'java', 'python'], 'AesGcmKey': ['cc', 'java',", "Unless required by applicable law or agreed to in writing, software # distributed", "streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates", "'python'], 'EciesAeadHkdfPrivateKey': ['cc', 'java', 'go', 'python'], 'AesCmacKey': ['cc', 'java', 'go', 'python'], 'HmacKey': ['cc',", "STREAMING_AEAD_KEY_TYPES + HYBRID_PRIVATE_KEY_TYPES + MAC_KEY_TYPES + SIGNATURE_KEY_TYPES + PRF_KEY_TYPES) # All languages that", "'go', 'python'], 'EcdsaPrivateKey': ['cc', 'java', 'go', 'python'], 'Ed25519PrivateKey': ['cc', 'java', 'go', 'python'], 'RsaSsaPkcs1PrivateKey':", "'AES_CMAC': mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256': signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384':", "['AesSivKey'] STREAMING_AEAD_KEY_TYPES = [ 'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey', ] HYBRID_PRIVATE_KEY_TYPES = ['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES = [", "governing permissions and # limitations under the License. \"\"\"All KeyTypes and which languages", "are supported by a KeyType SUPPORTED_LANGUAGES = { 'AesEaxKey': ['cc', 'java', 'python'], 'AesGcmKey':", "'java', 'go', 'python'], 'HmacKey': ['cc', 'java', 'go', 'python'], 'EcdsaPrivateKey': ['cc', 'java', 'go', 'python'],", "this file except in compliance with the License. # You may obtain a", "signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384': signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521': signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363,", "signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519': signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4,", "# All languages supported by cross-language tests. ALL_LANGUAGES = ['cc', 'java', 'go', 'python']", "= { 'AesEaxKey': ['AES128_EAX', 'AES256_EAX'], 'AesGcmKey': ['AES128_GCM', 'AES256_GCM'], 'AesGcmSivKey': ['AES128_GCM_SIV', 'AES256_GCM_SIV'], 'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256',", "'ECDSA_P256', 'ECDSA_P384', 'ECDSA_P384_SHA384', 'ECDSA_P521', 'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363' ], 'Ed25519PrivateKey': ['ED25519'], 'RsaSsaPkcs1PrivateKey': [", "'AesCmacKey': ['cc', 'java', 'go', 'python'], 'HmacKey': ['cc', 'java', 'go', 'python'], 'EcdsaPrivateKey': ['cc', 'java',", "ANY KIND, either express or implied. # See the License for the specific", "'python'], 'AesCtrHmacAeadKey': ['cc', 'java', 'go', 'python'], 'ChaCha20Poly1305Key': ['java', 'go'], 'XChaCha20Poly1305Key': ['cc', 'java', 'go',", "# All languages that are supported by a KeyType SUPPORTED_LANGUAGES = { 'AesEaxKey':", "'AesCtrHmacAeadKey': ['cc', 'java', 'go', 'python'], 'ChaCha20Poly1305Key': ['java', 'go'], 'XChaCha20Poly1305Key': ['cc', 'java', 'go', 'python'],", "supported by a KeyType SUPPORTED_LANGUAGES = { 'AesEaxKey': ['cc', 'java', 'python'], 'AesGcmKey': ['cc',", "KeyTypes and which languages support them.\"\"\" # Placeholder for import for type annotations", "'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305': tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.' + 'ChaCha20Poly1305Key'),", "'ECDSA_P521': signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519': signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4':", "tink import streaming_aead from tink.proto import tink_pb2 # All languages supported by cross-language", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305': tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.' + 'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV':", "For each KeyType, a list of all KeyTemplate Names that must be supported.", "'java', 'go', 'python'], } KEY_TYPE_FROM_URL = { 'type.googleapis.com/google.crypto.tink.' + key_type: key_type for key_type", "mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256': signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384': signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521': signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363,", "['cc', 'java', 'go', 'python'] # All KeyTypes (without the prefix 'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES =", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "'RsaSsaPkcs1PrivateKey': ['cc', 'java', 'python'], 'RsaSsaPssPrivateKey': ['cc', 'java', 'python'], 'AesCmacPrfKey': ['cc', 'java', 'go', 'python'],", "['AES_CMAC_PRF'], 'HmacPrfKey': ['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'], 'HkdfPrfKey': ['<KEY>'], } # KeyTemplate (as Protobuf) for each", "tink.proto import tink_pb2 # All languages supported by cross-language tests. ALL_LANGUAGES = ['cc',", "'AesGcmHkdfStreamingKey': [ 'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB', ], 'EciesAeadHkdfPrivateKey': [ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ], 'AesCmacKey': ['AES_CMAC'],", "prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256, } SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME = { name: SUPPORTED_LANGUAGES[KEY_TYPE_FROM_URL[template.type_url]]", "aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305': tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.' + 'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305,", "'go'], 'XChaCha20Poly1305Key': ['cc', 'java', 'go', 'python'], 'AesSivKey': ['cc', 'java', 'go', 'python'], 'AesCtrHmacStreamingKey': ['cc',", "'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC': mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG,", "= ['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES = [ 'AesCmacKey', 'HmacKey', ] SIGNATURE_KEY_TYPES = [ 'EcdsaPrivateKey', 'Ed25519PrivateKey',", "'java', 'go', 'python'], 'AesGcmHkdfStreamingKey': ['cc', 'java', 'go', 'python'], 'EciesAeadHkdfPrivateKey': ['cc', 'java', 'go', 'python'],", "OF ANY KIND, either express or implied. # See the License for the", "'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key', ] DAEAD_KEY_TYPES = ['AesSivKey'] STREAMING_AEAD_KEY_TYPES = [ 'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey', ]", "which languages support them.\"\"\" # Placeholder for import for type annotations from tink", "'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'], 'AesSivKey': ['AES256_SIV'], 'AesCtrHmacStreamingKey': [ 'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB', ], 'AesGcmHkdfStreamingKey': [", "['AES128_GCM', 'AES256_GCM'], 'AesGcmSivKey': ['AES128_GCM_SIV', 'AES256_GCM_SIV'], 'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'], 'AesSivKey':", "'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG' ], 'EcdsaPrivateKey': [ 'ECDSA_P256', 'ECDSA_P384', 'ECDSA_P384_SHA384', 'ECDSA_P521', 'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363',", "KEY_TEMPLATE_NAMES = { 'AesEaxKey': ['AES128_EAX', 'AES256_EAX'], 'AesGcmKey': ['AES128_GCM', 'AES256_GCM'], 'AesGcmSivKey': ['AES128_GCM_SIV', 'AES256_GCM_SIV'], 'AesCtrHmacAeadKey':", "'RsaSsaPssPrivateKey': ['cc', 'java', 'python'], 'AesCmacPrfKey': ['cc', 'java', 'go', 'python'], 'HmacPrfKey': ['cc', 'java', 'go',", "'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'], 'AesSivKey': ['AES256_SIV'], 'AesCtrHmacStreamingKey': [ 'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB',", "'HmacKey', ] SIGNATURE_KEY_TYPES = [ 'EcdsaPrivateKey', 'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey', ] PRF_KEY_TYPES = [", "'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG' ], 'EcdsaPrivateKey': [ 'ECDSA_P256', 'ECDSA_P384', 'ECDSA_P384_SHA384', 'ECDSA_P521', 'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363'", "['<KEY>'], } # KeyTemplate (as Protobuf) for each KeyTemplate name. KEY_TEMPLATE = {", "ALL_KEY_TYPES = ( AEAD_KEY_TYPES + DAEAD_KEY_TYPES + STREAMING_AEAD_KEY_TYPES + HYBRID_PRIVATE_KEY_TYPES + MAC_KEY_TYPES +", "under the License. \"\"\"All KeyTypes and which languages support them.\"\"\" # Placeholder for", "for type annotations from tink import aead from tink import daead from tink", "'python'], 'RsaSsaPssPrivateKey': ['cc', 'java', 'python'], 'AesCmacPrfKey': ['cc', 'java', 'go', 'python'], 'HmacPrfKey': ['cc', 'java',", "'go', 'python'], 'EciesAeadHkdfPrivateKey': ['cc', 'java', 'go', 'python'], 'AesCmacKey': ['cc', 'java', 'go', 'python'], 'HmacKey':", "'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB':", "[ 'ECDSA_P256', 'ECDSA_P384', 'ECDSA_P384_SHA384', 'ECDSA_P521', 'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363' ], 'Ed25519PrivateKey': ['ED25519'], 'RsaSsaPkcs1PrivateKey':", "supported by cross-language tests. ALL_LANGUAGES = ['cc', 'java', 'go', 'python'] # All KeyTypes", "= [ 'AesCmacKey', 'HmacKey', ] SIGNATURE_KEY_TYPES = [ 'EcdsaPrivateKey', 'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey', ]", "'python'], 'AesCmacPrfKey': ['cc', 'java', 'go', 'python'], 'HmacPrfKey': ['cc', 'java', 'go', 'python'], 'HkdfPrfKey': ['cc',", "specific language governing permissions and # limitations under the License. \"\"\"All KeyTypes and", "['cc', 'python'], 'AesCtrHmacAeadKey': ['cc', 'java', 'go', 'python'], 'ChaCha20Poly1305Key': ['java', 'go'], 'XChaCha20Poly1305Key': ['cc', 'java',", "= ['AesSivKey'] STREAMING_AEAD_KEY_TYPES = [ 'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey', ] HYBRID_PRIVATE_KEY_TYPES = ['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES =", "signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256,", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "'HkdfPrfKey', ] ALL_KEY_TYPES = ( AEAD_KEY_TYPES + DAEAD_KEY_TYPES + STREAMING_AEAD_KEY_TYPES + HYBRID_PRIVATE_KEY_TYPES +", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "'go', 'python'], 'Ed25519PrivateKey': ['cc', 'java', 'go', 'python'], 'RsaSsaPkcs1PrivateKey': ['cc', 'java', 'python'], 'RsaSsaPssPrivateKey': ['cc',", "'AES256_EAX'], 'AesGcmKey': ['AES128_GCM', 'AES256_GCM'], 'AesGcmSivKey': ['AES128_GCM_SIV', 'AES256_GCM_SIV'], 'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key':", "'go', 'python'], 'HmacPrfKey': ['cc', 'java', 'go', 'python'], 'HkdfPrfKey': ['cc', 'java', 'go', 'python'], }", "'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey': ['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'], 'HkdfPrfKey': ['<KEY>'], } # KeyTemplate (as", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB':", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "['cc', 'java', 'go', 'python'], } KEY_TYPE_FROM_URL = { 'type.googleapis.com/google.crypto.tink.' + key_type: key_type for", "[ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ], 'AesCmacKey': ['AES_CMAC'], 'HmacKey': [ 'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG' ],", "support them.\"\"\" # Placeholder for import for type annotations from tink import aead", "'java', 'go', 'python'], 'RsaSsaPkcs1PrivateKey': ['cc', 'java', 'python'], 'RsaSsaPssPrivateKey': ['cc', 'java', 'python'], 'AesCmacPrfKey': ['cc',", "'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512':", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "'python'], } KEY_TYPE_FROM_URL = { 'type.googleapis.com/google.crypto.tink.' + key_type: key_type for key_type in ALL_KEY_TYPES}", "], 'EcdsaPrivateKey': [ 'ECDSA_P256', 'ECDSA_P384', 'ECDSA_P384_SHA384', 'ECDSA_P521', 'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363' ], 'Ed25519PrivateKey':", "'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key', ] DAEAD_KEY_TYPES = ['AesSivKey'] STREAMING_AEAD_KEY_TYPES = [ 'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey', ] HYBRID_PRIVATE_KEY_TYPES", "'java', 'go', 'python'], 'EcdsaPrivateKey': ['cc', 'java', 'go', 'python'], 'Ed25519PrivateKey': ['cc', 'java', 'go', 'python'],", "['java', 'go'], 'XChaCha20Poly1305Key': ['cc', 'java', 'go', 'python'], 'AesSivKey': ['cc', 'java', 'go', 'python'], 'AesCtrHmacStreamingKey':", "required by applicable law or agreed to in writing, software # distributed under", "'AesCtrHmacStreamingKey': [ 'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB', ], 'AesGcmHkdfStreamingKey': [ 'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB', ], 'EciesAeadHkdfPrivateKey': [", "applicable law or agreed to in writing, software # distributed under the License", "from tink import daead from tink import hybrid from tink import mac from", "'python'] # All KeyTypes (without the prefix 'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES = [ 'AesEaxKey', 'AesGcmKey',", "['cc', 'java', 'go', 'python'], 'EcdsaPrivateKey': ['cc', 'java', 'go', 'python'], 'Ed25519PrivateKey': ['cc', 'java', 'go',", "'ECDSA_P384': signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521': signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363':", "language governing permissions and # limitations under the License. \"\"\"All KeyTypes and which", "prefix 'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES = [ 'AesEaxKey', 'AesGcmKey', 'AesGcmSivKey', 'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key', ] DAEAD_KEY_TYPES", "'AES256_GCM_SIV'], 'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'], 'AesSivKey': ['AES256_SIV'], 'AesCtrHmacStreamingKey': [ 'AES128_CTR_HMAC_SHA256_4KB',", "aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305': tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.' + 'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV,", "'XChaCha20Poly1305Key': ['cc', 'java', 'go', 'python'], 'AesSivKey': ['cc', 'java', 'go', 'python'], 'AesCtrHmacStreamingKey': ['cc', 'java',", "or agreed to in writing, software # distributed under the License is distributed", "= { 'AesEaxKey': ['cc', 'java', 'python'], 'AesGcmKey': ['cc', 'java', 'go', 'python'], 'AesGcmSivKey': ['cc',", "output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB,", "'python'], 'AesGcmSivKey': ['cc', 'python'], 'AesCtrHmacAeadKey': ['cc', 'java', 'go', 'python'], 'ChaCha20Poly1305Key': ['java', 'go'], 'XChaCha20Poly1305Key':", "'java', 'python'], 'RsaSsaPssPrivateKey': ['cc', 'java', 'python'], 'AesCmacPrfKey': ['cc', 'java', 'go', 'python'], 'HmacPrfKey': ['cc',", "'python'], 'AesCtrHmacStreamingKey': ['cc', 'java', 'go', 'python'], 'AesGcmHkdfStreamingKey': ['cc', 'java', 'go', 'python'], 'EciesAeadHkdfPrivateKey': ['cc',", "'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ], 'AesCmacKey': ['AES_CMAC'], 'HmacKey': [ 'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG' ], 'EcdsaPrivateKey': [", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'], 'AesSivKey': ['AES256_SIV'], 'AesCtrHmacStreamingKey': [ 'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB', ], 'AesGcmHkdfStreamingKey': [ 'AES128_GCM_HKDF_4KB',", "'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256, } SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME = { name: SUPPORTED_LANGUAGES[KEY_TYPE_FROM_URL[template.type_url]] for", "'ECDSA_P521', 'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363' ], 'Ed25519PrivateKey': ['ED25519'], 'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ],", "hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC': mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256':", "'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305': tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.' + 'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305':", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "writing, software # distributed under the License is distributed on an \"AS IS\"", "'java', 'go', 'python'], 'ChaCha20Poly1305Key': ['java', 'go'], 'XChaCha20Poly1305Key': ['cc', 'java', 'go', 'python'], 'AesSivKey': ['cc',", "must be supported. KEY_TEMPLATE_NAMES = { 'AesEaxKey': ['AES128_EAX', 'AES256_EAX'], 'AesGcmKey': ['AES128_GCM', 'AES256_GCM'], 'AesGcmSivKey':", "'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256, } SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME = { name: SUPPORTED_LANGUAGES[KEY_TYPE_FROM_URL[template.type_url]] for name, template", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "from tink import prf from tink import signature from tink import streaming_aead from", "key_type for key_type in ALL_KEY_TYPES} # For each KeyType, a list of all", "License. # You may obtain a copy of the License at # #", "mac from tink import prf from tink import signature from tink import streaming_aead", "STREAMING_AEAD_KEY_TYPES = [ 'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey', ] HYBRID_PRIVATE_KEY_TYPES = ['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES = [ 'AesCmacKey',", "KeyType, a list of all KeyTemplate Names that must be supported. KEY_TEMPLATE_NAMES =", "'python'], 'AesGcmKey': ['cc', 'java', 'go', 'python'], 'AesGcmSivKey': ['cc', 'python'], 'AesCtrHmacAeadKey': ['cc', 'java', 'go',", "a KeyType SUPPORTED_LANGUAGES = { 'AesEaxKey': ['cc', 'java', 'python'], 'AesGcmKey': ['cc', 'java', 'go',", "{ 'AesEaxKey': ['cc', 'java', 'python'], 'AesGcmKey': ['cc', 'java', 'go', 'python'], 'AesGcmSivKey': ['cc', 'python'],", "compliance with the License. # You may obtain a copy of the License", "], 'EciesAeadHkdfPrivateKey': [ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ], 'AesCmacKey': ['AES_CMAC'], 'HmacKey': [ 'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG',", "+ PRF_KEY_TYPES) # All languages that are supported by a KeyType SUPPORTED_LANGUAGES =", "mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256': signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384': signature.signature_key_templates.ECDSA_P384,", "each KeyTemplate name. KEY_TEMPLATE = { 'AES128_EAX': aead.aead_key_templates.AES128_EAX, 'AES256_EAX': aead.aead_key_templates.AES256_EAX, 'AES128_GCM': aead.aead_key_templates.AES128_GCM, 'AES256_GCM':", "'ChaCha20Poly1305Key': ['java', 'go'], 'XChaCha20Poly1305Key': ['cc', 'java', 'go', 'python'], 'AesSivKey': ['cc', 'java', 'go', 'python'],", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC': mac.mac_key_templates.AES_CMAC,", "'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256, }", "aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305': tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.' + 'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB,", "[ 'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey', ] HYBRID_PRIVATE_KEY_TYPES = ['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES = [ 'AesCmacKey', 'HmacKey', ]", "'HmacPrfKey', 'HkdfPrfKey', ] ALL_KEY_TYPES = ( AEAD_KEY_TYPES + DAEAD_KEY_TYPES + STREAMING_AEAD_KEY_TYPES + HYBRID_PRIVATE_KEY_TYPES", "import for type annotations from tink import aead from tink import daead from", "'go', 'python'], 'RsaSsaPkcs1PrivateKey': ['cc', 'java', 'python'], 'RsaSsaPssPrivateKey': ['cc', 'java', 'python'], 'AesCmacPrfKey': ['cc', 'java',", "not use this file except in compliance with the License. # You may", "['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'], 'AesSivKey': ['AES256_SIV'], 'AesCtrHmacStreamingKey': [ 'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB', ],", "['cc', 'java', 'go', 'python'], 'Ed25519PrivateKey': ['cc', 'java', 'go', 'python'], 'RsaSsaPkcs1PrivateKey': ['cc', 'java', 'python'],", "'AES128_GCM': aead.aead_key_templates.AES128_GCM, 'AES256_GCM': aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305':", "= [ 'AesEaxKey', 'AesGcmKey', 'AesGcmSivKey', 'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key', ] DAEAD_KEY_TYPES = ['AesSivKey'] STREAMING_AEAD_KEY_TYPES", "License, Version 2.0 (the \"License\"); # you may not use this file except", "'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB', ], 'AesGcmHkdfStreamingKey': [ 'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB', ], 'EciesAeadHkdfPrivateKey': [ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256'", "'AesGcmSivKey': ['AES128_GCM_SIV', 'AES256_GCM_SIV'], 'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'], 'AesSivKey': ['AES256_SIV'], 'AesCtrHmacStreamingKey':", "'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519': signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4':", "'python'], 'ChaCha20Poly1305Key': ['java', 'go'], 'XChaCha20Poly1305Key': ['cc', 'java', 'go', 'python'], 'AesSivKey': ['cc', 'java', 'go',", "tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.' + 'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB,", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "'AesGcmSivKey', 'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key', ] DAEAD_KEY_TYPES = ['AesSivKey'] STREAMING_AEAD_KEY_TYPES = [ 'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey',", "languages supported by cross-language tests. ALL_LANGUAGES = ['cc', 'java', 'go', 'python'] # All", "['cc', 'java', 'python'], 'RsaSsaPssPrivateKey': ['cc', 'java', 'python'], 'AesCmacPrfKey': ['cc', 'java', 'go', 'python'], 'HmacPrfKey':", "'java', 'go', 'python'], 'EciesAeadHkdfPrivateKey': ['cc', 'java', 'go', 'python'], 'AesCmacKey': ['cc', 'java', 'go', 'python'],", "], 'AesCmacKey': ['AES_CMAC'], 'HmacKey': [ 'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG' ], 'EcdsaPrivateKey': [ 'ECDSA_P256',", "'RsaSsaPssPrivateKey', ] PRF_KEY_TYPES = [ 'AesCmacPrfKey', 'HmacPrfKey', 'HkdfPrfKey', ] ALL_KEY_TYPES = ( AEAD_KEY_TYPES", "PRF_KEY_TYPES = [ 'AesCmacPrfKey', 'HmacPrfKey', 'HkdfPrfKey', ] ALL_KEY_TYPES = ( AEAD_KEY_TYPES + DAEAD_KEY_TYPES", "streaming_aead from tink.proto import tink_pb2 # All languages supported by cross-language tests. ALL_LANGUAGES", "signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519': signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4,", "# you may not use this file except in compliance with the License.", "'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363' ], 'Ed25519PrivateKey': ['ED25519'], 'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4',", "'AesCmacPrfKey', 'HmacPrfKey', 'HkdfPrfKey', ] ALL_KEY_TYPES = ( AEAD_KEY_TYPES + DAEAD_KEY_TYPES + STREAMING_AEAD_KEY_TYPES +", "agreed to in writing, software # distributed under the License is distributed on", "SIGNATURE_KEY_TYPES + PRF_KEY_TYPES) # All languages that are supported by a KeyType SUPPORTED_LANGUAGES", "the License. \"\"\"All KeyTypes and which languages support them.\"\"\" # Placeholder for import", "{ 'AES128_EAX': aead.aead_key_templates.AES128_EAX, 'AES256_EAX': aead.aead_key_templates.AES256_EAX, 'AES128_GCM': aead.aead_key_templates.AES128_GCM, 'AES256_GCM': aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV,", "streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC':", "(the \"License\"); # you may not use this file except in compliance with", "streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC': mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG':", "] DAEAD_KEY_TYPES = ['AesSivKey'] STREAMING_AEAD_KEY_TYPES = [ 'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey', ] HYBRID_PRIVATE_KEY_TYPES = ['EciesAeadHkdfPrivateKey']", "] ALL_KEY_TYPES = ( AEAD_KEY_TYPES + DAEAD_KEY_TYPES + STREAMING_AEAD_KEY_TYPES + HYBRID_PRIVATE_KEY_TYPES + MAC_KEY_TYPES", "KEY_TEMPLATE = { 'AES128_EAX': aead.aead_key_templates.AES128_EAX, 'AES256_EAX': aead.aead_key_templates.AES256_EAX, 'AES128_GCM': aead.aead_key_templates.AES128_GCM, 'AES256_GCM': aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV,", "# Unless required by applicable law or agreed to in writing, software #", "'go', 'python'], 'AesSivKey': ['cc', 'java', 'go', 'python'], 'AesCtrHmacStreamingKey': ['cc', 'java', 'go', 'python'], 'AesGcmHkdfStreamingKey':", "by applicable law or agreed to in writing, software # distributed under the", "KeyTypes (without the prefix 'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES = [ 'AesEaxKey', 'AesGcmKey', 'AesGcmSivKey', 'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key',", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "from tink import streaming_aead from tink.proto import tink_pb2 # All languages supported by", "type_url=('type.googleapis.com/google.crypto.tink.' + 'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB':", "prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256, } SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME = { name: SUPPORTED_LANGUAGES[KEY_TYPE_FROM_URL[template.type_url]] for name,", "] SIGNATURE_KEY_TYPES = [ 'EcdsaPrivateKey', 'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey', ] PRF_KEY_TYPES = [ 'AesCmacPrfKey',", "['cc', 'java', 'python'], 'AesCmacPrfKey': ['cc', 'java', 'go', 'python'], 'HmacPrfKey': ['cc', 'java', 'go', 'python'],", "['cc', 'java', 'go', 'python'], 'AesCmacKey': ['cc', 'java', 'go', 'python'], 'HmacKey': ['cc', 'java', 'go',", "# All KeyTypes (without the prefix 'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES = [ 'AesEaxKey', 'AesGcmKey', 'AesGcmSivKey',", "DAEAD_KEY_TYPES = ['AesSivKey'] STREAMING_AEAD_KEY_TYPES = [ 'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey', ] HYBRID_PRIVATE_KEY_TYPES = ['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES", "hybrid from tink import mac from tink import prf from tink import signature", "All languages supported by cross-language tests. ALL_LANGUAGES = ['cc', 'java', 'go', 'python'] #", "'AesGcmHkdfStreamingKey', ] HYBRID_PRIVATE_KEY_TYPES = ['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES = [ 'AesCmacKey', 'HmacKey', ] SIGNATURE_KEY_TYPES =", "file except in compliance with the License. # You may obtain a copy", "All languages that are supported by a KeyType SUPPORTED_LANGUAGES = { 'AesEaxKey': ['cc',", "tink import aead from tink import daead from tink import hybrid from tink", "'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey': ['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'], 'HkdfPrfKey': ['<KEY>'], } # KeyTemplate", "'AesGcmSivKey': ['cc', 'python'], 'AesCtrHmacAeadKey': ['cc', 'java', 'go', 'python'], 'ChaCha20Poly1305Key': ['java', 'go'], 'XChaCha20Poly1305Key': ['cc',", "signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519': signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC,", "[ 'EcdsaPrivateKey', 'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey', ] PRF_KEY_TYPES = [ 'AesCmacPrfKey', 'HmacPrfKey', 'HkdfPrfKey', ]", "prf from tink import signature from tink import streaming_aead from tink.proto import tink_pb2", "'HkdfPrfKey': ['cc', 'java', 'go', 'python'], } KEY_TYPE_FROM_URL = { 'type.googleapis.com/google.crypto.tink.' + key_type: key_type", "daead from tink import hybrid from tink import mac from tink import prf", "languages that are supported by a KeyType SUPPORTED_LANGUAGES = { 'AesEaxKey': ['cc', 'java',", "License for the specific language governing permissions and # limitations under the License.", "'python'], 'HkdfPrfKey': ['cc', 'java', 'go', 'python'], } KEY_TYPE_FROM_URL = { 'type.googleapis.com/google.crypto.tink.' + key_type:", "for the specific language governing permissions and # limitations under the License. \"\"\"All", "['cc', 'java', 'go', 'python'], 'EciesAeadHkdfPrivateKey': ['cc', 'java', 'go', 'python'], 'AesCmacKey': ['cc', 'java', 'go',", "# Placeholder for import for type annotations from tink import aead from tink", "'python'], 'RsaSsaPkcs1PrivateKey': ['cc', 'java', 'python'], 'RsaSsaPssPrivateKey': ['cc', 'java', 'python'], 'AesCmacPrfKey': ['cc', 'java', 'go',", "a list of all KeyTemplate Names that must be supported. KEY_TEMPLATE_NAMES = {", "to in writing, software # distributed under the License is distributed on an", "'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256': signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384': signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521': signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363':", "{ 'AesEaxKey': ['AES128_EAX', 'AES256_EAX'], 'AesGcmKey': ['AES128_GCM', 'AES256_GCM'], 'AesGcmSivKey': ['AES128_GCM_SIV', 'AES256_GCM_SIV'], 'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'],", "import mac from tink import prf from tink import signature from tink import", "'AesCtrHmacStreamingKey': ['cc', 'java', 'go', 'python'], 'AesGcmHkdfStreamingKey': ['cc', 'java', 'go', 'python'], 'EciesAeadHkdfPrivateKey': ['cc', 'java',", "implied. # See the License for the specific language governing permissions and #", "\"License\"); # you may not use this file except in compliance with the", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "AEAD_KEY_TYPES = [ 'AesEaxKey', 'AesGcmKey', 'AesGcmSivKey', 'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key', ] DAEAD_KEY_TYPES = ['AesSivKey']", "'python'], 'AesCmacKey': ['cc', 'java', 'go', 'python'], 'HmacKey': ['cc', 'java', 'go', 'python'], 'EcdsaPrivateKey': ['cc',", "HYBRID_PRIVATE_KEY_TYPES = ['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES = [ 'AesCmacKey', 'HmacKey', ] SIGNATURE_KEY_TYPES = [ 'EcdsaPrivateKey',", "'java', 'python'], 'AesCmacPrfKey': ['cc', 'java', 'go', 'python'], 'HmacPrfKey': ['cc', 'java', 'go', 'python'], 'HkdfPrfKey':", "['cc', 'java', 'go', 'python'], 'AesGcmSivKey': ['cc', 'python'], 'AesCtrHmacAeadKey': ['cc', 'java', 'go', 'python'], 'ChaCha20Poly1305Key':", "tink import mac from tink import prf from tink import signature from tink", "+ DAEAD_KEY_TYPES + STREAMING_AEAD_KEY_TYPES + HYBRID_PRIVATE_KEY_TYPES + MAC_KEY_TYPES + SIGNATURE_KEY_TYPES + PRF_KEY_TYPES) #", "[ 'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB', ], 'EciesAeadHkdfPrivateKey': [ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ], 'AesCmacKey': ['AES_CMAC'], 'HmacKey':", "'EciesAeadHkdfPrivateKey': [ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ], 'AesCmacKey': ['AES_CMAC'], 'HmacKey': [ 'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG'", "= ['cc', 'java', 'go', 'python'] # All KeyTypes (without the prefix 'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES", "[ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey': ['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'], 'HkdfPrfKey': ['<KEY>'], } #", "import hybrid from tink import mac from tink import prf from tink import", "'AesGcmKey': ['AES128_GCM', 'AES256_GCM'], 'AesGcmSivKey': ['AES128_GCM_SIV', 'AES256_GCM_SIV'], 'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'],", "import daead from tink import hybrid from tink import mac from tink import", "MAC_KEY_TYPES + SIGNATURE_KEY_TYPES + PRF_KEY_TYPES) # All languages that are supported by a", "or implied. # See the License for the specific language governing permissions and", "PRF_KEY_TYPES) # All languages that are supported by a KeyType SUPPORTED_LANGUAGES = {", "permissions and # limitations under the License. \"\"\"All KeyTypes and which languages support", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "[ 'AesEaxKey', 'AesGcmKey', 'AesGcmSivKey', 'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key', ] DAEAD_KEY_TYPES = ['AesSivKey'] STREAMING_AEAD_KEY_TYPES =", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC': mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG,", "['cc', 'java', 'go', 'python'], 'RsaSsaPkcs1PrivateKey': ['cc', 'java', 'python'], 'RsaSsaPssPrivateKey': ['cc', 'java', 'python'], 'AesCmacPrfKey':", "from tink import hybrid from tink import mac from tink import prf from", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "[ 'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB', ], 'AesGcmHkdfStreamingKey': [ 'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB', ], 'EciesAeadHkdfPrivateKey': [ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM',", "in writing, software # distributed under the License is distributed on an \"AS", "and which languages support them.\"\"\" # Placeholder for import for type annotations from", "+ 'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB,", "signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256,", "+ key_type: key_type for key_type in ALL_KEY_TYPES} # For each KeyType, a list", "'ECDSA_P256': signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384': signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521': signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363':", "# See the License for the specific language governing permissions and # limitations", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "# For each KeyType, a list of all KeyTemplate Names that must be", "['cc', 'java', 'go', 'python'], 'AesGcmHkdfStreamingKey': ['cc', 'java', 'go', 'python'], 'EciesAeadHkdfPrivateKey': ['cc', 'java', 'go',", "signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256, } SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME", "'go', 'python'], 'AesGcmHkdfStreamingKey': ['cc', 'java', 'go', 'python'], 'EciesAeadHkdfPrivateKey': ['cc', 'java', 'go', 'python'], 'AesCmacKey':", "'AES256_EAX': aead.aead_key_templates.AES256_EAX, 'AES128_GCM': aead.aead_key_templates.AES128_GCM, 'AES256_GCM': aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256':", "] PRF_KEY_TYPES = [ 'AesCmacPrfKey', 'HmacPrfKey', 'HkdfPrfKey', ] ALL_KEY_TYPES = ( AEAD_KEY_TYPES +", "['AES256_SIV'], 'AesCtrHmacStreamingKey': [ 'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB', ], 'AesGcmHkdfStreamingKey': [ 'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB', ], 'EciesAeadHkdfPrivateKey':", "for key_type in ALL_KEY_TYPES} # For each KeyType, a list of all KeyTemplate", "'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey', ] PRF_KEY_TYPES = [ 'AesCmacPrfKey', 'HmacPrfKey', 'HkdfPrfKey', ] ALL_KEY_TYPES =", "['cc', 'java', 'go', 'python'], 'HmacPrfKey': ['cc', 'java', 'go', 'python'], 'HkdfPrfKey': ['cc', 'java', 'go',", "list of all KeyTemplate Names that must be supported. KEY_TEMPLATE_NAMES = { 'AesEaxKey':", "aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305': tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.' +", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256': signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384': signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384,", "you may not use this file except in compliance with the License. #", "] HYBRID_PRIVATE_KEY_TYPES = ['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES = [ 'AesCmacKey', 'HmacKey', ] SIGNATURE_KEY_TYPES = [", "'java', 'go', 'python'], 'AesCmacKey': ['cc', 'java', 'go', 'python'], 'HmacKey': ['cc', 'java', 'go', 'python'],", "['cc', 'java', 'go', 'python'], 'AesCtrHmacStreamingKey': ['cc', 'java', 'go', 'python'], 'AesGcmHkdfStreamingKey': ['cc', 'java', 'go',", "'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256':", "'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey': ['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'], 'HkdfPrfKey': ['<KEY>'], } # KeyTemplate (as Protobuf) for", "= [ 'EcdsaPrivateKey', 'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey', ] PRF_KEY_TYPES = [ 'AesCmacPrfKey', 'HmacPrfKey', 'HkdfPrfKey',", "'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363' ], 'Ed25519PrivateKey': ['ED25519'], 'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey': [", "'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC': mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG,", "use this file except in compliance with the License. # You may obtain", "annotations from tink import aead from tink import daead from tink import hybrid", "key_type in ALL_KEY_TYPES} # For each KeyType, a list of all KeyTemplate Names", "tink import daead from tink import hybrid from tink import mac from tink", "+ MAC_KEY_TYPES + SIGNATURE_KEY_TYPES + PRF_KEY_TYPES) # All languages that are supported by", "streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC': mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG':", "them.\"\"\" # Placeholder for import for type annotations from tink import aead from", "import streaming_aead from tink.proto import tink_pb2 # All languages supported by cross-language tests.", "'python'], 'HmacPrfKey': ['cc', 'java', 'go', 'python'], 'HkdfPrfKey': ['cc', 'java', 'go', 'python'], } KEY_TYPE_FROM_URL", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256': signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384': signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521': signature.signature_key_templates.ECDSA_P521,", "KeyTemplate name. KEY_TEMPLATE = { 'AES128_EAX': aead.aead_key_templates.AES128_EAX, 'AES256_EAX': aead.aead_key_templates.AES256_EAX, 'AES128_GCM': aead.aead_key_templates.AES128_GCM, 'AES256_GCM': aead.aead_key_templates.AES256_GCM,", "by cross-language tests. ALL_LANGUAGES = ['cc', 'java', 'go', 'python'] # All KeyTypes (without", "'go', 'python'], 'AesGcmSivKey': ['cc', 'python'], 'AesCtrHmacAeadKey': ['cc', 'java', 'go', 'python'], 'ChaCha20Poly1305Key': ['java', 'go'],", "# limitations under the License. \"\"\"All KeyTypes and which languages support them.\"\"\" #", "aead from tink import daead from tink import hybrid from tink import mac", "'AES256_GCM': aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305': tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.'", "'go', 'python'], 'ChaCha20Poly1305Key': ['java', 'go'], 'XChaCha20Poly1305Key': ['cc', 'java', 'go', 'python'], 'AesSivKey': ['cc', 'java',", "2.0 (the \"License\"); # you may not use this file except in compliance", "'HmacKey': [ 'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG' ], 'EcdsaPrivateKey': [ 'ECDSA_P256', 'ECDSA_P384', 'ECDSA_P384_SHA384', 'ECDSA_P521',", "'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey': ['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'], 'HkdfPrfKey': ['<KEY>'], }", "all KeyTemplate Names that must be supported. KEY_TEMPLATE_NAMES = { 'AesEaxKey': ['AES128_EAX', 'AES256_EAX'],", "'java', 'go', 'python'], 'Ed25519PrivateKey': ['cc', 'java', 'go', 'python'], 'RsaSsaPkcs1PrivateKey': ['cc', 'java', 'python'], 'RsaSsaPssPrivateKey':", "'ED25519': signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256':", "'AesEaxKey', 'AesGcmKey', 'AesGcmSivKey', 'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key', ] DAEAD_KEY_TYPES = ['AesSivKey'] STREAMING_AEAD_KEY_TYPES = [", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "'ECDSA_P521_IEEE_P1363' ], 'Ed25519PrivateKey': ['ED25519'], 'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4'", "'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519': signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF':", "'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG' ], 'EcdsaPrivateKey': [ 'ECDSA_P256', 'ECDSA_P384', 'ECDSA_P384_SHA384', 'ECDSA_P521', 'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363',", "the prefix 'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES = [ 'AesEaxKey', 'AesGcmKey', 'AesGcmSivKey', 'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key', ]", "import tink_pb2 # All languages supported by cross-language tests. ALL_LANGUAGES = ['cc', 'java',", "[ 'AesCmacPrfKey', 'HmacPrfKey', 'HkdfPrfKey', ] ALL_KEY_TYPES = ( AEAD_KEY_TYPES + DAEAD_KEY_TYPES + STREAMING_AEAD_KEY_TYPES", "# # Unless required by applicable law or agreed to in writing, software", "and # limitations under the License. \"\"\"All KeyTypes and which languages support them.\"\"\"", "+ HYBRID_PRIVATE_KEY_TYPES + MAC_KEY_TYPES + SIGNATURE_KEY_TYPES + PRF_KEY_TYPES) # All languages that are", "signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512,", "express or implied. # See the License for the specific language governing permissions", "be supported. KEY_TEMPLATE_NAMES = { 'AesEaxKey': ['AES128_EAX', 'AES256_EAX'], 'AesGcmKey': ['AES128_GCM', 'AES256_GCM'], 'AesGcmSivKey': ['AES128_GCM_SIV',", "tink import prf from tink import signature from tink import streaming_aead from tink.proto", "'AES256_GCM_HKDF_1MB', ], 'EciesAeadHkdfPrivateKey': [ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ], 'AesCmacKey': ['AES_CMAC'], 'HmacKey': [ 'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG',", "'java', 'go', 'python'], 'AesSivKey': ['cc', 'java', 'go', 'python'], 'AesCtrHmacStreamingKey': ['cc', 'java', 'go', 'python'],", "tink_pb2 # All languages supported by cross-language tests. ALL_LANGUAGES = ['cc', 'java', 'go',", "'AesCmacKey', 'HmacKey', ] SIGNATURE_KEY_TYPES = [ 'EcdsaPrivateKey', 'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey', ] PRF_KEY_TYPES =", "either express or implied. # See the License for the specific language governing", "limitations under the License. \"\"\"All KeyTypes and which languages support them.\"\"\" # Placeholder", "tink import hybrid from tink import mac from tink import prf from tink", "ALL_LANGUAGES = ['cc', 'java', 'go', 'python'] # All KeyTypes (without the prefix 'type.googleapis.com/google.crypto.tink.')", "'Ed25519PrivateKey': ['cc', 'java', 'go', 'python'], 'RsaSsaPkcs1PrivateKey': ['cc', 'java', 'python'], 'RsaSsaPssPrivateKey': ['cc', 'java', 'python'],", "['AES128_GCM_SIV', 'AES256_GCM_SIV'], 'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'], 'AesSivKey': ['AES256_SIV'], 'AesCtrHmacStreamingKey': [", "Placeholder for import for type annotations from tink import aead from tink import", "'EciesAeadHkdfPrivateKey': ['cc', 'java', 'go', 'python'], 'AesCmacKey': ['cc', 'java', 'go', 'python'], 'HmacKey': ['cc', 'java',", "'go', 'python'], 'HkdfPrfKey': ['cc', 'java', 'go', 'python'], } KEY_TYPE_FROM_URL = { 'type.googleapis.com/google.crypto.tink.' +", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey': ['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'], 'HkdfPrfKey':", "[ 'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG' ], 'EcdsaPrivateKey': [ 'ECDSA_P256', 'ECDSA_P384', 'ECDSA_P384_SHA384', 'ECDSA_P521', 'ECDSA_P256_IEEE_P1363',", "'go', 'python'], 'AesCtrHmacStreamingKey': ['cc', 'java', 'go', 'python'], 'AesGcmHkdfStreamingKey': ['cc', 'java', 'go', 'python'], 'EciesAeadHkdfPrivateKey':", "key_type: key_type for key_type in ALL_KEY_TYPES} # For each KeyType, a list of", "['AES_CMAC'], 'HmacKey': [ 'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG' ], 'EcdsaPrivateKey': [ 'ECDSA_P256', 'ECDSA_P384', 'ECDSA_P384_SHA384',", "# KeyTemplate (as Protobuf) for each KeyTemplate name. KEY_TEMPLATE = { 'AES128_EAX': aead.aead_key_templates.AES128_EAX,", "], 'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey': ['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'], 'HkdfPrfKey': ['<KEY>'], } # KeyTemplate (as Protobuf)", "'AesCmacPrfKey': ['cc', 'java', 'go', 'python'], 'HmacPrfKey': ['cc', 'java', 'go', 'python'], 'HkdfPrfKey': ['cc', 'java',", "for each KeyTemplate name. KEY_TEMPLATE = { 'AES128_EAX': aead.aead_key_templates.AES128_EAX, 'AES256_EAX': aead.aead_key_templates.AES256_EAX, 'AES128_GCM': aead.aead_key_templates.AES128_GCM,", "DAEAD_KEY_TYPES + STREAMING_AEAD_KEY_TYPES + HYBRID_PRIVATE_KEY_TYPES + MAC_KEY_TYPES + SIGNATURE_KEY_TYPES + PRF_KEY_TYPES) # All", "'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305': tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.' + 'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB':", "the License. # You may obtain a copy of the License at #", "'HMAC_SHA512_512BITTAG' ], 'EcdsaPrivateKey': [ 'ECDSA_P256', 'ECDSA_P384', 'ECDSA_P384_SHA384', 'ECDSA_P521', 'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363' ],", "'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256, } SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME = { name:", "'python'], 'AesSivKey': ['cc', 'java', 'go', 'python'], 'AesCtrHmacStreamingKey': ['cc', 'java', 'go', 'python'], 'AesGcmHkdfStreamingKey': ['cc',", "prf.prf_key_templates.HKDF_SHA256, } SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME = { name: SUPPORTED_LANGUAGES[KEY_TYPE_FROM_URL[template.type_url]] for name, template in KEY_TEMPLATE.items() }", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "= [ 'AesCmacPrfKey', 'HmacPrfKey', 'HkdfPrfKey', ] ALL_KEY_TYPES = ( AEAD_KEY_TYPES + DAEAD_KEY_TYPES +", "'EcdsaPrivateKey': [ 'ECDSA_P256', 'ECDSA_P384', 'ECDSA_P384_SHA384', 'ECDSA_P521', 'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363' ], 'Ed25519PrivateKey': ['ED25519'],", "'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB', ], 'EciesAeadHkdfPrivateKey': [ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ], 'AesCmacKey': ['AES_CMAC'], 'HmacKey': [", "'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256': signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384': signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521': signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363':", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "'CHACHA20_POLY1305': tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.' + 'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB':", "['cc', 'java', 'go', 'python'], 'HkdfPrfKey': ['cc', 'java', 'go', 'python'], } KEY_TYPE_FROM_URL = {", "in ALL_KEY_TYPES} # For each KeyType, a list of all KeyTemplate Names that", "mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256': signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384': signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521': signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363,", "'java', 'go', 'python'], 'AesGcmSivKey': ['cc', 'python'], 'AesCtrHmacAeadKey': ['cc', 'java', 'go', 'python'], 'ChaCha20Poly1305Key': ['java',", "aead.aead_key_templates.AES128_EAX, 'AES256_EAX': aead.aead_key_templates.AES256_EAX, 'AES128_GCM': aead.aead_key_templates.AES128_GCM, 'AES256_GCM': aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256,", "'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES = [ 'AesEaxKey', 'AesGcmKey', 'AesGcmSivKey', 'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key', ] DAEAD_KEY_TYPES =", "tests. ALL_LANGUAGES = ['cc', 'java', 'go', 'python'] # All KeyTypes (without the prefix", "'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256, } SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME = { name: SUPPORTED_LANGUAGES[KEY_TYPE_FROM_URL[template.type_url]] for name, template in KEY_TEMPLATE.items()", "signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256, } SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME = {", "'AesSivKey': ['cc', 'java', 'go', 'python'], 'AesCtrHmacStreamingKey': ['cc', 'java', 'go', 'python'], 'AesGcmHkdfStreamingKey': ['cc', 'java',", "'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey', ] HYBRID_PRIVATE_KEY_TYPES = ['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES = [ 'AesCmacKey', 'HmacKey', ] SIGNATURE_KEY_TYPES", ".ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC': mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256': signature.signature_key_templates.ECDSA_P256,", "SIGNATURE_KEY_TYPES = [ 'EcdsaPrivateKey', 'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey', ] PRF_KEY_TYPES = [ 'AesCmacPrfKey', 'HmacPrfKey',", "with the License. # You may obtain a copy of the License at", "'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ], 'AesCmacKey': ['AES_CMAC'], 'HmacKey': [ 'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG' ], 'EcdsaPrivateKey':", "'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'], 'AesSivKey': ['AES256_SIV'], 'AesCtrHmacStreamingKey': [ 'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB', ], 'AesGcmHkdfStreamingKey': [ 'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB',", "['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES = [ 'AesCmacKey', 'HmacKey', ] SIGNATURE_KEY_TYPES = [ 'EcdsaPrivateKey', 'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey',", "'HmacPrfKey': ['cc', 'java', 'go', 'python'], 'HkdfPrfKey': ['cc', 'java', 'go', 'python'], } KEY_TYPE_FROM_URL =", "= { 'type.googleapis.com/google.crypto.tink.' + key_type: key_type for key_type in ALL_KEY_TYPES} # For each", "} KEY_TYPE_FROM_URL = { 'type.googleapis.com/google.crypto.tink.' + key_type: key_type for key_type in ALL_KEY_TYPES} #", "'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256,", "SUPPORTED_LANGUAGES = { 'AesEaxKey': ['cc', 'java', 'python'], 'AesGcmKey': ['cc', 'java', 'go', 'python'], 'AesGcmSivKey':", "All KeyTypes (without the prefix 'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES = [ 'AesEaxKey', 'AesGcmKey', 'AesGcmSivKey', 'AesCtrHmacAeadKey',", "signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519': signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4,", "'AesEaxKey': ['AES128_EAX', 'AES256_EAX'], 'AesGcmKey': ['AES128_GCM', 'AES256_GCM'], 'AesGcmSivKey': ['AES128_GCM_SIV', 'AES256_GCM_SIV'], 'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key':", "'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC': mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG,", "'AesGcmKey', 'AesGcmSivKey', 'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key', ] DAEAD_KEY_TYPES = ['AesSivKey'] STREAMING_AEAD_KEY_TYPES = [ 'AesCtrHmacStreamingKey',", "law or agreed to in writing, software # distributed under the License is", "the License for the specific language governing permissions and # limitations under the", "HYBRID_PRIVATE_KEY_TYPES + MAC_KEY_TYPES + SIGNATURE_KEY_TYPES + PRF_KEY_TYPES) # All languages that are supported", "'AES256_GCM'], 'AesGcmSivKey': ['AES128_GCM_SIV', 'AES256_GCM_SIV'], 'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'], 'AesSivKey': ['AES256_SIV'],", "'ECDSA_P384', 'ECDSA_P384_SHA384', 'ECDSA_P521', 'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363' ], 'Ed25519PrivateKey': ['ED25519'], 'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4',", "'HkdfPrfKey': ['<KEY>'], } # KeyTemplate (as Protobuf) for each KeyTemplate name. KEY_TEMPLATE =", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "( AEAD_KEY_TYPES + DAEAD_KEY_TYPES + STREAMING_AEAD_KEY_TYPES + HYBRID_PRIVATE_KEY_TYPES + MAC_KEY_TYPES + SIGNATURE_KEY_TYPES +", "streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC': mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG':", "'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256': signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384': signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384':", "AEAD_KEY_TYPES + DAEAD_KEY_TYPES + STREAMING_AEAD_KEY_TYPES + HYBRID_PRIVATE_KEY_TYPES + MAC_KEY_TYPES + SIGNATURE_KEY_TYPES + PRF_KEY_TYPES)", "'Ed25519PrivateKey': ['ED25519'], 'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey':", "'HMAC_PRF_SHA512'], 'HkdfPrfKey': ['<KEY>'], } # KeyTemplate (as Protobuf) for each KeyTemplate name. KEY_TEMPLATE", "import prf from tink import signature from tink import streaming_aead from tink.proto import", "[ 'AesCmacKey', 'HmacKey', ] SIGNATURE_KEY_TYPES = [ 'EcdsaPrivateKey', 'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey', ] PRF_KEY_TYPES", "the specific language governing permissions and # limitations under the License. \"\"\"All KeyTypes", "['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'], 'HkdfPrfKey': ['<KEY>'], } # KeyTemplate (as Protobuf) for each KeyTemplate name.", "from tink import signature from tink import streaming_aead from tink.proto import tink_pb2 #", "in compliance with the License. # You may obtain a copy of the", "MAC_KEY_TYPES = [ 'AesCmacKey', 'HmacKey', ] SIGNATURE_KEY_TYPES = [ 'EcdsaPrivateKey', 'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey',", "from tink import aead from tink import daead from tink import hybrid from", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "{ 'type.googleapis.com/google.crypto.tink.' + key_type: key_type for key_type in ALL_KEY_TYPES} # For each KeyType,", "'go', 'python'] # All KeyTypes (without the prefix 'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES = [ 'AesEaxKey',", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "from tink import mac from tink import prf from tink import signature from", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "cross-language tests. ALL_LANGUAGES = ['cc', 'java', 'go', 'python'] # All KeyTypes (without the", "Protobuf) for each KeyTemplate name. KEY_TEMPLATE = { 'AES128_EAX': aead.aead_key_templates.AES128_EAX, 'AES256_EAX': aead.aead_key_templates.AES256_EAX, 'AES128_GCM':", "'python'], 'Ed25519PrivateKey': ['cc', 'java', 'go', 'python'], 'RsaSsaPkcs1PrivateKey': ['cc', 'java', 'python'], 'RsaSsaPssPrivateKey': ['cc', 'java',", "KeyTemplate (as Protobuf) for each KeyTemplate name. KEY_TEMPLATE = { 'AES128_EAX': aead.aead_key_templates.AES128_EAX, 'AES256_EAX':", "['cc', 'java', 'python'], 'AesGcmKey': ['cc', 'java', 'go', 'python'], 'AesGcmSivKey': ['cc', 'python'], 'AesCtrHmacAeadKey': ['cc',", "aead.aead_key_templates.AES128_GCM, 'AES256_GCM': aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305': tink_pb2.KeyTemplate(", "See the License for the specific language governing permissions and # limitations under", "daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM,", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "'AesCmacKey': ['AES_CMAC'], 'HmacKey': [ 'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG' ], 'EcdsaPrivateKey': [ 'ECDSA_P256', 'ECDSA_P384',", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "['cc', 'java', 'go', 'python'], 'HmacKey': ['cc', 'java', 'go', 'python'], 'EcdsaPrivateKey': ['cc', 'java', 'go',", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB,", "'java', 'go', 'python'] # All KeyTypes (without the prefix 'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES = [", "'java', 'go', 'python'], 'HmacPrfKey': ['cc', 'java', 'go', 'python'], 'HkdfPrfKey': ['cc', 'java', 'go', 'python'],", "(without the prefix 'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES = [ 'AesEaxKey', 'AesGcmKey', 'AesGcmSivKey', 'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key',", "'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256, } SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME =", "that are supported by a KeyType SUPPORTED_LANGUAGES = { 'AesEaxKey': ['cc', 'java', 'python'],", "(as Protobuf) for each KeyTemplate name. KEY_TEMPLATE = { 'AES128_EAX': aead.aead_key_templates.AES128_EAX, 'AES256_EAX': aead.aead_key_templates.AES256_EAX,", "'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'], 'AesSivKey': ['AES256_SIV'], 'AesCtrHmacStreamingKey': [ 'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB', ], 'AesGcmHkdfStreamingKey':", "'python'], 'EcdsaPrivateKey': ['cc', 'java', 'go', 'python'], 'Ed25519PrivateKey': ['cc', 'java', 'go', 'python'], 'RsaSsaPkcs1PrivateKey': ['cc',", "'python'], 'AesGcmHkdfStreamingKey': ['cc', 'java', 'go', 'python'], 'EciesAeadHkdfPrivateKey': ['cc', 'java', 'go', 'python'], 'AesCmacKey': ['cc',", "'java', 'go', 'python'], 'AesCtrHmacStreamingKey': ['cc', 'java', 'go', 'python'], 'AesGcmHkdfStreamingKey': ['cc', 'java', 'go', 'python'],", "languages support them.\"\"\" # Placeholder for import for type annotations from tink import", "'type.googleapis.com/google.crypto.tink.' + key_type: key_type for key_type in ALL_KEY_TYPES} # For each KeyType, a", "aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305': tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.' + 'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK),", "signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521': signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519': signature.signature_key_templates.ED25519,", "each KeyType, a list of all KeyTemplate Names that must be supported. KEY_TEMPLATE_NAMES", "prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256, } SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME = { name: SUPPORTED_LANGUAGES[KEY_TYPE_FROM_URL[template.type_url]] for name, template in", "signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521': signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363,", "'AesGcmHkdfStreamingKey': ['cc', 'java', 'go', 'python'], 'EciesAeadHkdfPrivateKey': ['cc', 'java', 'go', 'python'], 'AesCmacKey': ['cc', 'java',", "License. \"\"\"All KeyTypes and which languages support them.\"\"\" # Placeholder for import for", "= { 'AES128_EAX': aead.aead_key_templates.AES128_EAX, 'AES256_EAX': aead.aead_key_templates.AES256_EAX, 'AES128_GCM': aead.aead_key_templates.AES128_GCM, 'AES256_GCM': aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV':", "'EcdsaPrivateKey', 'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey', ] PRF_KEY_TYPES = [ 'AesCmacPrfKey', 'HmacPrfKey', 'HkdfPrfKey', ] ALL_KEY_TYPES", "for import for type annotations from tink import aead from tink import daead", "['cc', 'java', 'go', 'python'], 'AesSivKey': ['cc', 'java', 'go', 'python'], 'AesCtrHmacStreamingKey': ['cc', 'java', 'go',", "= [ 'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey', ] HYBRID_PRIVATE_KEY_TYPES = ['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES = [ 'AesCmacKey', 'HmacKey',", "+ SIGNATURE_KEY_TYPES + PRF_KEY_TYPES) # All languages that are supported by a KeyType", "Version 2.0 (the \"License\"); # you may not use this file except in", "KeyType SUPPORTED_LANGUAGES = { 'AesEaxKey': ['cc', 'java', 'python'], 'AesGcmKey': ['cc', 'java', 'go', 'python'],", "'go', 'python'], } KEY_TYPE_FROM_URL = { 'type.googleapis.com/google.crypto.tink.' + key_type: key_type for key_type in", "except in compliance with the License. # You may obtain a copy of", "that must be supported. KEY_TEMPLATE_NAMES = { 'AesEaxKey': ['AES128_EAX', 'AES256_EAX'], 'AesGcmKey': ['AES128_GCM', 'AES256_GCM'],", "], 'AesGcmHkdfStreamingKey': [ 'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB', ], 'EciesAeadHkdfPrivateKey': [ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ], 'AesCmacKey':", "['ED25519'], 'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey': ['AES_CMAC_PRF'],", "import aead from tink import daead from tink import hybrid from tink import", "'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256':", "[ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey': ['HMAC_PRF_SHA256',", "} # KeyTemplate (as Protobuf) for each KeyTemplate name. KEY_TEMPLATE = { 'AES128_EAX':", "ALL_KEY_TYPES} # For each KeyType, a list of all KeyTemplate Names that must", "'EcdsaPrivateKey': ['cc', 'java', 'go', 'python'], 'Ed25519PrivateKey': ['cc', 'java', 'go', 'python'], 'RsaSsaPkcs1PrivateKey': ['cc', 'java',", "signature from tink import streaming_aead from tink.proto import tink_pb2 # All languages supported", "'AesSivKey': ['AES256_SIV'], 'AesCtrHmacStreamingKey': [ 'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB', ], 'AesGcmHkdfStreamingKey': [ 'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB', ],", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "'go', 'python'], 'HmacKey': ['cc', 'java', 'go', 'python'], 'EcdsaPrivateKey': ['cc', 'java', 'go', 'python'], 'Ed25519PrivateKey':", "+ STREAMING_AEAD_KEY_TYPES + HYBRID_PRIVATE_KEY_TYPES + MAC_KEY_TYPES + SIGNATURE_KEY_TYPES + PRF_KEY_TYPES) # All languages", "'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519': signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4':", "signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519': signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4,", "'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey', ] PRF_KEY_TYPES = [ 'AesCmacPrfKey', 'HmacPrfKey', 'HkdfPrfKey', ] ALL_KEY_TYPES = (", "tink import signature from tink import streaming_aead from tink.proto import tink_pb2 # All", "'XChaCha20Poly1305Key', ] DAEAD_KEY_TYPES = ['AesSivKey'] STREAMING_AEAD_KEY_TYPES = [ 'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey', ] HYBRID_PRIVATE_KEY_TYPES =", "'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM':", "'HmacKey': ['cc', 'java', 'go', 'python'], 'EcdsaPrivateKey': ['cc', 'java', 'go', 'python'], 'Ed25519PrivateKey': ['cc', 'java',", "type annotations from tink import aead from tink import daead from tink import", "aead.aead_key_templates.AES256_EAX, 'AES128_GCM': aead.aead_key_templates.AES128_GCM, 'AES256_GCM': aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256,", "'ECDSA_P384_SHA384', 'ECDSA_P521', 'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363' ], 'Ed25519PrivateKey': ['ED25519'], 'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4'", "'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363' ], 'Ed25519PrivateKey': ['ED25519'], 'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey':", "'AesGcmKey': ['cc', 'java', 'go', 'python'], 'AesGcmSivKey': ['cc', 'python'], 'AesCtrHmacAeadKey': ['cc', 'java', 'go', 'python'],", "\"\"\"All KeyTypes and which languages support them.\"\"\" # Placeholder for import for type", "['XCHACHA20_POLY1305'], 'AesSivKey': ['AES256_SIV'], 'AesCtrHmacStreamingKey': [ 'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB', ], 'AesGcmHkdfStreamingKey': [ 'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB',", "'AES128_EAX': aead.aead_key_templates.AES128_EAX, 'AES256_EAX': aead.aead_key_templates.AES256_EAX, 'AES128_GCM': aead.aead_key_templates.AES128_GCM, 'AES256_GCM': aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256':", "'java', 'python'], 'AesGcmKey': ['cc', 'java', 'go', 'python'], 'AesGcmSivKey': ['cc', 'python'], 'AesCtrHmacAeadKey': ['cc', 'java',", "['cc', 'java', 'go', 'python'], 'ChaCha20Poly1305Key': ['java', 'go'], 'XChaCha20Poly1305Key': ['cc', 'java', 'go', 'python'], 'AesSivKey':", "'java', 'go', 'python'], 'HkdfPrfKey': ['cc', 'java', 'go', 'python'], } KEY_TYPE_FROM_URL = { 'type.googleapis.com/google.crypto.tink.'", "'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB', ], 'EciesAeadHkdfPrivateKey': [ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ], 'AesCmacKey': ['AES_CMAC'], 'HmacKey': [ 'HMAC_SHA256_128BITTAG',", "'python'], 'HmacKey': ['cc', 'java', 'go', 'python'], 'EcdsaPrivateKey': ['cc', 'java', 'go', 'python'], 'Ed25519PrivateKey': ['cc',", "'AesEaxKey': ['cc', 'java', 'python'], 'AesGcmKey': ['cc', 'java', 'go', 'python'], 'AesGcmSivKey': ['cc', 'python'], 'AesCtrHmacAeadKey':", "from tink.proto import tink_pb2 # All languages supported by cross-language tests. ALL_LANGUAGES =", "name. KEY_TEMPLATE = { 'AES128_EAX': aead.aead_key_templates.AES128_EAX, 'AES256_EAX': aead.aead_key_templates.AES256_EAX, 'AES128_GCM': aead.aead_key_templates.AES128_GCM, 'AES256_GCM': aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV':", "supported. KEY_TEMPLATE_NAMES = { 'AesEaxKey': ['AES128_EAX', 'AES256_EAX'], 'AesGcmKey': ['AES128_GCM', 'AES256_GCM'], 'AesGcmSivKey': ['AES128_GCM_SIV', 'AES256_GCM_SIV'],", "'HmacPrfKey': ['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'], 'HkdfPrfKey': ['<KEY>'], } # KeyTemplate (as Protobuf) for each KeyTemplate", "KEY_TYPE_FROM_URL = { 'type.googleapis.com/google.crypto.tink.' + key_type: key_type for key_type in ALL_KEY_TYPES} # For", "['AES128_EAX', 'AES256_EAX'], 'AesGcmKey': ['AES128_GCM', 'AES256_GCM'], 'AesGcmSivKey': ['AES128_GCM_SIV', 'AES256_GCM_SIV'], 'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'],", "], 'Ed25519PrivateKey': ['ED25519'], 'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ],", "'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256': signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384': signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521':", "KeyTemplate Names that must be supported. KEY_TEMPLATE_NAMES = { 'AesEaxKey': ['AES128_EAX', 'AES256_EAX'], 'AesGcmKey':", "], 'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey': ['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'], 'HkdfPrfKey': ['<KEY>'],", "'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521': signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519':", "hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC': mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG':", "= ( AEAD_KEY_TYPES + DAEAD_KEY_TYPES + STREAMING_AEAD_KEY_TYPES + HYBRID_PRIVATE_KEY_TYPES + MAC_KEY_TYPES + SIGNATURE_KEY_TYPES", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "'go', 'python'], 'AesCmacKey': ['cc', 'java', 'go', 'python'], 'HmacKey': ['cc', 'java', 'go', 'python'], 'EcdsaPrivateKey':", "'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey': ['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'],", "of all KeyTemplate Names that must be supported. KEY_TEMPLATE_NAMES = { 'AesEaxKey': ['AES128_EAX',", "Names that must be supported. KEY_TEMPLATE_NAMES = { 'AesEaxKey': ['AES128_EAX', 'AES256_EAX'], 'AesGcmKey': ['AES128_GCM',", "'AES256_CTR_HMAC_SHA256_4KB', ], 'AesGcmHkdfStreamingKey': [ 'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB', ], 'EciesAeadHkdfPrivateKey': [ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ],", "import signature from tink import streaming_aead from tink.proto import tink_pb2 # All languages" ]
[ "key hash {}'.format(key['public_key'], key_hash)) else: logging.warning(\"Couldn't public key for key hash {}\".format(key_hash)) response", "level=logging.INFO) app = Flask(__name__) # sample config used for testing config = {", "= None try: if key_hash in config['keys']: key = config['keys'][key_hash] response = jsonify({", "to sign {}'.format(data)) rs = RemoteSigner(config, data) response = jsonify({ 'signature': rs.sign(key['private_handle']) })", "rs.sign(key['private_handle']) }) logging.info('Response is {}'.format(response)) else: logging.warning(\"Couldn't find key {}\".format(key_hash)) response = Response('Key", "released under the MIT license ######################################################### from flask import Flask, request, Response, json,", "except Exception as e: data = {'error': str(e)} logging.error('Exception thrown during request: {}'.format(str(e)))", "if key_hash in config['keys']: key = config['keys'][key_hash] response = jsonify({ 'public_key': key['public_key'] })", "flask response {}'.format(response)) return response @app.route('/keys/<key_hash>', methods=['GET']) def get_public_key(key_hash): response = None try:", "flask response {}'.format(response)) return response @app.route('/authorized_keys', methods=['GET']) def authorized_keys(): return app.response_class( response=json.dumps({}), status=200,", "from src.remote_signer import RemoteSigner from os import path import logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s',", "data = request.get_json(force=True) if key_hash in config['keys']: logging.info('Found key_hash {} in config'.format(key_hash)) key", "by <NAME>, <EMAIL> # Copyright (c) 2018 Blockscale LLC # released under the", "logging.warning(\"Couldn't find key {}\".format(key_hash)) response = Response('Key not found', status=404) except Exception as", "json, jsonify from src.remote_signer import RemoteSigner from os import path import logging logging.basicConfig(filename='./remote-signer.log',", "logging.error('Exception thrown during request: {}'.format(str(e))) response = app.response_class( response=json.dumps(data), status=500, mimetype='application/json' ) logging.info('Returning", "{}'.format(json.dumps(config, indent=2))) @app.route('/keys/<key_hash>', methods=['POST']) def sign(key_hash): response = None try: data = request.get_json(force=True)", "= Response('Key not found', status=404) except Exception as e: data = {'error': str(e)}", "thrown during request: {}'.format(str(e))) response = app.response_class( response=json.dumps(data), status=500, mimetype='application/json' ) logging.info('Returning flask", "authorized_keys(): return app.response_class( response=json.dumps({}), status=200, mimetype='application/json' ) if __name__ == '__main__': app.run(host='127.0.0.1', port=5000,", "config['keys']: logging.info('Found key_hash {} in config'.format(key_hash)) key = config['keys'][key_hash] logging.info('Attempting to sign {}'.format(data))", "# sample config used for testing config = { 'hsm_username': 'resigner', 'hsm_slot': 1,", "key for key hash {}\".format(key_hash)) response = Response('Key not found', status=404) except Exception", "with open('keys.json', 'r') as myfile: json_blob = myfile.read().replace('\\n', '') logging.info('Parsed keys.json successfully as", "as JSON') config = json.loads(json_blob) logging.info('Config contains: {}'.format(json.dumps(config, indent=2))) @app.route('/keys/<key_hash>', methods=['POST']) def sign(key_hash):", "methods=['GET']) def get_public_key(key_hash): response = None try: if key_hash in config['keys']: key =", "{}'.format(data)) rs = RemoteSigner(config, data) response = jsonify({ 'signature': rs.sign(key['private_handle']) }) logging.info('Response is", "from flask import Flask, request, Response, json, jsonify from src.remote_signer import RemoteSigner from", "RemoteSigner from os import path import logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s', level=logging.INFO) app =", "= jsonify({ 'signature': rs.sign(key['private_handle']) }) logging.info('Response is {}'.format(response)) else: logging.warning(\"Couldn't find key {}\".format(key_hash))", "Flask, request, Response, json, jsonify from src.remote_signer import RemoteSigner from os import path", "in config['keys']: logging.info('Found key_hash {} in config'.format(key_hash)) key = config['keys'][key_hash] logging.info('Attempting to sign", "contains: {}'.format(json.dumps(config, indent=2))) @app.route('/keys/<key_hash>', methods=['POST']) def sign(key_hash): response = None try: data =", "{}'.format(response)) return response @app.route('/authorized_keys', methods=['GET']) def authorized_keys(): return app.response_class( response=json.dumps({}), status=200, mimetype='application/json' )", "return app.response_class( response=json.dumps({}), status=200, mimetype='application/json' ) if __name__ == '__main__': app.run(host='127.0.0.1', port=5000, debug=True)", "jsonify from src.remote_signer import RemoteSigner from os import path import logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s", "is {}'.format(response)) else: logging.warning(\"Couldn't find key {}\".format(key_hash)) response = Response('Key not found', status=404)", "response {}'.format(response)) return response @app.route('/keys/<key_hash>', methods=['GET']) def get_public_key(key_hash): response = None try: if", "= config['keys'][key_hash] response = jsonify({ 'public_key': key['public_key'] }) logging.info('Found public key {} for", "under the MIT license ######################################################### from flask import Flask, request, Response, json, jsonify", "hash {}'.format(key['public_key'], key_hash)) else: logging.warning(\"Couldn't public key for key hash {}\".format(key_hash)) response =", "{}'.format(key['public_key'], key_hash)) else: logging.warning(\"Couldn't public key for key hash {}\".format(key_hash)) response = Response('Key", "logging.info('Returning flask response {}'.format(response)) return response @app.route('/keys/<key_hash>', methods=['GET']) def get_public_key(key_hash): response = None", "'<KEY>': { 'public_key': '<KEY>', 'private_handle': 7, 'public_handle': 9 } } } logging.info('Opening keys.json')", "open('keys.json', 'r') as myfile: json_blob = myfile.read().replace('\\n', '') logging.info('Parsed keys.json successfully as JSON')", "during request: {}'.format(str(e))) response = app.response_class( response=json.dumps(data), status=500, mimetype='application/json' ) logging.info('Returning flask response", "None try: data = request.get_json(force=True) if key_hash in config['keys']: logging.info('Found key_hash {} in", "Flask(__name__) # sample config used for testing config = { 'hsm_username': 'resigner', 'hsm_slot':", "for testing config = { 'hsm_username': 'resigner', 'hsm_slot': 1, 'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr': 'http://node.internal:8732',", "logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s', level=logging.INFO) app = Flask(__name__) # sample config used for testing", "used for testing config = { 'hsm_username': 'resigner', 'hsm_slot': 1, 'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr':", "'http://node.internal:8732', 'keys': { '<KEY>': { 'public_key': '<KEY>', 'private_handle': 7, 'public_handle': 9 } }", "data = {'error': str(e)} logging.error('Exception thrown during request: {}'.format(str(e))) response = app.response_class( response=json.dumps(data),", "= config['keys'][key_hash] logging.info('Attempting to sign {}'.format(data)) rs = RemoteSigner(config, data) response = jsonify({", ") logging.info('Returning flask response {}'.format(response)) return response @app.route('/keys/<key_hash>', methods=['GET']) def get_public_key(key_hash): response =", "response = Response('Key not found', status=404) except Exception as e: data = {'error':", "app = Flask(__name__) # sample config used for testing config = { 'hsm_username':", "key {} for key hash {}'.format(key['public_key'], key_hash)) else: logging.warning(\"Couldn't public key for key", "key {}\".format(key_hash)) response = Response('Key not found', status=404) except Exception as e: data", "'hsm_slot': 1, 'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr': 'http://node.internal:8732', 'keys': { '<KEY>': { 'public_key': '<KEY>', 'private_handle':", "str(e)} logging.error('Exception thrown during request: {}'.format(str(e))) response = app.response_class( response=json.dumps(data), status=500, mimetype='application/json' )", "myfile.read().replace('\\n', '') logging.info('Parsed keys.json successfully as JSON') config = json.loads(json_blob) logging.info('Config contains: {}'.format(json.dumps(config,", "'hsm_username': 'resigner', 'hsm_slot': 1, 'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr': 'http://node.internal:8732', 'keys': { '<KEY>': { 'public_key':", "= app.response_class( response=json.dumps(data), status=500, mimetype='application/json' ) logging.info('Returning flask response {}'.format(response)) return response @app.route('/keys/<key_hash>',", "config'.format(key_hash)) key = config['keys'][key_hash] logging.info('Attempting to sign {}'.format(data)) rs = RemoteSigner(config, data) response", "} } } logging.info('Opening keys.json') if path.isfile('keys.json'): logging.info('Found keys.json') with open('keys.json', 'r') as", "status=500, mimetype='application/json' ) logging.info('Returning flask response {}'.format(response)) return response @app.route('/keys/<key_hash>', methods=['GET']) def get_public_key(key_hash):", "sample config used for testing config = { 'hsm_username': 'resigner', 'hsm_slot': 1, 'hsm_lib':", "'signature': rs.sign(key['private_handle']) }) logging.info('Response is {}'.format(response)) else: logging.warning(\"Couldn't find key {}\".format(key_hash)) response =", "'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr': 'http://node.internal:8732', 'keys': { '<KEY>': { 'public_key': '<KEY>', 'private_handle': 7, 'public_handle':", "try: if key_hash in config['keys']: key = config['keys'][key_hash] response = jsonify({ 'public_key': key['public_key']", "key['public_key'] }) logging.info('Found public key {} for key hash {}'.format(key['public_key'], key_hash)) else: logging.warning(\"Couldn't", "myfile: json_blob = myfile.read().replace('\\n', '') logging.info('Parsed keys.json successfully as JSON') config = json.loads(json_blob)", "response = jsonify({ 'signature': rs.sign(key['private_handle']) }) logging.info('Response is {}'.format(response)) else: logging.warning(\"Couldn't find key", "response = jsonify({ 'public_key': key['public_key'] }) logging.info('Found public key {} for key hash", "import path import logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s', level=logging.INFO) app = Flask(__name__) # sample", "# Written by <NAME>, <EMAIL> # Copyright (c) 2018 Blockscale LLC # released", "######################################################### from flask import Flask, request, Response, json, jsonify from src.remote_signer import RemoteSigner", "}) logging.info('Response is {}'.format(response)) else: logging.warning(\"Couldn't find key {}\".format(key_hash)) response = Response('Key not", "'resigner', 'hsm_slot': 1, 'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr': 'http://node.internal:8732', 'keys': { '<KEY>': { 'public_key': '<KEY>',", "<NAME>, <EMAIL> # Copyright (c) 2018 Blockscale LLC # released under the MIT", "{ 'public_key': '<KEY>', 'private_handle': 7, 'public_handle': 9 } } } logging.info('Opening keys.json') if", "= { 'hsm_username': 'resigner', 'hsm_slot': 1, 'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr': 'http://node.internal:8732', 'keys': { '<KEY>':", "successfully as JSON') config = json.loads(json_blob) logging.info('Config contains: {}'.format(json.dumps(config, indent=2))) @app.route('/keys/<key_hash>', methods=['POST']) def", "Copyright (c) 2018 Blockscale LLC # released under the MIT license ######################################################### from", "status=404) except Exception as e: data = {'error': str(e)} logging.error('Exception thrown during request:", "key = config['keys'][key_hash] logging.info('Attempting to sign {}'.format(data)) rs = RemoteSigner(config, data) response =", "@app.route('/authorized_keys', methods=['GET']) def authorized_keys(): return app.response_class( response=json.dumps({}), status=200, mimetype='application/json' ) if __name__ ==", "{'error': str(e)} logging.error('Exception thrown during request: {}'.format(str(e))) response = app.response_class( response=json.dumps(data), status=500, mimetype='application/json'", "'private_handle': 7, 'public_handle': 9 } } } logging.info('Opening keys.json') if path.isfile('keys.json'): logging.info('Found keys.json')", "import logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s', level=logging.INFO) app = Flask(__name__) # sample config used", "testing config = { 'hsm_username': 'resigner', 'hsm_slot': 1, 'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr': 'http://node.internal:8732', 'keys':", "'r') as myfile: json_blob = myfile.read().replace('\\n', '') logging.info('Parsed keys.json successfully as JSON') config", "key_hash {} in config'.format(key_hash)) key = config['keys'][key_hash] logging.info('Attempting to sign {}'.format(data)) rs =", "response @app.route('/authorized_keys', methods=['GET']) def authorized_keys(): return app.response_class( response=json.dumps({}), status=200, mimetype='application/json' ) if __name__", "src.remote_signer import RemoteSigner from os import path import logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s', level=logging.INFO)", "the MIT license ######################################################### from flask import Flask, request, Response, json, jsonify from", "if path.isfile('keys.json'): logging.info('Found keys.json') with open('keys.json', 'r') as myfile: json_blob = myfile.read().replace('\\n', '')", "keys.json') with open('keys.json', 'r') as myfile: json_blob = myfile.read().replace('\\n', '') logging.info('Parsed keys.json successfully", "logging.info('Parsed keys.json successfully as JSON') config = json.loads(json_blob) logging.info('Config contains: {}'.format(json.dumps(config, indent=2))) @app.route('/keys/<key_hash>',", "'<KEY>', 'private_handle': 7, 'public_handle': 9 } } } logging.info('Opening keys.json') if path.isfile('keys.json'): logging.info('Found", "python3 ######################################################### # Written by <NAME>, <EMAIL> # Copyright (c) 2018 Blockscale LLC", "os import path import logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s', level=logging.INFO) app = Flask(__name__) #", "for key hash {}'.format(key['public_key'], key_hash)) else: logging.warning(\"Couldn't public key for key hash {}\".format(key_hash))", "None try: if key_hash in config['keys']: key = config['keys'][key_hash] response = jsonify({ 'public_key':", "key_hash in config['keys']: logging.info('Found key_hash {} in config'.format(key_hash)) key = config['keys'][key_hash] logging.info('Attempting to", "{ 'hsm_username': 'resigner', 'hsm_slot': 1, 'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr': 'http://node.internal:8732', 'keys': { '<KEY>': {", "import RemoteSigner from os import path import logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s', level=logging.INFO) app", "logging.warning(\"Couldn't public key for key hash {}\".format(key_hash)) response = Response('Key not found', status=404)", "public key for key hash {}\".format(key_hash)) response = Response('Key not found', status=404) except", "= Flask(__name__) # sample config used for testing config = { 'hsm_username': 'resigner',", "{} in config'.format(key_hash)) key = config['keys'][key_hash] logging.info('Attempting to sign {}'.format(data)) rs = RemoteSigner(config,", "= {'error': str(e)} logging.error('Exception thrown during request: {}'.format(str(e))) response = app.response_class( response=json.dumps(data), status=500,", "JSON') config = json.loads(json_blob) logging.info('Config contains: {}'.format(json.dumps(config, indent=2))) @app.route('/keys/<key_hash>', methods=['POST']) def sign(key_hash): response", "7, 'public_handle': 9 } } } logging.info('Opening keys.json') if path.isfile('keys.json'): logging.info('Found keys.json') with", "= jsonify({ 'public_key': key['public_key'] }) logging.info('Found public key {} for key hash {}'.format(key['public_key'],", "indent=2))) @app.route('/keys/<key_hash>', methods=['POST']) def sign(key_hash): response = None try: data = request.get_json(force=True) if", "import Flask, request, Response, json, jsonify from src.remote_signer import RemoteSigner from os import", "Response, json, jsonify from src.remote_signer import RemoteSigner from os import path import logging", "{}'.format(str(e))) response = app.response_class( response=json.dumps(data), status=500, mimetype='application/json' ) logging.info('Returning flask response {}'.format(response)) return", "config['keys']: key = config['keys'][key_hash] response = jsonify({ 'public_key': key['public_key'] }) logging.info('Found public key", "= None try: data = request.get_json(force=True) if key_hash in config['keys']: logging.info('Found key_hash {}", ") logging.info('Returning flask response {}'.format(response)) return response @app.route('/authorized_keys', methods=['GET']) def authorized_keys(): return app.response_class(", "if key_hash in config['keys']: logging.info('Found key_hash {} in config'.format(key_hash)) key = config['keys'][key_hash] logging.info('Attempting", "def authorized_keys(): return app.response_class( response=json.dumps({}), status=200, mimetype='application/json' ) if __name__ == '__main__': app.run(host='127.0.0.1',", "'/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr': 'http://node.internal:8732', 'keys': { '<KEY>': { 'public_key': '<KEY>', 'private_handle': 7, 'public_handle': 9", "try: data = request.get_json(force=True) if key_hash in config['keys']: logging.info('Found key_hash {} in config'.format(key_hash))", "jsonify({ 'public_key': key['public_key'] }) logging.info('Found public key {} for key hash {}'.format(key['public_key'], key_hash))", "######################################################### # Written by <NAME>, <EMAIL> # Copyright (c) 2018 Blockscale LLC #", "config = json.loads(json_blob) logging.info('Config contains: {}'.format(json.dumps(config, indent=2))) @app.route('/keys/<key_hash>', methods=['POST']) def sign(key_hash): response =", "2018 Blockscale LLC # released under the MIT license ######################################################### from flask import", "config used for testing config = { 'hsm_username': 'resigner', 'hsm_slot': 1, 'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so',", "response @app.route('/keys/<key_hash>', methods=['GET']) def get_public_key(key_hash): response = None try: if key_hash in config['keys']:", "{} for key hash {}'.format(key['public_key'], key_hash)) else: logging.warning(\"Couldn't public key for key hash", "Response('Key not found', status=404) except Exception as e: data = {'error': str(e)} logging.error('Exception", "app.response_class( response=json.dumps(data), status=500, mimetype='application/json' ) logging.info('Returning flask response {}'.format(response)) return response @app.route('/authorized_keys', methods=['GET'])", "'') logging.info('Parsed keys.json successfully as JSON') config = json.loads(json_blob) logging.info('Config contains: {}'.format(json.dumps(config, indent=2)))", "key_hash in config['keys']: key = config['keys'][key_hash] response = jsonify({ 'public_key': key['public_key'] }) logging.info('Found", "@app.route('/keys/<key_hash>', methods=['POST']) def sign(key_hash): response = None try: data = request.get_json(force=True) if key_hash", "else: logging.warning(\"Couldn't public key for key hash {}\".format(key_hash)) response = Response('Key not found',", "logging.info('Config contains: {}'.format(json.dumps(config, indent=2))) @app.route('/keys/<key_hash>', methods=['POST']) def sign(key_hash): response = None try: data", "logging.info('Opening keys.json') if path.isfile('keys.json'): logging.info('Found keys.json') with open('keys.json', 'r') as myfile: json_blob =", "format='%(asctime)s %(message)s', level=logging.INFO) app = Flask(__name__) # sample config used for testing config", "status=500, mimetype='application/json' ) logging.info('Returning flask response {}'.format(response)) return response @app.route('/authorized_keys', methods=['GET']) def authorized_keys():", "get_public_key(key_hash): response = None try: if key_hash in config['keys']: key = config['keys'][key_hash] response", "Written by <NAME>, <EMAIL> # Copyright (c) 2018 Blockscale LLC # released under", "found', status=404) except Exception as e: data = {'error': str(e)} logging.error('Exception thrown during", "sign {}'.format(data)) rs = RemoteSigner(config, data) response = jsonify({ 'signature': rs.sign(key['private_handle']) }) logging.info('Response", "json_blob = myfile.read().replace('\\n', '') logging.info('Parsed keys.json successfully as JSON') config = json.loads(json_blob) logging.info('Config", "from os import path import logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s', level=logging.INFO) app = Flask(__name__)", "not found', status=404) except Exception as e: data = {'error': str(e)} logging.error('Exception thrown", "app.response_class( response=json.dumps(data), status=500, mimetype='application/json' ) logging.info('Returning flask response {}'.format(response)) return response @app.route('/keys/<key_hash>', methods=['GET'])", "logging.info('Found public key {} for key hash {}'.format(key['public_key'], key_hash)) else: logging.warning(\"Couldn't public key", "key_hash)) else: logging.warning(\"Couldn't public key for key hash {}\".format(key_hash)) response = Response('Key not", "'public_handle': 9 } } } logging.info('Opening keys.json') if path.isfile('keys.json'): logging.info('Found keys.json') with open('keys.json',", "flask import Flask, request, Response, json, jsonify from src.remote_signer import RemoteSigner from os", "%(message)s', level=logging.INFO) app = Flask(__name__) # sample config used for testing config =", "response=json.dumps(data), status=500, mimetype='application/json' ) logging.info('Returning flask response {}'.format(response)) return response @app.route('/authorized_keys', methods=['GET']) def", "= RemoteSigner(config, data) response = jsonify({ 'signature': rs.sign(key['private_handle']) }) logging.info('Response is {}'.format(response)) else:", "request, Response, json, jsonify from src.remote_signer import RemoteSigner from os import path import", "methods=['POST']) def sign(key_hash): response = None try: data = request.get_json(force=True) if key_hash in", "logging.info('Found keys.json') with open('keys.json', 'r') as myfile: json_blob = myfile.read().replace('\\n', '') logging.info('Parsed keys.json", "as myfile: json_blob = myfile.read().replace('\\n', '') logging.info('Parsed keys.json successfully as JSON') config =", "1, 'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr': 'http://node.internal:8732', 'keys': { '<KEY>': { 'public_key': '<KEY>', 'private_handle': 7,", "jsonify({ 'signature': rs.sign(key['private_handle']) }) logging.info('Response is {}'.format(response)) else: logging.warning(\"Couldn't find key {}\".format(key_hash)) response", "@app.route('/keys/<key_hash>', methods=['GET']) def get_public_key(key_hash): response = None try: if key_hash in config['keys']: key", "keys.json successfully as JSON') config = json.loads(json_blob) logging.info('Config contains: {}'.format(json.dumps(config, indent=2))) @app.route('/keys/<key_hash>', methods=['POST'])", "Blockscale LLC # released under the MIT license ######################################################### from flask import Flask,", "request: {}'.format(str(e))) response = app.response_class( response=json.dumps(data), status=500, mimetype='application/json' ) logging.info('Returning flask response {}'.format(response))", "for key hash {}\".format(key_hash)) response = Response('Key not found', status=404) except Exception as", "}) logging.info('Found public key {} for key hash {}'.format(key['public_key'], key_hash)) else: logging.warning(\"Couldn't public", "# Copyright (c) 2018 Blockscale LLC # released under the MIT license #########################################################", "'public_key': '<KEY>', 'private_handle': 7, 'public_handle': 9 } } } logging.info('Opening keys.json') if path.isfile('keys.json'):", "def sign(key_hash): response = None try: data = request.get_json(force=True) if key_hash in config['keys']:", "MIT license ######################################################### from flask import Flask, request, Response, json, jsonify from src.remote_signer", "= request.get_json(force=True) if key_hash in config['keys']: logging.info('Found key_hash {} in config'.format(key_hash)) key =", "LLC # released under the MIT license ######################################################### from flask import Flask, request,", "'node_addr': 'http://node.internal:8732', 'keys': { '<KEY>': { 'public_key': '<KEY>', 'private_handle': 7, 'public_handle': 9 }", "hash {}\".format(key_hash)) response = Response('Key not found', status=404) except Exception as e: data", "public key {} for key hash {}'.format(key['public_key'], key_hash)) else: logging.warning(\"Couldn't public key for", "#!/usr/bin/env python3 ######################################################### # Written by <NAME>, <EMAIL> # Copyright (c) 2018 Blockscale", "# released under the MIT license ######################################################### from flask import Flask, request, Response,", "e: data = {'error': str(e)} logging.error('Exception thrown during request: {}'.format(str(e))) response = app.response_class(", "key = config['keys'][key_hash] response = jsonify({ 'public_key': key['public_key'] }) logging.info('Found public key {}", "{}'.format(response)) else: logging.warning(\"Couldn't find key {}\".format(key_hash)) response = Response('Key not found', status=404) except", "Exception as e: data = {'error': str(e)} logging.error('Exception thrown during request: {}'.format(str(e))) response", "license ######################################################### from flask import Flask, request, Response, json, jsonify from src.remote_signer import", "config['keys'][key_hash] response = jsonify({ 'public_key': key['public_key'] }) logging.info('Found public key {} for key", "in config['keys']: key = config['keys'][key_hash] response = jsonify({ 'public_key': key['public_key'] }) logging.info('Found public", "def get_public_key(key_hash): response = None try: if key_hash in config['keys']: key = config['keys'][key_hash]", "= app.response_class( response=json.dumps(data), status=500, mimetype='application/json' ) logging.info('Returning flask response {}'.format(response)) return response @app.route('/authorized_keys',", "return response @app.route('/keys/<key_hash>', methods=['GET']) def get_public_key(key_hash): response = None try: if key_hash in", "data) response = jsonify({ 'signature': rs.sign(key['private_handle']) }) logging.info('Response is {}'.format(response)) else: logging.warning(\"Couldn't find", "json.loads(json_blob) logging.info('Config contains: {}'.format(json.dumps(config, indent=2))) @app.route('/keys/<key_hash>', methods=['POST']) def sign(key_hash): response = None try:", "{ '<KEY>': { 'public_key': '<KEY>', 'private_handle': 7, 'public_handle': 9 } } } logging.info('Opening", "else: logging.warning(\"Couldn't find key {}\".format(key_hash)) response = Response('Key not found', status=404) except Exception", "find key {}\".format(key_hash)) response = Response('Key not found', status=404) except Exception as e:", "response = None try: data = request.get_json(force=True) if key_hash in config['keys']: logging.info('Found key_hash", "rs = RemoteSigner(config, data) response = jsonify({ 'signature': rs.sign(key['private_handle']) }) logging.info('Response is {}'.format(response))", "9 } } } logging.info('Opening keys.json') if path.isfile('keys.json'): logging.info('Found keys.json') with open('keys.json', 'r')", "logging.info('Found key_hash {} in config'.format(key_hash)) key = config['keys'][key_hash] logging.info('Attempting to sign {}'.format(data)) rs", "request.get_json(force=True) if key_hash in config['keys']: logging.info('Found key_hash {} in config'.format(key_hash)) key = config['keys'][key_hash]", "= myfile.read().replace('\\n', '') logging.info('Parsed keys.json successfully as JSON') config = json.loads(json_blob) logging.info('Config contains:", "key hash {}\".format(key_hash)) response = Response('Key not found', status=404) except Exception as e:", "= json.loads(json_blob) logging.info('Config contains: {}'.format(json.dumps(config, indent=2))) @app.route('/keys/<key_hash>', methods=['POST']) def sign(key_hash): response = None", "{}\".format(key_hash)) response = Response('Key not found', status=404) except Exception as e: data =", "methods=['GET']) def authorized_keys(): return app.response_class( response=json.dumps({}), status=200, mimetype='application/json' ) if __name__ == '__main__':", "mimetype='application/json' ) logging.info('Returning flask response {}'.format(response)) return response @app.route('/keys/<key_hash>', methods=['GET']) def get_public_key(key_hash): response", "'keys': { '<KEY>': { 'public_key': '<KEY>', 'private_handle': 7, 'public_handle': 9 } } }", "logging.info('Response is {}'.format(response)) else: logging.warning(\"Couldn't find key {}\".format(key_hash)) response = Response('Key not found',", "'public_key': key['public_key'] }) logging.info('Found public key {} for key hash {}'.format(key['public_key'], key_hash)) else:", "} logging.info('Opening keys.json') if path.isfile('keys.json'): logging.info('Found keys.json') with open('keys.json', 'r') as myfile: json_blob", "sign(key_hash): response = None try: data = request.get_json(force=True) if key_hash in config['keys']: logging.info('Found", "response=json.dumps(data), status=500, mimetype='application/json' ) logging.info('Returning flask response {}'.format(response)) return response @app.route('/keys/<key_hash>', methods=['GET']) def", "mimetype='application/json' ) logging.info('Returning flask response {}'.format(response)) return response @app.route('/authorized_keys', methods=['GET']) def authorized_keys(): return", "config['keys'][key_hash] logging.info('Attempting to sign {}'.format(data)) rs = RemoteSigner(config, data) response = jsonify({ 'signature':", "(c) 2018 Blockscale LLC # released under the MIT license ######################################################### from flask", "in config'.format(key_hash)) key = config['keys'][key_hash] logging.info('Attempting to sign {}'.format(data)) rs = RemoteSigner(config, data)", "logging.info('Attempting to sign {}'.format(data)) rs = RemoteSigner(config, data) response = jsonify({ 'signature': rs.sign(key['private_handle'])", "response = None try: if key_hash in config['keys']: key = config['keys'][key_hash] response =", "RemoteSigner(config, data) response = jsonify({ 'signature': rs.sign(key['private_handle']) }) logging.info('Response is {}'.format(response)) else: logging.warning(\"Couldn't", "config = { 'hsm_username': 'resigner', 'hsm_slot': 1, 'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr': 'http://node.internal:8732', 'keys': {", "as e: data = {'error': str(e)} logging.error('Exception thrown during request: {}'.format(str(e))) response =", "} } logging.info('Opening keys.json') if path.isfile('keys.json'): logging.info('Found keys.json') with open('keys.json', 'r') as myfile:", "logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s', level=logging.INFO) app = Flask(__name__) # sample config used for", "keys.json') if path.isfile('keys.json'): logging.info('Found keys.json') with open('keys.json', 'r') as myfile: json_blob = myfile.read().replace('\\n',", "path.isfile('keys.json'): logging.info('Found keys.json') with open('keys.json', 'r') as myfile: json_blob = myfile.read().replace('\\n', '') logging.info('Parsed", "logging.info('Returning flask response {}'.format(response)) return response @app.route('/authorized_keys', methods=['GET']) def authorized_keys(): return app.response_class( response=json.dumps({}),", "response {}'.format(response)) return response @app.route('/authorized_keys', methods=['GET']) def authorized_keys(): return app.response_class( response=json.dumps({}), status=200, mimetype='application/json'", "<EMAIL> # Copyright (c) 2018 Blockscale LLC # released under the MIT license", "path import logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s', level=logging.INFO) app = Flask(__name__) # sample config", "return response @app.route('/authorized_keys', methods=['GET']) def authorized_keys(): return app.response_class( response=json.dumps({}), status=200, mimetype='application/json' ) if", "response = app.response_class( response=json.dumps(data), status=500, mimetype='application/json' ) logging.info('Returning flask response {}'.format(response)) return response", "{}'.format(response)) return response @app.route('/keys/<key_hash>', methods=['GET']) def get_public_key(key_hash): response = None try: if key_hash" ]
[ "0x1 UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO = 0x4 def read_unwind_info(view, address):", "None: runtime_function['BeginAddress'] += view.start runtime_function['EndAddress'] += view.start runtime_function['UnwindData'] += view.start return runtime_function, address", "is None: continue start_address = runtime_function['BeginAddress'] if not view.is_offset_executable(start_address): continue if view.get_functions_containing(start_address): continue", "def read_unwind_info(view, address): unwind_info, address = UNWIND_INFO_t.read(view, address) if unwind_info is not None:", "break update_percentage(thread, unwind_entrys, unwind_entrys_end, runtime_address, 'Parsing Unwind Info - Found {0} functions'.format(len(funcs))) runtime_function,", "unwind_codes if unwind_info['Flags'] & UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address = read_runtime_function(view, address) return unwind_info, address", "UNWIND_CODE_t.read(view, address) if unwind_code is not None: split_bits(unwind_code, 'UnwindOpAndInfo', [ ('UnwindOp', 0, 4),", "for i in range(unwind_info['CountOfCodes']): unwind_code, address = read_unwind_code(view, address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] = unwind_codes", "]) if unwind_info['Version'] == 1: unwind_codes = [ ] for i in range(unwind_info['CountOfCodes']):", "read_runtime_function(view, runtime_address) if runtime_function is None: continue start_address = runtime_function['BeginAddress'] if not view.is_offset_executable(start_address):", "unwind_entrys, unwind_entrys_end, runtime_address, 'Parsing Unwind Info - Found {0} functions'.format(len(funcs))) runtime_function, _ =", "in range(unwind_info['CountOfCodes']): unwind_code, address = read_unwind_code(view, address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] = unwind_codes if unwind_info['Flags']", "if unwind_info is not None: split_bits(unwind_info, 'VersionAndFlags', [ ('Version', 0, 3), ('Flags', 3,", "= read_runtime_function(view, runtime_address) if runtime_function is None: continue start_address = runtime_function['BeginAddress'] if not", "if runtime_function is not None: runtime_function['BeginAddress'] += view.start runtime_function['EndAddress'] += view.start runtime_function['UnwindData'] +=", "unwind_info['Version'] == 1: unwind_codes = [ ] for i in range(unwind_info['CountOfCodes']): unwind_code, address", "log.log_info('Exception Data @ 0x{0:X} => 0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for runtime_address in range(unwind_entrys, unwind_entrys_end, 12):", "info_address) if unwind_info is None: continue if 'FunctionEntry' in unwind_info: continue funcs.add(start_address) if", "4) ]) if unwind_info['Version'] == 1: unwind_codes = [ ] for i in", "if not view.is_offset_executable(start_address): continue if view.get_functions_containing(start_address): continue info_address = runtime_function['UnwindData'] unwind_info, _ =", "split_bits, update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t = BinjaStruct('<III', names = ('BeginAddress', 'EndAddress', 'UnwindData')) def", "if thread.cancelled: break update_percentage(thread, unwind_entrys, unwind_entrys_end, runtime_address, 'Parsing Unwind Info - Found {0}", "[ ('FrameRegister', 0, 4), ('FrameOffset', 4, 4) ]) if unwind_info['Version'] == 1: unwind_codes", "read_runtime_function(view, address) return unwind_info, address UNWIND_CODE_t = BinjaStruct('<BB', names = ('CodeOffset', 'UnwindOpAndInfo')) def", "import log from .utils import BinjaStruct, read_pe_header, split_bits, update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t =", "[ ('UnwindOp', 0, 4), ('OpInfo', 4, 4) ]) return unwind_code, address def parse_unwind_info(thread,", "# https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t = BinjaStruct('<III', names = ('BeginAddress', 'EndAddress', 'UnwindData')) def read_runtime_function(view, address):", "= 0x0 UNW_FLAG_EHANDLER = 0x1 UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO =", "BinjaStruct('<BBBB', names = ('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER = 0x0 UNW_FLAG_EHANDLER = 0x1", "unwind_info is not None: split_bits(unwind_info, 'VersionAndFlags', [ ('Version', 0, 3), ('Flags', 3, 5)", "not thread.cancelled: thread.progress = 'Creating {0} Function'.format(len(funcs)) log.log_info('Found {0} functions'.format(len(funcs))) for func in", "+= view.start return runtime_function, address UNWIND_INFO_t = BinjaStruct('<BBBB', names = ('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes',", "parse_unwind_info(thread, view): base_address = view.start pe = read_pe_header(view) unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys =", "= [ ] for i in range(unwind_info['CountOfCodes']): unwind_code, address = read_unwind_code(view, address) unwind_codes.append(unwind_code)", "view.start pe = read_pe_header(view) unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys = base_address + unwind_directory.VirtualAddress unwind_entrys_end", "https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t = BinjaStruct('<III', names = ('BeginAddress', 'EndAddress', 'UnwindData')) def read_runtime_function(view, address): runtime_function,", "UNW_FLAG_EHANDLER = 0x1 UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO = 0x4 def", "12): if thread.cancelled: break update_percentage(thread, unwind_entrys, unwind_entrys_end, runtime_address, 'Parsing Unwind Info - Found", "is None: continue if 'FunctionEntry' in unwind_info: continue funcs.add(start_address) if not thread.cancelled: thread.progress", "unwind_entrys_end, runtime_address, 'Parsing Unwind Info - Found {0} functions'.format(len(funcs))) runtime_function, _ = read_runtime_function(view,", "range(unwind_info['CountOfCodes']): unwind_code, address = read_unwind_code(view, address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] = unwind_codes if unwind_info['Flags'] &", "UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address = read_runtime_function(view, address) return unwind_info, address UNWIND_CODE_t = BinjaStruct('<BB', names", "unwind_entrys_end)) for runtime_address in range(unwind_entrys, unwind_entrys_end, 12): if thread.cancelled: break update_percentage(thread, unwind_entrys, unwind_entrys_end,", "UNWIND_INFO_t.read(view, address) if unwind_info is not None: split_bits(unwind_info, 'VersionAndFlags', [ ('Version', 0, 3),", "= set() log.log_info('Exception Data @ 0x{0:X} => 0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for runtime_address in range(unwind_entrys,", "is not None: split_bits(unwind_info, 'VersionAndFlags', [ ('Version', 0, 3), ('Flags', 3, 5) ])", "Found {0} functions'.format(len(funcs))) runtime_function, _ = read_runtime_function(view, runtime_address) if runtime_function is None: continue", "== 1: unwind_codes = [ ] for i in range(unwind_info['CountOfCodes']): unwind_code, address =", "0x4 def read_unwind_info(view, address): unwind_info, address = UNWIND_INFO_t.read(view, address) if unwind_info is not", "= 0x2 UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO = 0x4 def read_unwind_info(view, address): unwind_info, address", "4, 4) ]) return unwind_code, address def parse_unwind_info(thread, view): base_address = view.start pe", "runtime_address) if runtime_function is None: continue start_address = runtime_function['BeginAddress'] if not view.is_offset_executable(start_address): continue", "read_unwind_code(view, address): unwind_code, address = UNWIND_CODE_t.read(view, address) if unwind_code is not None: split_bits(unwind_code,", "= ('CodeOffset', 'UnwindOpAndInfo')) def read_unwind_code(view, address): unwind_code, address = UNWIND_CODE_t.read(view, address) if unwind_code", "]) split_bits(unwind_info, 'FrameRegisterAndOffset', [ ('FrameRegister', 0, 4), ('FrameOffset', 4, 4) ]) if unwind_info['Version']", "continue funcs.add(start_address) if not thread.cancelled: thread.progress = 'Creating {0} Function'.format(len(funcs)) log.log_info('Found {0} functions'.format(len(funcs)))", "unwind_entrys_end, 12): if thread.cancelled: break update_percentage(thread, unwind_entrys, unwind_entrys_end, runtime_address, 'Parsing Unwind Info -", "unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys = base_address + unwind_directory.VirtualAddress unwind_entrys_end = unwind_entrys + unwind_directory.Size", "if unwind_info['Version'] == 1: unwind_codes = [ ] for i in range(unwind_info['CountOfCodes']): unwind_code,", "if unwind_code is not None: split_bits(unwind_code, 'UnwindOpAndInfo', [ ('UnwindOp', 0, 4), ('OpInfo', 4,", "unwind_entrys + unwind_directory.Size funcs = set() log.log_info('Exception Data @ 0x{0:X} => 0x{1:X}'.format(unwind_entrys, unwind_entrys_end))", "4) ]) return unwind_code, address def parse_unwind_info(thread, view): base_address = view.start pe =", "3, 5) ]) split_bits(unwind_info, 'FrameRegisterAndOffset', [ ('FrameRegister', 0, 4), ('FrameOffset', 4, 4) ])", "5) ]) split_bits(unwind_info, 'FrameRegisterAndOffset', [ ('FrameRegister', 0, 4), ('FrameOffset', 4, 4) ]) if", "runtime_function is not None: runtime_function['BeginAddress'] += view.start runtime_function['EndAddress'] += view.start runtime_function['UnwindData'] += view.start", "unwind_info['FunctionEntry'], address = read_runtime_function(view, address) return unwind_info, address UNWIND_CODE_t = BinjaStruct('<BB', names =", "return unwind_code, address def parse_unwind_info(thread, view): base_address = view.start pe = read_pe_header(view) unwind_directory", "'EndAddress', 'UnwindData')) def read_runtime_function(view, address): runtime_function, address = RUNTIME_FUNCTION_t.read(view, address, 4) if runtime_function", "4) if runtime_function is not None: runtime_function['BeginAddress'] += view.start runtime_function['EndAddress'] += view.start runtime_function['UnwindData']", "unwind_entrys_end = unwind_entrys + unwind_directory.Size funcs = set() log.log_info('Exception Data @ 0x{0:X} =>", "UNW_FLAG_CHAININFO = 0x4 def read_unwind_info(view, address): unwind_info, address = UNWIND_INFO_t.read(view, address) if unwind_info", "UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO = 0x4 def read_unwind_info(view, address): unwind_info,", "return runtime_function, address UNWIND_INFO_t = BinjaStruct('<BBBB', names = ('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER", "binaryninja import log from .utils import BinjaStruct, read_pe_header, split_bits, update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t", "None: split_bits(unwind_info, 'VersionAndFlags', [ ('Version', 0, 3), ('Flags', 3, 5) ]) split_bits(unwind_info, 'FrameRegisterAndOffset',", "('Version', 0, 3), ('Flags', 3, 5) ]) split_bits(unwind_info, 'FrameRegisterAndOffset', [ ('FrameRegister', 0, 4),", "('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER = 0x0 UNW_FLAG_EHANDLER = 0x1 UNW_FLAG_UHANDLER = 0x2", "UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO = 0x4 def read_unwind_info(view, address): unwind_info, address = UNWIND_INFO_t.read(view,", "unwind_code, address = read_unwind_code(view, address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] = unwind_codes if unwind_info['Flags'] & UNW_FLAG_CHAININFO:", "_ = read_runtime_function(view, runtime_address) if runtime_function is None: continue start_address = runtime_function['BeginAddress'] if", "functions'.format(len(funcs))) runtime_function, _ = read_runtime_function(view, runtime_address) if runtime_function is None: continue start_address =", "funcs.add(start_address) if not thread.cancelled: thread.progress = 'Creating {0} Function'.format(len(funcs)) log.log_info('Found {0} functions'.format(len(funcs))) for", "names = ('BeginAddress', 'EndAddress', 'UnwindData')) def read_runtime_function(view, address): runtime_function, address = RUNTIME_FUNCTION_t.read(view, address,", "& UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address = read_runtime_function(view, address) return unwind_info, address UNWIND_CODE_t = BinjaStruct('<BB',", "{0} functions'.format(len(funcs))) runtime_function, _ = read_runtime_function(view, runtime_address) if runtime_function is None: continue start_address", "runtime_function, _ = read_runtime_function(view, runtime_address) if runtime_function is None: continue start_address = runtime_function['BeginAddress']", "runtime_function['BeginAddress'] if not view.is_offset_executable(start_address): continue if view.get_functions_containing(start_address): continue info_address = runtime_function['UnwindData'] unwind_info, _", "Info - Found {0} functions'.format(len(funcs))) runtime_function, _ = read_runtime_function(view, runtime_address) if runtime_function is", "split_bits(unwind_code, 'UnwindOpAndInfo', [ ('UnwindOp', 0, 4), ('OpInfo', 4, 4) ]) return unwind_code, address", "funcs = set() log.log_info('Exception Data @ 0x{0:X} => 0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for runtime_address in", "- Found {0} functions'.format(len(funcs))) runtime_function, _ = read_runtime_function(view, runtime_address) if runtime_function is None:", "0x2 UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO = 0x4 def read_unwind_info(view, address): unwind_info, address =", "base_address = view.start pe = read_pe_header(view) unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys = base_address +", "('CodeOffset', 'UnwindOpAndInfo')) def read_unwind_code(view, address): unwind_code, address = UNWIND_CODE_t.read(view, address) if unwind_code is", "is not None: split_bits(unwind_code, 'UnwindOpAndInfo', [ ('UnwindOp', 0, 4), ('OpInfo', 4, 4) ])", "runtime_function is None: continue start_address = runtime_function['BeginAddress'] if not view.is_offset_executable(start_address): continue if view.get_functions_containing(start_address):", "runtime_address in range(unwind_entrys, unwind_entrys_end, 12): if thread.cancelled: break update_percentage(thread, unwind_entrys, unwind_entrys_end, runtime_address, 'Parsing", "address, 4) if runtime_function is not None: runtime_function['BeginAddress'] += view.start runtime_function['EndAddress'] += view.start", "runtime_function['UnwindData'] += view.start return runtime_function, address UNWIND_INFO_t = BinjaStruct('<BBBB', names = ('VersionAndFlags', 'SizeOfProlog',", "unwind_info['UnwindCodes'] = unwind_codes if unwind_info['Flags'] & UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address = read_runtime_function(view, address) return", "update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t = BinjaStruct('<III', names = ('BeginAddress', 'EndAddress', 'UnwindData')) def read_runtime_function(view,", "= BinjaStruct('<III', names = ('BeginAddress', 'EndAddress', 'UnwindData')) def read_runtime_function(view, address): runtime_function, address =", "continue start_address = runtime_function['BeginAddress'] if not view.is_offset_executable(start_address): continue if view.get_functions_containing(start_address): continue info_address =", "= BinjaStruct('<BBBB', names = ('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER = 0x0 UNW_FLAG_EHANDLER =", "'FunctionEntry' in unwind_info: continue funcs.add(start_address) if not thread.cancelled: thread.progress = 'Creating {0} Function'.format(len(funcs))", "= UNWIND_INFO_t.read(view, address) if unwind_info is not None: split_bits(unwind_info, 'VersionAndFlags', [ ('Version', 0,", "unwind_info is None: continue if 'FunctionEntry' in unwind_info: continue funcs.add(start_address) if not thread.cancelled:", "thread.progress = 'Creating {0} Function'.format(len(funcs)) log.log_info('Found {0} functions'.format(len(funcs))) for func in funcs: view.create_user_function(func)", "0x{0:X} => 0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for runtime_address in range(unwind_entrys, unwind_entrys_end, 12): if thread.cancelled: break", "unwind_info, address = UNWIND_INFO_t.read(view, address) if unwind_info is not None: split_bits(unwind_info, 'VersionAndFlags', [", "unwind_codes = [ ] for i in range(unwind_info['CountOfCodes']): unwind_code, address = read_unwind_code(view, address)", "if unwind_info is None: continue if 'FunctionEntry' in unwind_info: continue funcs.add(start_address) if not", "('UnwindOp', 0, 4), ('OpInfo', 4, 4) ]) return unwind_code, address def parse_unwind_info(thread, view):", "read_runtime_function(view, address): runtime_function, address = RUNTIME_FUNCTION_t.read(view, address, 4) if runtime_function is not None:", "address) if unwind_info is not None: split_bits(unwind_info, 'VersionAndFlags', [ ('Version', 0, 3), ('Flags',", "not view.is_offset_executable(start_address): continue if view.get_functions_containing(start_address): continue info_address = runtime_function['UnwindData'] unwind_info, _ = read_unwind_info(view,", "= ('BeginAddress', 'EndAddress', 'UnwindData')) def read_runtime_function(view, address): runtime_function, address = RUNTIME_FUNCTION_t.read(view, address, 4)", "0, 3), ('Flags', 3, 5) ]) split_bits(unwind_info, 'FrameRegisterAndOffset', [ ('FrameRegister', 0, 4), ('FrameOffset',", "i in range(unwind_info['CountOfCodes']): unwind_code, address = read_unwind_code(view, address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] = unwind_codes if", "('OpInfo', 4, 4) ]) return unwind_code, address def parse_unwind_info(thread, view): base_address = view.start", "= ('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER = 0x0 UNW_FLAG_EHANDLER = 0x1 UNW_FLAG_UHANDLER =", "address = UNWIND_CODE_t.read(view, address) if unwind_code is not None: split_bits(unwind_code, 'UnwindOpAndInfo', [ ('UnwindOp',", "'UnwindOpAndInfo', [ ('UnwindOp', 0, 4), ('OpInfo', 4, 4) ]) return unwind_code, address def", "view.start runtime_function['EndAddress'] += view.start runtime_function['UnwindData'] += view.start return runtime_function, address UNWIND_INFO_t = BinjaStruct('<BBBB',", "[ ('Version', 0, 3), ('Flags', 3, 5) ]) split_bits(unwind_info, 'FrameRegisterAndOffset', [ ('FrameRegister', 0,", "UNW_FLAG_NHANDLER = 0x0 UNW_FLAG_EHANDLER = 0x1 UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO", "('FrameRegister', 0, 4), ('FrameOffset', 4, 4) ]) if unwind_info['Version'] == 1: unwind_codes =", "address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] = unwind_codes if unwind_info['Flags'] & UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address = read_runtime_function(view,", "4), ('OpInfo', 4, 4) ]) return unwind_code, address def parse_unwind_info(thread, view): base_address =", "= read_pe_header(view) unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys = base_address + unwind_directory.VirtualAddress unwind_entrys_end = unwind_entrys", "Data @ 0x{0:X} => 0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for runtime_address in range(unwind_entrys, unwind_entrys_end, 12): if", "if not thread.cancelled: thread.progress = 'Creating {0} Function'.format(len(funcs)) log.log_info('Found {0} functions'.format(len(funcs))) for func", "runtime_function['UnwindData'] unwind_info, _ = read_unwind_info(view, info_address) if unwind_info is None: continue if 'FunctionEntry'", "def read_unwind_code(view, address): unwind_code, address = UNWIND_CODE_t.read(view, address) if unwind_code is not None:", "address): unwind_info, address = UNWIND_INFO_t.read(view, address) if unwind_info is not None: split_bits(unwind_info, 'VersionAndFlags',", "unwind_code, address def parse_unwind_info(thread, view): base_address = view.start pe = read_pe_header(view) unwind_directory =", "RUNTIME_FUNCTION_t.read(view, address, 4) if runtime_function is not None: runtime_function['BeginAddress'] += view.start runtime_function['EndAddress'] +=", "@ 0x{0:X} => 0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for runtime_address in range(unwind_entrys, unwind_entrys_end, 12): if thread.cancelled:", "log from .utils import BinjaStruct, read_pe_header, split_bits, update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t = BinjaStruct('<III',", "[ ] for i in range(unwind_info['CountOfCodes']): unwind_code, address = read_unwind_code(view, address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes']", "address) if unwind_code is not None: split_bits(unwind_code, 'UnwindOpAndInfo', [ ('UnwindOp', 0, 4), ('OpInfo',", "for runtime_address in range(unwind_entrys, unwind_entrys_end, 12): if thread.cancelled: break update_percentage(thread, unwind_entrys, unwind_entrys_end, runtime_address,", "continue if view.get_functions_containing(start_address): continue info_address = runtime_function['UnwindData'] unwind_info, _ = read_unwind_info(view, info_address) if", "unwind_entrys = base_address + unwind_directory.VirtualAddress unwind_entrys_end = unwind_entrys + unwind_directory.Size funcs = set()", "if view.get_functions_containing(start_address): continue info_address = runtime_function['UnwindData'] unwind_info, _ = read_unwind_info(view, info_address) if unwind_info", "in unwind_info: continue funcs.add(start_address) if not thread.cancelled: thread.progress = 'Creating {0} Function'.format(len(funcs)) log.log_info('Found", "split_bits(unwind_info, 'VersionAndFlags', [ ('Version', 0, 3), ('Flags', 3, 5) ]) split_bits(unwind_info, 'FrameRegisterAndOffset', [", "from .utils import BinjaStruct, read_pe_header, split_bits, update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t = BinjaStruct('<III', names", "thread.cancelled: break update_percentage(thread, unwind_entrys, unwind_entrys_end, runtime_address, 'Parsing Unwind Info - Found {0} functions'.format(len(funcs)))", "]) return unwind_code, address def parse_unwind_info(thread, view): base_address = view.start pe = read_pe_header(view)", "BinjaStruct, read_pe_header, split_bits, update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t = BinjaStruct('<III', names = ('BeginAddress', 'EndAddress',", "read_unwind_info(view, info_address) if unwind_info is None: continue if 'FunctionEntry' in unwind_info: continue funcs.add(start_address)", "=> 0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for runtime_address in range(unwind_entrys, unwind_entrys_end, 12): if thread.cancelled: break update_percentage(thread,", "address def parse_unwind_info(thread, view): base_address = view.start pe = read_pe_header(view) unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3]", "continue info_address = runtime_function['UnwindData'] unwind_info, _ = read_unwind_info(view, info_address) if unwind_info is None:", "if unwind_info['Flags'] & UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address = read_runtime_function(view, address) return unwind_info, address UNWIND_CODE_t", "pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys = base_address + unwind_directory.VirtualAddress unwind_entrys_end = unwind_entrys + unwind_directory.Size funcs =", "] for i in range(unwind_info['CountOfCodes']): unwind_code, address = read_unwind_code(view, address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] =", "unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] = unwind_codes if unwind_info['Flags'] & UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address = read_runtime_function(view, address)", "address UNWIND_INFO_t = BinjaStruct('<BBBB', names = ('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER = 0x0", "= UNWIND_CODE_t.read(view, address) if unwind_code is not None: split_bits(unwind_code, 'UnwindOpAndInfo', [ ('UnwindOp', 0,", "pe = read_pe_header(view) unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys = base_address + unwind_directory.VirtualAddress unwind_entrys_end =", "+ unwind_directory.VirtualAddress unwind_entrys_end = unwind_entrys + unwind_directory.Size funcs = set() log.log_info('Exception Data @", "unwind_directory.Size funcs = set() log.log_info('Exception Data @ 0x{0:X} => 0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for runtime_address", "info_address = runtime_function['UnwindData'] unwind_info, _ = read_unwind_info(view, info_address) if unwind_info is None: continue", "+= view.start runtime_function['EndAddress'] += view.start runtime_function['UnwindData'] += view.start return runtime_function, address UNWIND_INFO_t =", "RUNTIME_FUNCTION_t = BinjaStruct('<III', names = ('BeginAddress', 'EndAddress', 'UnwindData')) def read_runtime_function(view, address): runtime_function, address", "= view.start pe = read_pe_header(view) unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys = base_address + unwind_directory.VirtualAddress", "= unwind_entrys + unwind_directory.Size funcs = set() log.log_info('Exception Data @ 0x{0:X} => 0x{1:X}'.format(unwind_entrys,", "names = ('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER = 0x0 UNW_FLAG_EHANDLER = 0x1 UNW_FLAG_UHANDLER", "1: unwind_codes = [ ] for i in range(unwind_info['CountOfCodes']): unwind_code, address = read_unwind_code(view,", "address = RUNTIME_FUNCTION_t.read(view, address, 4) if runtime_function is not None: runtime_function['BeginAddress'] += view.start", "= BinjaStruct('<BB', names = ('CodeOffset', 'UnwindOpAndInfo')) def read_unwind_code(view, address): unwind_code, address = UNWIND_CODE_t.read(view,", "('Flags', 3, 5) ]) split_bits(unwind_info, 'FrameRegisterAndOffset', [ ('FrameRegister', 0, 4), ('FrameOffset', 4, 4)", "0, 4), ('FrameOffset', 4, 4) ]) if unwind_info['Version'] == 1: unwind_codes = [", "= runtime_function['BeginAddress'] if not view.is_offset_executable(start_address): continue if view.get_functions_containing(start_address): continue info_address = runtime_function['UnwindData'] unwind_info,", "None: continue if 'FunctionEntry' in unwind_info: continue funcs.add(start_address) if not thread.cancelled: thread.progress =", "continue if 'FunctionEntry' in unwind_info: continue funcs.add(start_address) if not thread.cancelled: thread.progress = 'Creating", "runtime_function['BeginAddress'] += view.start runtime_function['EndAddress'] += view.start runtime_function['UnwindData'] += view.start return runtime_function, address UNWIND_INFO_t", "= 0x1 UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO = 0x4 def read_unwind_info(view,", "= read_runtime_function(view, address) return unwind_info, address UNWIND_CODE_t = BinjaStruct('<BB', names = ('CodeOffset', 'UnwindOpAndInfo'))", "set() log.log_info('Exception Data @ 0x{0:X} => 0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for runtime_address in range(unwind_entrys, unwind_entrys_end,", "runtime_function, address = RUNTIME_FUNCTION_t.read(view, address, 4) if runtime_function is not None: runtime_function['BeginAddress'] +=", "'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER = 0x0 UNW_FLAG_EHANDLER = 0x1 UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_FHANDLER", "= 0x3 UNW_FLAG_CHAININFO = 0x4 def read_unwind_info(view, address): unwind_info, address = UNWIND_INFO_t.read(view, address)", "= 0x4 def read_unwind_info(view, address): unwind_info, address = UNWIND_INFO_t.read(view, address) if unwind_info is", "not None: split_bits(unwind_info, 'VersionAndFlags', [ ('Version', 0, 3), ('Flags', 3, 5) ]) split_bits(unwind_info,", "= read_unwind_code(view, address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] = unwind_codes if unwind_info['Flags'] & UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address", "unwind_info: continue funcs.add(start_address) if not thread.cancelled: thread.progress = 'Creating {0} Function'.format(len(funcs)) log.log_info('Found {0}", "+ unwind_directory.Size funcs = set() log.log_info('Exception Data @ 0x{0:X} => 0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for", "in range(unwind_entrys, unwind_entrys_end, 12): if thread.cancelled: break update_percentage(thread, unwind_entrys, unwind_entrys_end, runtime_address, 'Parsing Unwind", "def read_runtime_function(view, address): runtime_function, address = RUNTIME_FUNCTION_t.read(view, address, 4) if runtime_function is not", "address = read_runtime_function(view, address) return unwind_info, address UNWIND_CODE_t = BinjaStruct('<BB', names = ('CodeOffset',", "BinjaStruct('<III', names = ('BeginAddress', 'EndAddress', 'UnwindData')) def read_runtime_function(view, address): runtime_function, address = RUNTIME_FUNCTION_t.read(view,", "+= view.start runtime_function['UnwindData'] += view.start return runtime_function, address UNWIND_INFO_t = BinjaStruct('<BBBB', names =", "unwind_info['Flags'] & UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address = read_runtime_function(view, address) return unwind_info, address UNWIND_CODE_t =", "address = read_unwind_code(view, address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] = unwind_codes if unwind_info['Flags'] & UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'],", "'VersionAndFlags', [ ('Version', 0, 3), ('Flags', 3, 5) ]) split_bits(unwind_info, 'FrameRegisterAndOffset', [ ('FrameRegister',", "4, 4) ]) if unwind_info['Version'] == 1: unwind_codes = [ ] for i", "'Parsing Unwind Info - Found {0} functions'.format(len(funcs))) runtime_function, _ = read_runtime_function(view, runtime_address) if", "if runtime_function is None: continue start_address = runtime_function['BeginAddress'] if not view.is_offset_executable(start_address): continue if", "view.is_offset_executable(start_address): continue if view.get_functions_containing(start_address): continue info_address = runtime_function['UnwindData'] unwind_info, _ = read_unwind_info(view, info_address)", "= unwind_codes if unwind_info['Flags'] & UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address = read_runtime_function(view, address) return unwind_info,", "Unwind Info - Found {0} functions'.format(len(funcs))) runtime_function, _ = read_runtime_function(view, runtime_address) if runtime_function", "'FrameRegisterAndOffset', [ ('FrameRegister', 0, 4), ('FrameOffset', 4, 4) ]) if unwind_info['Version'] == 1:", "address): unwind_code, address = UNWIND_CODE_t.read(view, address) if unwind_code is not None: split_bits(unwind_code, 'UnwindOpAndInfo',", "range(unwind_entrys, unwind_entrys_end, 12): if thread.cancelled: break update_percentage(thread, unwind_entrys, unwind_entrys_end, runtime_address, 'Parsing Unwind Info", "import BinjaStruct, read_pe_header, split_bits, update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t = BinjaStruct('<III', names = ('BeginAddress',", "0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for runtime_address in range(unwind_entrys, unwind_entrys_end, 12): if thread.cancelled: break update_percentage(thread, unwind_entrys,", "None: continue start_address = runtime_function['BeginAddress'] if not view.is_offset_executable(start_address): continue if view.get_functions_containing(start_address): continue info_address", "if 'FunctionEntry' in unwind_info: continue funcs.add(start_address) if not thread.cancelled: thread.progress = 'Creating {0}", "('BeginAddress', 'EndAddress', 'UnwindData')) def read_runtime_function(view, address): runtime_function, address = RUNTIME_FUNCTION_t.read(view, address, 4) if", "not None: runtime_function['BeginAddress'] += view.start runtime_function['EndAddress'] += view.start runtime_function['UnwindData'] += view.start return runtime_function,", "read_pe_header(view) unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys = base_address + unwind_directory.VirtualAddress unwind_entrys_end = unwind_entrys +", "= pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys = base_address + unwind_directory.VirtualAddress unwind_entrys_end = unwind_entrys + unwind_directory.Size funcs", "base_address + unwind_directory.VirtualAddress unwind_entrys_end = unwind_entrys + unwind_directory.Size funcs = set() log.log_info('Exception Data", "view): base_address = view.start pe = read_pe_header(view) unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys = base_address", "address): runtime_function, address = RUNTIME_FUNCTION_t.read(view, address, 4) if runtime_function is not None: runtime_function['BeginAddress']", "_ = read_unwind_info(view, info_address) if unwind_info is None: continue if 'FunctionEntry' in unwind_info:", "thread.cancelled: thread.progress = 'Creating {0} Function'.format(len(funcs)) log.log_info('Found {0} functions'.format(len(funcs))) for func in funcs:", "update_percentage(thread, unwind_entrys, unwind_entrys_end, runtime_address, 'Parsing Unwind Info - Found {0} functions'.format(len(funcs))) runtime_function, _", "return unwind_info, address UNWIND_CODE_t = BinjaStruct('<BB', names = ('CodeOffset', 'UnwindOpAndInfo')) def read_unwind_code(view, address):", "unwind_info, _ = read_unwind_info(view, info_address) if unwind_info is None: continue if 'FunctionEntry' in", "= base_address + unwind_directory.VirtualAddress unwind_entrys_end = unwind_entrys + unwind_directory.Size funcs = set() log.log_info('Exception", "address UNWIND_CODE_t = BinjaStruct('<BB', names = ('CodeOffset', 'UnwindOpAndInfo')) def read_unwind_code(view, address): unwind_code, address", "names = ('CodeOffset', 'UnwindOpAndInfo')) def read_unwind_code(view, address): unwind_code, address = UNWIND_CODE_t.read(view, address) if", "unwind_code, address = UNWIND_CODE_t.read(view, address) if unwind_code is not None: split_bits(unwind_code, 'UnwindOpAndInfo', [", "address = UNWIND_INFO_t.read(view, address) if unwind_info is not None: split_bits(unwind_info, 'VersionAndFlags', [ ('Version',", "unwind_directory.VirtualAddress unwind_entrys_end = unwind_entrys + unwind_directory.Size funcs = set() log.log_info('Exception Data @ 0x{0:X}", "runtime_address, 'Parsing Unwind Info - Found {0} functions'.format(len(funcs))) runtime_function, _ = read_runtime_function(view, runtime_address)", "start_address = runtime_function['BeginAddress'] if not view.is_offset_executable(start_address): continue if view.get_functions_containing(start_address): continue info_address = runtime_function['UnwindData']", "view.start runtime_function['UnwindData'] += view.start return runtime_function, address UNWIND_INFO_t = BinjaStruct('<BBBB', names = ('VersionAndFlags',", "= read_unwind_info(view, info_address) if unwind_info is None: continue if 'FunctionEntry' in unwind_info: continue", "4), ('FrameOffset', 4, 4) ]) if unwind_info['Version'] == 1: unwind_codes = [ ]", "UNWIND_INFO_t = BinjaStruct('<BBBB', names = ('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER = 0x0 UNW_FLAG_EHANDLER", "BinjaStruct('<BB', names = ('CodeOffset', 'UnwindOpAndInfo')) def read_unwind_code(view, address): unwind_code, address = UNWIND_CODE_t.read(view, address)", "= runtime_function['UnwindData'] unwind_info, _ = read_unwind_info(view, info_address) if unwind_info is None: continue if", ".utils import BinjaStruct, read_pe_header, split_bits, update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t = BinjaStruct('<III', names =", "not None: split_bits(unwind_code, 'UnwindOpAndInfo', [ ('UnwindOp', 0, 4), ('OpInfo', 4, 4) ]) return", "def parse_unwind_info(thread, view): base_address = view.start pe = read_pe_header(view) unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys", "'UnwindData')) def read_runtime_function(view, address): runtime_function, address = RUNTIME_FUNCTION_t.read(view, address, 4) if runtime_function is", "('FrameOffset', 4, 4) ]) if unwind_info['Version'] == 1: unwind_codes = [ ] for", "runtime_function, address UNWIND_INFO_t = BinjaStruct('<BBBB', names = ('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER =", "0x3 UNW_FLAG_CHAININFO = 0x4 def read_unwind_info(view, address): unwind_info, address = UNWIND_INFO_t.read(view, address) if", "address) return unwind_info, address UNWIND_CODE_t = BinjaStruct('<BB', names = ('CodeOffset', 'UnwindOpAndInfo')) def read_unwind_code(view,", "runtime_function['EndAddress'] += view.start runtime_function['UnwindData'] += view.start return runtime_function, address UNWIND_INFO_t = BinjaStruct('<BBBB', names", "read_unwind_info(view, address): unwind_info, address = UNWIND_INFO_t.read(view, address) if unwind_info is not None: split_bits(unwind_info,", "from binaryninja import log from .utils import BinjaStruct, read_pe_header, split_bits, update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx", "unwind_info, address UNWIND_CODE_t = BinjaStruct('<BB', names = ('CodeOffset', 'UnwindOpAndInfo')) def read_unwind_code(view, address): unwind_code,", "unwind_code is not None: split_bits(unwind_code, 'UnwindOpAndInfo', [ ('UnwindOp', 0, 4), ('OpInfo', 4, 4)", "None: split_bits(unwind_code, 'UnwindOpAndInfo', [ ('UnwindOp', 0, 4), ('OpInfo', 4, 4) ]) return unwind_code,", "is not None: runtime_function['BeginAddress'] += view.start runtime_function['EndAddress'] += view.start runtime_function['UnwindData'] += view.start return", "'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER = 0x0 UNW_FLAG_EHANDLER = 0x1 UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_FHANDLER =", "read_unwind_code(view, address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] = unwind_codes if unwind_info['Flags'] & UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address =", "0x0 UNW_FLAG_EHANDLER = 0x1 UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO = 0x4", "'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER = 0x0 UNW_FLAG_EHANDLER = 0x1 UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_FHANDLER = 0x3", "split_bits(unwind_info, 'FrameRegisterAndOffset', [ ('FrameRegister', 0, 4), ('FrameOffset', 4, 4) ]) if unwind_info['Version'] ==", "'UnwindOpAndInfo')) def read_unwind_code(view, address): unwind_code, address = UNWIND_CODE_t.read(view, address) if unwind_code is not", "view.start return runtime_function, address UNWIND_INFO_t = BinjaStruct('<BBBB', names = ('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset'))", "view.get_functions_containing(start_address): continue info_address = runtime_function['UnwindData'] unwind_info, _ = read_unwind_info(view, info_address) if unwind_info is", "0, 4), ('OpInfo', 4, 4) ]) return unwind_code, address def parse_unwind_info(thread, view): base_address", "UNWIND_CODE_t = BinjaStruct('<BB', names = ('CodeOffset', 'UnwindOpAndInfo')) def read_unwind_code(view, address): unwind_code, address =", "= RUNTIME_FUNCTION_t.read(view, address, 4) if runtime_function is not None: runtime_function['BeginAddress'] += view.start runtime_function['EndAddress']", "3), ('Flags', 3, 5) ]) split_bits(unwind_info, 'FrameRegisterAndOffset', [ ('FrameRegister', 0, 4), ('FrameOffset', 4,", "read_pe_header, split_bits, update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t = BinjaStruct('<III', names = ('BeginAddress', 'EndAddress', 'UnwindData'))" ]
[ "fig.add_trace(traces[0]) idx = len(fig.data) - 1 for i, tr in enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx],", "z = corners.T tr = go.Scatter3d( x=x, y=y, z=z, line=dict(color='rgba(0, 0, 0, .5)'),", "def plot_camera(fig, R, t, K, color='rgb(0, 0, 255)'): \"\"\"Plot a camera as a", "z=[z], u=[u], v=[v], w=[w], anchor='tip', showscale=False, colorscale=[[0, color], [1, color]], sizemode='absolute') fig.add_trace(tr) W,", "\"\"\" 3D visualization primitives based on Plotly. We might want to instead use", "to instead use a more powerful library like Open3D. Plotly however supports animations,", "z = t u, v, w = R @ -np.array([0, 0, 1]) tr", "+ t x, y, z = corners.T tr = go.Scatter3d( x=x, y=y, z=z,", "z=z, line=dict(color='rgba(0, 0, 0, .5)'), marker=dict(size=0.0001), showlegend=False) fig.add_trace(tr) def create_slider_animation(fig, traces): \"\"\"Create a", "`fig.show()` to render the figure. \"\"\" import plotly.graph_objects as go import numpy as", "of 3D points.\"\"\" x, y, z = pts.T tr = go.Scatter3d( x=x, y=y,", "{\"args\": [ [str(i)], {\"frame\": {\"redraw\": True}, \"mode\": \"immediate\"}], \"label\": i, \"method\": \"animate\"} slider['steps'].append(step)", "as np from ..pixlib.geometry.utils import to_homogeneous def init_figure(height=800): \"\"\"Initialize a 3D figure.\"\"\" fig", "for i, tr in enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx], data=[tr])) step = {\"args\": [ [str(i)],", "1) Initialize a figure with `fig = init_figure()` 2) Plot points, cameras, lines,", "`fig = init_figure()` 2) Plot points, cameras, lines, or create a slider animation.", "y=-1., z=0)), scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showbackground=False), aspectmode='data', dragmode='orbit'), margin=dict(l=0, r=0, b=0, t=0, pad=0)) #", "import numpy as np from ..pixlib.geometry.utils import to_homogeneous def init_figure(height=800): \"\"\"Initialize a 3D", "u, v, w = R @ -np.array([0, 0, 1]) tr = go.Cone( x=[x],", "0, 255)'): \"\"\"Plot a camera as a cone with camera frustum.\"\"\" x, y,", "= to_homogeneous(corners) @ np.linalg.inv(K).T corners = (corners/2) @ R.T + t x, y,", "x, y, z = corners.T tr = go.Scatter3d( x=x, y=y, z=z, line=dict(color='rgba(0, 0,", "visualization primitives based on Plotly. We might want to instead use a more", "= (corners/2) @ R.T + t x, y, z = corners.T tr =", "y, z = corners.T tr = go.Scatter3d( x=x, y=y, z=z, line=dict(color='rgba(0, 0, 0,", "a camera as a cone with camera frustum.\"\"\" x, y, z = t", "color]], sizemode='absolute') fig.add_trace(tr) W, H = K[0, 2]*2, K[1, 2]*2 corners = np.array([[0,", "H = K[0, 2]*2, K[1, 2]*2 corners = np.array([[0, 0], [W, 0], [W,", "0], [W, H], [0, H], [0, 0]]) corners = to_homogeneous(corners) @ np.linalg.inv(K).T corners", "frames = [] fig.add_trace(traces[0]) idx = len(fig.data) - 1 for i, tr in", "plot_camera(fig, R, t, K, color='rgb(0, 0, 255)'): \"\"\"Plot a camera as a cone", "on Plotly. We might want to instead use a more powerful library like", "figure.\"\"\" fig = go.Figure() fig.update_layout( height=height, scene_camera=dict( eye=dict(x=0., y=-.1, z=-2), up=dict(x=0, y=-1., z=0)),", "w = R @ -np.array([0, 0, 1]) tr = go.Cone( x=[x], y=[y], z=[z],", "traces (e.g. 3D points).\"\"\" slider = {'steps': []} frames = [] fig.add_trace(traces[0]) idx", "3D visualization primitives based on Plotly. We might want to instead use a", "y, z = t u, v, w = R @ -np.array([0, 0, 1])", "y=y, z=z, line=dict(color='rgba(0, 0, 0, .5)'), marker=dict(size=0.0001), showlegend=False) fig.add_trace(tr) def create_slider_animation(fig, traces): \"\"\"Create", "t=0, pad=0)) # noqa E741 return fig def plot_points(fig, pts, color='rgba(255, 0, 0,", "v=[v], w=[w], anchor='tip', showscale=False, colorscale=[[0, color], [1, color]], sizemode='absolute') fig.add_trace(tr) W, H =", "len(fig.data) - 1 for i, tr in enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx], data=[tr])) step =", "= {\"args\": [ [str(i)], {\"frame\": {\"redraw\": True}, \"mode\": \"immediate\"}], \"label\": i, \"method\": \"animate\"}", "points, cameras, lines, or create a slider animation. 3) Call `fig.show()` to render", "as a cone with camera frustum.\"\"\" x, y, z = t u, v,", "with `fig = init_figure()` 2) Plot points, cameras, lines, or create a slider", "[ [str(i)], {\"frame\": {\"redraw\": True}, \"mode\": \"immediate\"}], \"label\": i, \"method\": \"animate\"} slider['steps'].append(step) fig.frames", "tr in enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx], data=[tr])) step = {\"args\": [ [str(i)], {\"frame\": {\"redraw\":", "create a slider animation. 3) Call `fig.show()` to render the figure. \"\"\" import", "corners = np.array([[0, 0], [W, 0], [W, H], [0, H], [0, 0]]) corners", "W, H = K[0, 2]*2, K[1, 2]*2 corners = np.array([[0, 0], [W, 0],", "cameras, lines, or create a slider animation. 3) Call `fig.show()` to render the", "aspectmode='data', dragmode='orbit'), margin=dict(l=0, r=0, b=0, t=0, pad=0)) # noqa E741 return fig def", "go.Figure() fig.update_layout( height=height, scene_camera=dict( eye=dict(x=0., y=-.1, z=-2), up=dict(x=0, y=-1., z=0)), scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showbackground=False),", "3D points.\"\"\" x, y, z = pts.T tr = go.Scatter3d( x=x, y=y, z=z,", "t, K, color='rgb(0, 0, 255)'): \"\"\"Plot a camera as a cone with camera", "to render the figure. \"\"\" import plotly.graph_objects as go import numpy as np", "a slider that animates a list of traces (e.g. 3D points).\"\"\" slider =", "step = {\"args\": [ [str(i)], {\"frame\": {\"redraw\": True}, \"mode\": \"immediate\"}], \"label\": i, \"method\":", "in enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx], data=[tr])) step = {\"args\": [ [str(i)], {\"frame\": {\"redraw\": True},", "H], [0, 0]]) corners = to_homogeneous(corners) @ np.linalg.inv(K).T corners = (corners/2) @ R.T", "numpy as np from ..pixlib.geometry.utils import to_homogeneous def init_figure(height=800): \"\"\"Initialize a 3D figure.\"\"\"", "True}, \"mode\": \"immediate\"}], \"label\": i, \"method\": \"animate\"} slider['steps'].append(step) fig.frames = tuple(frames) fig.layout.sliders =", "z = pts.T tr = go.Scatter3d( x=x, y=y, z=z, mode='markers', marker_size=ps, marker_color=color, marker_line_width=.2)", "3D points).\"\"\" slider = {'steps': []} frames = [] fig.add_trace(traces[0]) idx = len(fig.data)", "a set of 3D points.\"\"\" x, y, z = pts.T tr = go.Scatter3d(", "corners = (corners/2) @ R.T + t x, y, z = corners.T tr", "showlegend=False) fig.add_trace(tr) def create_slider_animation(fig, traces): \"\"\"Create a slider that animates a list of", "eye=dict(x=0., y=-.1, z=-2), up=dict(x=0, y=-1., z=0)), scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showbackground=False), aspectmode='data', dragmode='orbit'), margin=dict(l=0, r=0,", "t x, y, z = corners.T tr = go.Scatter3d( x=x, y=y, z=z, line=dict(color='rgba(0,", ".5)'), marker=dict(size=0.0001), showlegend=False) fig.add_trace(tr) def create_slider_animation(fig, traces): \"\"\"Create a slider that animates a", "animates a list of traces (e.g. 3D points).\"\"\" slider = {'steps': []} frames", "K[0, 2]*2, K[1, 2]*2 corners = np.array([[0, 0], [W, 0], [W, H], [0,", "however supports animations, buttons and sliders. 1) Initialize a figure with `fig =", "corners.T tr = go.Scatter3d( x=x, y=y, z=z, line=dict(color='rgba(0, 0, 0, .5)'), marker=dict(size=0.0001), showlegend=False)", "a more powerful library like Open3D. Plotly however supports animations, buttons and sliders.", "init_figure(height=800): \"\"\"Initialize a 3D figure.\"\"\" fig = go.Figure() fig.update_layout( height=height, scene_camera=dict( eye=dict(x=0., y=-.1,", "t u, v, w = R @ -np.array([0, 0, 1]) tr = go.Cone(", "lines, or create a slider animation. 3) Call `fig.show()` to render the figure.", "go.Scatter3d( x=x, y=y, z=z, mode='markers', marker_size=ps, marker_color=color, marker_line_width=.2) fig.add_trace(tr) def plot_camera(fig, R, t,", "R @ -np.array([0, 0, 1]) tr = go.Cone( x=[x], y=[y], z=[z], u=[u], v=[v],", "E741 return fig def plot_points(fig, pts, color='rgba(255, 0, 0, 1)', ps=2): \"\"\"Plot a", "figure with `fig = init_figure()` 2) Plot points, cameras, lines, or create a", "Plot points, cameras, lines, or create a slider animation. 3) Call `fig.show()` to", "to_homogeneous def init_figure(height=800): \"\"\"Initialize a 3D figure.\"\"\" fig = go.Figure() fig.update_layout( height=height, scene_camera=dict(", "height=height, scene_camera=dict( eye=dict(x=0., y=-.1, z=-2), up=dict(x=0, y=-1., z=0)), scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showbackground=False), aspectmode='data', dragmode='orbit'),", "= go.Cone( x=[x], y=[y], z=[z], u=[u], v=[v], w=[w], anchor='tip', showscale=False, colorscale=[[0, color], [1,", "[0, H], [0, 0]]) corners = to_homogeneous(corners) @ np.linalg.inv(K).T corners = (corners/2) @", "margin=dict(l=0, r=0, b=0, t=0, pad=0)) # noqa E741 return fig def plot_points(fig, pts,", "2]*2 corners = np.array([[0, 0], [W, 0], [W, H], [0, H], [0, 0]])", "tr = go.Cone( x=[x], y=[y], z=[z], u=[u], v=[v], w=[w], anchor='tip', showscale=False, colorscale=[[0, color],", "more powerful library like Open3D. Plotly however supports animations, buttons and sliders. 1)", "{\"frame\": {\"redraw\": True}, \"mode\": \"immediate\"}], \"label\": i, \"method\": \"animate\"} slider['steps'].append(step) fig.frames = tuple(frames)", "use a more powerful library like Open3D. Plotly however supports animations, buttons and", "points.\"\"\" x, y, z = pts.T tr = go.Scatter3d( x=x, y=y, z=z, mode='markers',", "v, w = R @ -np.array([0, 0, 1]) tr = go.Cone( x=[x], y=[y],", "2) Plot points, cameras, lines, or create a slider animation. 3) Call `fig.show()`", "i, tr in enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx], data=[tr])) step = {\"args\": [ [str(i)], {\"frame\":", "z=0)), scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showbackground=False), aspectmode='data', dragmode='orbit'), margin=dict(l=0, r=0, b=0, t=0, pad=0)) # noqa", "go import numpy as np from ..pixlib.geometry.utils import to_homogeneous def init_figure(height=800): \"\"\"Initialize a", "list of traces (e.g. 3D points).\"\"\" slider = {'steps': []} frames = []", "(corners/2) @ R.T + t x, y, z = corners.T tr = go.Scatter3d(", "y=-.1, z=-2), up=dict(x=0, y=-1., z=0)), scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showbackground=False), aspectmode='data', dragmode='orbit'), margin=dict(l=0, r=0, b=0,", "{'steps': []} frames = [] fig.add_trace(traces[0]) idx = len(fig.data) - 1 for i,", "R, t, K, color='rgb(0, 0, 255)'): \"\"\"Plot a camera as a cone with", "pts, color='rgba(255, 0, 0, 1)', ps=2): \"\"\"Plot a set of 3D points.\"\"\" x,", "with camera frustum.\"\"\" x, y, z = t u, v, w = R", "fig.add_trace(tr) W, H = K[0, 2]*2, K[1, 2]*2 corners = np.array([[0, 0], [W,", "0, 0, .5)'), marker=dict(size=0.0001), showlegend=False) fig.add_trace(tr) def create_slider_animation(fig, traces): \"\"\"Create a slider that", "color], [1, color]], sizemode='absolute') fig.add_trace(tr) W, H = K[0, 2]*2, K[1, 2]*2 corners", "color='rgba(255, 0, 0, 1)', ps=2): \"\"\"Plot a set of 3D points.\"\"\" x, y,", "init_figure()` 2) Plot points, cameras, lines, or create a slider animation. 3) Call", "= [] fig.add_trace(traces[0]) idx = len(fig.data) - 1 for i, tr in enumerate(traces):", "yaxis=dict(showbackground=False), aspectmode='data', dragmode='orbit'), margin=dict(l=0, r=0, b=0, t=0, pad=0)) # noqa E741 return fig", "animations, buttons and sliders. 1) Initialize a figure with `fig = init_figure()` 2)", "a figure with `fig = init_figure()` 2) Plot points, cameras, lines, or create", "= K[0, 2]*2, K[1, 2]*2 corners = np.array([[0, 0], [W, 0], [W, H],", "R.T + t x, y, z = corners.T tr = go.Scatter3d( x=x, y=y,", "fig.add_trace(tr) def create_slider_animation(fig, traces): \"\"\"Create a slider that animates a list of traces", "traces): \"\"\"Create a slider that animates a list of traces (e.g. 3D points).\"\"\"", "1]) tr = go.Cone( x=[x], y=[y], z=[z], u=[u], v=[v], w=[w], anchor='tip', showscale=False, colorscale=[[0,", "[] fig.add_trace(traces[0]) idx = len(fig.data) - 1 for i, tr in enumerate(traces): frames.append(go.Frame(name=str(i),", "as go import numpy as np from ..pixlib.geometry.utils import to_homogeneous def init_figure(height=800): \"\"\"Initialize", "Plotly however supports animations, buttons and sliders. 1) Initialize a figure with `fig", "[str(i)], {\"frame\": {\"redraw\": True}, \"mode\": \"immediate\"}], \"label\": i, \"method\": \"animate\"} slider['steps'].append(step) fig.frames =", "[1, color]], sizemode='absolute') fig.add_trace(tr) W, H = K[0, 2]*2, K[1, 2]*2 corners =", "{\"redraw\": True}, \"mode\": \"immediate\"}], \"label\": i, \"method\": \"animate\"} slider['steps'].append(step) fig.frames = tuple(frames) fig.layout.sliders", "def plot_points(fig, pts, color='rgba(255, 0, 0, 1)', ps=2): \"\"\"Plot a set of 3D", "u=[u], v=[v], w=[w], anchor='tip', showscale=False, colorscale=[[0, color], [1, color]], sizemode='absolute') fig.add_trace(tr) W, H", "\"\"\"Initialize a 3D figure.\"\"\" fig = go.Figure() fig.update_layout( height=height, scene_camera=dict( eye=dict(x=0., y=-.1, z=-2),", "set of 3D points.\"\"\" x, y, z = pts.T tr = go.Scatter3d( x=x,", "a cone with camera frustum.\"\"\" x, y, z = t u, v, w", "np.array([[0, 0], [W, 0], [W, H], [0, H], [0, 0]]) corners = to_homogeneous(corners)", "that animates a list of traces (e.g. 3D points).\"\"\" slider = {'steps': []}", "= {'steps': []} frames = [] fig.add_trace(traces[0]) idx = len(fig.data) - 1 for", "r=0, b=0, t=0, pad=0)) # noqa E741 return fig def plot_points(fig, pts, color='rgba(255,", "255)'): \"\"\"Plot a camera as a cone with camera frustum.\"\"\" x, y, z", "frustum.\"\"\" x, y, z = t u, v, w = R @ -np.array([0,", "colorscale=[[0, color], [1, color]], sizemode='absolute') fig.add_trace(tr) W, H = K[0, 2]*2, K[1, 2]*2", "0, 1]) tr = go.Cone( x=[x], y=[y], z=[z], u=[u], v=[v], w=[w], anchor='tip', showscale=False,", "library like Open3D. Plotly however supports animations, buttons and sliders. 1) Initialize a", "from ..pixlib.geometry.utils import to_homogeneous def init_figure(height=800): \"\"\"Initialize a 3D figure.\"\"\" fig = go.Figure()", "mode='markers', marker_size=ps, marker_color=color, marker_line_width=.2) fig.add_trace(tr) def plot_camera(fig, R, t, K, color='rgb(0, 0, 255)'):", "want to instead use a more powerful library like Open3D. Plotly however supports", "0]]) corners = to_homogeneous(corners) @ np.linalg.inv(K).T corners = (corners/2) @ R.T + t", "= corners.T tr = go.Scatter3d( x=x, y=y, z=z, line=dict(color='rgba(0, 0, 0, .5)'), marker=dict(size=0.0001),", "0, .5)'), marker=dict(size=0.0001), showlegend=False) fig.add_trace(tr) def create_slider_animation(fig, traces): \"\"\"Create a slider that animates", "points).\"\"\" slider = {'steps': []} frames = [] fig.add_trace(traces[0]) idx = len(fig.data) -", "frames.append(go.Frame(name=str(i), traces=[idx], data=[tr])) step = {\"args\": [ [str(i)], {\"frame\": {\"redraw\": True}, \"mode\": \"immediate\"}],", "camera as a cone with camera frustum.\"\"\" x, y, z = t u,", "y=[y], z=[z], u=[u], v=[v], w=[w], anchor='tip', showscale=False, colorscale=[[0, color], [1, color]], sizemode='absolute') fig.add_trace(tr)", "a slider animation. 3) Call `fig.show()` to render the figure. \"\"\" import plotly.graph_objects", "= go.Scatter3d( x=x, y=y, z=z, line=dict(color='rgba(0, 0, 0, .5)'), marker=dict(size=0.0001), showlegend=False) fig.add_trace(tr) def", "= init_figure()` 2) Plot points, cameras, lines, or create a slider animation. 3)", "of traces (e.g. 3D points).\"\"\" slider = {'steps': []} frames = [] fig.add_trace(traces[0])", "- 1 for i, tr in enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx], data=[tr])) step = {\"args\":", "scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showbackground=False), aspectmode='data', dragmode='orbit'), margin=dict(l=0, r=0, b=0, t=0, pad=0)) # noqa E741", "b=0, t=0, pad=0)) # noqa E741 return fig def plot_points(fig, pts, color='rgba(255, 0,", "x=x, y=y, z=z, mode='markers', marker_size=ps, marker_color=color, marker_line_width=.2) fig.add_trace(tr) def plot_camera(fig, R, t, K,", "w=[w], anchor='tip', showscale=False, colorscale=[[0, color], [1, color]], sizemode='absolute') fig.add_trace(tr) W, H = K[0,", "animation. 3) Call `fig.show()` to render the figure. \"\"\" import plotly.graph_objects as go", "xaxis=dict(showbackground=False), yaxis=dict(showbackground=False), aspectmode='data', dragmode='orbit'), margin=dict(l=0, r=0, b=0, t=0, pad=0)) # noqa E741 return", "to_homogeneous(corners) @ np.linalg.inv(K).T corners = (corners/2) @ R.T + t x, y, z", "def init_figure(height=800): \"\"\"Initialize a 3D figure.\"\"\" fig = go.Figure() fig.update_layout( height=height, scene_camera=dict( eye=dict(x=0.,", "\"mode\": \"immediate\"}], \"label\": i, \"method\": \"animate\"} slider['steps'].append(step) fig.frames = tuple(frames) fig.layout.sliders = (slider,)", "@ R.T + t x, y, z = corners.T tr = go.Scatter3d( x=x,", "= R @ -np.array([0, 0, 1]) tr = go.Cone( x=[x], y=[y], z=[z], u=[u],", "color='rgb(0, 0, 255)'): \"\"\"Plot a camera as a cone with camera frustum.\"\"\" x,", "= len(fig.data) - 1 for i, tr in enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx], data=[tr])) step", "sizemode='absolute') fig.add_trace(tr) W, H = K[0, 2]*2, K[1, 2]*2 corners = np.array([[0, 0],", "idx = len(fig.data) - 1 for i, tr in enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx], data=[tr]))", "1 for i, tr in enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx], data=[tr])) step = {\"args\": [", "plot_points(fig, pts, color='rgba(255, 0, 0, 1)', ps=2): \"\"\"Plot a set of 3D points.\"\"\"", "<filename>pixloc/visualization/viz_3d.py \"\"\" 3D visualization primitives based on Plotly. We might want to instead", "x, y, z = t u, v, w = R @ -np.array([0, 0,", "z=z, mode='markers', marker_size=ps, marker_color=color, marker_line_width=.2) fig.add_trace(tr) def plot_camera(fig, R, t, K, color='rgb(0, 0,", "fig.add_trace(tr) def plot_camera(fig, R, t, K, color='rgb(0, 0, 255)'): \"\"\"Plot a camera as", "camera frustum.\"\"\" x, y, z = t u, v, w = R @", "@ np.linalg.inv(K).T corners = (corners/2) @ R.T + t x, y, z =", "fig def plot_points(fig, pts, color='rgba(255, 0, 0, 1)', ps=2): \"\"\"Plot a set of", "3) Call `fig.show()` to render the figure. \"\"\" import plotly.graph_objects as go import", "slider animation. 3) Call `fig.show()` to render the figure. \"\"\" import plotly.graph_objects as", "up=dict(x=0, y=-1., z=0)), scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showbackground=False), aspectmode='data', dragmode='orbit'), margin=dict(l=0, r=0, b=0, t=0, pad=0))", "np from ..pixlib.geometry.utils import to_homogeneous def init_figure(height=800): \"\"\"Initialize a 3D figure.\"\"\" fig =", "based on Plotly. We might want to instead use a more powerful library", "buttons and sliders. 1) Initialize a figure with `fig = init_figure()` 2) Plot", "= pts.T tr = go.Scatter3d( x=x, y=y, z=z, mode='markers', marker_size=ps, marker_color=color, marker_line_width=.2) fig.add_trace(tr)", "Call `fig.show()` to render the figure. \"\"\" import plotly.graph_objects as go import numpy", "import to_homogeneous def init_figure(height=800): \"\"\"Initialize a 3D figure.\"\"\" fig = go.Figure() fig.update_layout( height=height,", "We might want to instead use a more powerful library like Open3D. Plotly", "Initialize a figure with `fig = init_figure()` 2) Plot points, cameras, lines, or", "showscale=False, colorscale=[[0, color], [1, color]], sizemode='absolute') fig.add_trace(tr) W, H = K[0, 2]*2, K[1,", "\"\"\"Plot a camera as a cone with camera frustum.\"\"\" x, y, z =", "slider that animates a list of traces (e.g. 3D points).\"\"\" slider = {'steps':", "dragmode='orbit'), margin=dict(l=0, r=0, b=0, t=0, pad=0)) # noqa E741 return fig def plot_points(fig,", "[0, 0]]) corners = to_homogeneous(corners) @ np.linalg.inv(K).T corners = (corners/2) @ R.T +", "z=-2), up=dict(x=0, y=-1., z=0)), scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showbackground=False), aspectmode='data', dragmode='orbit'), margin=dict(l=0, r=0, b=0, t=0,", "anchor='tip', showscale=False, colorscale=[[0, color], [1, color]], sizemode='absolute') fig.add_trace(tr) W, H = K[0, 2]*2,", "np.linalg.inv(K).T corners = (corners/2) @ R.T + t x, y, z = corners.T", "traces=[idx], data=[tr])) step = {\"args\": [ [str(i)], {\"frame\": {\"redraw\": True}, \"mode\": \"immediate\"}], \"label\":", "import plotly.graph_objects as go import numpy as np from ..pixlib.geometry.utils import to_homogeneous def", "K[1, 2]*2 corners = np.array([[0, 0], [W, 0], [W, H], [0, H], [0,", "3D figure.\"\"\" fig = go.Figure() fig.update_layout( height=height, scene_camera=dict( eye=dict(x=0., y=-.1, z=-2), up=dict(x=0, y=-1.,", "def create_slider_animation(fig, traces): \"\"\"Create a slider that animates a list of traces (e.g.", "= go.Scatter3d( x=x, y=y, z=z, mode='markers', marker_size=ps, marker_color=color, marker_line_width=.2) fig.add_trace(tr) def plot_camera(fig, R,", "= go.Figure() fig.update_layout( height=height, scene_camera=dict( eye=dict(x=0., y=-.1, z=-2), up=dict(x=0, y=-1., z=0)), scene=dict( xaxis=dict(showbackground=False),", "-np.array([0, 0, 1]) tr = go.Cone( x=[x], y=[y], z=[z], u=[u], v=[v], w=[w], anchor='tip',", "or create a slider animation. 3) Call `fig.show()` to render the figure. \"\"\"", "tr = go.Scatter3d( x=x, y=y, z=z, line=dict(color='rgba(0, 0, 0, .5)'), marker=dict(size=0.0001), showlegend=False) fig.add_trace(tr)", "\"\"\"Create a slider that animates a list of traces (e.g. 3D points).\"\"\" slider", "(e.g. 3D points).\"\"\" slider = {'steps': []} frames = [] fig.add_trace(traces[0]) idx =", "sliders. 1) Initialize a figure with `fig = init_figure()` 2) Plot points, cameras,", "= np.array([[0, 0], [W, 0], [W, H], [0, H], [0, 0]]) corners =", "cone with camera frustum.\"\"\" x, y, z = t u, v, w =", "marker_line_width=.2) fig.add_trace(tr) def plot_camera(fig, R, t, K, color='rgb(0, 0, 255)'): \"\"\"Plot a camera", "marker_size=ps, marker_color=color, marker_line_width=.2) fig.add_trace(tr) def plot_camera(fig, R, t, K, color='rgb(0, 0, 255)'): \"\"\"Plot", "corners = to_homogeneous(corners) @ np.linalg.inv(K).T corners = (corners/2) @ R.T + t x,", "slider = {'steps': []} frames = [] fig.add_trace(traces[0]) idx = len(fig.data) - 1", "and sliders. 1) Initialize a figure with `fig = init_figure()` 2) Plot points,", "powerful library like Open3D. Plotly however supports animations, buttons and sliders. 1) Initialize", "1)', ps=2): \"\"\"Plot a set of 3D points.\"\"\" x, y, z = pts.T", "fig.update_layout( height=height, scene_camera=dict( eye=dict(x=0., y=-.1, z=-2), up=dict(x=0, y=-1., z=0)), scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showbackground=False), aspectmode='data',", "y=y, z=z, mode='markers', marker_size=ps, marker_color=color, marker_line_width=.2) fig.add_trace(tr) def plot_camera(fig, R, t, K, color='rgb(0,", "= t u, v, w = R @ -np.array([0, 0, 1]) tr =", "@ -np.array([0, 0, 1]) tr = go.Cone( x=[x], y=[y], z=[z], u=[u], v=[v], w=[w],", "2]*2, K[1, 2]*2 corners = np.array([[0, 0], [W, 0], [W, H], [0, H],", "0], [W, 0], [W, H], [0, H], [0, 0]]) corners = to_homogeneous(corners) @", "H], [0, H], [0, 0]]) corners = to_homogeneous(corners) @ np.linalg.inv(K).T corners = (corners/2)", "y, z = pts.T tr = go.Scatter3d( x=x, y=y, z=z, mode='markers', marker_size=ps, marker_color=color,", "supports animations, buttons and sliders. 1) Initialize a figure with `fig = init_figure()`", "might want to instead use a more powerful library like Open3D. Plotly however", "the figure. \"\"\" import plotly.graph_objects as go import numpy as np from ..pixlib.geometry.utils", "marker_color=color, marker_line_width=.2) fig.add_trace(tr) def plot_camera(fig, R, t, K, color='rgb(0, 0, 255)'): \"\"\"Plot a", "create_slider_animation(fig, traces): \"\"\"Create a slider that animates a list of traces (e.g. 3D", "marker=dict(size=0.0001), showlegend=False) fig.add_trace(tr) def create_slider_animation(fig, traces): \"\"\"Create a slider that animates a list", "..pixlib.geometry.utils import to_homogeneous def init_figure(height=800): \"\"\"Initialize a 3D figure.\"\"\" fig = go.Figure() fig.update_layout(", "go.Cone( x=[x], y=[y], z=[z], u=[u], v=[v], w=[w], anchor='tip', showscale=False, colorscale=[[0, color], [1, color]],", "ps=2): \"\"\"Plot a set of 3D points.\"\"\" x, y, z = pts.T tr", "Open3D. Plotly however supports animations, buttons and sliders. 1) Initialize a figure with", "like Open3D. Plotly however supports animations, buttons and sliders. 1) Initialize a figure", "plotly.graph_objects as go import numpy as np from ..pixlib.geometry.utils import to_homogeneous def init_figure(height=800):", "a list of traces (e.g. 3D points).\"\"\" slider = {'steps': []} frames =", "[W, 0], [W, H], [0, H], [0, 0]]) corners = to_homogeneous(corners) @ np.linalg.inv(K).T", "0, 0, 1)', ps=2): \"\"\"Plot a set of 3D points.\"\"\" x, y, z", "primitives based on Plotly. We might want to instead use a more powerful", "return fig def plot_points(fig, pts, color='rgba(255, 0, 0, 1)', ps=2): \"\"\"Plot a set", "tr = go.Scatter3d( x=x, y=y, z=z, mode='markers', marker_size=ps, marker_color=color, marker_line_width=.2) fig.add_trace(tr) def plot_camera(fig,", "K, color='rgb(0, 0, 255)'): \"\"\"Plot a camera as a cone with camera frustum.\"\"\"", "instead use a more powerful library like Open3D. Plotly however supports animations, buttons", "scene_camera=dict( eye=dict(x=0., y=-.1, z=-2), up=dict(x=0, y=-1., z=0)), scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showbackground=False), aspectmode='data', dragmode='orbit'), margin=dict(l=0,", "0, 1)', ps=2): \"\"\"Plot a set of 3D points.\"\"\" x, y, z =", "line=dict(color='rgba(0, 0, 0, .5)'), marker=dict(size=0.0001), showlegend=False) fig.add_trace(tr) def create_slider_animation(fig, traces): \"\"\"Create a slider", "Plotly. We might want to instead use a more powerful library like Open3D.", "# noqa E741 return fig def plot_points(fig, pts, color='rgba(255, 0, 0, 1)', ps=2):", "noqa E741 return fig def plot_points(fig, pts, color='rgba(255, 0, 0, 1)', ps=2): \"\"\"Plot", "x=x, y=y, z=z, line=dict(color='rgba(0, 0, 0, .5)'), marker=dict(size=0.0001), showlegend=False) fig.add_trace(tr) def create_slider_animation(fig, traces):", "[W, H], [0, H], [0, 0]]) corners = to_homogeneous(corners) @ np.linalg.inv(K).T corners =", "x, y, z = pts.T tr = go.Scatter3d( x=x, y=y, z=z, mode='markers', marker_size=ps,", "render the figure. \"\"\" import plotly.graph_objects as go import numpy as np from", "x=[x], y=[y], z=[z], u=[u], v=[v], w=[w], anchor='tip', showscale=False, colorscale=[[0, color], [1, color]], sizemode='absolute')", "\"\"\"Plot a set of 3D points.\"\"\" x, y, z = pts.T tr =", "[]} frames = [] fig.add_trace(traces[0]) idx = len(fig.data) - 1 for i, tr", "pad=0)) # noqa E741 return fig def plot_points(fig, pts, color='rgba(255, 0, 0, 1)',", "fig = go.Figure() fig.update_layout( height=height, scene_camera=dict( eye=dict(x=0., y=-.1, z=-2), up=dict(x=0, y=-1., z=0)), scene=dict(", "figure. \"\"\" import plotly.graph_objects as go import numpy as np from ..pixlib.geometry.utils import", "a 3D figure.\"\"\" fig = go.Figure() fig.update_layout( height=height, scene_camera=dict( eye=dict(x=0., y=-.1, z=-2), up=dict(x=0,", "go.Scatter3d( x=x, y=y, z=z, line=dict(color='rgba(0, 0, 0, .5)'), marker=dict(size=0.0001), showlegend=False) fig.add_trace(tr) def create_slider_animation(fig,", "pts.T tr = go.Scatter3d( x=x, y=y, z=z, mode='markers', marker_size=ps, marker_color=color, marker_line_width=.2) fig.add_trace(tr) def", "data=[tr])) step = {\"args\": [ [str(i)], {\"frame\": {\"redraw\": True}, \"mode\": \"immediate\"}], \"label\": i,", "\"\"\" import plotly.graph_objects as go import numpy as np from ..pixlib.geometry.utils import to_homogeneous", "enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx], data=[tr])) step = {\"args\": [ [str(i)], {\"frame\": {\"redraw\": True}, \"mode\":" ]
[ "= True def check_victory(check_grids: np.ndarray) -> set[int]: \"\"\"return empty set if no victory,", "set if no victory, else set of id of the wining grids\"\"\" return", "<filename>day04/c.py import numpy as np GRID_SIZE = 5 def read_bingo_grid(lines: list[str]) -> list[list[int]]:", "np.ndarray, number: int) -> None: checked_grids[np.where(grids == number)] = True def check_victory(check_grids: np.ndarray)", "\"\"\"return empty set if no victory, else set of id of the wining", "np GRID_SIZE = 5 def read_bingo_grid(lines: list[str]) -> list[list[int]]: return [[int(n) for n", "number: int) -> None: checked_grids[np.where(grids == number)] = True def check_victory(check_grids: np.ndarray) ->", "def sum_grid(grid: np.ndarray, checked_grid: np.ndarray) -> int: grid[checked_grid] = 0 return grid.sum() def", "True def check_victory(check_grids: np.ndarray) -> set[int]: \"\"\"return empty set if no victory, else", "index = list(winning_set)[0] s = sum_grid(grids[index], checked_grids[index]) print(\"part1:\", s * random_numbers[i]) q1_done =", "len(grids) == len(winning_set): s = sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win]) print(\"part2:\", random_numbers[i], s, random_numbers[i] * s)", "GRID_SIZE = 5 def read_bingo_grid(lines: list[str]) -> list[list[int]]: return [[int(n) for n in", "bingo_step(grids: np.ndarray, checked_grids: np.ndarray, number: int) -> None: checked_grids[np.where(grids == number)] = True", "open(\"input.txt\") as f: lines = f.readlines() random_numbers = [int(n) for n in lines[0].split(\",\")]", "f: lines = f.readlines() random_numbers = [int(n) for n in lines[0].split(\",\")] grids =", "_ in range(len(grids))]) win = False i = 0 q1_done = False while", "False while not win: bingo_step(grids, checked_grids, random_numbers[i]) winning_set = check_victory(checked_grids) if len(winning_set) ==", "np.ndarray, checked_grids: np.ndarray, number: int) -> None: checked_grids[np.where(grids == number)] = True def", "int: grid[checked_grid] = 0 return grid.sum() def main() -> None: with open(\"input.txt\") as", "i + GRID_SIZE]) for i in range(2, len(lines), 1 + GRID_SIZE)]) checked_grids =", "s = sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win]) print(\"part2:\", random_numbers[i], s, random_numbers[i] * s) return i +=", "GRID_SIZE]) for i in range(2, len(lines), 1 + GRID_SIZE)]) checked_grids = np.array([[[False for", "list(set(range(len(grids))).difference(winning_set))[0] if len(grids) == len(winning_set): s = sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win]) print(\"part2:\", random_numbers[i], s, random_numbers[i]", "for _ in range(len(grids))]) win = False i = 0 q1_done = False", "[[int(n) for n in line.split()] for line in lines] def bingo_step(grids: np.ndarray, checked_grids:", "= sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win]) print(\"part2:\", random_numbers[i], s, random_numbers[i] * s) return i += 1", "-> int: grid[checked_grid] = 0 return grid.sum() def main() -> None: with open(\"input.txt\")", "= np.array([read_bingo_grid(lines[i : i + GRID_SIZE]) for i in range(2, len(lines), 1 +", "in range(2, len(lines), 1 + GRID_SIZE)]) checked_grids = np.array([[[False for _ in range(GRID_SIZE)]", "range(GRID_SIZE)] for _ in range(GRID_SIZE)] for _ in range(len(grids))]) win = False i", "s * random_numbers[i]) q1_done = True if len(grids) == len(winning_set) + 1: index_last_to_win", "check_victory(check_grids: np.ndarray) -> set[int]: \"\"\"return empty set if no victory, else set of", "sum_grid(grid: np.ndarray, checked_grid: np.ndarray) -> int: grid[checked_grid] = 0 return grid.sum() def main()", "grids\"\"\" return set(np.where(check_grids.sum(axis=1).max(axis=1) == 5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1) == 5)[0] ) def sum_grid(grid: np.ndarray, checked_grid:", "1 + GRID_SIZE)]) checked_grids = np.array([[[False for _ in range(GRID_SIZE)] for _ in", "random_numbers = [int(n) for n in lines[0].split(\",\")] grids = np.array([read_bingo_grid(lines[i : i +", "GRID_SIZE)]) checked_grids = np.array([[[False for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)] for", ": i + GRID_SIZE]) for i in range(2, len(lines), 1 + GRID_SIZE)]) checked_grids", "if len(winning_set) == 1 and not q1_done: index = list(winning_set)[0] s = sum_grid(grids[index],", "numpy as np GRID_SIZE = 5 def read_bingo_grid(lines: list[str]) -> list[list[int]]: return [[int(n)", "in range(len(grids))]) win = False i = 0 q1_done = False while not", "+ GRID_SIZE]) for i in range(2, len(lines), 1 + GRID_SIZE)]) checked_grids = np.array([[[False", "f.readlines() random_numbers = [int(n) for n in lines[0].split(\",\")] grids = np.array([read_bingo_grid(lines[i : i", "for i in range(2, len(lines), 1 + GRID_SIZE)]) checked_grids = np.array([[[False for _", "int) -> None: checked_grids[np.where(grids == number)] = True def check_victory(check_grids: np.ndarray) -> set[int]:", "= np.array([[[False for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)] for _ in", "def bingo_step(grids: np.ndarray, checked_grids: np.ndarray, number: int) -> None: checked_grids[np.where(grids == number)] =", "= True if len(grids) == len(winning_set) + 1: index_last_to_win = list(set(range(len(grids))).difference(winning_set))[0] if len(grids)", "n in lines[0].split(\",\")] grids = np.array([read_bingo_grid(lines[i : i + GRID_SIZE]) for i in", "for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)] for _ in range(len(grids))]) win", "set(np.where(check_grids.sum(axis=1).max(axis=1) == 5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1) == 5)[0] ) def sum_grid(grid: np.ndarray, checked_grid: np.ndarray) ->", "s = sum_grid(grids[index], checked_grids[index]) print(\"part1:\", s * random_numbers[i]) q1_done = True if len(grids)", "read_bingo_grid(lines: list[str]) -> list[list[int]]: return [[int(n) for n in line.split()] for line in", "while not win: bingo_step(grids, checked_grids, random_numbers[i]) winning_set = check_victory(checked_grids) if len(winning_set) == 1", "empty set if no victory, else set of id of the wining grids\"\"\"", "range(len(grids))]) win = False i = 0 q1_done = False while not win:", "5 def read_bingo_grid(lines: list[str]) -> list[list[int]]: return [[int(n) for n in line.split()] for", "number)] = True def check_victory(check_grids: np.ndarray) -> set[int]: \"\"\"return empty set if no", "np.array([[[False for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)] for _ in range(len(grids))])", "of the wining grids\"\"\" return set(np.where(check_grids.sum(axis=1).max(axis=1) == 5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1) == 5)[0] ) def", "+ 1: index_last_to_win = list(set(range(len(grids))).difference(winning_set))[0] if len(grids) == len(winning_set): s = sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win])", "the wining grids\"\"\" return set(np.where(check_grids.sum(axis=1).max(axis=1) == 5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1) == 5)[0] ) def sum_grid(grid:", "as np GRID_SIZE = 5 def read_bingo_grid(lines: list[str]) -> list[list[int]]: return [[int(n) for", "range(GRID_SIZE)] for _ in range(len(grids))]) win = False i = 0 q1_done =", "len(winning_set) == 1 and not q1_done: index = list(winning_set)[0] s = sum_grid(grids[index], checked_grids[index])", "in range(GRID_SIZE)] for _ in range(len(grids))]) win = False i = 0 q1_done", "= 0 return grid.sum() def main() -> None: with open(\"input.txt\") as f: lines", "== 1 and not q1_done: index = list(winning_set)[0] s = sum_grid(grids[index], checked_grids[index]) print(\"part1:\",", "q1_done: index = list(winning_set)[0] s = sum_grid(grids[index], checked_grids[index]) print(\"part1:\", s * random_numbers[i]) q1_done", "victory, else set of id of the wining grids\"\"\" return set(np.where(check_grids.sum(axis=1).max(axis=1) == 5)[0]).union(", "len(lines), 1 + GRID_SIZE)]) checked_grids = np.array([[[False for _ in range(GRID_SIZE)] for _", "0 return grid.sum() def main() -> None: with open(\"input.txt\") as f: lines =", "return set(np.where(check_grids.sum(axis=1).max(axis=1) == 5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1) == 5)[0] ) def sum_grid(grid: np.ndarray, checked_grid: np.ndarray)", "q1_done = False while not win: bingo_step(grids, checked_grids, random_numbers[i]) winning_set = check_victory(checked_grids) if", "set of id of the wining grids\"\"\" return set(np.where(check_grids.sum(axis=1).max(axis=1) == 5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1) ==", "len(winning_set) + 1: index_last_to_win = list(set(range(len(grids))).difference(winning_set))[0] if len(grids) == len(winning_set): s = sum_grid(grids[index_last_to_win],", "import numpy as np GRID_SIZE = 5 def read_bingo_grid(lines: list[str]) -> list[list[int]]: return", "+ GRID_SIZE)]) checked_grids = np.array([[[False for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)]", "sum_grid(grids[index], checked_grids[index]) print(\"part1:\", s * random_numbers[i]) q1_done = True if len(grids) == len(winning_set)", "and not q1_done: index = list(winning_set)[0] s = sum_grid(grids[index], checked_grids[index]) print(\"part1:\", s *", "def read_bingo_grid(lines: list[str]) -> list[list[int]]: return [[int(n) for n in line.split()] for line", "checked_grids[index_last_to_win]) print(\"part2:\", random_numbers[i], s, random_numbers[i] * s) return i += 1 if __name__", "1: index_last_to_win = list(set(range(len(grids))).difference(winning_set))[0] if len(grids) == len(winning_set): s = sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win]) print(\"part2:\",", "if no victory, else set of id of the wining grids\"\"\" return set(np.where(check_grids.sum(axis=1).max(axis=1)", "= False while not win: bingo_step(grids, checked_grids, random_numbers[i]) winning_set = check_victory(checked_grids) if len(winning_set)", "False i = 0 q1_done = False while not win: bingo_step(grids, checked_grids, random_numbers[i])", "len(grids) == len(winning_set) + 1: index_last_to_win = list(set(range(len(grids))).difference(winning_set))[0] if len(grids) == len(winning_set): s", "= False i = 0 q1_done = False while not win: bingo_step(grids, checked_grids,", "return [[int(n) for n in line.split()] for line in lines] def bingo_step(grids: np.ndarray,", "n in line.split()] for line in lines] def bingo_step(grids: np.ndarray, checked_grids: np.ndarray, number:", "in lines[0].split(\",\")] grids = np.array([read_bingo_grid(lines[i : i + GRID_SIZE]) for i in range(2,", "= sum_grid(grids[index], checked_grids[index]) print(\"part1:\", s * random_numbers[i]) q1_done = True if len(grids) ==", "_ in range(GRID_SIZE)] for _ in range(GRID_SIZE)] for _ in range(len(grids))]) win =", "checked_grids, random_numbers[i]) winning_set = check_victory(checked_grids) if len(winning_set) == 1 and not q1_done: index", "print(\"part2:\", random_numbers[i], s, random_numbers[i] * s) return i += 1 if __name__ ==", "else set of id of the wining grids\"\"\" return set(np.where(check_grids.sum(axis=1).max(axis=1) == 5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1)", "s, random_numbers[i] * s) return i += 1 if __name__ == \"__main__\": main()", "def check_victory(check_grids: np.ndarray) -> set[int]: \"\"\"return empty set if no victory, else set", "i in range(2, len(lines), 1 + GRID_SIZE)]) checked_grids = np.array([[[False for _ in", "-> None: with open(\"input.txt\") as f: lines = f.readlines() random_numbers = [int(n) for", "if len(grids) == len(winning_set): s = sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win]) print(\"part2:\", random_numbers[i], s, random_numbers[i] *", "in lines] def bingo_step(grids: np.ndarray, checked_grids: np.ndarray, number: int) -> None: checked_grids[np.where(grids ==", "main() -> None: with open(\"input.txt\") as f: lines = f.readlines() random_numbers = [int(n)", "print(\"part1:\", s * random_numbers[i]) q1_done = True if len(grids) == len(winning_set) + 1:", "5)[0] ) def sum_grid(grid: np.ndarray, checked_grid: np.ndarray) -> int: grid[checked_grid] = 0 return", "lines] def bingo_step(grids: np.ndarray, checked_grids: np.ndarray, number: int) -> None: checked_grids[np.where(grids == number)]", "== len(winning_set) + 1: index_last_to_win = list(set(range(len(grids))).difference(winning_set))[0] if len(grids) == len(winning_set): s =", "for n in line.split()] for line in lines] def bingo_step(grids: np.ndarray, checked_grids: np.ndarray,", "= check_victory(checked_grids) if len(winning_set) == 1 and not q1_done: index = list(winning_set)[0] s", "= 5 def read_bingo_grid(lines: list[str]) -> list[list[int]]: return [[int(n) for n in line.split()]", "range(2, len(lines), 1 + GRID_SIZE)]) checked_grids = np.array([[[False for _ in range(GRID_SIZE)] for", "as f: lines = f.readlines() random_numbers = [int(n) for n in lines[0].split(\",\")] grids", "= list(winning_set)[0] s = sum_grid(grids[index], checked_grids[index]) print(\"part1:\", s * random_numbers[i]) q1_done = True", "== 5)[0] ) def sum_grid(grid: np.ndarray, checked_grid: np.ndarray) -> int: grid[checked_grid] = 0", "random_numbers[i]) q1_done = True if len(grids) == len(winning_set) + 1: index_last_to_win = list(set(range(len(grids))).difference(winning_set))[0]", "== len(winning_set): s = sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win]) print(\"part2:\", random_numbers[i], s, random_numbers[i] * s) return", "no victory, else set of id of the wining grids\"\"\" return set(np.where(check_grids.sum(axis=1).max(axis=1) ==", "= f.readlines() random_numbers = [int(n) for n in lines[0].split(\",\")] grids = np.array([read_bingo_grid(lines[i :", "0 q1_done = False while not win: bingo_step(grids, checked_grids, random_numbers[i]) winning_set = check_victory(checked_grids)", "line.split()] for line in lines] def bingo_step(grids: np.ndarray, checked_grids: np.ndarray, number: int) ->", "np.ndarray) -> set[int]: \"\"\"return empty set if no victory, else set of id", "== 5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1) == 5)[0] ) def sum_grid(grid: np.ndarray, checked_grid: np.ndarray) -> int:", "np.ndarray) -> int: grid[checked_grid] = 0 return grid.sum() def main() -> None: with", "winning_set = check_victory(checked_grids) if len(winning_set) == 1 and not q1_done: index = list(winning_set)[0]", "checked_grids = np.array([[[False for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)] for _", "[int(n) for n in lines[0].split(\",\")] grids = np.array([read_bingo_grid(lines[i : i + GRID_SIZE]) for", "None: checked_grids[np.where(grids == number)] = True def check_victory(check_grids: np.ndarray) -> set[int]: \"\"\"return empty", "check_victory(checked_grids) if len(winning_set) == 1 and not q1_done: index = list(winning_set)[0] s =", "checked_grids: np.ndarray, number: int) -> None: checked_grids[np.where(grids == number)] = True def check_victory(check_grids:", "checked_grid: np.ndarray) -> int: grid[checked_grid] = 0 return grid.sum() def main() -> None:", "-> list[list[int]]: return [[int(n) for n in line.split()] for line in lines] def", "checked_grids[index]) print(\"part1:\", s * random_numbers[i]) q1_done = True if len(grids) == len(winning_set) +", "set[int]: \"\"\"return empty set if no victory, else set of id of the", "in line.split()] for line in lines] def bingo_step(grids: np.ndarray, checked_grids: np.ndarray, number: int)", "win = False i = 0 q1_done = False while not win: bingo_step(grids,", "win: bingo_step(grids, checked_grids, random_numbers[i]) winning_set = check_victory(checked_grids) if len(winning_set) == 1 and not", "== number)] = True def check_victory(check_grids: np.ndarray) -> set[int]: \"\"\"return empty set if", "5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1) == 5)[0] ) def sum_grid(grid: np.ndarray, checked_grid: np.ndarray) -> int: grid[checked_grid]", "in range(GRID_SIZE)] for _ in range(GRID_SIZE)] for _ in range(len(grids))]) win = False", "list[list[int]]: return [[int(n) for n in line.split()] for line in lines] def bingo_step(grids:", "True if len(grids) == len(winning_set) + 1: index_last_to_win = list(set(range(len(grids))).difference(winning_set))[0] if len(grids) ==", "list[str]) -> list[list[int]]: return [[int(n) for n in line.split()] for line in lines]", "for line in lines] def bingo_step(grids: np.ndarray, checked_grids: np.ndarray, number: int) -> None:", "if len(grids) == len(winning_set) + 1: index_last_to_win = list(set(range(len(grids))).difference(winning_set))[0] if len(grids) == len(winning_set):", "bingo_step(grids, checked_grids, random_numbers[i]) winning_set = check_victory(checked_grids) if len(winning_set) == 1 and not q1_done:", "np.ndarray, checked_grid: np.ndarray) -> int: grid[checked_grid] = 0 return grid.sum() def main() ->", "= 0 q1_done = False while not win: bingo_step(grids, checked_grids, random_numbers[i]) winning_set =", ") def sum_grid(grid: np.ndarray, checked_grid: np.ndarray) -> int: grid[checked_grid] = 0 return grid.sum()", "i = 0 q1_done = False while not win: bingo_step(grids, checked_grids, random_numbers[i]) winning_set", "lines[0].split(\",\")] grids = np.array([read_bingo_grid(lines[i : i + GRID_SIZE]) for i in range(2, len(lines),", "-> None: checked_grids[np.where(grids == number)] = True def check_victory(check_grids: np.ndarray) -> set[int]: \"\"\"return", "line in lines] def bingo_step(grids: np.ndarray, checked_grids: np.ndarray, number: int) -> None: checked_grids[np.where(grids", "= [int(n) for n in lines[0].split(\",\")] grids = np.array([read_bingo_grid(lines[i : i + GRID_SIZE])", "random_numbers[i], s, random_numbers[i] * s) return i += 1 if __name__ == \"__main__\":", "_ in range(GRID_SIZE)] for _ in range(len(grids))]) win = False i = 0", "-> set[int]: \"\"\"return empty set if no victory, else set of id of", "id of the wining grids\"\"\" return set(np.where(check_grids.sum(axis=1).max(axis=1) == 5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1) == 5)[0] )", "return grid.sum() def main() -> None: with open(\"input.txt\") as f: lines = f.readlines()", "None: with open(\"input.txt\") as f: lines = f.readlines() random_numbers = [int(n) for n", "lines = f.readlines() random_numbers = [int(n) for n in lines[0].split(\",\")] grids = np.array([read_bingo_grid(lines[i", "* random_numbers[i]) q1_done = True if len(grids) == len(winning_set) + 1: index_last_to_win =", "checked_grids[np.where(grids == number)] = True def check_victory(check_grids: np.ndarray) -> set[int]: \"\"\"return empty set", "def main() -> None: with open(\"input.txt\") as f: lines = f.readlines() random_numbers =", "with open(\"input.txt\") as f: lines = f.readlines() random_numbers = [int(n) for n in", "random_numbers[i]) winning_set = check_victory(checked_grids) if len(winning_set) == 1 and not q1_done: index =", "np.array([read_bingo_grid(lines[i : i + GRID_SIZE]) for i in range(2, len(lines), 1 + GRID_SIZE)])", "np.where(check_grids.sum(axis=2).max(axis=1) == 5)[0] ) def sum_grid(grid: np.ndarray, checked_grid: np.ndarray) -> int: grid[checked_grid] =", "list(winning_set)[0] s = sum_grid(grids[index], checked_grids[index]) print(\"part1:\", s * random_numbers[i]) q1_done = True if", "sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win]) print(\"part2:\", random_numbers[i], s, random_numbers[i] * s) return i += 1 if", "len(winning_set): s = sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win]) print(\"part2:\", random_numbers[i], s, random_numbers[i] * s) return i", "q1_done = True if len(grids) == len(winning_set) + 1: index_last_to_win = list(set(range(len(grids))).difference(winning_set))[0] if", "grids = np.array([read_bingo_grid(lines[i : i + GRID_SIZE]) for i in range(2, len(lines), 1", "= list(set(range(len(grids))).difference(winning_set))[0] if len(grids) == len(winning_set): s = sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win]) print(\"part2:\", random_numbers[i], s,", "index_last_to_win = list(set(range(len(grids))).difference(winning_set))[0] if len(grids) == len(winning_set): s = sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win]) print(\"part2:\", random_numbers[i],", "grid.sum() def main() -> None: with open(\"input.txt\") as f: lines = f.readlines() random_numbers", "wining grids\"\"\" return set(np.where(check_grids.sum(axis=1).max(axis=1) == 5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1) == 5)[0] ) def sum_grid(grid: np.ndarray,", "for _ in range(GRID_SIZE)] for _ in range(len(grids))]) win = False i =", "grid[checked_grid] = 0 return grid.sum() def main() -> None: with open(\"input.txt\") as f:", "not win: bingo_step(grids, checked_grids, random_numbers[i]) winning_set = check_victory(checked_grids) if len(winning_set) == 1 and", "1 and not q1_done: index = list(winning_set)[0] s = sum_grid(grids[index], checked_grids[index]) print(\"part1:\", s", "not q1_done: index = list(winning_set)[0] s = sum_grid(grids[index], checked_grids[index]) print(\"part1:\", s * random_numbers[i])", "of id of the wining grids\"\"\" return set(np.where(check_grids.sum(axis=1).max(axis=1) == 5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1) == 5)[0]", "for n in lines[0].split(\",\")] grids = np.array([read_bingo_grid(lines[i : i + GRID_SIZE]) for i" ]
[ "alt.selection_single(name='year', fields=['year'], bind=slider) base = alt.Chart(pop).add_selection( select_year ).transform_filter( select_year ).transform_calculate( gender=if_(datum.sex == 1,", "# category: case studies import altair as alt from altair.expr import datum, if_", "select_year ).transform_calculate( gender=if_(datum.sex == 1, 'Male', 'Female') ) title = alt.Axis(title='population') color_scale =", "Time =============================== A population pyramid shows the distribution of age groups within a", "slider = alt.binding_range(min=1850, max=2000, step=10) select_year = alt.selection_single(name='year', fields=['year'], bind=slider) base = alt.Chart(pop).add_selection(", ").encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Female') middle = base.encode(", "that is bound to the year to visualize the age distribution over time.", "base.encode( y=alt.X('age:O', axis=None), text=alt.Text('age:Q'), ).mark_text().properties(width=20) right = base.transform_filter( datum.gender == 'Male' ).encode( y=alt.X('age:O',", ").mark_text().properties(width=20) right = base.transform_filter( datum.gender == 'Male' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title), color=alt.Color('gender:N',", "gender=if_(datum.sex == 1, 'Male', 'Female') ) title = alt.Axis(title='population') color_scale = alt.Scale(domain=['Male', 'Female'],", "uses a slider widget that is bound to the year to visualize the", "= data.population.url slider = alt.binding_range(min=1850, max=2000, step=10) select_year = alt.selection_single(name='year', fields=['year'], bind=slider) base", "y=alt.X('age:O', axis=None), text=alt.Text('age:Q'), ).mark_text().properties(width=20) right = base.transform_filter( datum.gender == 'Male' ).encode( y=alt.X('age:O', axis=None),", "the age distribution over time. ''' # category: case studies import altair as", "alt.Chart(pop).add_selection( select_year ).transform_filter( select_year ).transform_calculate( gender=if_(datum.sex == 1, 'Male', 'Female') ) title =", "from altair.expr import datum, if_ from vega_datasets import data pop = data.population.url slider", "distribution over time. ''' # category: case studies import altair as alt from", "alt.Scale(domain=['Male', 'Female'], range=['#1f77b4', '#e377c2']) left = base.transform_filter( datum.gender == 'Female' ).encode( y=alt.X('age:O', axis=None),", "the distribution of age groups within a population. It uses a slider widget", "studies import altair as alt from altair.expr import datum, if_ from vega_datasets import", ") title = alt.Axis(title='population') color_scale = alt.Scale(domain=['Male', 'Female'], range=['#1f77b4', '#e377c2']) left = base.transform_filter(", ").mark_bar().properties(title='Female') middle = base.encode( y=alt.X('age:O', axis=None), text=alt.Text('age:Q'), ).mark_text().properties(width=20) right = base.transform_filter( datum.gender ==", "== 'Female' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Female') middle", "= alt.selection_single(name='year', fields=['year'], bind=slider) base = alt.Chart(pop).add_selection( select_year ).transform_filter( select_year ).transform_calculate( gender=if_(datum.sex ==", "range=['#1f77b4', '#e377c2']) left = base.transform_filter( datum.gender == 'Female' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title,", "Over Time =============================== A population pyramid shows the distribution of age groups within", "age groups within a population. It uses a slider widget that is bound", "altair as alt from altair.expr import datum, if_ from vega_datasets import data pop", "alt.Axis(title='population') color_scale = alt.Scale(domain=['Male', 'Female'], range=['#1f77b4', '#e377c2']) left = base.transform_filter( datum.gender == 'Female'", "'Female' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Female') middle =", "as alt from altair.expr import datum, if_ from vega_datasets import data pop =", "population pyramid shows the distribution of age groups within a population. It uses", "a slider widget that is bound to the year to visualize the age", "'#e377c2']) left = base.transform_filter( datum.gender == 'Female' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')),", "axis=title, sort=alt.SortOrder('descending')), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Female') middle = base.encode( y=alt.X('age:O', axis=None), text=alt.Text('age:Q'), ).mark_text().properties(width=20)", "to the year to visualize the age distribution over time. ''' # category:", "case studies import altair as alt from altair.expr import datum, if_ from vega_datasets", "import data pop = data.population.url slider = alt.binding_range(min=1850, max=2000, step=10) select_year = alt.selection_single(name='year',", "scale=color_scale, legend=None) ).mark_bar().properties(title='Female') middle = base.encode( y=alt.X('age:O', axis=None), text=alt.Text('age:Q'), ).mark_text().properties(width=20) right = base.transform_filter(", "1, 'Male', 'Female') ) title = alt.Axis(title='population') color_scale = alt.Scale(domain=['Male', 'Female'], range=['#1f77b4', '#e377c2'])", "groups within a population. It uses a slider widget that is bound to", "data.population.url slider = alt.binding_range(min=1850, max=2000, step=10) select_year = alt.selection_single(name='year', fields=['year'], bind=slider) base =", "== 'Male' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Male') left |", "= alt.binding_range(min=1850, max=2000, step=10) select_year = alt.selection_single(name='year', fields=['year'], bind=slider) base = alt.Chart(pop).add_selection( select_year", ").transform_calculate( gender=if_(datum.sex == 1, 'Male', 'Female') ) title = alt.Axis(title='population') color_scale = alt.Scale(domain=['Male',", "altair.expr import datum, if_ from vega_datasets import data pop = data.population.url slider =", "import datum, if_ from vega_datasets import data pop = data.population.url slider = alt.binding_range(min=1850,", "category: case studies import altair as alt from altair.expr import datum, if_ from", "x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Female') middle = base.encode( y=alt.X('age:O', axis=None), text=alt.Text('age:Q'),", "over time. ''' # category: case studies import altair as alt from altair.expr", "distribution of age groups within a population. It uses a slider widget that", "vega_datasets import data pop = data.population.url slider = alt.binding_range(min=1850, max=2000, step=10) select_year =", ").transform_filter( select_year ).transform_calculate( gender=if_(datum.sex == 1, 'Male', 'Female') ) title = alt.Axis(title='population') color_scale", "= base.transform_filter( datum.gender == 'Male' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title), color=alt.Color('gender:N', scale=color_scale, legend=None)", "= base.transform_filter( datum.gender == 'Female' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')), color=alt.Color('gender:N', scale=color_scale,", "== 1, 'Male', 'Female') ) title = alt.Axis(title='population') color_scale = alt.Scale(domain=['Male', 'Female'], range=['#1f77b4',", "left = base.transform_filter( datum.gender == 'Female' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')), color=alt.Color('gender:N',", "title = alt.Axis(title='population') color_scale = alt.Scale(domain=['Male', 'Female'], range=['#1f77b4', '#e377c2']) left = base.transform_filter( datum.gender", "legend=None) ).mark_bar().properties(title='Female') middle = base.encode( y=alt.X('age:O', axis=None), text=alt.Text('age:Q'), ).mark_text().properties(width=20) right = base.transform_filter( datum.gender", "Pyramid Over Time =============================== A population pyramid shows the distribution of age groups", "= alt.Axis(title='population') color_scale = alt.Scale(domain=['Male', 'Female'], range=['#1f77b4', '#e377c2']) left = base.transform_filter( datum.gender ==", "slider widget that is bound to the year to visualize the age distribution", "'Female'], range=['#1f77b4', '#e377c2']) left = base.transform_filter( datum.gender == 'Female' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q',", "from vega_datasets import data pop = data.population.url slider = alt.binding_range(min=1850, max=2000, step=10) select_year", "''' # category: case studies import altair as alt from altair.expr import datum,", "if_ from vega_datasets import data pop = data.population.url slider = alt.binding_range(min=1850, max=2000, step=10)", "datum, if_ from vega_datasets import data pop = data.population.url slider = alt.binding_range(min=1850, max=2000,", "bind=slider) base = alt.Chart(pop).add_selection( select_year ).transform_filter( select_year ).transform_calculate( gender=if_(datum.sex == 1, 'Male', 'Female')", "data pop = data.population.url slider = alt.binding_range(min=1850, max=2000, step=10) select_year = alt.selection_single(name='year', fields=['year'],", "axis=None), x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Female') middle = base.encode( y=alt.X('age:O', axis=None),", "'Female') ) title = alt.Axis(title='population') color_scale = alt.Scale(domain=['Male', 'Female'], range=['#1f77b4', '#e377c2']) left =", "Population Pyramid Over Time =============================== A population pyramid shows the distribution of age", "y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Male') left | middle | right", "alt.binding_range(min=1850, max=2000, step=10) select_year = alt.selection_single(name='year', fields=['year'], bind=slider) base = alt.Chart(pop).add_selection( select_year ).transform_filter(", "pyramid shows the distribution of age groups within a population. It uses a", "import altair as alt from altair.expr import datum, if_ from vega_datasets import data", ").encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Male') left | middle |", "'Male', 'Female') ) title = alt.Axis(title='population') color_scale = alt.Scale(domain=['Male', 'Female'], range=['#1f77b4', '#e377c2']) left", "within a population. It uses a slider widget that is bound to the", "datum.gender == 'Female' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Female')", "a population. It uses a slider widget that is bound to the year", "the year to visualize the age distribution over time. ''' # category: case", "''' US Population Pyramid Over Time =============================== A population pyramid shows the distribution", "= alt.Chart(pop).add_selection( select_year ).transform_filter( select_year ).transform_calculate( gender=if_(datum.sex == 1, 'Male', 'Female') ) title", "= alt.Scale(domain=['Male', 'Female'], range=['#1f77b4', '#e377c2']) left = base.transform_filter( datum.gender == 'Female' ).encode( y=alt.X('age:O',", "base.transform_filter( datum.gender == 'Female' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')), color=alt.Color('gender:N', scale=color_scale, legend=None)", "sort=alt.SortOrder('descending')), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Female') middle = base.encode( y=alt.X('age:O', axis=None), text=alt.Text('age:Q'), ).mark_text().properties(width=20) right", "color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Female') middle = base.encode( y=alt.X('age:O', axis=None), text=alt.Text('age:Q'), ).mark_text().properties(width=20) right =", "alt from altair.expr import datum, if_ from vega_datasets import data pop = data.population.url", "of age groups within a population. It uses a slider widget that is", "'Male' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Male') left | middle", "step=10) select_year = alt.selection_single(name='year', fields=['year'], bind=slider) base = alt.Chart(pop).add_selection( select_year ).transform_filter( select_year ).transform_calculate(", "shows the distribution of age groups within a population. It uses a slider", "base.transform_filter( datum.gender == 'Male' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Male')", "fields=['year'], bind=slider) base = alt.Chart(pop).add_selection( select_year ).transform_filter( select_year ).transform_calculate( gender=if_(datum.sex == 1, 'Male',", "datum.gender == 'Male' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Male') left", "widget that is bound to the year to visualize the age distribution over", "y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Female') middle = base.encode( y=alt.X('age:O',", "to visualize the age distribution over time. ''' # category: case studies import", "pop = data.population.url slider = alt.binding_range(min=1850, max=2000, step=10) select_year = alt.selection_single(name='year', fields=['year'], bind=slider)", "color_scale = alt.Scale(domain=['Male', 'Female'], range=['#1f77b4', '#e377c2']) left = base.transform_filter( datum.gender == 'Female' ).encode(", "select_year = alt.selection_single(name='year', fields=['year'], bind=slider) base = alt.Chart(pop).add_selection( select_year ).transform_filter( select_year ).transform_calculate( gender=if_(datum.sex", "= base.encode( y=alt.X('age:O', axis=None), text=alt.Text('age:Q'), ).mark_text().properties(width=20) right = base.transform_filter( datum.gender == 'Male' ).encode(", "=============================== A population pyramid shows the distribution of age groups within a population.", "select_year ).transform_filter( select_year ).transform_calculate( gender=if_(datum.sex == 1, 'Male', 'Female') ) title = alt.Axis(title='population')", "US Population Pyramid Over Time =============================== A population pyramid shows the distribution of", "year to visualize the age distribution over time. ''' # category: case studies", "right = base.transform_filter( datum.gender == 'Male' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title), color=alt.Color('gender:N', scale=color_scale,", "max=2000, step=10) select_year = alt.selection_single(name='year', fields=['year'], bind=slider) base = alt.Chart(pop).add_selection( select_year ).transform_filter( select_year", "A population pyramid shows the distribution of age groups within a population. It", "It uses a slider widget that is bound to the year to visualize", "bound to the year to visualize the age distribution over time. ''' #", "axis=None), text=alt.Text('age:Q'), ).mark_text().properties(width=20) right = base.transform_filter( datum.gender == 'Male' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q',", "base = alt.Chart(pop).add_selection( select_year ).transform_filter( select_year ).transform_calculate( gender=if_(datum.sex == 1, 'Male', 'Female') )", "text=alt.Text('age:Q'), ).mark_text().properties(width=20) right = base.transform_filter( datum.gender == 'Male' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title),", "is bound to the year to visualize the age distribution over time. '''", "<filename>altair/vegalite/v2/examples/us_population_pyramid_over_time.py<gh_stars>1-10 ''' US Population Pyramid Over Time =============================== A population pyramid shows the", "population. It uses a slider widget that is bound to the year to", "age distribution over time. ''' # category: case studies import altair as alt", "time. ''' # category: case studies import altair as alt from altair.expr import", "visualize the age distribution over time. ''' # category: case studies import altair", "middle = base.encode( y=alt.X('age:O', axis=None), text=alt.Text('age:Q'), ).mark_text().properties(width=20) right = base.transform_filter( datum.gender == 'Male'" ]
[ "[ migrations.CreateModel( name='Token', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name',", "'0003_auto_20180404_1515'), ] operations = [ migrations.CreateModel( name='Token', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified',", "primary_key=True, serialize=False)), ('token', models.TextField()), ('expires', models.DateTimeField(blank=True, null=True)), ], options={ 'ordering': ('name',), 'permissions': (('view_token',", "import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20180404_1515'), ] operations", "operations = [ migrations.CreateModel( name='Token', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False,", "model_utils.fields class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20180404_1515'), ] operations = [ migrations.CreateModel(", "class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20180404_1515'), ] operations = [ migrations.CreateModel( name='Token',", "name='Token', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name', models.CharField(max_length=20, primary_key=True,", "('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name', models.CharField(max_length=20, primary_key=True, serialize=False)), ('token', models.TextField()), ('expires', models.DateTimeField(blank=True, null=True)),", "('name', models.CharField(max_length=20, primary_key=True, serialize=False)), ('token', models.TextField()), ('expires', models.DateTimeField(blank=True, null=True)), ], options={ 'ordering': ('name',),", "models.TextField()), ('expires', models.DateTimeField(blank=True, null=True)), ], options={ 'ordering': ('name',), 'permissions': (('view_token', 'Can view token'),),", "editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name', models.CharField(max_length=20, primary_key=True, serialize=False)), ('token', models.TextField()), ('expires',", "from django.db import migrations, models import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies =", "verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name', models.CharField(max_length=20, primary_key=True, serialize=False)), ('token', models.TextField()), ('expires', models.DateTimeField(blank=True,", "django.db import migrations, models import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies = [", "models.CharField(max_length=20, primary_key=True, serialize=False)), ('token', models.TextField()), ('expires', models.DateTimeField(blank=True, null=True)), ], options={ 'ordering': ('name',), 'permissions':", "dependencies = [ ('core', '0003_auto_20180404_1515'), ] operations = [ migrations.CreateModel( name='Token', fields=[ ('created',", "model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name', models.CharField(max_length=20, primary_key=True, serialize=False)), ('token', models.TextField()), ('expires', models.DateTimeField(blank=True, null=True)), ],", "models.DateTimeField(blank=True, null=True)), ], options={ 'ordering': ('name',), 'permissions': (('view_token', 'Can view token'),), }, ),", "django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20180404_1515'), ] operations =", "null=True)), ], options={ 'ordering': ('name',), 'permissions': (('view_token', 'Can view token'),), }, ), ]", "fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name', models.CharField(max_length=20, primary_key=True, serialize=False)),", "Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20180404_1515'), ] operations = [ migrations.CreateModel( name='Token', fields=[", "import model_utils.fields class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20180404_1515'), ] operations = [", "<reponame>ministryofjustice/mtp-api<gh_stars>1-10 from django.db import migrations, models import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies", "serialize=False)), ('token', models.TextField()), ('expires', models.DateTimeField(blank=True, null=True)), ], options={ 'ordering': ('name',), 'permissions': (('view_token', 'Can", "verbose_name='modified')), ('name', models.CharField(max_length=20, primary_key=True, serialize=False)), ('token', models.TextField()), ('expires', models.DateTimeField(blank=True, null=True)), ], options={ 'ordering':", "[ ('core', '0003_auto_20180404_1515'), ] operations = [ migrations.CreateModel( name='Token', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False,", "('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name', models.CharField(max_length=20, primary_key=True, serialize=False)), ('token',", "import migrations, models import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies = [ ('core',", "migrations.CreateModel( name='Token', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name', models.CharField(max_length=20,", "editable=False, verbose_name='modified')), ('name', models.CharField(max_length=20, primary_key=True, serialize=False)), ('token', models.TextField()), ('expires', models.DateTimeField(blank=True, null=True)), ], options={", "('expires', models.DateTimeField(blank=True, null=True)), ], options={ 'ordering': ('name',), 'permissions': (('view_token', 'Can view token'),), },", "= [ migrations.CreateModel( name='Token', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),", "('token', models.TextField()), ('expires', models.DateTimeField(blank=True, null=True)), ], options={ 'ordering': ('name',), 'permissions': (('view_token', 'Can view", "models import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20180404_1515'), ]", "= [ ('core', '0003_auto_20180404_1515'), ] operations = [ migrations.CreateModel( name='Token', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now,", "('core', '0003_auto_20180404_1515'), ] operations = [ migrations.CreateModel( name='Token', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),", "model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name', models.CharField(max_length=20, primary_key=True, serialize=False)), ('token', models.TextField()),", "] operations = [ migrations.CreateModel( name='Token', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now,", "migrations, models import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20180404_1515')," ]
[ "= db.Column(db.DateTime) # # def __init__(self, uuid, payload, datetime): # self.uuid = uuid", "self.uuid = uuid # self.payload = payload # self.datetime = datetime # #", "payload # self.datetime = datetime # # def __repr__(self): # return '<Data %r>'", "= db.Column(db.Integer, primary_key=True) uuid = db.Column(db.Integer) response = db.Column(db.Text) datetime = db.Column(db.DateTime) def", "= db.Column(db.Text) datetime = db.Column(db.DateTime) def __init__(self, uuid, response, datetime): self.uuid = uuid", "import db class Data(db.Model): id = db.Column(db.Integer, primary_key=True) uuid = db.Column(db.Integer) response =", "self.datetime = datetime # # def __repr__(self): # return '<Data %r>' % self.payload", "class Data(db.Model): id = db.Column(db.Integer, primary_key=True) uuid = db.Column(db.Integer) response = db.Column(db.Text) datetime", "% self.response # # class Logs(db.Model): # id = db.Column(db.Integer, primary_key=True) # uuid", "= uuid self.response = response self.datetime = datetime def __repr__(self): return '<Data %r>'", "def __repr__(self): return '<Data %r>' % self.response # # class Logs(db.Model): # id", "uuid = db.Column(db.Integer) response = db.Column(db.Text) datetime = db.Column(db.DateTime) def __init__(self, uuid, response,", "response = db.Column(db.Text) datetime = db.Column(db.DateTime) def __init__(self, uuid, response, datetime): self.uuid =", "response self.datetime = datetime def __repr__(self): return '<Data %r>' % self.response # #", "__init__(self, uuid, payload, datetime): # self.uuid = uuid # self.payload = payload #", "= db.Column(db.Text) # datetime = db.Column(db.DateTime) # # def __init__(self, uuid, payload, datetime):", "uuid = db.Column(db.Integer) # payload = db.Column(db.Text) # datetime = db.Column(db.DateTime) # #", "datetime): # self.uuid = uuid # self.payload = payload # self.datetime = datetime", "return '<Data %r>' % self.response # # class Logs(db.Model): # id = db.Column(db.Integer,", "from palm_tree import db class Data(db.Model): id = db.Column(db.Integer, primary_key=True) uuid = db.Column(db.Integer)", "db.Column(db.Text) datetime = db.Column(db.DateTime) def __init__(self, uuid, response, datetime): self.uuid = uuid self.response", "# # class Logs(db.Model): # id = db.Column(db.Integer, primary_key=True) # uuid = db.Column(db.Integer)", "uuid # self.payload = payload # self.datetime = datetime # # def __repr__(self):", "primary_key=True) uuid = db.Column(db.Integer) response = db.Column(db.Text) datetime = db.Column(db.DateTime) def __init__(self, uuid,", "db.Column(db.Integer) response = db.Column(db.Text) datetime = db.Column(db.DateTime) def __init__(self, uuid, response, datetime): self.uuid", "db.Column(db.Integer, primary_key=True) # uuid = db.Column(db.Integer) # payload = db.Column(db.Text) # datetime =", "def __init__(self, uuid, payload, datetime): # self.uuid = uuid # self.payload = payload", "# def __init__(self, uuid, payload, datetime): # self.uuid = uuid # self.payload =", "db class Data(db.Model): id = db.Column(db.Integer, primary_key=True) uuid = db.Column(db.Integer) response = db.Column(db.Text)", "response, datetime): self.uuid = uuid self.response = response self.datetime = datetime def __repr__(self):", "%r>' % self.response # # class Logs(db.Model): # id = db.Column(db.Integer, primary_key=True) #", "db.Column(db.DateTime) def __init__(self, uuid, response, datetime): self.uuid = uuid self.response = response self.datetime", "self.payload = payload # self.datetime = datetime # # def __repr__(self): # return", "datetime = db.Column(db.DateTime) # # def __init__(self, uuid, payload, datetime): # self.uuid =", "id = db.Column(db.Integer, primary_key=True) uuid = db.Column(db.Integer) response = db.Column(db.Text) datetime = db.Column(db.DateTime)", "db.Column(db.Text) # datetime = db.Column(db.DateTime) # # def __init__(self, uuid, payload, datetime): #", "uuid, payload, datetime): # self.uuid = uuid # self.payload = payload # self.datetime", "payload, datetime): # self.uuid = uuid # self.payload = payload # self.datetime =", "db.Column(db.Integer, primary_key=True) uuid = db.Column(db.Integer) response = db.Column(db.Text) datetime = db.Column(db.DateTime) def __init__(self,", "uuid self.response = response self.datetime = datetime def __repr__(self): return '<Data %r>' %", "__init__(self, uuid, response, datetime): self.uuid = uuid self.response = response self.datetime = datetime", "id = db.Column(db.Integer, primary_key=True) # uuid = db.Column(db.Integer) # payload = db.Column(db.Text) #", "self.datetime = datetime def __repr__(self): return '<Data %r>' % self.response # # class", "# class Logs(db.Model): # id = db.Column(db.Integer, primary_key=True) # uuid = db.Column(db.Integer) #", "# payload = db.Column(db.Text) # datetime = db.Column(db.DateTime) # # def __init__(self, uuid,", "class Logs(db.Model): # id = db.Column(db.Integer, primary_key=True) # uuid = db.Column(db.Integer) # payload", "# uuid = db.Column(db.Integer) # payload = db.Column(db.Text) # datetime = db.Column(db.DateTime) #", "# self.datetime = datetime # # def __repr__(self): # return '<Data %r>' %", "palm_tree import db class Data(db.Model): id = db.Column(db.Integer, primary_key=True) uuid = db.Column(db.Integer) response", "self.response = response self.datetime = datetime def __repr__(self): return '<Data %r>' % self.response", "= db.Column(db.DateTime) def __init__(self, uuid, response, datetime): self.uuid = uuid self.response = response", "Data(db.Model): id = db.Column(db.Integer, primary_key=True) uuid = db.Column(db.Integer) response = db.Column(db.Text) datetime =", "# # def __init__(self, uuid, payload, datetime): # self.uuid = uuid # self.payload", "def __init__(self, uuid, response, datetime): self.uuid = uuid self.response = response self.datetime =", "= db.Column(db.Integer) # payload = db.Column(db.Text) # datetime = db.Column(db.DateTime) # # def", "primary_key=True) # uuid = db.Column(db.Integer) # payload = db.Column(db.Text) # datetime = db.Column(db.DateTime)", "= uuid # self.payload = payload # self.datetime = datetime # # def", "datetime): self.uuid = uuid self.response = response self.datetime = datetime def __repr__(self): return", "uuid, response, datetime): self.uuid = uuid self.response = response self.datetime = datetime def", "= datetime def __repr__(self): return '<Data %r>' % self.response # # class Logs(db.Model):", "db.Column(db.DateTime) # # def __init__(self, uuid, payload, datetime): # self.uuid = uuid #", "# self.payload = payload # self.datetime = datetime # # def __repr__(self): #", "# datetime = db.Column(db.DateTime) # # def __init__(self, uuid, payload, datetime): # self.uuid", "payload = db.Column(db.Text) # datetime = db.Column(db.DateTime) # # def __init__(self, uuid, payload,", "# id = db.Column(db.Integer, primary_key=True) # uuid = db.Column(db.Integer) # payload = db.Column(db.Text)", "__repr__(self): return '<Data %r>' % self.response # # class Logs(db.Model): # id =", "# self.uuid = uuid # self.payload = payload # self.datetime = datetime #", "Logs(db.Model): # id = db.Column(db.Integer, primary_key=True) # uuid = db.Column(db.Integer) # payload =", "'<Data %r>' % self.response # # class Logs(db.Model): # id = db.Column(db.Integer, primary_key=True)", "self.response # # class Logs(db.Model): # id = db.Column(db.Integer, primary_key=True) # uuid =", "db.Column(db.Integer) # payload = db.Column(db.Text) # datetime = db.Column(db.DateTime) # # def __init__(self,", "= db.Column(db.Integer, primary_key=True) # uuid = db.Column(db.Integer) # payload = db.Column(db.Text) # datetime", "= db.Column(db.Integer) response = db.Column(db.Text) datetime = db.Column(db.DateTime) def __init__(self, uuid, response, datetime):", "datetime = db.Column(db.DateTime) def __init__(self, uuid, response, datetime): self.uuid = uuid self.response =", "self.uuid = uuid self.response = response self.datetime = datetime def __repr__(self): return '<Data", "= payload # self.datetime = datetime # # def __repr__(self): # return '<Data", "datetime def __repr__(self): return '<Data %r>' % self.response # # class Logs(db.Model): #", "= response self.datetime = datetime def __repr__(self): return '<Data %r>' % self.response #" ]
[ "= iface self.pre_iface_state = _iface_state(iface) self.iface_state = self.pre_iface_state self.post_iface_state = '' def iface_up(self):", "state returns UP, DOWN, UNKNOWN \"\"\" state = command_util('ip', 'link', 'show', iface).stdout.read() search_result", "range_start[i] < 255: yield '.'.join([str(item) for item in range_start]) range_start[i] += 1 else:", "Unless required by applicable law or agreed to in writing, software # distributed", "def __exit__(self, type, value, trace): pass class IfaceState(object): \"\"\"Context manager to control state", "manager to control state of iface when dhcp checker is running \"\"\" def", "\"\"\" state = command_util('ip', 'link', 'show', iface).stdout.read() search_result = re.search(r'.*<(?P<state>.*)>.*', state) if search_result:", ">>> next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10' \"\"\" split_address = lambda ip_address: \\ [int(item) for item in", "return properties def format_options(options): \"\"\"Util for serializing dhcp options @options = [1,2,3] >>>", "self.rollback = rollback self.retry = retry self.iface = iface self.pre_iface_state = _iface_state(iface) self.iface_state", "= retry self.iface = iface self.pre_iface_state = _iface_state(iface) self.iface_state = self.pre_iface_state self.post_iface_state =", "+= 1 def get_item_properties(item, columns): \"\"\"Get specified in columns properties, with preserved order.", "with arbitrary keys \"\"\" properties = [] for key in columns: properties.append(item.get(key, ''))", "Apache License, Version 2.0 (the \"License\"); you may # not use this file", "resp])) return wrapper class VlansContext(object): \"\"\"Contains all logic to manage vlans \"\"\" def", "the License. You may obtain # a copy of the License at #", "ans[scapy.Ether].src, ans[scapy.IP].src, dhcp_options['server_id'], ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr) return dict(zip(DHCP_OFFER_COLUMNS, results)) def single_format(func): \"\"\"Manage", "broadcast multiple duplicated results # returned. This helper filter them out @functools.wraps(func) def", "'192.168.0.1', '192.168.0.2'), 'end'] \"\"\" for option in dhcp_options: if isinstance(option, (tuple, list)): header", "may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "list)): header = option[0] if len(option[1:]) > 1: yield (header, option) else: yield", "range_end[i] and range_start[i] < 255: yield '.'.join([str(item) for item in range_start]) range_start[i] +=", "@functools.wraps(func) def workaround(*args, **kwargs): args = args[0] if isinstance(args[0], (tuple, list)) else args", "scapy DHCP_OFFER_COLUMNS = ('iface', 'mac', 'server_ip', 'server_id', 'gateway', 'dport', 'message', 'yiaddr') def command_util(*command):", "!= 'UP': command_util('ifconfig', self.iface, 'up') self.iface_state = _iface_state(self.iface) self.retry -= 1 if self.iface_state", "stdout \"\"\" return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _check_vconfig(): \"\"\"Check vconfig installed or not", "#so ans[0][1] would be response to first request return [format_answer(response[1], iface) for response", "due to network infra on broadcast multiple duplicated results # returned. This helper", "**kwargs) return (dict(t) for t in set([tuple(d.items()) for d in resp])) return wrapper", "formatter def multiproc_map(func): # multiproc map could not work with format *args @functools.wraps(func)", "( iface, ans[scapy.Ether].src, ans[scapy.IP].src, dhcp_options['server_id'], ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr) return dict(zip(DHCP_OFFER_COLUMNS, results)) def", "'mac', 'server_ip', 'server_id', 'gateway', 'dport', 'message', 'yiaddr') def command_util(*command): \"\"\"object with stderr and", "with the License. You may obtain # a copy of the License at", "@functools.wraps(func) def formatter(*args, **kwargs): iface = args[0] ans = func(*args, **kwargs) #scapy stores", "str(iface), vifaces def __exit__(self, type, value, trace): pass class IfaceState(object): \"\"\"Context manager to", "the License. import functools import re import subprocess import sys from scapy import", "provided interface exists \"\"\" return not command_util(\"ip\", \"link\", \"show\", iface).stderr.read() def filtered_ifaces(ifaces): for", "else: yield (header, option[1]) def format_answer(ans, iface): dhcp_options = dict(_dhcp_options(ans[scapy.DHCP].options)) results = (", "permissions and limitations # under the License. import functools import re import subprocess", "'.'.join([str(item) for item in range_start]) range_start[i] += 1 else: i += 1 def", "= func(*args, **kwargs) return (dict(t) for t in set([tuple(d.items()) for d in resp]))", "UNKNOWN \"\"\" state = command_util('ip', 'link', 'show', iface).stdout.read() search_result = re.search(r'.*<(?P<state>.*)>.*', state) if", "4: # 255 - end of subnet if not range_start[i] == range_end[i] and", "if len(option[1:]) > 1: yield (header, option) else: yield (header, option[1]) def format_answer(ans,", "options @options = [1,2,3] >>> format_options([1, 2, 3]) '\\x01\\x02\\x03' \"\"\" return \"\".join((chr(item) for", "duplicated results # returned. This helper filter them out @functools.wraps(func) def wrapper(*args, **kwargs):", "my best to ifup iface {0}.'.format(self.iface)) def __enter__(self): self.iface_up() return self.iface def __exit__(self,", "DHCP_OFFER_COLUMNS = ('iface', 'mac', 'server_ip', 'server_id', 'gateway', 'dport', 'message', 'yiaddr') def command_util(*command): \"\"\"object", "stderr and stdout \"\"\" return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _check_vconfig(): \"\"\"Check vconfig installed", "limitations # under the License. import functools import re import subprocess import sys", "for d in resp])) return wrapper class VlansContext(object): \"\"\"Contains all logic to manage", "class VlansContext(object): \"\"\"Contains all logic to manage vlans \"\"\" def __init__(self, config): \"\"\"Initialize", "scapy import all as scapy DHCP_OFFER_COLUMNS = ('iface', 'mac', 'server_ip', 'server_id', 'gateway', 'dport',", "use this file except in compliance with the License. You may obtain #", "raise EnvironmentError( 'Tried my best to ifup iface {0}.'.format(self.iface)) def __enter__(self): self.iface_up() return", "= _iface_state(self.iface) self.retry -= 1 if self.iface_state != 'UP': raise EnvironmentError( 'Tried my", "with format *args @functools.wraps(func) def workaround(*args, **kwargs): args = args[0] if isinstance(args[0], (tuple,", "control state of iface when dhcp checker is running \"\"\" def __init__(self, iface,", "\"\"\"Given start_range, end_range generate list of ips >>> next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10' \"\"\" split_address =", "for item in options)) def _dhcp_options(dhcp_options): \"\"\"Dhcp options returned by scapy is not", "# under the License. import functools import re import subprocess import sys from", "**kwargs) #scapy stores all sequence of requests #so ans[0][1] would be response to", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "def iface_up(self): while self.retry and self.iface_state != 'UP': command_util('ifconfig', self.iface, 'up') self.iface_state =", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "return 'UP' else: return 'DOWN' return 'UNKNOWN' def check_network_up(iface): return _iface_state(iface) == 'UP'", "iface {0} is down.'.format( iface)) else: yield iface def pick_ip(range_start, range_end): \"\"\"Given start_range,", "implied. See the # License for the specific language governing permissions and limitations", "down.'.format( iface)) else: yield iface def pick_ip(range_start, range_end): \"\"\"Given start_range, end_range generate list", "if isinstance(args[0], (tuple, list)) else args return func(*args, **kwargs) return workaround def filter_duplicated_results(func):", "(dict(t) for t in set([tuple(d.items()) for d in resp])) return wrapper class VlansContext(object):", "results = ( iface, ans[scapy.Ether].src, ans[scapy.IP].src, dhcp_options['server_id'], ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr) return dict(zip(DHCP_OFFER_COLUMNS,", "1: yield (header, option) else: yield (header, option[1]) def format_answer(ans, iface): dhcp_options =", "could not work with format *args @functools.wraps(func) def workaround(*args, **kwargs): args = args[0]", "self.iface_state = self.pre_iface_state self.post_iface_state = '' def iface_up(self): while self.retry and self.iface_state !=", "ans[scapy.BOOTP].yiaddr) return dict(zip(DHCP_OFFER_COLUMNS, results)) def single_format(func): \"\"\"Manage format of dhcp response \"\"\" @functools.wraps(func)", "you may # not use this file except in compliance with the License.", "'gateway', 'dport', 'message', 'yiaddr') def command_util(*command): \"\"\"object with stderr and stdout \"\"\" return", "func(*args, **kwargs) #scapy stores all sequence of requests #so ans[0][1] would be response", "not \"\"\" return not command_util('which', 'vconfig').stderr.read() def _iface_state(iface): \"\"\"For a given iface return", "\"\"\"For a given iface return it's state returns UP, DOWN, UNKNOWN \"\"\" state", "language governing permissions and limitations # under the License. import functools import re", "{0} is down.'.format( iface)) else: yield iface def pick_ip(range_start, range_end): \"\"\"Given start_range, end_range", "key in columns: properties.append(item.get(key, '')) return properties def format_options(options): \"\"\"Util for serializing dhcp", "while i < 4: # 255 - end of subnet if not range_start[i]", "KIND, either express or implied. See the # License for the specific language", "does not exist.'.format(iface)) else: if not check_network_up(iface): sys.stderr.write('Network for iface {0} is down.'.format(", "def __enter__(self): for iface, vlans in self.config.iteritems(): vifaces = [] for vlan in", "request return [format_answer(response[1], iface) for response in ans] return formatter def multiproc_map(func): #", "iface).stderr.read() def filtered_ifaces(ifaces): for iface in ifaces: if not check_iface_exist(iface): sys.stderr.write('Iface {0} does", "#scapy stores all sequence of requests #so ans[0][1] would be response to first", "option[0] if len(option[1:]) > 1: yield (header, option) else: yield (header, option[1]) def", "file except in compliance with the License. You may obtain # a copy", "yield (header, option) else: yield (header, option[1]) def format_answer(ans, iface): dhcp_options = dict(_dhcp_options(ans[scapy.DHCP].options))", "\"\"\" return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _check_vconfig(): \"\"\"Check vconfig installed or not \"\"\"", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "def pick_ip(range_start, range_end): \"\"\"Given start_range, end_range generate list of ips >>> next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10'", "\"\"\"Util for serializing dhcp options @options = [1,2,3] >>> format_options([1, 2, 3]) '\\x01\\x02\\x03'", "returns UP, DOWN, UNKNOWN \"\"\" state = command_util('ip', 'link', 'show', iface).stdout.read() search_result =", "\"show\", iface).stderr.read() def filtered_ifaces(ifaces): for iface in ifaces: if not check_iface_exist(iface): sys.stderr.write('Iface {0}", "'server_id', 'gateway', 'dport', 'message', 'yiaddr') def command_util(*command): \"\"\"object with stderr and stdout \"\"\"", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "'\\x01\\x02\\x03' \"\"\" return \"\".join((chr(item) for item in options)) def _dhcp_options(dhcp_options): \"\"\"Dhcp options returned", "filter them out @functools.wraps(func) def wrapper(*args, **kwargs): resp = func(*args, **kwargs) return (dict(t)", "1 if self.iface_state != 'UP': raise EnvironmentError( 'Tried my best to ifup iface", "not command_util('which', 'vconfig').stderr.read() def _iface_state(iface): \"\"\"For a given iface return it's state returns", "of subnet if not range_start[i] == range_end[i] and range_start[i] < 255: yield '.'.join([str(item)", "return _iface_state(iface) == 'UP' def check_iface_exist(iface): \"\"\"Check provided interface exists \"\"\" return not", "else args return func(*args, **kwargs) return workaround def filter_duplicated_results(func): # due to network", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "dict :param columns: list with arbitrary keys \"\"\" properties = [] for key", "not command_util(\"ip\", \"link\", \"show\", iface).stderr.read() def filtered_ifaces(ifaces): for iface in ifaces: if not", "'UP' else: return 'DOWN' return 'UNKNOWN' def check_network_up(iface): return _iface_state(iface) == 'UP' def", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "command_util('ip', 'link', 'show', iface).stdout.read() search_result = re.search(r'.*<(?P<state>.*)>.*', state) if search_result: state_list = search_result.groupdict().get('state',", "isinstance(option, (tuple, list)): header = option[0] if len(option[1:]) > 1: yield (header, option)", "results)) def single_format(func): \"\"\"Manage format of dhcp response \"\"\" @functools.wraps(func) def formatter(*args, **kwargs):", "def multiproc_map(func): # multiproc map could not work with format *args @functools.wraps(func) def", "self.pre_iface_state self.post_iface_state = '' def iface_up(self): while self.retry and self.iface_state != 'UP': command_util('ifconfig',", "and range_start[i] < 255: yield '.'.join([str(item) for item in range_start]) range_start[i] += 1", "the # License for the specific language governing permissions and limitations # under", "'UP': raise EnvironmentError( 'Tried my best to ifup iface {0}.'.format(self.iface)) def __enter__(self): self.iface_up()", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "import subprocess import sys from scapy import all as scapy DHCP_OFFER_COLUMNS = ('iface',", "[1,2,3] >>> format_options([1, 2, 3]) '\\x01\\x02\\x03' \"\"\" return \"\".join((chr(item) for item in options))", "> 1: yield (header, option) else: yield (header, option[1]) def format_answer(ans, iface): dhcp_options", "item: dict :param columns: list with arbitrary keys \"\"\" properties = [] for", "in state_list: return 'UP' else: return 'DOWN' return 'UNKNOWN' def check_network_up(iface): return _iface_state(iface)", "ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr) return dict(zip(DHCP_OFFER_COLUMNS, results)) def single_format(func): \"\"\"Manage format of dhcp response", "This helper filter them out @functools.wraps(func) def wrapper(*args, **kwargs): resp = func(*args, **kwargs)", "You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "filter_duplicated_results(func): # due to network infra on broadcast multiple duplicated results # returned.", "\"\"\"Check provided interface exists \"\"\" return not command_util(\"ip\", \"link\", \"show\", iface).stderr.read() def filtered_ifaces(ifaces):", "vconfig installed or not \"\"\" return not command_util('which', 'vconfig').stderr.read() def _iface_state(iface): \"\"\"For a", "2, 3]) '\\x01\\x02\\x03' \"\"\" return \"\".join((chr(item) for item in options)) def _dhcp_options(dhcp_options): \"\"\"Dhcp", "required by applicable law or agreed to in writing, software # distributed under", "def formatter(*args, **kwargs): iface = args[0] ans = func(*args, **kwargs) #scapy stores all", "255 - end of subnet if not range_start[i] == range_end[i] and range_start[i] <", "applicable law or agreed to in writing, software # distributed under the License", "self.iface def __exit__(self, exc_type, exc_val, exc_tb): if self.pre_iface_state != 'UP' and self.rollback: command_util('ifconfig',", "while self.retry and self.iface_state != 'UP': command_util('ifconfig', self.iface, 'up') self.iface_state = _iface_state(self.iface) self.retry", "if 'UP' in state_list: return 'UP' else: return 'DOWN' return 'UNKNOWN' def check_network_up(iface):", "sys from scapy import all as scapy DHCP_OFFER_COLUMNS = ('iface', 'mac', 'server_ip', 'server_id',", "'UNKNOWN' def check_network_up(iface): return _iface_state(iface) == 'UP' def check_iface_exist(iface): \"\"\"Check provided interface exists", "'message', 'yiaddr') def command_util(*command): \"\"\"object with stderr and stdout \"\"\" return subprocess.Popen(command, stdout=subprocess.PIPE,", "\"\"\" return not command_util(\"ip\", \"link\", \"show\", iface).stderr.read() def filtered_ifaces(ifaces): for iface in ifaces:", "'up') self.iface_state = _iface_state(self.iface) self.retry -= 1 if self.iface_state != 'UP': raise EnvironmentError(", "self.pre_iface_state = _iface_state(iface) self.iface_state = self.pre_iface_state self.post_iface_state = '' def iface_up(self): while self.retry", "in compliance with the License. You may obtain # a copy of the", "or agreed to in writing, software # distributed under the License is distributed", "vifaces.append('{0}.{1}'.format(iface, vlan)) yield str(iface), vifaces def __exit__(self, type, value, trace): pass class IfaceState(object):", "and self.iface_state != 'UP': command_util('ifconfig', self.iface, 'up') self.iface_state = _iface_state(self.iface) self.retry -= 1", "list with arbitrary keys \"\"\" properties = [] for key in columns: properties.append(item.get(key,", "end of subnet if not range_start[i] == range_end[i] and range_start[i] < 255: yield", "returned. This helper filter them out @functools.wraps(func) def wrapper(*args, **kwargs): resp = func(*args,", "in columns properties, with preserved order. Required for correct cli table generation :param", "returned by scapy is not in usable format [('message-type', 2), ('server_id', '192.168.0.5'), ('name_server',", "@options = [1,2,3] >>> format_options([1, 2, 3]) '\\x01\\x02\\x03' \"\"\" return \"\".join((chr(item) for item", "< 255: yield '.'.join([str(item) for item in range_start]) range_start[i] += 1 else: i", "longer that 4 items while i < 4: # 255 - end of", "255: yield '.'.join([str(item) for item in range_start]) range_start[i] += 1 else: i +=", "= option[0] if len(option[1:]) > 1: yield (header, option) else: yield (header, option[1])", "scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr) return dict(zip(DHCP_OFFER_COLUMNS, results)) def single_format(func): \"\"\"Manage format of dhcp response \"\"\"", "return formatter def multiproc_map(func): # multiproc map could not work with format *args", "them out @functools.wraps(func) def wrapper(*args, **kwargs): resp = func(*args, **kwargs) return (dict(t) for", "vlan in vlans: if vlan > 0: vifaces.append('{0}.{1}'.format(iface, vlan)) yield str(iface), vifaces def", "iface, vlans in self.config.iteritems(): vifaces = [] for vlan in vlans: if vlan", "response \"\"\" @functools.wraps(func) def formatter(*args, **kwargs): iface = args[0] ans = func(*args, **kwargs)", ":param item: dict :param columns: list with arbitrary keys \"\"\" properties = []", "# multiproc map could not work with format *args @functools.wraps(func) def workaround(*args, **kwargs):", "*args @functools.wraps(func) def workaround(*args, **kwargs): args = args[0] if isinstance(args[0], (tuple, list)) else", "Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the \"License\");", "self.config = config def __enter__(self): for iface, vlans in self.config.iteritems(): vifaces = []", "License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "writing, software # distributed under the License is distributed on an \"AS IS\"", "of ips >>> next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10' \"\"\" split_address = lambda ip_address: \\ [int(item) for", "in usable format [('message-type', 2), ('server_id', '192.168.0.5'), ('name_server', '192.168.0.1', '192.168.0.2'), 'end'] \"\"\" for", "def _iface_state(iface): \"\"\"For a given iface return it's state returns UP, DOWN, UNKNOWN", "manage vlans \"\"\" def __init__(self, config): \"\"\"Initialize VlansContext @config - list or tuple", "return not command_util('which', 'vconfig').stderr.read() def _iface_state(iface): \"\"\"For a given iface return it's state", "stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _check_vconfig(): \"\"\"Check vconfig installed or not \"\"\" return not command_util('which',", "dhcp response \"\"\" @functools.wraps(func) def formatter(*args, **kwargs): iface = args[0] ans = func(*args,", "or tuple of (iface, vlan) pairs \"\"\" self.config = config def __enter__(self): for", "self.retry and self.iface_state != 'UP': command_util('ifconfig', self.iface, 'up') self.iface_state = _iface_state(self.iface) self.retry -=", ":param columns: list with arbitrary keys \"\"\" properties = [] for key in", "in columns: properties.append(item.get(key, '')) return properties def format_options(options): \"\"\"Util for serializing dhcp options", "generation :param item: dict :param columns: list with arbitrary keys \"\"\" properties =", "'' def iface_up(self): while self.retry and self.iface_state != 'UP': command_util('ifconfig', self.iface, 'up') self.iface_state", "exc_tb): if self.pre_iface_state != 'UP' and self.rollback: command_util('ifconfig', self.iface, 'down') self.post_iface_state = _iface_state(self.iface)", "range_start[i] += 1 else: i += 1 def get_item_properties(item, columns): \"\"\"Get specified in", "list)) else args return func(*args, **kwargs) return workaround def filter_duplicated_results(func): # due to", "= split_address(range_start) range_end = split_address(range_end) i = 0 # ipv4 subnet cant be", "= 0 # ipv4 subnet cant be longer that 4 items while i", "infra on broadcast multiple duplicated results # returned. This helper filter them out", "by scapy is not in usable format [('message-type', 2), ('server_id', '192.168.0.5'), ('name_server', '192.168.0.1',", "columns): \"\"\"Get specified in columns properties, with preserved order. Required for correct cli", "# due to network infra on broadcast multiple duplicated results # returned. This", "dhcp checker is running \"\"\" def __init__(self, iface, rollback=True, retry=3): self.rollback = rollback", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "def workaround(*args, **kwargs): args = args[0] if isinstance(args[0], (tuple, list)) else args return", "> 0: vifaces.append('{0}.{1}'.format(iface, vlan)) yield str(iface), vifaces def __exit__(self, type, value, trace): pass", "next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10' \"\"\" split_address = lambda ip_address: \\ [int(item) for item in ip_address.split('.')]", "-= 1 if self.iface_state != 'UP': raise EnvironmentError( 'Tried my best to ifup", "__exit__(self, exc_type, exc_val, exc_tb): if self.pre_iface_state != 'UP' and self.rollback: command_util('ifconfig', self.iface, 'down')", "in ans] return formatter def multiproc_map(func): # multiproc map could not work with", "self.config.iteritems(): vifaces = [] for vlan in vlans: if vlan > 0: vifaces.append('{0}.{1}'.format(iface,", "Licensed under the Apache License, Version 2.0 (the \"License\"); you may # not", "columns: list with arbitrary keys \"\"\" properties = [] for key in columns:", "def __init__(self, iface, rollback=True, retry=3): self.rollback = rollback self.retry = retry self.iface =", "\"\"\" for option in dhcp_options: if isinstance(option, (tuple, list)): header = option[0] if", "for item in ip_address.split('.')] range_start = split_address(range_start) range_end = split_address(range_end) i = 0", "range_end = split_address(range_end) i = 0 # ipv4 subnet cant be longer that", "for option in dhcp_options: if isinstance(option, (tuple, list)): header = option[0] if len(option[1:])", "2.0 (the \"License\"); you may # not use this file except in compliance", "be response to first request return [format_answer(response[1], iface) for response in ans] return", "def get_item_properties(item, columns): \"\"\"Get specified in columns properties, with preserved order. Required for", "!= 'UP': raise EnvironmentError( 'Tried my best to ifup iface {0}.'.format(self.iface)) def __enter__(self):", "return self.iface def __exit__(self, exc_type, exc_val, exc_tb): if self.pre_iface_state != 'UP' and self.rollback:", "all as scapy DHCP_OFFER_COLUMNS = ('iface', 'mac', 'server_ip', 'server_id', 'gateway', 'dport', 'message', 'yiaddr')", "all logic to manage vlans \"\"\" def __init__(self, config): \"\"\"Initialize VlansContext @config -", "not exist.'.format(iface)) else: if not check_network_up(iface): sys.stderr.write('Network for iface {0} is down.'.format( iface))", "# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT", "(iface, vlan) pairs \"\"\" self.config = config def __enter__(self): for iface, vlans in", "DOWN, UNKNOWN \"\"\" state = command_util('ip', 'link', 'show', iface).stdout.read() search_result = re.search(r'.*<(?P<state>.*)>.*', state)", "re.search(r'.*<(?P<state>.*)>.*', state) if search_result: state_list = search_result.groupdict().get('state', []) if 'UP' in state_list: return", "('name_server', '192.168.0.1', '192.168.0.2'), 'end'] \"\"\" for option in dhcp_options: if isinstance(option, (tuple, list)):", "args[0] ans = func(*args, **kwargs) #scapy stores all sequence of requests #so ans[0][1]", "License, Version 2.0 (the \"License\"); you may # not use this file except", "wrapper class VlansContext(object): \"\"\"Contains all logic to manage vlans \"\"\" def __init__(self, config):", "[int(item) for item in ip_address.split('.')] range_start = split_address(range_start) range_end = split_address(range_end) i =", "interface exists \"\"\" return not command_util(\"ip\", \"link\", \"show\", iface).stderr.read() def filtered_ifaces(ifaces): for iface", "# ipv4 subnet cant be longer that 4 items while i < 4:", "correct cli table generation :param item: dict :param columns: list with arbitrary keys", "License. import functools import re import subprocess import sys from scapy import all", "ans] return formatter def multiproc_map(func): # multiproc map could not work with format", "work with format *args @functools.wraps(func) def workaround(*args, **kwargs): args = args[0] if isinstance(args[0],", "map could not work with format *args @functools.wraps(func) def workaround(*args, **kwargs): args =", "ans[0][1] would be response to first request return [format_answer(response[1], iface) for response in", "**kwargs): iface = args[0] ans = func(*args, **kwargs) #scapy stores all sequence of", "**kwargs): args = args[0] if isinstance(args[0], (tuple, list)) else args return func(*args, **kwargs)", "# returned. This helper filter them out @functools.wraps(func) def wrapper(*args, **kwargs): resp =", "iface).stdout.read() search_result = re.search(r'.*<(?P<state>.*)>.*', state) if search_result: state_list = search_result.groupdict().get('state', []) if 'UP'", "ifaces: if not check_iface_exist(iface): sys.stderr.write('Iface {0} does not exist.'.format(iface)) else: if not check_network_up(iface):", "set([tuple(d.items()) for d in resp])) return wrapper class VlansContext(object): \"\"\"Contains all logic to", "return (dict(t) for t in set([tuple(d.items()) for d in resp])) return wrapper class", "iface return it's state returns UP, DOWN, UNKNOWN \"\"\" state = command_util('ip', 'link',", "\"\"\"Manage format of dhcp response \"\"\" @functools.wraps(func) def formatter(*args, **kwargs): iface = args[0]", "= rollback self.retry = retry self.iface = iface self.pre_iface_state = _iface_state(iface) self.iface_state =", "installed or not \"\"\" return not command_util('which', 'vconfig').stderr.read() def _iface_state(iface): \"\"\"For a given", "table generation :param item: dict :param columns: list with arbitrary keys \"\"\" properties", "filtered_ifaces(ifaces): for iface in ifaces: if not check_iface_exist(iface): sys.stderr.write('Iface {0} does not exist.'.format(iface))", "def single_format(func): \"\"\"Manage format of dhcp response \"\"\" @functools.wraps(func) def formatter(*args, **kwargs): iface", "**kwargs) return workaround def filter_duplicated_results(func): # due to network infra on broadcast multiple", "config def __enter__(self): for iface, vlans in self.config.iteritems(): vifaces = [] for vlan", "agreed to in writing, software # distributed under the License is distributed on", "yield str(iface), vifaces def __exit__(self, type, value, trace): pass class IfaceState(object): \"\"\"Context manager", "'Tried my best to ifup iface {0}.'.format(self.iface)) def __enter__(self): self.iface_up() return self.iface def", "func(*args, **kwargs) return (dict(t) for t in set([tuple(d.items()) for d in resp])) return", "_iface_state(iface) self.iface_state = self.pre_iface_state self.post_iface_state = '' def iface_up(self): while self.retry and self.iface_state", "cli table generation :param item: dict :param columns: list with arbitrary keys \"\"\"", "('server_id', '192.168.0.5'), ('name_server', '192.168.0.1', '192.168.0.2'), 'end'] \"\"\" for option in dhcp_options: if isinstance(option,", "get_item_properties(item, columns): \"\"\"Get specified in columns properties, with preserved order. Required for correct", "args[0] if isinstance(args[0], (tuple, list)) else args return func(*args, **kwargs) return workaround def", "option in dhcp_options: if isinstance(option, (tuple, list)): header = option[0] if len(option[1:]) >", "\"\"\"Contains all logic to manage vlans \"\"\" def __init__(self, config): \"\"\"Initialize VlansContext @config", "sys.stderr.write('Iface {0} does not exist.'.format(iface)) else: if not check_network_up(iface): sys.stderr.write('Network for iface {0}", "item in options)) def _dhcp_options(dhcp_options): \"\"\"Dhcp options returned by scapy is not in", "\"\"\" self.config = config def __enter__(self): for iface, vlans in self.config.iteritems(): vifaces =", "iface when dhcp checker is running \"\"\" def __init__(self, iface, rollback=True, retry=3): self.rollback", "for item in range_start]) range_start[i] += 1 else: i += 1 def get_item_properties(item,", "iface, rollback=True, retry=3): self.rollback = rollback self.retry = retry self.iface = iface self.pre_iface_state", "# Unless required by applicable law or agreed to in writing, software #", "check_iface_exist(iface): sys.stderr.write('Iface {0} does not exist.'.format(iface)) else: if not check_network_up(iface): sys.stderr.write('Network for iface", "('iface', 'mac', 'server_ip', 'server_id', 'gateway', 'dport', 'message', 'yiaddr') def command_util(*command): \"\"\"object with stderr", "Copyright 2013 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0", "by applicable law or agreed to in writing, software # distributed under the", "resp = func(*args, **kwargs) return (dict(t) for t in set([tuple(d.items()) for d in", "under the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "'yiaddr') def command_util(*command): \"\"\"object with stderr and stdout \"\"\" return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)", "len(option[1:]) > 1: yield (header, option) else: yield (header, option[1]) def format_answer(ans, iface):", "dhcp_options['server_id'], ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr) return dict(zip(DHCP_OFFER_COLUMNS, results)) def single_format(func): \"\"\"Manage format of", "sys.stderr.write('Network for iface {0} is down.'.format( iface)) else: yield iface def pick_ip(range_start, range_end):", "rollback=True, retry=3): self.rollback = rollback self.retry = retry self.iface = iface self.pre_iface_state =", "'end'] \"\"\" for option in dhcp_options: if isinstance(option, (tuple, list)): header = option[0]", "\"\"\" return not command_util('which', 'vconfig').stderr.read() def _iface_state(iface): \"\"\"For a given iface return it's", "UP, DOWN, UNKNOWN \"\"\" state = command_util('ip', 'link', 'show', iface).stdout.read() search_result = re.search(r'.*<(?P<state>.*)>.*',", "VlansContext(object): \"\"\"Contains all logic to manage vlans \"\"\" def __init__(self, config): \"\"\"Initialize VlansContext", "exc_type, exc_val, exc_tb): if self.pre_iface_state != 'UP' and self.rollback: command_util('ifconfig', self.iface, 'down') self.post_iface_state", "return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _check_vconfig(): \"\"\"Check vconfig installed or not \"\"\" return", "range_start[i] == range_end[i] and range_start[i] < 255: yield '.'.join([str(item) for item in range_start])", "ifup iface {0}.'.format(self.iface)) def __enter__(self): self.iface_up() return self.iface def __exit__(self, exc_type, exc_val, exc_tb):", "= [] for key in columns: properties.append(item.get(key, '')) return properties def format_options(options): \"\"\"Util", "keys \"\"\" properties = [] for key in columns: properties.append(item.get(key, '')) return properties", "import functools import re import subprocess import sys from scapy import all as", "# # Licensed under the Apache License, Version 2.0 (the \"License\"); you may", "iface {0}.'.format(self.iface)) def __enter__(self): self.iface_up() return self.iface def __exit__(self, exc_type, exc_val, exc_tb): if", "'link', 'show', iface).stdout.read() search_result = re.search(r'.*<(?P<state>.*)>.*', state) if search_result: state_list = search_result.groupdict().get('state', [])", "i < 4: # 255 - end of subnet if not range_start[i] ==", "except in compliance with the License. You may obtain # a copy of", "if isinstance(option, (tuple, list)): header = option[0] if len(option[1:]) > 1: yield (header,", "= ('iface', 'mac', 'server_ip', 'server_id', 'gateway', 'dport', 'message', 'yiaddr') def command_util(*command): \"\"\"object with", "'dport', 'message', 'yiaddr') def command_util(*command): \"\"\"object with stderr and stdout \"\"\" return subprocess.Popen(command,", "\"\"\" return \"\".join((chr(item) for item in options)) def _dhcp_options(dhcp_options): \"\"\"Dhcp options returned by", "yield (header, option[1]) def format_answer(ans, iface): dhcp_options = dict(_dhcp_options(ans[scapy.DHCP].options)) results = ( iface,", "_check_vconfig(): \"\"\"Check vconfig installed or not \"\"\" return not command_util('which', 'vconfig').stderr.read() def _iface_state(iface):", "to in writing, software # distributed under the License is distributed on an", "serializing dhcp options @options = [1,2,3] >>> format_options([1, 2, 3]) '\\x01\\x02\\x03' \"\"\" return", "= _iface_state(iface) self.iface_state = self.pre_iface_state self.post_iface_state = '' def iface_up(self): while self.retry and", "vlan)) yield str(iface), vifaces def __exit__(self, type, value, trace): pass class IfaceState(object): \"\"\"Context", "if search_result: state_list = search_result.groupdict().get('state', []) if 'UP' in state_list: return 'UP' else:", "else: i += 1 def get_item_properties(item, columns): \"\"\"Get specified in columns properties, with", "{0} does not exist.'.format(iface)) else: if not check_network_up(iface): sys.stderr.write('Network for iface {0} is", "vifaces = [] for vlan in vlans: if vlan > 0: vifaces.append('{0}.{1}'.format(iface, vlan))", "subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _check_vconfig(): \"\"\"Check vconfig installed or not \"\"\" return not", "command_util(*command): \"\"\"object with stderr and stdout \"\"\" return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _check_vconfig():", "split_address(range_end) i = 0 # ipv4 subnet cant be longer that 4 items", "format_options([1, 2, 3]) '\\x01\\x02\\x03' \"\"\" return \"\".join((chr(item) for item in options)) def _dhcp_options(dhcp_options):", "4 items while i < 4: # 255 - end of subnet if", "self.iface_up() return self.iface def __exit__(self, exc_type, exc_val, exc_tb): if self.pre_iface_state != 'UP' and", "to first request return [format_answer(response[1], iface) for response in ans] return formatter def", "distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT #", "1 else: i += 1 def get_item_properties(item, columns): \"\"\"Get specified in columns properties,", "(header, option[1]) def format_answer(ans, iface): dhcp_options = dict(_dhcp_options(ans[scapy.DHCP].options)) results = ( iface, ans[scapy.Ether].src,", "def filter_duplicated_results(func): # due to network infra on broadcast multiple duplicated results #", "# not use this file except in compliance with the License. You may", "to manage vlans \"\"\" def __init__(self, config): \"\"\"Initialize VlansContext @config - list or", "'')) return properties def format_options(options): \"\"\"Util for serializing dhcp options @options = [1,2,3]", "out @functools.wraps(func) def wrapper(*args, **kwargs): resp = func(*args, **kwargs) return (dict(t) for t", "columns: properties.append(item.get(key, '')) return properties def format_options(options): \"\"\"Util for serializing dhcp options @options", "# License for the specific language governing permissions and limitations # under the", "results # returned. This helper filter them out @functools.wraps(func) def wrapper(*args, **kwargs): resp", "config): \"\"\"Initialize VlansContext @config - list or tuple of (iface, vlan) pairs \"\"\"", "return workaround def filter_duplicated_results(func): # due to network infra on broadcast multiple duplicated", "i += 1 def get_item_properties(item, columns): \"\"\"Get specified in columns properties, with preserved", "IfaceState(object): \"\"\"Context manager to control state of iface when dhcp checker is running", "= search_result.groupdict().get('state', []) if 'UP' in state_list: return 'UP' else: return 'DOWN' return", "vlan > 0: vifaces.append('{0}.{1}'.format(iface, vlan)) yield str(iface), vifaces def __exit__(self, type, value, trace):", "pick_ip(range_start, range_end): \"\"\"Given start_range, end_range generate list of ips >>> next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10' \"\"\"", "or not \"\"\" return not command_util('which', 'vconfig').stderr.read() def _iface_state(iface): \"\"\"For a given iface", "[('message-type', 2), ('server_id', '192.168.0.5'), ('name_server', '192.168.0.1', '192.168.0.2'), 'end'] \"\"\" for option in dhcp_options:", "args return func(*args, **kwargs) return workaround def filter_duplicated_results(func): # due to network infra", "Inc. # # Licensed under the Apache License, Version 2.0 (the \"License\"); you", "== 'UP' def check_iface_exist(iface): \"\"\"Check provided interface exists \"\"\" return not command_util(\"ip\", \"link\",", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "in vlans: if vlan > 0: vifaces.append('{0}.{1}'.format(iface, vlan)) yield str(iface), vifaces def __exit__(self,", "in writing, software # distributed under the License is distributed on an \"AS", "'UP': command_util('ifconfig', self.iface, 'up') self.iface_state = _iface_state(self.iface) self.retry -= 1 if self.iface_state !=", "Version 2.0 (the \"License\"); you may # not use this file except in", "multiproc_map(func): # multiproc map could not work with format *args @functools.wraps(func) def workaround(*args,", "on broadcast multiple duplicated results # returned. This helper filter them out @functools.wraps(func)", "iface): dhcp_options = dict(_dhcp_options(ans[scapy.DHCP].options)) results = ( iface, ans[scapy.Ether].src, ans[scapy.IP].src, dhcp_options['server_id'], ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport,", "'vconfig').stderr.read() def _iface_state(iface): \"\"\"For a given iface return it's state returns UP, DOWN,", "(tuple, list)): header = option[0] if len(option[1:]) > 1: yield (header, option) else:", "_iface_state(iface): \"\"\"For a given iface return it's state returns UP, DOWN, UNKNOWN \"\"\"", "def __init__(self, config): \"\"\"Initialize VlansContext @config - list or tuple of (iface, vlan)", "scapy is not in usable format [('message-type', 2), ('server_id', '192.168.0.5'), ('name_server', '192.168.0.1', '192.168.0.2'),", "of dhcp response \"\"\" @functools.wraps(func) def formatter(*args, **kwargs): iface = args[0] ans =", "logic to manage vlans \"\"\" def __init__(self, config): \"\"\"Initialize VlansContext @config - list", "# 255 - end of subnet if not range_start[i] == range_end[i] and range_start[i]", "rollback self.retry = retry self.iface = iface self.pre_iface_state = _iface_state(iface) self.iface_state = self.pre_iface_state", "\"License\"); you may # not use this file except in compliance with the", "'DOWN' return 'UNKNOWN' def check_network_up(iface): return _iface_state(iface) == 'UP' def check_iface_exist(iface): \"\"\"Check provided", "single_format(func): \"\"\"Manage format of dhcp response \"\"\" @functools.wraps(func) def formatter(*args, **kwargs): iface =", "not work with format *args @functools.wraps(func) def workaround(*args, **kwargs): args = args[0] if", "dhcp_options = dict(_dhcp_options(ans[scapy.DHCP].options)) results = ( iface, ans[scapy.Ether].src, ans[scapy.IP].src, dhcp_options['server_id'], ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']],", "else: return 'DOWN' return 'UNKNOWN' def check_network_up(iface): return _iface_state(iface) == 'UP' def check_iface_exist(iface):", "in range_start]) range_start[i] += 1 else: i += 1 def get_item_properties(item, columns): \"\"\"Get", "for vlan in vlans: if vlan > 0: vifaces.append('{0}.{1}'.format(iface, vlan)) yield str(iface), vifaces", "(tuple, list)) else args return func(*args, **kwargs) return workaround def filter_duplicated_results(func): # due", "the Apache License, Version 2.0 (the \"License\"); you may # not use this", "dict(_dhcp_options(ans[scapy.DHCP].options)) results = ( iface, ans[scapy.Ether].src, ans[scapy.IP].src, dhcp_options['server_id'], ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr) return", "search_result.groupdict().get('state', []) if 'UP' in state_list: return 'UP' else: return 'DOWN' return 'UNKNOWN'", "format of dhcp response \"\"\" @functools.wraps(func) def formatter(*args, **kwargs): iface = args[0] ans", "\"\"\" @functools.wraps(func) def formatter(*args, **kwargs): iface = args[0] ans = func(*args, **kwargs) #scapy", "format *args @functools.wraps(func) def workaround(*args, **kwargs): args = args[0] if isinstance(args[0], (tuple, list))", "= [1,2,3] >>> format_options([1, 2, 3]) '\\x01\\x02\\x03' \"\"\" return \"\".join((chr(item) for item in", "formatter(*args, **kwargs): iface = args[0] ans = func(*args, **kwargs) #scapy stores all sequence", "not use this file except in compliance with the License. You may obtain", "args = args[0] if isinstance(args[0], (tuple, list)) else args return func(*args, **kwargs) return", "_dhcp_options(dhcp_options): \"\"\"Dhcp options returned by scapy is not in usable format [('message-type', 2),", "wrapper(*args, **kwargs): resp = func(*args, **kwargs) return (dict(t) for t in set([tuple(d.items()) for", "EnvironmentError( 'Tried my best to ifup iface {0}.'.format(self.iface)) def __enter__(self): self.iface_up() return self.iface", "[] for key in columns: properties.append(item.get(key, '')) return properties def format_options(options): \"\"\"Util for", "for response in ans] return formatter def multiproc_map(func): # multiproc map could not", "= args[0] if isinstance(args[0], (tuple, list)) else args return func(*args, **kwargs) return workaround", "License for the specific language governing permissions and limitations # under the License.", "if not check_iface_exist(iface): sys.stderr.write('Iface {0} does not exist.'.format(iface)) else: if not check_network_up(iface): sys.stderr.write('Network", "is down.'.format( iface)) else: yield iface def pick_ip(range_start, range_end): \"\"\"Given start_range, end_range generate", "yield iface def pick_ip(range_start, range_end): \"\"\"Given start_range, end_range generate list of ips >>>", "return func(*args, **kwargs) return workaround def filter_duplicated_results(func): # due to network infra on", "func(*args, **kwargs) return workaround def filter_duplicated_results(func): # due to network infra on broadcast", "list or tuple of (iface, vlan) pairs \"\"\" self.config = config def __enter__(self):", "class IfaceState(object): \"\"\"Context manager to control state of iface when dhcp checker is", "\"\"\" def __init__(self, iface, rollback=True, retry=3): self.rollback = rollback self.retry = retry self.iface", "__enter__(self): for iface, vlans in self.config.iteritems(): vifaces = [] for vlan in vlans:", "3]) '\\x01\\x02\\x03' \"\"\" return \"\".join((chr(item) for item in options)) def _dhcp_options(dhcp_options): \"\"\"Dhcp options", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the #", "def filtered_ifaces(ifaces): for iface in ifaces: if not check_iface_exist(iface): sys.stderr.write('Iface {0} does not", "return not command_util(\"ip\", \"link\", \"show\", iface).stderr.read() def filtered_ifaces(ifaces): for iface in ifaces: if", "as scapy DHCP_OFFER_COLUMNS = ('iface', 'mac', 'server_ip', 'server_id', 'gateway', 'dport', 'message', 'yiaddr') def", "= [] for vlan in vlans: if vlan > 0: vifaces.append('{0}.{1}'.format(iface, vlan)) yield", "yield '.'.join([str(item) for item in range_start]) range_start[i] += 1 else: i += 1", "= args[0] ans = func(*args, **kwargs) #scapy stores all sequence of requests #so", "state = command_util('ip', 'link', 'show', iface).stdout.read() search_result = re.search(r'.*<(?P<state>.*)>.*', state) if search_result: state_list", "OF ANY KIND, either express or implied. See the # License for the", "first request return [format_answer(response[1], iface) for response in ans] return formatter def multiproc_map(func):", "for serializing dhcp options @options = [1,2,3] >>> format_options([1, 2, 3]) '\\x01\\x02\\x03' \"\"\"", "iface self.pre_iface_state = _iface_state(iface) self.iface_state = self.pre_iface_state self.post_iface_state = '' def iface_up(self): while", "def __exit__(self, exc_type, exc_val, exc_tb): if self.pre_iface_state != 'UP' and self.rollback: command_util('ifconfig', self.iface,", "\"\"\" split_address = lambda ip_address: \\ [int(item) for item in ip_address.split('.')] range_start =", "start_range, end_range generate list of ips >>> next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10' \"\"\" split_address = lambda", "check_network_up(iface): return _iface_state(iface) == 'UP' def check_iface_exist(iface): \"\"\"Check provided interface exists \"\"\" return", "order. Required for correct cli table generation :param item: dict :param columns: list", "format_options(options): \"\"\"Util for serializing dhcp options @options = [1,2,3] >>> format_options([1, 2, 3])", "that 4 items while i < 4: # 255 - end of subnet", "return it's state returns UP, DOWN, UNKNOWN \"\"\" state = command_util('ip', 'link', 'show',", "ip_address.split('.')] range_start = split_address(range_start) range_end = split_address(range_end) i = 0 # ipv4 subnet", "= lambda ip_address: \\ [int(item) for item in ip_address.split('.')] range_start = split_address(range_start) range_end", "specific language governing permissions and limitations # under the License. import functools import", "search_result: state_list = search_result.groupdict().get('state', []) if 'UP' in state_list: return 'UP' else: return", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the", "items while i < 4: # 255 - end of subnet if not", "generate list of ips >>> next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10' \"\"\" split_address = lambda ip_address: \\", "pass class IfaceState(object): \"\"\"Context manager to control state of iface when dhcp checker", "exist.'.format(iface)) else: if not check_network_up(iface): sys.stderr.write('Network for iface {0} is down.'.format( iface)) else:", "workaround(*args, **kwargs): args = args[0] if isinstance(args[0], (tuple, list)) else args return func(*args,", "pairs \"\"\" self.config = config def __enter__(self): for iface, vlans in self.config.iteritems(): vifaces", "item in range_start]) range_start[i] += 1 else: i += 1 def get_item_properties(item, columns):", "in set([tuple(d.items()) for d in resp])) return wrapper class VlansContext(object): \"\"\"Contains all logic", "(the \"License\"); you may # not use this file except in compliance with", "command_util('ifconfig', self.iface, 'up') self.iface_state = _iface_state(self.iface) self.retry -= 1 if self.iface_state != 'UP':", "from scapy import all as scapy DHCP_OFFER_COLUMNS = ('iface', 'mac', 'server_ip', 'server_id', 'gateway',", "# # Unless required by applicable law or agreed to in writing, software", "__exit__(self, type, value, trace): pass class IfaceState(object): \"\"\"Context manager to control state of", "be longer that 4 items while i < 4: # 255 - end", "for iface {0} is down.'.format( iface)) else: yield iface def pick_ip(range_start, range_end): \"\"\"Given", "vifaces def __exit__(self, type, value, trace): pass class IfaceState(object): \"\"\"Context manager to control", "ipv4 subnet cant be longer that 4 items while i < 4: #", "sequence of requests #so ans[0][1] would be response to first request return [format_answer(response[1],", "import sys from scapy import all as scapy DHCP_OFFER_COLUMNS = ('iface', 'mac', 'server_ip',", "'show', iface).stdout.read() search_result = re.search(r'.*<(?P<state>.*)>.*', state) if search_result: state_list = search_result.groupdict().get('state', []) if", "exc_val, exc_tb): if self.pre_iface_state != 'UP' and self.rollback: command_util('ifconfig', self.iface, 'down') self.post_iface_state =", "state) if search_result: state_list = search_result.groupdict().get('state', []) if 'UP' in state_list: return 'UP'", "(header, option) else: yield (header, option[1]) def format_answer(ans, iface): dhcp_options = dict(_dhcp_options(ans[scapy.DHCP].options)) results", "import all as scapy DHCP_OFFER_COLUMNS = ('iface', 'mac', 'server_ip', 'server_id', 'gateway', 'dport', 'message',", "properties = [] for key in columns: properties.append(item.get(key, '')) return properties def format_options(options):", "License. You may obtain # a copy of the License at # #", "for t in set([tuple(d.items()) for d in resp])) return wrapper class VlansContext(object): \"\"\"Contains", "iface_up(self): while self.retry and self.iface_state != 'UP': command_util('ifconfig', self.iface, 'up') self.iface_state = _iface_state(self.iface)", "the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "- list or tuple of (iface, vlan) pairs \"\"\" self.config = config def", "def check_iface_exist(iface): \"\"\"Check provided interface exists \"\"\" return not command_util(\"ip\", \"link\", \"show\", iface).stderr.read()", "dict(zip(DHCP_OFFER_COLUMNS, results)) def single_format(func): \"\"\"Manage format of dhcp response \"\"\" @functools.wraps(func) def formatter(*args,", "iface in ifaces: if not check_iface_exist(iface): sys.stderr.write('Iface {0} does not exist.'.format(iface)) else: if", "return 'DOWN' return 'UNKNOWN' def check_network_up(iface): return _iface_state(iface) == 'UP' def check_iface_exist(iface): \"\"\"Check", ">>> format_options([1, 2, 3]) '\\x01\\x02\\x03' \"\"\" return \"\".join((chr(item) for item in options)) def", "in dhcp_options: if isinstance(option, (tuple, list)): header = option[0] if len(option[1:]) > 1:", "all sequence of requests #so ans[0][1] would be response to first request return", "response to first request return [format_answer(response[1], iface) for response in ans] return formatter", "else: yield iface def pick_ip(range_start, range_end): \"\"\"Given start_range, end_range generate list of ips", "ANY KIND, either express or implied. See the # License for the specific", "@functools.wraps(func) def wrapper(*args, **kwargs): resp = func(*args, **kwargs) return (dict(t) for t in", "and limitations # under the License. import functools import re import subprocess import", "multiproc map could not work with format *args @functools.wraps(func) def workaround(*args, **kwargs): args", "cant be longer that 4 items while i < 4: # 255 -", "if self.iface_state != 'UP': raise EnvironmentError( 'Tried my best to ifup iface {0}.'.format(self.iface))", "exists \"\"\" return not command_util(\"ip\", \"link\", \"show\", iface).stderr.read() def filtered_ifaces(ifaces): for iface in", "= '' def iface_up(self): while self.retry and self.iface_state != 'UP': command_util('ifconfig', self.iface, 'up')", "in resp])) return wrapper class VlansContext(object): \"\"\"Contains all logic to manage vlans \"\"\"", "for correct cli table generation :param item: dict :param columns: list with arbitrary", "not check_iface_exist(iface): sys.stderr.write('Iface {0} does not exist.'.format(iface)) else: if not check_network_up(iface): sys.stderr.write('Network for", "**kwargs): resp = func(*args, **kwargs) return (dict(t) for t in set([tuple(d.items()) for d", "self.iface_state = _iface_state(self.iface) self.retry -= 1 if self.iface_state != 'UP': raise EnvironmentError( 'Tried", "0 # ipv4 subnet cant be longer that 4 items while i <", "\"\"\" properties = [] for key in columns: properties.append(item.get(key, '')) return properties def", "0: vifaces.append('{0}.{1}'.format(iface, vlan)) yield str(iface), vifaces def __exit__(self, type, value, trace): pass class", "\\ [int(item) for item in ip_address.split('.')] range_start = split_address(range_start) range_end = split_address(range_end) i", "in ifaces: if not check_iface_exist(iface): sys.stderr.write('Iface {0} does not exist.'.format(iface)) else: if not", "given iface return it's state returns UP, DOWN, UNKNOWN \"\"\" state = command_util('ip',", "def wrapper(*args, **kwargs): resp = func(*args, **kwargs) return (dict(t) for t in set([tuple(d.items())", "for iface, vlans in self.config.iteritems(): vifaces = [] for vlan in vlans: if", "re import subprocess import sys from scapy import all as scapy DHCP_OFFER_COLUMNS =", "response in ans] return formatter def multiproc_map(func): # multiproc map could not work", "multiple duplicated results # returned. This helper filter them out @functools.wraps(func) def wrapper(*args,", "type, value, trace): pass class IfaceState(object): \"\"\"Context manager to control state of iface", "in ip_address.split('.')] range_start = split_address(range_start) range_end = split_address(range_end) i = 0 # ipv4", "== range_end[i] and range_start[i] < 255: yield '.'.join([str(item) for item in range_start]) range_start[i]", "self.iface_state != 'UP': raise EnvironmentError( 'Tried my best to ifup iface {0}.'.format(self.iface)) def", "2), ('server_id', '192.168.0.5'), ('name_server', '192.168.0.1', '192.168.0.2'), 'end'] \"\"\" for option in dhcp_options: if", "[]) if 'UP' in state_list: return 'UP' else: return 'DOWN' return 'UNKNOWN' def", "under the Apache License, Version 2.0 (the \"License\"); you may # not use", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See", "_iface_state(iface) == 'UP' def check_iface_exist(iface): \"\"\"Check provided interface exists \"\"\" return not command_util(\"ip\",", "to control state of iface when dhcp checker is running \"\"\" def __init__(self,", "__init__(self, iface, rollback=True, retry=3): self.rollback = rollback self.retry = retry self.iface = iface", "when dhcp checker is running \"\"\" def __init__(self, iface, rollback=True, retry=3): self.rollback =", "self.iface = iface self.pre_iface_state = _iface_state(iface) self.iface_state = self.pre_iface_state self.post_iface_state = '' def", "def _check_vconfig(): \"\"\"Check vconfig installed or not \"\"\" return not command_util('which', 'vconfig').stderr.read() def", "stderr=subprocess.PIPE) def _check_vconfig(): \"\"\"Check vconfig installed or not \"\"\" return not command_util('which', 'vconfig').stderr.read()", "option) else: yield (header, option[1]) def format_answer(ans, iface): dhcp_options = dict(_dhcp_options(ans[scapy.DHCP].options)) results =", "governing permissions and limitations # under the License. import functools import re import", "properties def format_options(options): \"\"\"Util for serializing dhcp options @options = [1,2,3] >>> format_options([1,", "ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr) return dict(zip(DHCP_OFFER_COLUMNS, results)) def single_format(func): \"\"\"Manage format of dhcp", "< 4: # 255 - end of subnet if not range_start[i] == range_end[i]", "\"\"\"Initialize VlansContext @config - list or tuple of (iface, vlan) pairs \"\"\" self.config", "end_range generate list of ips >>> next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10' \"\"\" split_address = lambda ip_address:", "See the # License for the specific language governing permissions and limitations #", "self.retry -= 1 if self.iface_state != 'UP': raise EnvironmentError( 'Tried my best to", "def format_options(options): \"\"\"Util for serializing dhcp options @options = [1,2,3] >>> format_options([1, 2,", "\"\".join((chr(item) for item in options)) def _dhcp_options(dhcp_options): \"\"\"Dhcp options returned by scapy is", "self.iface, 'up') self.iface_state = _iface_state(self.iface) self.retry -= 1 if self.iface_state != 'UP': raise", "for key in columns: properties.append(item.get(key, '')) return properties def format_options(options): \"\"\"Util for serializing", "= split_address(range_end) i = 0 # ipv4 subnet cant be longer that 4", "law or agreed to in writing, software # distributed under the License is", "1 def get_item_properties(item, columns): \"\"\"Get specified in columns properties, with preserved order. Required", "ans[scapy.IP].src, dhcp_options['server_id'], ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr) return dict(zip(DHCP_OFFER_COLUMNS, results)) def single_format(func): \"\"\"Manage format", "requests #so ans[0][1] would be response to first request return [format_answer(response[1], iface) for", "Required for correct cli table generation :param item: dict :param columns: list with", "of (iface, vlan) pairs \"\"\" self.config = config def __enter__(self): for iface, vlans", "'192.168.0.2'), 'end'] \"\"\" for option in dhcp_options: if isinstance(option, (tuple, list)): header =", "\"\"\"Context manager to control state of iface when dhcp checker is running \"\"\"", "else: if not check_network_up(iface): sys.stderr.write('Network for iface {0} is down.'.format( iface)) else: yield", "vlans \"\"\" def __init__(self, config): \"\"\"Initialize VlansContext @config - list or tuple of", "express or implied. See the # License for the specific language governing permissions", "subnet cant be longer that 4 items while i < 4: # 255", "iface = args[0] ans = func(*args, **kwargs) #scapy stores all sequence of requests", "self.retry = retry self.iface = iface self.pre_iface_state = _iface_state(iface) self.iface_state = self.pre_iface_state self.post_iface_state", "def __enter__(self): self.iface_up() return self.iface def __exit__(self, exc_type, exc_val, exc_tb): if self.pre_iface_state !=", "with stderr and stdout \"\"\" return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _check_vconfig(): \"\"\"Check vconfig", "of iface when dhcp checker is running \"\"\" def __init__(self, iface, rollback=True, retry=3):", "header = option[0] if len(option[1:]) > 1: yield (header, option) else: yield (header,", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "CONDITIONS OF ANY KIND, either express or implied. See the # License for", "'UP' def check_iface_exist(iface): \"\"\"Check provided interface exists \"\"\" return not command_util(\"ip\", \"link\", \"show\",", "if not check_network_up(iface): sys.stderr.write('Network for iface {0} is down.'.format( iface)) else: yield iface", "list of ips >>> next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10' \"\"\" split_address = lambda ip_address: \\ [int(item)", "tuple of (iface, vlan) pairs \"\"\" self.config = config def __enter__(self): for iface,", "for the specific language governing permissions and limitations # under the License. import", "- end of subnet if not range_start[i] == range_end[i] and range_start[i] < 255:", "range_start = split_address(range_start) range_end = split_address(range_end) i = 0 # ipv4 subnet cant", "command_util(\"ip\", \"link\", \"show\", iface).stderr.read() def filtered_ifaces(ifaces): for iface in ifaces: if not check_iface_exist(iface):", "'UP' in state_list: return 'UP' else: return 'DOWN' return 'UNKNOWN' def check_network_up(iface): return", "vlans: if vlan > 0: vifaces.append('{0}.{1}'.format(iface, vlan)) yield str(iface), vifaces def __exit__(self, type,", "def command_util(*command): \"\"\"object with stderr and stdout \"\"\" return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def", "to ifup iface {0}.'.format(self.iface)) def __enter__(self): self.iface_up() return self.iface def __exit__(self, exc_type, exc_val,", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "in self.config.iteritems(): vifaces = [] for vlan in vlans: if vlan > 0:", "{0}.'.format(self.iface)) def __enter__(self): self.iface_up() return self.iface def __exit__(self, exc_type, exc_val, exc_tb): if self.pre_iface_state", "def check_network_up(iface): return _iface_state(iface) == 'UP' def check_iface_exist(iface): \"\"\"Check provided interface exists \"\"\"", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "options returned by scapy is not in usable format [('message-type', 2), ('server_id', '192.168.0.5'),", "\"link\", \"show\", iface).stderr.read() def filtered_ifaces(ifaces): for iface in ifaces: if not check_iface_exist(iface): sys.stderr.write('Iface", "_iface_state(self.iface) self.retry -= 1 if self.iface_state != 'UP': raise EnvironmentError( 'Tried my best", "__enter__(self): self.iface_up() return self.iface def __exit__(self, exc_type, exc_val, exc_tb): if self.pre_iface_state != 'UP'", "isinstance(args[0], (tuple, list)) else args return func(*args, **kwargs) return workaround def filter_duplicated_results(func): #", "compliance with the License. You may obtain # a copy of the License", "split_address(range_start) range_end = split_address(range_end) i = 0 # ipv4 subnet cant be longer", "def _dhcp_options(dhcp_options): \"\"\"Dhcp options returned by scapy is not in usable format [('message-type',", "ans = func(*args, **kwargs) #scapy stores all sequence of requests #so ans[0][1] would", "+= 1 else: i += 1 def get_item_properties(item, columns): \"\"\"Get specified in columns", "t in set([tuple(d.items()) for d in resp])) return wrapper class VlansContext(object): \"\"\"Contains all", "\"\"\"object with stderr and stdout \"\"\" return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _check_vconfig(): \"\"\"Check", "i = 0 # ipv4 subnet cant be longer that 4 items while", "and stdout \"\"\" return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _check_vconfig(): \"\"\"Check vconfig installed or", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "not range_start[i] == range_end[i] and range_start[i] < 255: yield '.'.join([str(item) for item in", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "\"\"\"Get specified in columns properties, with preserved order. Required for correct cli table", "'192.168.0.5'), ('name_server', '192.168.0.1', '192.168.0.2'), 'end'] \"\"\" for option in dhcp_options: if isinstance(option, (tuple,", "def format_answer(ans, iface): dhcp_options = dict(_dhcp_options(ans[scapy.DHCP].options)) results = ( iface, ans[scapy.Ether].src, ans[scapy.IP].src, dhcp_options['server_id'],", "@config - list or tuple of (iface, vlan) pairs \"\"\" self.config = config", "\"\"\"Dhcp options returned by scapy is not in usable format [('message-type', 2), ('server_id',", "if vlan > 0: vifaces.append('{0}.{1}'.format(iface, vlan)) yield str(iface), vifaces def __exit__(self, type, value,", "return [format_answer(response[1], iface) for response in ans] return formatter def multiproc_map(func): # multiproc", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "if not range_start[i] == range_end[i] and range_start[i] < 255: yield '.'.join([str(item) for item", "retry self.iface = iface self.pre_iface_state = _iface_state(iface) self.iface_state = self.pre_iface_state self.post_iface_state = ''", "running \"\"\" def __init__(self, iface, rollback=True, retry=3): self.rollback = rollback self.retry = retry", "d in resp])) return wrapper class VlansContext(object): \"\"\"Contains all logic to manage vlans", "self.post_iface_state = '' def iface_up(self): while self.retry and self.iface_state != 'UP': command_util('ifconfig', self.iface,", "value, trace): pass class IfaceState(object): \"\"\"Context manager to control state of iface when", "check_network_up(iface): sys.stderr.write('Network for iface {0} is down.'.format( iface)) else: yield iface def pick_ip(range_start,", "= command_util('ip', 'link', 'show', iface).stdout.read() search_result = re.search(r'.*<(?P<state>.*)>.*', state) if search_result: state_list =", "[format_answer(response[1], iface) for response in ans] return formatter def multiproc_map(func): # multiproc map", "= re.search(r'.*<(?P<state>.*)>.*', state) if search_result: state_list = search_result.groupdict().get('state', []) if 'UP' in state_list:", "options)) def _dhcp_options(dhcp_options): \"\"\"Dhcp options returned by scapy is not in usable format", "to network infra on broadcast multiple duplicated results # returned. This helper filter", "not check_network_up(iface): sys.stderr.write('Network for iface {0} is down.'.format( iface)) else: yield iface def", "checker is running \"\"\" def __init__(self, iface, rollback=True, retry=3): self.rollback = rollback self.retry", "lambda ip_address: \\ [int(item) for item in ip_address.split('.')] range_start = split_address(range_start) range_end =", "= dict(_dhcp_options(ans[scapy.DHCP].options)) results = ( iface, ans[scapy.Ether].src, ans[scapy.IP].src, dhcp_options['server_id'], ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr)", "retry=3): self.rollback = rollback self.retry = retry self.iface = iface self.pre_iface_state = _iface_state(iface)", "may # not use this file except in compliance with the License. You", "a given iface return it's state returns UP, DOWN, UNKNOWN \"\"\" state =", "either express or implied. See the # License for the specific language governing", "self.iface_state != 'UP': command_util('ifconfig', self.iface, 'up') self.iface_state = _iface_state(self.iface) self.retry -= 1 if", "would be response to first request return [format_answer(response[1], iface) for response in ans]", "helper filter them out @functools.wraps(func) def wrapper(*args, **kwargs): resp = func(*args, **kwargs) return", "this file except in compliance with the License. You may obtain # a", "properties.append(item.get(key, '')) return properties def format_options(options): \"\"\"Util for serializing dhcp options @options =", "range_end): \"\"\"Given start_range, end_range generate list of ips >>> next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10' \"\"\" split_address", "properties, with preserved order. Required for correct cli table generation :param item: dict", "= config def __enter__(self): for iface, vlans in self.config.iteritems(): vifaces = [] for", "or implied. See the # License for the specific language governing permissions and", "\"\"\"Check vconfig installed or not \"\"\" return not command_util('which', 'vconfig').stderr.read() def _iface_state(iface): \"\"\"For", "network infra on broadcast multiple duplicated results # returned. This helper filter them", "= self.pre_iface_state self.post_iface_state = '' def iface_up(self): while self.retry and self.iface_state != 'UP':", "ip_address: \\ [int(item) for item in ip_address.split('.')] range_start = split_address(range_start) range_end = split_address(range_end)", "subnet if not range_start[i] == range_end[i] and range_start[i] < 255: yield '.'.join([str(item) for", "split_address = lambda ip_address: \\ [int(item) for item in ip_address.split('.')] range_start = split_address(range_start)", "specified in columns properties, with preserved order. Required for correct cli table generation", "stores all sequence of requests #so ans[0][1] would be response to first request", "dhcp_options: if isinstance(option, (tuple, list)): header = option[0] if len(option[1:]) > 1: yield", "columns properties, with preserved order. Required for correct cli table generation :param item:", "iface)) else: yield iface def pick_ip(range_start, range_end): \"\"\"Given start_range, end_range generate list of", "functools import re import subprocess import sys from scapy import all as scapy", "iface) for response in ans] return formatter def multiproc_map(func): # multiproc map could", "of requests #so ans[0][1] would be response to first request return [format_answer(response[1], iface)", "2013 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the", "import re import subprocess import sys from scapy import all as scapy DHCP_OFFER_COLUMNS", "'server_ip', 'server_id', 'gateway', 'dport', 'message', 'yiaddr') def command_util(*command): \"\"\"object with stderr and stdout", "for iface in ifaces: if not check_iface_exist(iface): sys.stderr.write('Iface {0} does not exist.'.format(iface)) else:", "command_util('which', 'vconfig').stderr.read() def _iface_state(iface): \"\"\"For a given iface return it's state returns UP,", "state_list: return 'UP' else: return 'DOWN' return 'UNKNOWN' def check_network_up(iface): return _iface_state(iface) ==", "under the License. import functools import re import subprocess import sys from scapy", "in options)) def _dhcp_options(dhcp_options): \"\"\"Dhcp options returned by scapy is not in usable", "not in usable format [('message-type', 2), ('server_id', '192.168.0.5'), ('name_server', '192.168.0.1', '192.168.0.2'), 'end'] \"\"\"", "workaround def filter_duplicated_results(func): # due to network infra on broadcast multiple duplicated results", "is running \"\"\" def __init__(self, iface, rollback=True, retry=3): self.rollback = rollback self.retry =", "vlans in self.config.iteritems(): vifaces = [] for vlan in vlans: if vlan >", "with preserved order. Required for correct cli table generation :param item: dict :param", "the specific language governing permissions and limitations # under the License. import functools", "return 'UNKNOWN' def check_network_up(iface): return _iface_state(iface) == 'UP' def check_iface_exist(iface): \"\"\"Check provided interface", "subprocess import sys from scapy import all as scapy DHCP_OFFER_COLUMNS = ('iface', 'mac',", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "\"\"\" def __init__(self, config): \"\"\"Initialize VlansContext @config - list or tuple of (iface,", "state of iface when dhcp checker is running \"\"\" def __init__(self, iface, rollback=True,", "= ( iface, ans[scapy.Ether].src, ans[scapy.IP].src, dhcp_options['server_id'], ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr) return dict(zip(DHCP_OFFER_COLUMNS, results))", "'192.168.1.10' \"\"\" split_address = lambda ip_address: \\ [int(item) for item in ip_address.split('.')] range_start", "item in ip_address.split('.')] range_start = split_address(range_start) range_end = split_address(range_end) i = 0 #", "vlan) pairs \"\"\" self.config = config def __enter__(self): for iface, vlans in self.config.iteritems():", "VlansContext @config - list or tuple of (iface, vlan) pairs \"\"\" self.config =", "arbitrary keys \"\"\" properties = [] for key in columns: properties.append(item.get(key, '')) return", "trace): pass class IfaceState(object): \"\"\"Context manager to control state of iface when dhcp", "= func(*args, **kwargs) #scapy stores all sequence of requests #so ans[0][1] would be", "check_iface_exist(iface): \"\"\"Check provided interface exists \"\"\" return not command_util(\"ip\", \"link\", \"show\", iface).stderr.read() def", "format_answer(ans, iface): dhcp_options = dict(_dhcp_options(ans[scapy.DHCP].options)) results = ( iface, ans[scapy.Ether].src, ans[scapy.IP].src, dhcp_options['server_id'], ans[scapy.BOOTP].giaddr,", "it's state returns UP, DOWN, UNKNOWN \"\"\" state = command_util('ip', 'link', 'show', iface).stdout.read()", "iface def pick_ip(range_start, range_end): \"\"\"Given start_range, end_range generate list of ips >>> next(pick_ip('192.168.1.10','192.168.1.13'))", "search_result = re.search(r'.*<(?P<state>.*)>.*', state) if search_result: state_list = search_result.groupdict().get('state', []) if 'UP' in", "state_list = search_result.groupdict().get('state', []) if 'UP' in state_list: return 'UP' else: return 'DOWN'", "return \"\".join((chr(item) for item in options)) def _dhcp_options(dhcp_options): \"\"\"Dhcp options returned by scapy", "preserved order. Required for correct cli table generation :param item: dict :param columns:", "range_start]) range_start[i] += 1 else: i += 1 def get_item_properties(item, columns): \"\"\"Get specified", "# Copyright 2013 Mirantis, Inc. # # Licensed under the Apache License, Version", "__init__(self, config): \"\"\"Initialize VlansContext @config - list or tuple of (iface, vlan) pairs", "dhcp options @options = [1,2,3] >>> format_options([1, 2, 3]) '\\x01\\x02\\x03' \"\"\" return \"\".join((chr(item)", "OR CONDITIONS OF ANY KIND, either express or implied. See the # License", "obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "# Licensed under the Apache License, Version 2.0 (the \"License\"); you may #", "iface, ans[scapy.Ether].src, ans[scapy.IP].src, dhcp_options['server_id'], ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr) return dict(zip(DHCP_OFFER_COLUMNS, results)) def single_format(func):", "usable format [('message-type', 2), ('server_id', '192.168.0.5'), ('name_server', '192.168.0.1', '192.168.0.2'), 'end'] \"\"\" for option", "best to ifup iface {0}.'.format(self.iface)) def __enter__(self): self.iface_up() return self.iface def __exit__(self, exc_type,", "ips >>> next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10' \"\"\" split_address = lambda ip_address: \\ [int(item) for item", "option[1]) def format_answer(ans, iface): dhcp_options = dict(_dhcp_options(ans[scapy.DHCP].options)) results = ( iface, ans[scapy.Ether].src, ans[scapy.IP].src,", "return wrapper class VlansContext(object): \"\"\"Contains all logic to manage vlans \"\"\" def __init__(self,", "[] for vlan in vlans: if vlan > 0: vifaces.append('{0}.{1}'.format(iface, vlan)) yield str(iface),", "return dict(zip(DHCP_OFFER_COLUMNS, results)) def single_format(func): \"\"\"Manage format of dhcp response \"\"\" @functools.wraps(func) def", "is not in usable format [('message-type', 2), ('server_id', '192.168.0.5'), ('name_server', '192.168.0.1', '192.168.0.2'), 'end']", "format [('message-type', 2), ('server_id', '192.168.0.5'), ('name_server', '192.168.0.1', '192.168.0.2'), 'end'] \"\"\" for option in" ]
[ "schemas.category import CategorySchema from schemas.facts_in_data import FactsInDataSchema from schemas.market import MarketSchema from schemas.period", "from schemas.brand import BrandSchema from schemas.category import CategorySchema from schemas.facts_in_data import FactsInDataSchema from", "import FactsInDataSchema from schemas.market import MarketSchema from schemas.period import PeriodSchema class JohnsonScannerDataSchema(ma.SQLAlchemySchema): market", "schemas.brand import BrandSchema from schemas.category import CategorySchema from schemas.facts_in_data import FactsInDataSchema from schemas.market", "= ma.Nested(BrandSchema) category = ma.Nested(CategorySchema) period = ma.Nested(PeriodSchema) facts = ma.Nested(FactsInDataSchema, many=True) class", "from schemas.market import MarketSchema from schemas.period import PeriodSchema class JohnsonScannerDataSchema(ma.SQLAlchemySchema): market = ma.Nested(MarketSchema)", "ma import ma from models.johnson_scanner_data import JohnsonScannerDataModel from schemas.brand import BrandSchema from schemas.category", "period = ma.Nested(PeriodSchema) facts = ma.Nested(FactsInDataSchema, many=True) class Meta: model = JohnsonScannerDataModel dump_only", "= ma.Nested(CategorySchema) period = ma.Nested(PeriodSchema) facts = ma.Nested(FactsInDataSchema, many=True) class Meta: model =", "facts = ma.Nested(FactsInDataSchema, many=True) class Meta: model = JohnsonScannerDataModel dump_only = (\"id\",) #", "schemas.facts_in_data import FactsInDataSchema from schemas.market import MarketSchema from schemas.period import PeriodSchema class JohnsonScannerDataSchema(ma.SQLAlchemySchema):", "schemas.market import MarketSchema from schemas.period import PeriodSchema class JohnsonScannerDataSchema(ma.SQLAlchemySchema): market = ma.Nested(MarketSchema) brand", "import PeriodSchema class JohnsonScannerDataSchema(ma.SQLAlchemySchema): market = ma.Nested(MarketSchema) brand = ma.Nested(BrandSchema) category = ma.Nested(CategorySchema)", "BrandSchema from schemas.category import CategorySchema from schemas.facts_in_data import FactsInDataSchema from schemas.market import MarketSchema", "ma.Nested(PeriodSchema) facts = ma.Nested(FactsInDataSchema, many=True) class Meta: model = JohnsonScannerDataModel dump_only = (\"id\",)", "import BrandSchema from schemas.category import CategorySchema from schemas.facts_in_data import FactsInDataSchema from schemas.market import", "ma.Nested(BrandSchema) category = ma.Nested(CategorySchema) period = ma.Nested(PeriodSchema) facts = ma.Nested(FactsInDataSchema, many=True) class Meta:", "MarketSchema from schemas.period import PeriodSchema class JohnsonScannerDataSchema(ma.SQLAlchemySchema): market = ma.Nested(MarketSchema) brand = ma.Nested(BrandSchema)", "from schemas.facts_in_data import FactsInDataSchema from schemas.market import MarketSchema from schemas.period import PeriodSchema class", "JohnsonScannerDataModel from schemas.brand import BrandSchema from schemas.category import CategorySchema from schemas.facts_in_data import FactsInDataSchema", "many=True) class Meta: model = JohnsonScannerDataModel dump_only = (\"id\",) # include_fk = False", "brand = ma.Nested(BrandSchema) category = ma.Nested(CategorySchema) period = ma.Nested(PeriodSchema) facts = ma.Nested(FactsInDataSchema, many=True)", "ma from models.johnson_scanner_data import JohnsonScannerDataModel from schemas.brand import BrandSchema from schemas.category import CategorySchema", "from schemas.category import CategorySchema from schemas.facts_in_data import FactsInDataSchema from schemas.market import MarketSchema from", "schemas.period import PeriodSchema class JohnsonScannerDataSchema(ma.SQLAlchemySchema): market = ma.Nested(MarketSchema) brand = ma.Nested(BrandSchema) category =", "from ma import ma from models.johnson_scanner_data import JohnsonScannerDataModel from schemas.brand import BrandSchema from", "= ma.Nested(PeriodSchema) facts = ma.Nested(FactsInDataSchema, many=True) class Meta: model = JohnsonScannerDataModel dump_only =", "from models.johnson_scanner_data import JohnsonScannerDataModel from schemas.brand import BrandSchema from schemas.category import CategorySchema from", "ma.Nested(CategorySchema) period = ma.Nested(PeriodSchema) facts = ma.Nested(FactsInDataSchema, many=True) class Meta: model = JohnsonScannerDataModel", "models.johnson_scanner_data import JohnsonScannerDataModel from schemas.brand import BrandSchema from schemas.category import CategorySchema from schemas.facts_in_data", "ma.Nested(MarketSchema) brand = ma.Nested(BrandSchema) category = ma.Nested(CategorySchema) period = ma.Nested(PeriodSchema) facts = ma.Nested(FactsInDataSchema,", "ma.Nested(FactsInDataSchema, many=True) class Meta: model = JohnsonScannerDataModel dump_only = (\"id\",) # include_fk =", "import CategorySchema from schemas.facts_in_data import FactsInDataSchema from schemas.market import MarketSchema from schemas.period import", "CategorySchema from schemas.facts_in_data import FactsInDataSchema from schemas.market import MarketSchema from schemas.period import PeriodSchema", "from schemas.period import PeriodSchema class JohnsonScannerDataSchema(ma.SQLAlchemySchema): market = ma.Nested(MarketSchema) brand = ma.Nested(BrandSchema) category", "= ma.Nested(MarketSchema) brand = ma.Nested(BrandSchema) category = ma.Nested(CategorySchema) period = ma.Nested(PeriodSchema) facts =", "import ma from models.johnson_scanner_data import JohnsonScannerDataModel from schemas.brand import BrandSchema from schemas.category import", "category = ma.Nested(CategorySchema) period = ma.Nested(PeriodSchema) facts = ma.Nested(FactsInDataSchema, many=True) class Meta: model", "JohnsonScannerDataSchema(ma.SQLAlchemySchema): market = ma.Nested(MarketSchema) brand = ma.Nested(BrandSchema) category = ma.Nested(CategorySchema) period = ma.Nested(PeriodSchema)", "class JohnsonScannerDataSchema(ma.SQLAlchemySchema): market = ma.Nested(MarketSchema) brand = ma.Nested(BrandSchema) category = ma.Nested(CategorySchema) period =", "= ma.Nested(FactsInDataSchema, many=True) class Meta: model = JohnsonScannerDataModel dump_only = (\"id\",) # include_fk", "PeriodSchema class JohnsonScannerDataSchema(ma.SQLAlchemySchema): market = ma.Nested(MarketSchema) brand = ma.Nested(BrandSchema) category = ma.Nested(CategorySchema) period", "import JohnsonScannerDataModel from schemas.brand import BrandSchema from schemas.category import CategorySchema from schemas.facts_in_data import", "market = ma.Nested(MarketSchema) brand = ma.Nested(BrandSchema) category = ma.Nested(CategorySchema) period = ma.Nested(PeriodSchema) facts", "import MarketSchema from schemas.period import PeriodSchema class JohnsonScannerDataSchema(ma.SQLAlchemySchema): market = ma.Nested(MarketSchema) brand =", "FactsInDataSchema from schemas.market import MarketSchema from schemas.period import PeriodSchema class JohnsonScannerDataSchema(ma.SQLAlchemySchema): market =" ]
[ "and compare the results of with your # improved architecture. # # Be", "pass to fully-connected layer batch = batch.view(-1, self.num_flat_features(batch)) # Connect the reshaped features", "an activition function to 'batch' #batch = func.sigmoid(batch) return batch def num_flat_features(self, inputs):", "Pass the output of conv3 to the pooling layer batch = self.pool4(batch) batch", "initializations replacing each '_' with # the necessary value based on the provided", "Apply max-pooling with a [3x3] kernel using tiling (*NO SLIDING WINDOW*) self.conv7 =", "the starter code for the baseline architecture you will use # to get", "nn.BatchNorm2d(4) # Initialized weights using the Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight) self.pool1 = nn.MaxPool2d(kernel_size=3, stride=1)", "output channels, [6x6] kernel, initialization: xavier self.conv4 = nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3) self.conv4_normed =", "= nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO: Output layer: what should out_features be? self.out_features =", "= self.pool4(batch) batch = func.rrelu(self.conv7_normed(self.conv7(batch))) batch = func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass the output of", "nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv8_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5 = nn.MaxPool2d(kernel_size=4, stride=4) # Define", "batch def num_flat_features(self, inputs): # Get the dimensions of the layers excluding the", "fc2 self.fc2 = nn.Linear(in_features=512, out_features=128) self.fc2_normed = nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3 self.fc3 =", "'batch' #batch = func.sigmoid(batch) return batch def num_flat_features(self, inputs): # Get the dimensions", "batch of images through each layer of the network, applying non-linearities after each", "be called \"forward\" for PyTorch to automagically perform the forward pass. Params: -------", "= nn.MaxPool2d(kernel_size=4, stride=4) # Define 2 fully connected layers: #TODO: fc1 self.fc1 =", "layer of the network, applying non-linearities after each layer. Note that this function", "pass. Params: ------- - batch: (Tensor) An input batch of images Returns: --------", "# # Description: # # This file contains the starter code for the", "Be sure to fill in the code in the areas marked #TODO. ################################################################################", "create_split_loaders import matplotlib.pyplot as plt import numpy as np import os class Arch2CNN(nn.Module):", "-> fc3 (outputs) ======= conv1 -> conv2 -> maxpool -> conv3 -> conv4", "conv3 to the pooling layer batch = self.pool4(batch) batch = func.rrelu(self.conv7_normed(self.conv7(batch))) batch =", "8 output channels, [5x5] kernel, initialization: xavier self.conv5 = nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3) self.conv5_normed", "# Get the dimensions of the layers excluding the inputs size = inputs.size()[1:]", "code for the baseline architecture you will use # to get a little", "of the layers excluding the inputs size = inputs.size()[1:] # Track the number", "Code author: <NAME> (+ modifications by <NAME>) # # Filename: baseline_cnn.py # #", "Description: # # This file contains the starter code for the baseline architecture", "self.conv4_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv5: X input channels,", "batch = func.rrelu(self.conv3_normed(self.conv3(batch))) batch = func.rrelu(self.conv4_normed(self.conv4(batch))) batch = self.pool3(batch) batch = func.rrelu(self.conv5_normed(self.conv5(batch))) batch", "in the areas marked #TODO. ################################################################################ # PyTorch and neural network imports import", "of the conv3 to pass to fully-connected layer batch = batch.view(-1, self.num_flat_features(batch)) #", "conv2 and conv3 similarly batch = func.rrelu(self.conv2_normed(self.conv2(batch))) batch = self.pool2(batch) batch = func.rrelu(self.conv3_normed(self.conv3(batch)))", "to fully-connected layer batch = batch.view(-1, self.num_flat_features(batch)) # Connect the reshaped features of", "pooling layer batch = self.pool5(batch) # Reshape the output of the conv3 to", "Get the dimensions of the layers excluding the inputs size = inputs.size()[1:] #", "baseline_cnn.py # # Description: # # This file contains the starter code for", "initialization: xavier self.conv2 = nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3) self.conv2_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2", "batch = self.pool4(batch) batch = func.rrelu(self.conv7_normed(self.conv7(batch))) batch = func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass the output", "CSE 253: Programming Assignment 3 # Winter 2019 # Code author: <NAME> (+", "use # to get a little practice with PyTorch and compare the results", "the output of conv3 to the pooling layer batch = self.pool5(batch) # Reshape", "xray_dataloader_zscored import ChestXrayDataset, create_split_loaders import matplotlib.pyplot as plt import numpy as np import", "#TODO: fc1 self.fc1 = nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed = nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2 self.fc2", "-> maxpool -> conv3 -> conv4 ->maxpool -> conv5 -> conv6 -> maxpool", "maxpool -> conv7 -> conv8 -> maxpool -> fc1 -> fc2 -> fc3", "non-linearities after each layer. Note that this function *needs* to be called \"forward\"", "self.fc2_normed = nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3 self.fc3 = nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO: Output", "self.conv2_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv3: X input", "images Returns: -------- - logits: (Variable) The output of the network \"\"\" #", "import torchvision from torchvision import transforms, utils from xray_dataloader_zscored import ChestXrayDataset, create_split_loaders import", "utf-8 # In[ ]: ################################################################################ # CSE 253: Programming Assignment 3 # Winter", "kernel_size=3) self.conv2_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv3: X", "self.pool3 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv5: X input channels, 8 output channels, [5x5]", "self.conv5 = nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3) self.conv5_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6 = nn.Conv2d(in_channels=8, out_channels=8,", "func.rrelu(self.fc1_normed(self.fc1(batch))) batch = func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect fc1 to fc2 - this layer is", "#TODO: conv2: 4 input channels, 8 output channels, [3x3] kernel, initialization: xavier self.conv2", "that this function *needs* to be called \"forward\" for PyTorch to automagically perform", "the areas marked #TODO. ################################################################################ # PyTorch and neural network imports import torch", "reshaped features of the pooled conv3 to fc1 batch = func.rrelu(self.fc1_normed(self.fc1(batch))) batch =", "to fc1 batch = func.rrelu(self.fc1_normed(self.fc1(batch))) batch = func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect fc1 to fc2", "\"\"\" def __init__(self): super(Arch2CNN, self).__init__() # conv1: 1 input channel, 4 output channels,", "[8x8] kernel, initialization: xavier self.conv3 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3) self.conv3_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight)", "torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv3: X input channels, 12 output", "- batch: (Tensor) An input batch of images Returns: -------- - logits: (Variable)", "# In[ ]: ################################################################################ # CSE 253: Programming Assignment 3 # Winter 2019", "first convolution, followed by ReLU non-linearity; # use batch-normalization on its outputs batch", "batch = func.rrelu(self.conv1_normed(self.conv1(batch))) batch = self.pool1(batch) # Apply conv2 and conv3 similarly batch", "the provided specs for each layer #TODO: conv2: 4 input channels, 8 output", "nn.Linear(in_features=512, out_features=128) self.fc2_normed = nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3 self.fc3 = nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight)", "transforms, utils from xray_dataloader_zscored import ChestXrayDataset, create_split_loaders import matplotlib.pyplot as plt import numpy", "Arch2CNN(nn.Module): \"\"\" <<<<<<< HEAD conv1 -> maxpool -> conv2 -> maxpool -> conv3", "outputs batch = func.rrelu(self.conv1_normed(self.conv1(batch))) batch = self.pool1(batch) # Apply conv2 and conv3 similarly", "Add batch-normalization to the outputs of conv1 self.conv1_normed = nn.BatchNorm2d(4) # Initialized weights", "-> maxpool -> conv7 -> conv8 -> maxpool -> fc1 -> fc2 ->", "will use # to get a little practice with PyTorch and compare the", "to pass to fully-connected layer batch = batch.view(-1, self.num_flat_features(batch)) # Connect the reshaped", "with # the necessary value based on the provided specs for each layer", "def __init__(self): super(Arch2CNN, self).__init__() # conv1: 1 input channel, 4 output channels, [3x3]", "output channels, [3x3] kernel size self.conv1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3) # Add batch-normalization", "nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed = nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2 self.fc2 = nn.Linear(in_features=512, out_features=128) self.fc2_normed", "= func.rrelu(self.conv5_normed(self.conv5(batch))) batch = func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass the output of conv3 to the", "= nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2 self.fc2 = nn.Linear(in_features=512, out_features=128) self.fc2_normed = nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight)", "the Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight) self.pool1 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Fill in the remaining", "to the pooling layer batch = self.pool5(batch) # Reshape the output of the", "In[ ]: ################################################################################ # CSE 253: Programming Assignment 3 # Winter 2019 #", "conv1 self.conv1_normed = nn.BatchNorm2d(4) # Initialized weights using the Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight) self.pool1", "than the rest (why?) batch = self.fc3(batch) # Return the class predictions #TODO:", "self.conv5_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv6_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight)", "nn import torch.nn.functional as func import torch.nn.init as torch_init import torch.optim as optim", "X input channels, 12 output channels, [8x8] kernel, initialization: xavier self.conv3 = nn.Conv2d(in_channels=8,", "-> conv3 -> conv4 -> conv5 -> maxpool -> fc1 -> fc2 ->", "inputs): # Get the dimensions of the layers excluding the inputs size =", "for PyTorch to automagically perform the forward pass. Params: ------- - batch: (Tensor)", "= func.rrelu(self.conv1_normed(self.conv1(batch))) batch = self.pool1(batch) # Apply conv2 and conv3 similarly batch =", "nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv7_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv8_normed", "3 # Winter 2019 # Code author: <NAME> (+ modifications by <NAME>) #", "as plt import numpy as np import os class Arch2CNN(nn.Module): \"\"\" <<<<<<< HEAD", "inputs.size()[1:] # Track the number of features num_features = 1 for s in", "# Winter 2019 # Code author: <NAME> (+ modifications by <NAME>) # #", "nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2 self.fc2 = nn.Linear(in_features=512, out_features=128) self.fc2_normed = nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO:", "torch.nn as nn import torch.nn.functional as func import torch.nn.init as torch_init import torch.optim", "# Track the number of features num_features = 1 for s in size:", "#TODO: conv4: X input channels, 10 output channels, [6x6] kernel, initialization: xavier self.conv4", "torch_init.xavier_normal_(self.conv4.weight) self.pool3 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv5: X input channels, 8 output channels,", "the class predictions #TODO: apply an activition function to 'batch' #batch = func.sigmoid(batch)", "based on the provided specs for each layer #TODO: conv2: 4 input channels,", "self.conv3_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4: X input channels, 10 output channels, [6x6]", "and neural network imports import torch from torch.autograd import Variable import torch.nn as", "->maxpool -> conv5 -> conv6 -> maxpool -> conv7 -> conv8 -> maxpool", "utils and dataloader import torchvision from torchvision import transforms, utils from xray_dataloader_zscored import", "output of the conv3 to pass to fully-connected layer batch = batch.view(-1, self.num_flat_features(batch))", "nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv5: X input channels, 8 output channels, [5x5] kernel, initialization:", "xavier self.conv3 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3) self.conv3_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4: X", "(Tensor) An input batch of images Returns: -------- - logits: (Variable) The output", "= nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5 = nn.MaxPool2d(kernel_size=4, stride=4) # Define 2 fully connected layers:", "be? self.out_features = 14 def forward(self, batch): \"\"\"Pass the batch of images through", "-> maxpool -> conv2 -> maxpool -> conv3 -> conv4 ->maxpool -> conv5", "the rest (why?) batch = self.fc3(batch) # Return the class predictions #TODO: apply", "= nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv8_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5", "perform the forward pass. Params: ------- - batch: (Tensor) An input batch of", "starter code for the baseline architecture you will use # to get a", "-> fc2 -> fc3 (outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\" def __init__(self): super(Arch2CNN, self).__init__() #", "layer is slightly different than the rest (why?) batch = self.fc3(batch) # Return", "func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass the output of conv3 to the pooling layer batch =", "super(Arch2CNN, self).__init__() # conv1: 1 input channel, 4 output channels, [3x3] kernel size", "nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3) self.conv3_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4: X input channels, 10", "conv6 -> maxpool -> conv7 -> conv8 -> maxpool -> fc1 -> fc2", "modifications by <NAME>) # # Filename: baseline_cnn.py # # Description: # # This", "nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv3: X input channels, 12 output channels, [8x8] kernel, initialization:", "self.conv6_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Apply max-pooling with a", "the pooling layer batch = self.pool5(batch) # Reshape the output of the conv3", "return batch def num_flat_features(self, inputs): # Get the dimensions of the layers excluding", "# Data utils and dataloader import torchvision from torchvision import transforms, utils from", "channels, [3x3] kernel size self.conv1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3) # Add batch-normalization to", "output channels, [8x8] kernel, initialization: xavier self.conv3 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3) self.conv3_normed =", "<NAME>) # # Filename: baseline_cnn.py # # Description: # # This file contains", "= self.pool5(batch) # Reshape the output of the conv3 to pass to fully-connected", "func import torch.nn.init as torch_init import torch.optim as optim # Data utils and", "= nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv8_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5 = nn.MaxPool2d(kernel_size=4, stride=4) #", "kernel using tiling (*NO SLIDING WINDOW*) self.conv7 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv7_normed =", "= func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass the output of conv3 to the pooling layer batch", "layer #TODO: conv2: 4 input channels, 8 output channels, [3x3] kernel, initialization: xavier", "utils from xray_dataloader_zscored import ChestXrayDataset, create_split_loaders import matplotlib.pyplot as plt import numpy as", "xavier self.conv5 = nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3) self.conv5_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6 = nn.Conv2d(in_channels=8,", "kernel_size=3) self.conv4_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv5: X input", "batch): \"\"\"Pass the batch of images through each layer of the network, applying", "size = inputs.size()[1:] # Track the number of features num_features = 1 for", "\"\"\" <<<<<<< HEAD conv1 -> maxpool -> conv2 -> maxpool -> conv3 ->", "ReLU non-linearity; # use batch-normalization on its outputs batch = func.rrelu(self.conv1_normed(self.conv1(batch))) batch =", "the pooled conv3 to fc1 batch = func.rrelu(self.fc1_normed(self.fc1(batch))) batch = func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect", "out_channels=8, kernel_size=3) self.conv7_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv8_normed =", "# Description: # # This file contains the starter code for the baseline", "self.pool3(batch) batch = func.rrelu(self.conv5_normed(self.conv5(batch))) batch = func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass the output of conv3", "optim # Data utils and dataloader import torchvision from torchvision import transforms, utils", "#TODO: fc3 self.fc3 = nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO: Output layer: what should out_features", "-> conv5 -> conv6 -> maxpool -> conv7 -> conv8 -> maxpool ->", "= func.rrelu(self.conv7_normed(self.conv7(batch))) batch = func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass the output of conv3 to the", "size self.conv1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3) # Add batch-normalization to the outputs of", "batch = func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass the output of conv3 to the pooling layer", "layer batch = self.pool4(batch) batch = func.rrelu(self.conv7_normed(self.conv7(batch))) batch = func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass the", "xavier self.conv2 = nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3) self.conv2_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2 =", "self.conv2 = nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3) self.conv2_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2 = nn.MaxPool2d(kernel_size=3,", "nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3) # Add batch-normalization to the outputs of conv1 self.conv1_normed =", "the output of the conv3 to pass to fully-connected layer batch = batch.view(-1,", "of the pooled conv3 to fc1 batch = func.rrelu(self.fc1_normed(self.fc1(batch))) batch = func.rrelu(self.fc2_normed(self.fc2(batch))) #", "self.conv1_normed = nn.BatchNorm2d(4) # Initialized weights using the Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight) self.pool1 =", "by <NAME>) # # Filename: baseline_cnn.py # # Description: # # This file", "<NAME> (+ modifications by <NAME>) # # Filename: baseline_cnn.py # # Description: #", "# Pass the output of conv3 to the pooling layer batch = self.pool4(batch)", "Pass the output of conv3 to the pooling layer batch = self.pool5(batch) #", "func.rrelu(self.conv1_normed(self.conv1(batch))) batch = self.pool1(batch) # Apply conv2 and conv3 similarly batch = func.rrelu(self.conv2_normed(self.conv2(batch)))", "= nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Apply max-pooling with a [3x3]", "out_features=512) self.fc1_normed = nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2 self.fc2 = nn.Linear(in_features=512, out_features=128) self.fc2_normed =", "applying non-linearities after each layer. Note that this function *needs* to be called", "features num_features = 1 for s in size: num_features *= s return num_features", "-> maxpool -> fc1 -> fc2 -> fc3 (outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\" def", "marked #TODO. ################################################################################ # PyTorch and neural network imports import torch from torch.autograd", "conv1 -> maxpool -> conv2 -> maxpool -> conv3 -> conv4 ->maxpool ->", "to the pooling layer batch = self.pool4(batch) batch = func.rrelu(self.conv7_normed(self.conv7(batch))) batch = func.rrelu(self.conv8_normed(self.conv8(batch)))", "(+ modifications by <NAME>) # # Filename: baseline_cnn.py # # Description: # #", "-> conv3 -> conv4 ->maxpool -> conv5 -> conv6 -> maxpool -> conv7", "batch = func.rrelu(self.conv4_normed(self.conv4(batch))) batch = self.pool3(batch) batch = func.rrelu(self.conv5_normed(self.conv5(batch))) batch = func.rrelu(self.conv6_normed(self.conv6(batch))) #", "logits: (Variable) The output of the network \"\"\" # Apply first convolution, followed", "excluding the inputs size = inputs.size()[1:] # Track the number of features num_features", "architecture. # # Be sure to fill in the code in the areas", "output of conv3 to the pooling layer batch = self.pool5(batch) # Reshape the", "fc1 self.fc1 = nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed = nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2 self.fc2 =", "kernel_size=3) self.conv5_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv6_normed = nn.BatchNorm2d(8)", "output of the network \"\"\" # Apply first convolution, followed by ReLU non-linearity;", "torch.optim as optim # Data utils and dataloader import torchvision from torchvision import", "conv1 -> conv2 -> maxpool -> conv3 -> conv4 -> conv5 -> maxpool", "the inputs size = inputs.size()[1:] # Track the number of features num_features =", "nn.MaxPool2d(kernel_size=4, stride=4) # Define 2 fully connected layers: #TODO: fc1 self.fc1 = nn.Linear(in_features=122*122*8,", "-> maxpool -> conv3 -> conv4 -> conv5 -> maxpool -> fc1 ->", "conv5 -> maxpool -> fc1 -> fc2 -> fc3 (outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\"", "kernel, initialization: xavier self.conv2 = nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3) self.conv2_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool", "channels, [8x8] kernel, initialization: xavier self.conv3 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3) self.conv3_normed = nn.BatchNorm2d(16)", "with PyTorch and compare the results of with your # improved architecture. #", "convolution, followed by ReLU non-linearity; # use batch-normalization on its outputs batch =", "the forward pass. Params: ------- - batch: (Tensor) An input batch of images", "(*NO SLIDING WINDOW*) self.conv7 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv7_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8", "-> fc2 -> fc3 (outputs) ======= conv1 -> conv2 -> maxpool -> conv3", "nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Fill in the remaining initializations replacing each '_' with #", "channels, 8 output channels, [5x5] kernel, initialization: xavier self.conv5 = nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3)", "= nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv7_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3)", "xavier self.conv4 = nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3) self.conv4_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3 = nn.MaxPool2d(kernel_size=3,", "#TODO: fc2 self.fc2 = nn.Linear(in_features=512, out_features=128) self.fc2_normed = nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3 self.fc3", "= nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3) # Add batch-normalization to the outputs of conv1 self.conv1_normed", "= nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv5: X input channels, 8 output channels, [5x5] kernel,", "Return the class predictions #TODO: apply an activition function to 'batch' #batch =", "func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass the output of conv3 to the pooling layer batch =", "fc3 (outputs) ======= conv1 -> conv2 -> maxpool -> conv3 -> conv4 ->", "neural network imports import torch from torch.autograd import Variable import torch.nn as nn", "layer. Note that this function *needs* to be called \"forward\" for PyTorch to", "batch = func.rrelu(self.conv2_normed(self.conv2(batch))) batch = self.pool2(batch) batch = func.rrelu(self.conv3_normed(self.conv3(batch))) batch = func.rrelu(self.conv4_normed(self.conv4(batch))) batch", "fully-connected layer batch = batch.view(-1, self.num_flat_features(batch)) # Connect the reshaped features of the", "torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2 self.fc2 = nn.Linear(in_features=512, out_features=128) self.fc2_normed = nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3", "similarly batch = func.rrelu(self.conv2_normed(self.conv2(batch))) batch = self.pool2(batch) batch = func.rrelu(self.conv3_normed(self.conv3(batch))) batch = func.rrelu(self.conv4_normed(self.conv4(batch)))", "contains the starter code for the baseline architecture you will use # to", "= func.rrelu(self.conv3_normed(self.conv3(batch))) batch = func.rrelu(self.conv4_normed(self.conv4(batch))) batch = self.pool3(batch) batch = func.rrelu(self.conv5_normed(self.conv5(batch))) batch =", "input channels, 8 output channels, [5x5] kernel, initialization: xavier self.conv5 = nn.Conv2d(in_channels=16, out_channels=8,", "conv4: X input channels, 10 output channels, [6x6] kernel, initialization: xavier self.conv4 =", "torch_init.xavier_normal_(self.conv1.weight) self.pool1 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Fill in the remaining initializations replacing each", "out_channels=8, kernel_size=3) self.conv5_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv6_normed =", "architecture you will use # to get a little practice with PyTorch and", "[6x6] kernel, initialization: xavier self.conv4 = nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3) self.conv4_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight)", "the code in the areas marked #TODO. ################################################################################ # PyTorch and neural network", "kernel, initialization: xavier self.conv3 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3) self.conv3_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO:", "#TODO: Output layer: what should out_features be? self.out_features = 14 def forward(self, batch):", "from xray_dataloader_zscored import ChestXrayDataset, create_split_loaders import matplotlib.pyplot as plt import numpy as np", "# Define 2 fully connected layers: #TODO: fc1 self.fc1 = nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed", "maxpool -> conv3 -> conv4 -> conv5 -> maxpool -> fc1 -> fc2", "initialization: xavier self.conv4 = nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3) self.conv4_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3 =", "each layer. Note that this function *needs* to be called \"forward\" for PyTorch", "its outputs batch = func.rrelu(self.conv1_normed(self.conv1(batch))) batch = self.pool1(batch) # Apply conv2 and conv3", "out_features=128) self.fc2_normed = nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3 self.fc3 = nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO:", "specs for each layer #TODO: conv2: 4 input channels, 8 output channels, [3x3]", "channels, [5x5] kernel, initialization: xavier self.conv5 = nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3) self.conv5_normed = nn.BatchNorm2d(8)", "stride=4) # Define 2 fully connected layers: #TODO: fc1 self.fc1 = nn.Linear(in_features=122*122*8, out_features=512)", "kernel_size=3) self.conv3_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4: X input channels, 10 output channels,", "self.conv1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3) # Add batch-normalization to the outputs of conv1", "value based on the provided specs for each layer #TODO: conv2: 4 input", "as torch_init import torch.optim as optim # Data utils and dataloader import torchvision", "import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as", "1 input channel, 4 output channels, [3x3] kernel size self.conv1 = nn.Conv2d(in_channels=1, out_channels=4,", "from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as func import", "= batch.view(-1, self.num_flat_features(batch)) # Connect the reshaped features of the pooled conv3 to", "the layers excluding the inputs size = inputs.size()[1:] # Track the number of", "provided specs for each layer #TODO: conv2: 4 input channels, 8 output channels,", "[5x5] kernel, initialization: xavier self.conv5 = nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3) self.conv5_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight)", "necessary value based on the provided specs for each layer #TODO: conv2: 4", "Filename: baseline_cnn.py # # Description: # # This file contains the starter code", "batch = func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass the output of conv3 to the pooling layer", "conv7 -> conv8 -> maxpool -> fc1 -> fc2 -> fc3 (outputs) =======", "Fill in the remaining initializations replacing each '_' with # the necessary value", "each '_' with # the necessary value based on the provided specs for", "# Code author: <NAME> (+ modifications by <NAME>) # # Filename: baseline_cnn.py #", "#TODO: Apply max-pooling with a [3x3] kernel using tiling (*NO SLIDING WINDOW*) self.conv7", "conv3 to the pooling layer batch = self.pool5(batch) # Reshape the output of", "out_channels=8, kernel_size=3) self.conv8_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5 = nn.MaxPool2d(kernel_size=4, stride=4) # Define 2", "batch-normalization to the outputs of conv1 self.conv1_normed = nn.BatchNorm2d(4) # Initialized weights using", "torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4: X input channels, 10 output channels, [6x6] kernel, initialization: xavier", "stride=1) #TODO: conv3: X input channels, 12 output channels, [8x8] kernel, initialization: xavier", "should out_features be? self.out_features = 14 def forward(self, batch): \"\"\"Pass the batch of", "activition function to 'batch' #batch = func.sigmoid(batch) return batch def num_flat_features(self, inputs): #", "of the network, applying non-linearities after each layer. Note that this function *needs*", "batch.view(-1, self.num_flat_features(batch)) # Connect the reshaped features of the pooled conv3 to fc1", "= self.pool2(batch) batch = func.rrelu(self.conv3_normed(self.conv3(batch))) batch = func.rrelu(self.conv4_normed(self.conv4(batch))) batch = self.pool3(batch) batch =", "the remaining initializations replacing each '_' with # the necessary value based on", "= nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed = nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2 self.fc2 = nn.Linear(in_features=512, out_features=128)", "conv2 -> maxpool -> conv3 -> conv4 ->maxpool -> conv5 -> conv6 ->", "channels, [6x6] kernel, initialization: xavier self.conv4 = nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3) self.conv4_normed = nn.BatchNorm2d(16)", "\"\"\" # Apply first convolution, followed by ReLU non-linearity; # use batch-normalization on", "conv2 -> maxpool -> conv3 -> conv4 -> conv5 -> maxpool -> fc1", "'_' with # the necessary value based on the provided specs for each", "# Apply conv2 and conv3 similarly batch = func.rrelu(self.conv2_normed(self.conv2(batch))) batch = self.pool2(batch) batch", "= self.pool3(batch) batch = func.rrelu(self.conv5_normed(self.conv5(batch))) batch = func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass the output of", "= nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3 self.fc3 = nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO: Output layer:", "Returns: -------- - logits: (Variable) The output of the network \"\"\" # Apply", "= nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3) self.conv5_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3)", "function to 'batch' #batch = func.sigmoid(batch) return batch def num_flat_features(self, inputs): # Get", "torch.nn.functional as func import torch.nn.init as torch_init import torch.optim as optim # Data", "plt import numpy as np import os class Arch2CNN(nn.Module): \"\"\" <<<<<<< HEAD conv1", "different than the rest (why?) batch = self.fc3(batch) # Return the class predictions", "# Pass the output of conv3 to the pooling layer batch = self.pool5(batch)", "import Variable import torch.nn as nn import torch.nn.functional as func import torch.nn.init as", "]: ################################################################################ # CSE 253: Programming Assignment 3 # Winter 2019 # Code", "self.conv6 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv6_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4 = nn.MaxPool2d(kernel_size=3, stride=1)", "through each layer of the network, applying non-linearities after each layer. Note that", "# # This file contains the starter code for the baseline architecture you", "Variable import torch.nn as nn import torch.nn.functional as func import torch.nn.init as torch_init", "of conv3 to the pooling layer batch = self.pool5(batch) # Reshape the output", "numpy as np import os class Arch2CNN(nn.Module): \"\"\" <<<<<<< HEAD conv1 -> maxpool", "-> fc1 -> fc2 -> fc3 (outputs) ======= conv1 -> conv2 -> maxpool", "conv3: X input channels, 12 output channels, [8x8] kernel, initialization: xavier self.conv3 =", "out_channels=8, kernel_size=3) self.conv6_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Apply max-pooling", "= 14 def forward(self, batch): \"\"\"Pass the batch of images through each layer", "self.pool1 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Fill in the remaining initializations replacing each '_'", "func.rrelu(self.conv2_normed(self.conv2(batch))) batch = self.pool2(batch) batch = func.rrelu(self.conv3_normed(self.conv3(batch))) batch = func.rrelu(self.conv4_normed(self.conv4(batch))) batch = self.pool3(batch)", "nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5 = nn.MaxPool2d(kernel_size=4, stride=4) # Define 2 fully connected layers: #TODO:", "-> conv7 -> conv8 -> maxpool -> fc1 -> fc2 -> fc3 (outputs)", "conv5: X input channels, 8 output channels, [5x5] kernel, initialization: xavier self.conv5 =", "Connect the reshaped features of the pooled conv3 to fc1 batch = func.rrelu(self.fc1_normed(self.fc1(batch)))", "-> conv2 -> maxpool -> conv3 -> conv4 ->maxpool -> conv5 -> conv6", "method torch_init.xavier_normal_(self.conv1.weight) self.pool1 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Fill in the remaining initializations replacing", "maxpool -> conv3 -> conv4 ->maxpool -> conv5 -> conv6 -> maxpool ->", "= func.sigmoid(batch) return batch def num_flat_features(self, inputs): # Get the dimensions of the", "torch.autograd import Variable import torch.nn as nn import torch.nn.functional as func import torch.nn.init", "channels, 8 output channels, [3x3] kernel, initialization: xavier self.conv2 = nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3)", "-> conv8 -> maxpool -> fc1 -> fc2 -> fc3 (outputs) ======= conv1", "torch_init.xavier_normal_(self.conv5.weight) self.conv6 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv6_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4 = nn.MaxPool2d(kernel_size=3,", "This file contains the starter code for the baseline architecture you will use", "features of the pooled conv3 to fc1 batch = func.rrelu(self.fc1_normed(self.fc1(batch))) batch = func.rrelu(self.fc2_normed(self.fc2(batch)))", "conv3 similarly batch = func.rrelu(self.conv2_normed(self.conv2(batch))) batch = self.pool2(batch) batch = func.rrelu(self.conv3_normed(self.conv3(batch))) batch =", "# to get a little practice with PyTorch and compare the results of", "-> conv4 -> conv5 -> maxpool -> fc1 -> fc2 -> fc3 (outputs)", "# CSE 253: Programming Assignment 3 # Winter 2019 # Code author: <NAME>", "#batch = func.sigmoid(batch) return batch def num_flat_features(self, inputs): # Get the dimensions of", "#TODO. ################################################################################ # PyTorch and neural network imports import torch from torch.autograd import", "fc1 to fc2 - this layer is slightly different than the rest (why?)", "os class Arch2CNN(nn.Module): \"\"\" <<<<<<< HEAD conv1 -> maxpool -> conv2 -> maxpool", "# coding: utf-8 # In[ ]: ################################################################################ # CSE 253: Programming Assignment 3", "fc2 - this layer is slightly different than the rest (why?) batch =", "torch.nn.init as torch_init import torch.optim as optim # Data utils and dataloader import", "author: <NAME> (+ modifications by <NAME>) # # Filename: baseline_cnn.py # # Description:", "def num_flat_features(self, inputs): # Get the dimensions of the layers excluding the inputs", "batch = self.fc3(batch) # Return the class predictions #TODO: apply an activition function", "self.fc3 = nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO: Output layer: what should out_features be? self.out_features", "using tiling (*NO SLIDING WINDOW*) self.conv7 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv7_normed = nn.BatchNorm2d(8)", "self.pool5(batch) # Reshape the output of the conv3 to pass to fully-connected layer", "self.pool4(batch) batch = func.rrelu(self.conv7_normed(self.conv7(batch))) batch = func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass the output of conv3", "fc1 -> fc2 -> fc3 (outputs) ======= conv1 -> conv2 -> maxpool ->", "dataloader import torchvision from torchvision import transforms, utils from xray_dataloader_zscored import ChestXrayDataset, create_split_loaders", "you will use # to get a little practice with PyTorch and compare", "the baseline architecture you will use # to get a little practice with", "Assignment 3 # Winter 2019 # Code author: <NAME> (+ modifications by <NAME>)", "conv8 -> maxpool -> fc1 -> fc2 -> fc3 (outputs) ======= conv1 ->", "conv2: 4 input channels, 8 output channels, [3x3] kernel, initialization: xavier self.conv2 =", "self.num_flat_features(batch)) # Connect the reshaped features of the pooled conv3 to fc1 batch", "out_channels=4, kernel_size=3) # Add batch-normalization to the outputs of conv1 self.conv1_normed = nn.BatchNorm2d(4)", "= func.rrelu(self.conv2_normed(self.conv2(batch))) batch = self.pool2(batch) batch = func.rrelu(self.conv3_normed(self.conv3(batch))) batch = func.rrelu(self.conv4_normed(self.conv4(batch))) batch =", "layer batch = self.pool5(batch) # Reshape the output of the conv3 to pass", "output channels, [3x3] kernel, initialization: xavier self.conv2 = nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3) self.conv2_normed =", "= func.rrelu(self.conv4_normed(self.conv4(batch))) batch = self.pool3(batch) batch = func.rrelu(self.conv5_normed(self.conv5(batch))) batch = func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass", "channels, [3x3] kernel, initialization: xavier self.conv2 = nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3) self.conv2_normed = nn.BatchNorm2d(8)", "stride=1) #TODO: conv5: X input channels, 8 output channels, [5x5] kernel, initialization: xavier", "X input channels, 8 output channels, [5x5] kernel, initialization: xavier self.conv5 = nn.Conv2d(in_channels=16,", "-> conv4 ->maxpool -> conv5 -> conv6 -> maxpool -> conv7 -> conv8", "self.fc1_normed = nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2 self.fc2 = nn.Linear(in_features=512, out_features=128) self.fc2_normed = nn.BatchNorm1d(128)", "nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3 self.fc3 = nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO: Output layer: what", "as optim # Data utils and dataloader import torchvision from torchvision import transforms,", "input channels, 8 output channels, [3x3] kernel, initialization: xavier self.conv2 = nn.Conv2d(in_channels=4, out_channels=8,", "= inputs.size()[1:] # Track the number of features num_features = 1 for s", "kernel_size=3) # Add batch-normalization to the outputs of conv1 self.conv1_normed = nn.BatchNorm2d(4) #", "# Be sure to fill in the code in the areas marked #TODO.", ">>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\" def __init__(self): super(Arch2CNN, self).__init__() # conv1: 1 input channel, 4", "= nn.BatchNorm2d(4) # Initialized weights using the Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight) self.pool1 = nn.MaxPool2d(kernel_size=3,", "nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3) self.conv2_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO:", "kernel_size=3) self.conv8_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5 = nn.MaxPool2d(kernel_size=4, stride=4) # Define 2 fully", "-> conv2 -> maxpool -> conv3 -> conv4 -> conv5 -> maxpool ->", "output channels, [5x5] kernel, initialization: xavier self.conv5 = nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3) self.conv5_normed =", "the batch of images through each layer of the network, applying non-linearities after", "channels, 10 output channels, [6x6] kernel, initialization: xavier self.conv4 = nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3)", "pooled conv3 to fc1 batch = func.rrelu(self.fc1_normed(self.fc1(batch))) batch = func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect fc1", "non-linearity; # use batch-normalization on its outputs batch = func.rrelu(self.conv1_normed(self.conv1(batch))) batch = self.pool1(batch)", "*needs* to be called \"forward\" for PyTorch to automagically perform the forward pass.", "import os class Arch2CNN(nn.Module): \"\"\" <<<<<<< HEAD conv1 -> maxpool -> conv2 ->", "outputs of conv1 self.conv1_normed = nn.BatchNorm2d(4) # Initialized weights using the Xavier-Normal method", "the network, applying non-linearities after each layer. Note that this function *needs* to", "import torch.optim as optim # Data utils and dataloader import torchvision from torchvision", "self.pool2(batch) batch = func.rrelu(self.conv3_normed(self.conv3(batch))) batch = func.rrelu(self.conv4_normed(self.conv4(batch))) batch = self.pool3(batch) batch = func.rrelu(self.conv5_normed(self.conv5(batch)))", "batch = self.pool5(batch) # Reshape the output of the conv3 to pass to", "batch = batch.view(-1, self.num_flat_features(batch)) # Connect the reshaped features of the pooled conv3", "__init__(self): super(Arch2CNN, self).__init__() # conv1: 1 input channel, 4 output channels, [3x3] kernel", "-> conv6 -> maxpool -> conv7 -> conv8 -> maxpool -> fc1 ->", "8 output channels, [3x3] kernel, initialization: xavier self.conv2 = nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3) self.conv2_normed", "pooling layer batch = self.pool4(batch) batch = func.rrelu(self.conv7_normed(self.conv7(batch))) batch = func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass", "= nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3) self.conv3_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4: X input channels,", "use batch-normalization on its outputs batch = func.rrelu(self.conv1_normed(self.conv1(batch))) batch = self.pool1(batch) # Apply", "-> conv5 -> maxpool -> fc1 -> fc2 -> fc3 (outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6", "batch = func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect fc1 to fc2 - this layer is slightly", "# use batch-normalization on its outputs batch = func.rrelu(self.conv1_normed(self.conv1(batch))) batch = self.pool1(batch) #", "self.out_features = 14 def forward(self, batch): \"\"\"Pass the batch of images through each", "import transforms, utils from xray_dataloader_zscored import ChestXrayDataset, create_split_loaders import matplotlib.pyplot as plt import", "the pooling layer batch = self.pool4(batch) batch = func.rrelu(self.conv7_normed(self.conv7(batch))) batch = func.rrelu(self.conv8_normed(self.conv8(batch))) #", "conv3 -> conv4 ->maxpool -> conv5 -> conv6 -> maxpool -> conv7 ->", "input channels, 12 output channels, [8x8] kernel, initialization: xavier self.conv3 = nn.Conv2d(in_channels=8, out_channels=16,", "the network \"\"\" # Apply first convolution, followed by ReLU non-linearity; # use", "PyTorch and compare the results of with your # improved architecture. # #", "################################################################################ # PyTorch and neural network imports import torch from torch.autograd import Variable", "input channel, 4 output channels, [3x3] kernel size self.conv1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3)", "Params: ------- - batch: (Tensor) An input batch of images Returns: -------- -", "= self.fc3(batch) # Return the class predictions #TODO: apply an activition function to", "output of conv3 to the pooling layer batch = self.pool4(batch) batch = func.rrelu(self.conv7_normed(self.conv7(batch)))", "tiling (*NO SLIDING WINDOW*) self.conv7 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv7_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight)", "each layer of the network, applying non-linearities after each layer. Note that this", "torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3 self.fc3 = nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO: Output layer: what should", "self.pool1(batch) # Apply conv2 and conv3 similarly batch = func.rrelu(self.conv2_normed(self.conv2(batch))) batch = self.pool2(batch)", "self.conv3 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3) self.conv3_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4: X input", "PyTorch and neural network imports import torch from torch.autograd import Variable import torch.nn", "PyTorch to automagically perform the forward pass. Params: ------- - batch: (Tensor) An", "\"\"\"Pass the batch of images through each layer of the network, applying non-linearities", "nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3) self.conv5_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv6_normed", "batch = func.rrelu(self.fc1_normed(self.fc1(batch))) batch = func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect fc1 to fc2 - this", "out_channels=16, kernel_size=3) self.conv3_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4: X input channels, 10 output", "#TODO: conv5: X input channels, 8 output channels, [5x5] kernel, initialization: xavier self.conv5", "func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect fc1 to fc2 - this layer is slightly different than", "Winter 2019 # Code author: <NAME> (+ modifications by <NAME>) # # Filename:", "out_features be? self.out_features = 14 def forward(self, batch): \"\"\"Pass the batch of images", "2 fully connected layers: #TODO: fc1 self.fc1 = nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed = nn.BatchNorm1d(512)", "[3x3] kernel size self.conv1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3) # Add batch-normalization to the", "forward(self, batch): \"\"\"Pass the batch of images through each layer of the network,", "4 input channels, 8 output channels, [3x3] kernel, initialization: xavier self.conv2 = nn.Conv2d(in_channels=4,", "(why?) batch = self.fc3(batch) # Return the class predictions #TODO: apply an activition", "# Connect fc1 to fc2 - this layer is slightly different than the", "inputs size = inputs.size()[1:] # Track the number of features num_features = 1", "called \"forward\" for PyTorch to automagically perform the forward pass. Params: ------- -", "# the necessary value based on the provided specs for each layer #TODO:", "# Connect the reshaped features of the pooled conv3 to fc1 batch =", "results of with your # improved architecture. # # Be sure to fill", "weights using the Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight) self.pool1 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Fill in", "automagically perform the forward pass. Params: ------- - batch: (Tensor) An input batch", "# This file contains the starter code for the baseline architecture you will", "num_flat_features(self, inputs): # Get the dimensions of the layers excluding the inputs size", "fc2 -> fc3 (outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\" def __init__(self): super(Arch2CNN, self).__init__() # conv1:", "Reshape the output of the conv3 to pass to fully-connected layer batch =", "layer batch = batch.view(-1, self.num_flat_features(batch)) # Connect the reshaped features of the pooled", "torch_init import torch.optim as optim # Data utils and dataloader import torchvision from", "nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO: Output layer: what should out_features be? self.out_features = 14", "conv3 to pass to fully-connected layer batch = batch.view(-1, self.num_flat_features(batch)) # Connect the", "images through each layer of the network, applying non-linearities after each layer. Note", "of images through each layer of the network, applying non-linearities after each layer.", "using the Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight) self.pool1 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Fill in the", "torchvision from torchvision import transforms, utils from xray_dataloader_zscored import ChestXrayDataset, create_split_loaders import matplotlib.pyplot", "Track the number of features num_features = 1 for s in size: num_features", "#TODO: Fill in the remaining initializations replacing each '_' with # the necessary", "number of features num_features = 1 for s in size: num_features *= s", "class predictions #TODO: apply an activition function to 'batch' #batch = func.sigmoid(batch) return", "= nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3) self.conv4_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO:", "# Return the class predictions #TODO: apply an activition function to 'batch' #batch", "func.sigmoid(batch) return batch def num_flat_features(self, inputs): # Get the dimensions of the layers", "in the code in the areas marked #TODO. ################################################################################ # PyTorch and neural", "self.fc2 = nn.Linear(in_features=512, out_features=128) self.fc2_normed = nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3 self.fc3 = nn.Linear(in_features=128,", "rest (why?) batch = self.fc3(batch) # Return the class predictions #TODO: apply an", "the dimensions of the layers excluding the inputs size = inputs.size()[1:] # Track", "what should out_features be? self.out_features = 14 def forward(self, batch): \"\"\"Pass the batch", "-------- - logits: (Variable) The output of the network \"\"\" # Apply first", "replacing each '_' with # the necessary value based on the provided specs", "func.rrelu(self.conv5_normed(self.conv5(batch))) batch = func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass the output of conv3 to the pooling", "python # coding: utf-8 # In[ ]: ################################################################################ # CSE 253: Programming Assignment", "func.rrelu(self.conv4_normed(self.conv4(batch))) batch = self.pool3(batch) batch = func.rrelu(self.conv5_normed(self.conv5(batch))) batch = func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass the", "each layer #TODO: conv2: 4 input channels, 8 output channels, [3x3] kernel, initialization:", "nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Apply max-pooling with a [3x3] kernel", "batch-normalization on its outputs batch = func.rrelu(self.conv1_normed(self.conv1(batch))) batch = self.pool1(batch) # Apply conv2", "batch: (Tensor) An input batch of images Returns: -------- - logits: (Variable) The", "of conv3 to the pooling layer batch = self.pool4(batch) batch = func.rrelu(self.conv7_normed(self.conv7(batch))) batch", "np import os class Arch2CNN(nn.Module): \"\"\" <<<<<<< HEAD conv1 -> maxpool -> conv2", "253: Programming Assignment 3 # Winter 2019 # Code author: <NAME> (+ modifications", "maxpool -> conv2 -> maxpool -> conv3 -> conv4 ->maxpool -> conv5 ->", "- logits: (Variable) The output of the network \"\"\" # Apply first convolution,", "------- - batch: (Tensor) An input batch of images Returns: -------- - logits:", "-> maxpool -> fc1 -> fc2 -> fc3 (outputs) ======= conv1 -> conv2", "torchvision import transforms, utils from xray_dataloader_zscored import ChestXrayDataset, create_split_loaders import matplotlib.pyplot as plt", "conv3 -> conv4 -> conv5 -> maxpool -> fc1 -> fc2 -> fc3", "(Variable) The output of the network \"\"\" # Apply first convolution, followed by", "as nn import torch.nn.functional as func import torch.nn.init as torch_init import torch.optim as", "network, applying non-linearities after each layer. Note that this function *needs* to be", "[3x3] kernel using tiling (*NO SLIDING WINDOW*) self.conv7 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv7_normed", "======= conv1 -> conv2 -> maxpool -> conv3 -> conv4 -> conv5 ->", "input batch of images Returns: -------- - logits: (Variable) The output of the", "= func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect fc1 to fc2 - this layer is slightly different", "channels, 12 output channels, [8x8] kernel, initialization: xavier self.conv3 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3)", "the outputs of conv1 self.conv1_normed = nn.BatchNorm2d(4) # Initialized weights using the Xavier-Normal", "torch_init.xavier_normal_(self.fc3.weight) #TODO: Output layer: what should out_features be? self.out_features = 14 def forward(self,", "= nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv6_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4", "The output of the network \"\"\" # Apply first convolution, followed by ReLU", "- this layer is slightly different than the rest (why?) batch = self.fc3(batch)", "SLIDING WINDOW*) self.conv7 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv7_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8 =", "Data utils and dataloader import torchvision from torchvision import transforms, utils from xray_dataloader_zscored", "= nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Fill in the remaining initializations replacing each '_' with", "# PyTorch and neural network imports import torch from torch.autograd import Variable import", "self.conv7 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv7_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8 = nn.Conv2d(in_channels=8, out_channels=8,", "the reshaped features of the pooled conv3 to fc1 batch = func.rrelu(self.fc1_normed(self.fc1(batch))) batch", "batch = func.rrelu(self.conv5_normed(self.conv5(batch))) batch = func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass the output of conv3 to", "nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4: X input channels, 10 output channels, [6x6] kernel, initialization:", "as func import torch.nn.init as torch_init import torch.optim as optim # Data utils", "slightly different than the rest (why?) batch = self.fc3(batch) # Return the class", "# Initialized weights using the Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight) self.pool1 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO:", "dimensions of the layers excluding the inputs size = inputs.size()[1:] # Track the", "\"forward\" for PyTorch to automagically perform the forward pass. Params: ------- - batch:", "code in the areas marked #TODO. ################################################################################ # PyTorch and neural network imports", "to be called \"forward\" for PyTorch to automagically perform the forward pass. Params:", "batch = self.pool3(batch) batch = func.rrelu(self.conv5_normed(self.conv5(batch))) batch = func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass the output", "conv3 to fc1 batch = func.rrelu(self.fc1_normed(self.fc1(batch))) batch = func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect fc1 to", "# # Filename: baseline_cnn.py # # Description: # # This file contains the", "with your # improved architecture. # # Be sure to fill in the", "your # improved architecture. # # Be sure to fill in the code", "fill in the code in the areas marked #TODO. ################################################################################ # PyTorch and", "batch of images Returns: -------- - logits: (Variable) The output of the network", "= self.pool1(batch) # Apply conv2 and conv3 similarly batch = func.rrelu(self.conv2_normed(self.conv2(batch))) batch =", "little practice with PyTorch and compare the results of with your # improved", "with a [3x3] kernel using tiling (*NO SLIDING WINDOW*) self.conv7 = nn.Conv2d(in_channels=8, out_channels=8,", "torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as func", "import torch.nn.functional as func import torch.nn.init as torch_init import torch.optim as optim #", "= nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv3: X input channels,", "self.fc3(batch) # Return the class predictions #TODO: apply an activition function to 'batch'", "-> fc3 (outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\" def __init__(self): super(Arch2CNN, self).__init__() # conv1: 1", "class Arch2CNN(nn.Module): \"\"\" <<<<<<< HEAD conv1 -> maxpool -> conv2 -> maxpool ->", "as np import os class Arch2CNN(nn.Module): \"\"\" <<<<<<< HEAD conv1 -> maxpool ->", "# Reshape the output of the conv3 to pass to fully-connected layer batch", "Connect fc1 to fc2 - this layer is slightly different than the rest", "torch_init.xavier_normal_(self.conv8.weight) self.pool5 = nn.MaxPool2d(kernel_size=4, stride=4) # Define 2 fully connected layers: #TODO: fc1", "apply an activition function to 'batch' #batch = func.sigmoid(batch) return batch def num_flat_features(self,", "imports import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional", "conv4 ->maxpool -> conv5 -> conv6 -> maxpool -> conv7 -> conv8 ->", "to 'batch' #batch = func.sigmoid(batch) return batch def num_flat_features(self, inputs): # Get the", "network \"\"\" # Apply first convolution, followed by ReLU non-linearity; # use batch-normalization", "layers: #TODO: fc1 self.fc1 = nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed = nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2", "Apply conv2 and conv3 similarly batch = func.rrelu(self.conv2_normed(self.conv2(batch))) batch = self.pool2(batch) batch =", "to get a little practice with PyTorch and compare the results of with", "out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO: Output layer: what should out_features be? self.out_features = 14 def", "# Filename: baseline_cnn.py # # Description: # # This file contains the starter", "of features num_features = 1 for s in size: num_features *= s return", "remaining initializations replacing each '_' with # the necessary value based on the", "the necessary value based on the provided specs for each layer #TODO: conv2:", "nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv3: X input channels, 12", "= nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv3: X input channels, 12 output channels, [8x8] kernel,", "import torch.nn.init as torch_init import torch.optim as optim # Data utils and dataloader", "# Add batch-normalization to the outputs of conv1 self.conv1_normed = nn.BatchNorm2d(4) # Initialized", "connected layers: #TODO: fc1 self.fc1 = nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed = nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO:", "layers excluding the inputs size = inputs.size()[1:] # Track the number of features", "14 def forward(self, batch): \"\"\"Pass the batch of images through each layer of", "and dataloader import torchvision from torchvision import transforms, utils from xray_dataloader_zscored import ChestXrayDataset,", "func.rrelu(self.conv3_normed(self.conv3(batch))) batch = func.rrelu(self.conv4_normed(self.conv4(batch))) batch = self.pool3(batch) batch = func.rrelu(self.conv5_normed(self.conv5(batch))) batch = func.rrelu(self.conv6_normed(self.conv6(batch)))", "kernel_size=3) self.conv7_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv8_normed = nn.BatchNorm2d(8)", "initialization: xavier self.conv3 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3) self.conv3_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4:", "function *needs* to be called \"forward\" for PyTorch to automagically perform the forward", "of conv1 self.conv1_normed = nn.BatchNorm2d(4) # Initialized weights using the Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight)", "self.pool4 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Apply max-pooling with a [3x3] kernel using tiling", "import torch.nn as nn import torch.nn.functional as func import torch.nn.init as torch_init import", "#!/usr/bin/env python # coding: utf-8 # In[ ]: ################################################################################ # CSE 253: Programming", "conv4 -> conv5 -> maxpool -> fc1 -> fc2 -> fc3 (outputs) >>>>>>>", "the results of with your # improved architecture. # # Be sure to", "nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv5: X input channels, 8 output", "self.fc1 = nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed = nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2 self.fc2 = nn.Linear(in_features=512,", "X input channels, 10 output channels, [6x6] kernel, initialization: xavier self.conv4 = nn.Conv2d(in_channels=16,", "= nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv5: X input channels, 8", "sure to fill in the code in the areas marked #TODO. ################################################################################ #", "kernel size self.conv1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3) # Add batch-normalization to the outputs", "Define 2 fully connected layers: #TODO: fc1 self.fc1 = nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed =", "to fill in the code in the areas marked #TODO. ################################################################################ # PyTorch", "fc3 self.fc3 = nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO: Output layer: what should out_features be?", "= nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3) self.conv2_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2 = nn.MaxPool2d(kernel_size=3, stride=1)", "4 output channels, [3x3] kernel size self.conv1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3) # Add", "self.conv8_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5 = nn.MaxPool2d(kernel_size=4, stride=4) # Define 2 fully connected", "= nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv6_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO:", "nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Apply max-pooling with a [3x3] kernel using tiling (*NO SLIDING", "self.pool5 = nn.MaxPool2d(kernel_size=4, stride=4) # Define 2 fully connected layers: #TODO: fc1 self.fc1", "and conv3 similarly batch = func.rrelu(self.conv2_normed(self.conv2(batch))) batch = self.pool2(batch) batch = func.rrelu(self.conv3_normed(self.conv3(batch))) batch", "baseline architecture you will use # to get a little practice with PyTorch", "################################################################################ # CSE 253: Programming Assignment 3 # Winter 2019 # Code author:", "coding: utf-8 # In[ ]: ################################################################################ # CSE 253: Programming Assignment 3 #", "on its outputs batch = func.rrelu(self.conv1_normed(self.conv1(batch))) batch = self.pool1(batch) # Apply conv2 and", "batch = self.pool1(batch) # Apply conv2 and conv3 similarly batch = func.rrelu(self.conv2_normed(self.conv2(batch))) batch", "import numpy as np import os class Arch2CNN(nn.Module): \"\"\" <<<<<<< HEAD conv1 ->", "for each layer #TODO: conv2: 4 input channels, 8 output channels, [3x3] kernel,", "out_channels=8, kernel_size=3) self.conv2_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv3:", "this function *needs* to be called \"forward\" for PyTorch to automagically perform the", "the number of features num_features = 1 for s in size: num_features *=", "2019 # Code author: <NAME> (+ modifications by <NAME>) # # Filename: baseline_cnn.py", "kernel_size=3) self.conv6_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Apply max-pooling with", "(outputs) ======= conv1 -> conv2 -> maxpool -> conv3 -> conv4 -> conv5", "Programming Assignment 3 # Winter 2019 # Code author: <NAME> (+ modifications by", "kernel, initialization: xavier self.conv5 = nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3) self.conv5_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6", "import ChestXrayDataset, create_split_loaders import matplotlib.pyplot as plt import numpy as np import os", "get a little practice with PyTorch and compare the results of with your", "fully connected layers: #TODO: fc1 self.fc1 = nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed = nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight)", "stride=1) #TODO: Apply max-pooling with a [3x3] kernel using tiling (*NO SLIDING WINDOW*)", "Output layer: what should out_features be? self.out_features = 14 def forward(self, batch): \"\"\"Pass", "stride=1) #TODO: Fill in the remaining initializations replacing each '_' with # the", "conv1: 1 input channel, 4 output channels, [3x3] kernel size self.conv1 = nn.Conv2d(in_channels=1,", "= nn.Linear(in_features=512, out_features=128) self.fc2_normed = nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3 self.fc3 = nn.Linear(in_features=128, out_features=14)", "of the network \"\"\" # Apply first convolution, followed by ReLU non-linearity; #", "batch = func.rrelu(self.conv7_normed(self.conv7(batch))) batch = func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass the output of conv3 to", "func.rrelu(self.conv7_normed(self.conv7(batch))) batch = func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass the output of conv3 to the pooling", "10 output channels, [6x6] kernel, initialization: xavier self.conv4 = nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3) self.conv4_normed", "of with your # improved architecture. # # Be sure to fill in", "WINDOW*) self.conv7 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv7_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8 = nn.Conv2d(in_channels=8,", "batch = self.pool2(batch) batch = func.rrelu(self.conv3_normed(self.conv3(batch))) batch = func.rrelu(self.conv4_normed(self.conv4(batch))) batch = self.pool3(batch) batch", "maxpool -> fc1 -> fc2 -> fc3 (outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\" def __init__(self):", "6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\" def __init__(self): super(Arch2CNN, self).__init__() # conv1: 1 input channel, 4 output", "#TODO: apply an activition function to 'batch' #batch = func.sigmoid(batch) return batch def", "-> fc1 -> fc2 -> fc3 (outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\" def __init__(self): super(Arch2CNN,", "in the remaining initializations replacing each '_' with # the necessary value based", "12 output channels, [8x8] kernel, initialization: xavier self.conv3 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3) self.conv3_normed", "Apply first convolution, followed by ReLU non-linearity; # use batch-normalization on its outputs", "a [3x3] kernel using tiling (*NO SLIDING WINDOW*) self.conv7 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3)", "torch_init.xavier_normal_(self.conv7.weight) self.conv8 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv8_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5 = nn.MaxPool2d(kernel_size=4,", "channel, 4 output channels, [3x3] kernel size self.conv1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3) #", "Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight) self.pool1 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Fill in the remaining initializations", "to automagically perform the forward pass. Params: ------- - batch: (Tensor) An input", "self.conv7_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv8_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight)", "HEAD conv1 -> maxpool -> conv2 -> maxpool -> conv3 -> conv4 ->maxpool", "layer: what should out_features be? self.out_features = 14 def forward(self, batch): \"\"\"Pass the", "is slightly different than the rest (why?) batch = self.fc3(batch) # Return the", "compare the results of with your # improved architecture. # # Be sure", "# conv1: 1 input channel, 4 output channels, [3x3] kernel size self.conv1 =", "improved architecture. # # Be sure to fill in the code in the", "# Apply first convolution, followed by ReLU non-linearity; # use batch-normalization on its", "(outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\" def __init__(self): super(Arch2CNN, self).__init__() # conv1: 1 input channel,", "from torchvision import transforms, utils from xray_dataloader_zscored import ChestXrayDataset, create_split_loaders import matplotlib.pyplot as", "# improved architecture. # # Be sure to fill in the code in", "conv5 -> conv6 -> maxpool -> conv7 -> conv8 -> maxpool -> fc1", "to fc2 - this layer is slightly different than the rest (why?) batch", "kernel, initialization: xavier self.conv4 = nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3) self.conv4_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3", "predictions #TODO: apply an activition function to 'batch' #batch = func.sigmoid(batch) return batch", "= nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Apply max-pooling with a [3x3] kernel using tiling (*NO", "after each layer. Note that this function *needs* to be called \"forward\" for", "#Maxpool self.pool2 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv3: X input channels, 12 output channels,", "fc1 -> fc2 -> fc3 (outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\" def __init__(self): super(Arch2CNN, self).__init__()", "nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv6_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Apply", "by ReLU non-linearity; # use batch-normalization on its outputs batch = func.rrelu(self.conv1_normed(self.conv1(batch))) batch", "file contains the starter code for the baseline architecture you will use #", "self.pool2 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv3: X input channels, 12 output channels, [8x8]", "self.conv8 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv8_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5 = nn.MaxPool2d(kernel_size=4, stride=4)", "= nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4: X input channels, 10 output channels, [6x6] kernel,", "maxpool -> fc1 -> fc2 -> fc3 (outputs) ======= conv1 -> conv2 ->", "nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv6_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4 =", "<<<<<<< HEAD conv1 -> maxpool -> conv2 -> maxpool -> conv3 -> conv4", "fc1 batch = func.rrelu(self.fc1_normed(self.fc1(batch))) batch = func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect fc1 to fc2 -", "# # Be sure to fill in the code in the areas marked", "ChestXrayDataset, create_split_loaders import matplotlib.pyplot as plt import numpy as np import os class", "input channels, 10 output channels, [6x6] kernel, initialization: xavier self.conv4 = nn.Conv2d(in_channels=16, out_channels=16,", "areas marked #TODO. ################################################################################ # PyTorch and neural network imports import torch from", "this layer is slightly different than the rest (why?) batch = self.fc3(batch) #", "Note that this function *needs* to be called \"forward\" for PyTorch to automagically", "torch_init.xavier_normal_(self.conv6.weight) self.pool4 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Apply max-pooling with a [3x3] kernel using", "practice with PyTorch and compare the results of with your # improved architecture.", "initialization: xavier self.conv5 = nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3) self.conv5_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6 =", "nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv8_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5 =", "forward pass. Params: ------- - batch: (Tensor) An input batch of images Returns:", "fc2 -> fc3 (outputs) ======= conv1 -> conv2 -> maxpool -> conv3 ->", "a little practice with PyTorch and compare the results of with your #", "import matplotlib.pyplot as plt import numpy as np import os class Arch2CNN(nn.Module): \"\"\"", "= func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass the output of conv3 to the pooling layer batch", "network imports import torch from torch.autograd import Variable import torch.nn as nn import", "to the outputs of conv1 self.conv1_normed = nn.BatchNorm2d(4) # Initialized weights using the", "def forward(self, batch): \"\"\"Pass the batch of images through each layer of the", "max-pooling with a [3x3] kernel using tiling (*NO SLIDING WINDOW*) self.conv7 = nn.Conv2d(in_channels=8,", "on the provided specs for each layer #TODO: conv2: 4 input channels, 8", "An input batch of images Returns: -------- - logits: (Variable) The output of", "Initialized weights using the Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight) self.pool1 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Fill", "for the baseline architecture you will use # to get a little practice", "matplotlib.pyplot as plt import numpy as np import os class Arch2CNN(nn.Module): \"\"\" <<<<<<<", "out_channels=16, kernel_size=3) self.conv4_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv5: X", "#TODO: conv3: X input channels, 12 output channels, [8x8] kernel, initialization: xavier self.conv3", "nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3) self.conv4_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv5:", "= func.rrelu(self.fc1_normed(self.fc1(batch))) batch = func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect fc1 to fc2 - this layer", "the output of conv3 to the pooling layer batch = self.pool4(batch) batch =", "self.conv4 = nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3) self.conv4_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3 = nn.MaxPool2d(kernel_size=3, stride=1)", "of images Returns: -------- - logits: (Variable) The output of the network \"\"\"", "the conv3 to pass to fully-connected layer batch = batch.view(-1, self.num_flat_features(batch)) # Connect", "fc3 (outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\" def __init__(self): super(Arch2CNN, self).__init__() # conv1: 1 input", "self).__init__() # conv1: 1 input channel, 4 output channels, [3x3] kernel size self.conv1", "[3x3] kernel, initialization: xavier self.conv2 = nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3) self.conv2_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight)", "followed by ReLU non-linearity; # use batch-normalization on its outputs batch = func.rrelu(self.conv1_normed(self.conv1(batch)))" ]
[ "= timedelta(weeks = 1) last_week = today - delta begin_date = last_week.strftime('%Y%m%d') url", "= json.loads(json_url.read()) except: raise RuntimeError('Failed to retrive New York Times data.') if articles['status']", "= today - delta begin_date = last_week.strftime('%Y%m%d') url = 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + topic +", "1) last_week = today - delta begin_date = last_week.strftime('%Y%m%d') url = 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' +", "else: return articles['response']['docs'][0:num_of_articles - 1], articles['response']['meta']['hits'] else: raise RuntimeError('Failed to find any New", "if num_of_articles > 5: return articles['response']['docs'][0:4], articles['response']['meta']['hits'] else: return articles['response']['docs'][0:num_of_articles - 1], articles['response']['meta']['hits']", "datetime, timedelta class NewsAPI: def __init__(self, nyt_api): self.nyt_access = nyt_api def get_nyt_last_week_articles(self, topic,", "+ '&begin_date=' + begin_date + '&sort=best&type_of_material=Article&api-key=' + self.nyt_access try: json_url = urllib.request.urlopen(url) articles", "last_week.strftime('%Y%m%d') url = 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + topic + '&begin_date=' + begin_date + '&sort=best&type_of_material=Article&api-key=' +", "self.nyt_access = nyt_api def get_nyt_last_week_articles(self, topic, today): delta = timedelta(weeks = 1) last_week", "to find any New York Times articles with query.') api = NewsAPI(credentials.NYT_API) date_time_obj", "= nyt_api def get_nyt_last_week_articles(self, topic, today): delta = timedelta(weeks = 1) last_week =", "get_nyt_last_week_articles(self, topic, today): delta = timedelta(weeks = 1) last_week = today - delta", "timedelta class NewsAPI: def __init__(self, nyt_api): self.nyt_access = nyt_api def get_nyt_last_week_articles(self, topic, today):", "5: return articles['response']['docs'][0:4], articles['response']['meta']['hits'] else: return articles['response']['docs'][0:num_of_articles - 1], articles['response']['meta']['hits'] else: raise RuntimeError('Failed", "def get_nyt_last_week_articles(self, topic, today): delta = timedelta(weeks = 1) last_week = today -", "+ begin_date + '&sort=best&type_of_material=Article&api-key=' + self.nyt_access try: json_url = urllib.request.urlopen(url) articles = json.loads(json_url.read())", "New York Times articles with query.') api = NewsAPI(credentials.NYT_API) date_time_obj = datetime.now() api.get_nyt_last_week_articles('election',", "url = 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + topic + '&begin_date=' + begin_date + '&sort=best&type_of_material=Article&api-key=' + self.nyt_access", "last_week = today - delta begin_date = last_week.strftime('%Y%m%d') url = 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + topic", "nyt_api): self.nyt_access = nyt_api def get_nyt_last_week_articles(self, topic, today): delta = timedelta(weeks = 1)", "NewsAPI: def __init__(self, nyt_api): self.nyt_access = nyt_api def get_nyt_last_week_articles(self, topic, today): delta =", "York Times articles with query.') api = NewsAPI(credentials.NYT_API) date_time_obj = datetime.now() api.get_nyt_last_week_articles('election', date_time_obj)", "today - delta begin_date = last_week.strftime('%Y%m%d') url = 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + topic + '&begin_date='", "Times data.') if articles['status'] != 'OK': num_of_articles = articles['response']['docs'].length() if num_of_articles > 5:", "credentials from datetime import datetime, timedelta class NewsAPI: def __init__(self, nyt_api): self.nyt_access =", "begin_date = last_week.strftime('%Y%m%d') url = 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + topic + '&begin_date=' + begin_date +", "= 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + topic + '&begin_date=' + begin_date + '&sort=best&type_of_material=Article&api-key=' + self.nyt_access try:", "!= 'OK': num_of_articles = articles['response']['docs'].length() if num_of_articles > 5: return articles['response']['docs'][0:4], articles['response']['meta']['hits'] else:", "York Times data.') if articles['status'] != 'OK': num_of_articles = articles['response']['docs'].length() if num_of_articles >", "- delta begin_date = last_week.strftime('%Y%m%d') url = 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + topic + '&begin_date=' +", "timedelta(weeks = 1) last_week = today - delta begin_date = last_week.strftime('%Y%m%d') url =", "'&begin_date=' + begin_date + '&sort=best&type_of_material=Article&api-key=' + self.nyt_access try: json_url = urllib.request.urlopen(url) articles =", "delta = timedelta(weeks = 1) last_week = today - delta begin_date = last_week.strftime('%Y%m%d')", "'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + topic + '&begin_date=' + begin_date + '&sort=best&type_of_material=Article&api-key=' + self.nyt_access try: json_url", "import datetime, timedelta class NewsAPI: def __init__(self, nyt_api): self.nyt_access = nyt_api def get_nyt_last_week_articles(self,", "New York Times data.') if articles['status'] != 'OK': num_of_articles = articles['response']['docs'].length() if num_of_articles", "raise RuntimeError('Failed to find any New York Times articles with query.') api =", "articles['response']['docs'][0:4], articles['response']['meta']['hits'] else: return articles['response']['docs'][0:num_of_articles - 1], articles['response']['meta']['hits'] else: raise RuntimeError('Failed to find", "nyt_api def get_nyt_last_week_articles(self, topic, today): delta = timedelta(weeks = 1) last_week = today", "num_of_articles = articles['response']['docs'].length() if num_of_articles > 5: return articles['response']['docs'][0:4], articles['response']['meta']['hits'] else: return articles['response']['docs'][0:num_of_articles", "find any New York Times articles with query.') api = NewsAPI(credentials.NYT_API) date_time_obj =", "'&sort=best&type_of_material=Article&api-key=' + self.nyt_access try: json_url = urllib.request.urlopen(url) articles = json.loads(json_url.read()) except: raise RuntimeError('Failed", "+ self.nyt_access try: json_url = urllib.request.urlopen(url) articles = json.loads(json_url.read()) except: raise RuntimeError('Failed to", "class NewsAPI: def __init__(self, nyt_api): self.nyt_access = nyt_api def get_nyt_last_week_articles(self, topic, today): delta", "json import urllib.request import credentials from datetime import datetime, timedelta class NewsAPI: def", "return articles['response']['docs'][0:4], articles['response']['meta']['hits'] else: return articles['response']['docs'][0:num_of_articles - 1], articles['response']['meta']['hits'] else: raise RuntimeError('Failed to", "data.') if articles['status'] != 'OK': num_of_articles = articles['response']['docs'].length() if num_of_articles > 5: return", "topic + '&begin_date=' + begin_date + '&sort=best&type_of_material=Article&api-key=' + self.nyt_access try: json_url = urllib.request.urlopen(url)", "import urllib.request import credentials from datetime import datetime, timedelta class NewsAPI: def __init__(self,", "begin_date + '&sort=best&type_of_material=Article&api-key=' + self.nyt_access try: json_url = urllib.request.urlopen(url) articles = json.loads(json_url.read()) except:", "__init__(self, nyt_api): self.nyt_access = nyt_api def get_nyt_last_week_articles(self, topic, today): delta = timedelta(weeks =", "RuntimeError('Failed to find any New York Times articles with query.') api = NewsAPI(credentials.NYT_API)", "any New York Times articles with query.') api = NewsAPI(credentials.NYT_API) date_time_obj = datetime.now()", "def __init__(self, nyt_api): self.nyt_access = nyt_api def get_nyt_last_week_articles(self, topic, today): delta = timedelta(weeks", "urllib.request import credentials from datetime import datetime, timedelta class NewsAPI: def __init__(self, nyt_api):", "articles = json.loads(json_url.read()) except: raise RuntimeError('Failed to retrive New York Times data.') if", "= 1) last_week = today - delta begin_date = last_week.strftime('%Y%m%d') url = 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q='", "delta begin_date = last_week.strftime('%Y%m%d') url = 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + topic + '&begin_date=' + begin_date", "from datetime import datetime, timedelta class NewsAPI: def __init__(self, nyt_api): self.nyt_access = nyt_api", "'OK': num_of_articles = articles['response']['docs'].length() if num_of_articles > 5: return articles['response']['docs'][0:4], articles['response']['meta']['hits'] else: return", "articles['response']['docs'].length() if num_of_articles > 5: return articles['response']['docs'][0:4], articles['response']['meta']['hits'] else: return articles['response']['docs'][0:num_of_articles - 1],", "= urllib.request.urlopen(url) articles = json.loads(json_url.read()) except: raise RuntimeError('Failed to retrive New York Times", "datetime import datetime, timedelta class NewsAPI: def __init__(self, nyt_api): self.nyt_access = nyt_api def", "retrive New York Times data.') if articles['status'] != 'OK': num_of_articles = articles['response']['docs'].length() if", "json.loads(json_url.read()) except: raise RuntimeError('Failed to retrive New York Times data.') if articles['status'] !=", "json_url = urllib.request.urlopen(url) articles = json.loads(json_url.read()) except: raise RuntimeError('Failed to retrive New York", "articles['response']['meta']['hits'] else: return articles['response']['docs'][0:num_of_articles - 1], articles['response']['meta']['hits'] else: raise RuntimeError('Failed to find any", "urllib.request.urlopen(url) articles = json.loads(json_url.read()) except: raise RuntimeError('Failed to retrive New York Times data.')", "> 5: return articles['response']['docs'][0:4], articles['response']['meta']['hits'] else: return articles['response']['docs'][0:num_of_articles - 1], articles['response']['meta']['hits'] else: raise", "articles['status'] != 'OK': num_of_articles = articles['response']['docs'].length() if num_of_articles > 5: return articles['response']['docs'][0:4], articles['response']['meta']['hits']", "import credentials from datetime import datetime, timedelta class NewsAPI: def __init__(self, nyt_api): self.nyt_access", "else: raise RuntimeError('Failed to find any New York Times articles with query.') api", "to retrive New York Times data.') if articles['status'] != 'OK': num_of_articles = articles['response']['docs'].length()", "except: raise RuntimeError('Failed to retrive New York Times data.') if articles['status'] != 'OK':", "1], articles['response']['meta']['hits'] else: raise RuntimeError('Failed to find any New York Times articles with", "RuntimeError('Failed to retrive New York Times data.') if articles['status'] != 'OK': num_of_articles =", "+ '&sort=best&type_of_material=Article&api-key=' + self.nyt_access try: json_url = urllib.request.urlopen(url) articles = json.loads(json_url.read()) except: raise", "raise RuntimeError('Failed to retrive New York Times data.') if articles['status'] != 'OK': num_of_articles", "if articles['status'] != 'OK': num_of_articles = articles['response']['docs'].length() if num_of_articles > 5: return articles['response']['docs'][0:4],", "topic, today): delta = timedelta(weeks = 1) last_week = today - delta begin_date", "= last_week.strftime('%Y%m%d') url = 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + topic + '&begin_date=' + begin_date + '&sort=best&type_of_material=Article&api-key='", "+ topic + '&begin_date=' + begin_date + '&sort=best&type_of_material=Article&api-key=' + self.nyt_access try: json_url =", "num_of_articles > 5: return articles['response']['docs'][0:4], articles['response']['meta']['hits'] else: return articles['response']['docs'][0:num_of_articles - 1], articles['response']['meta']['hits'] else:", "articles['response']['meta']['hits'] else: raise RuntimeError('Failed to find any New York Times articles with query.')", "import json import urllib.request import credentials from datetime import datetime, timedelta class NewsAPI:", "= articles['response']['docs'].length() if num_of_articles > 5: return articles['response']['docs'][0:4], articles['response']['meta']['hits'] else: return articles['response']['docs'][0:num_of_articles -", "- 1], articles['response']['meta']['hits'] else: raise RuntimeError('Failed to find any New York Times articles", "today): delta = timedelta(weeks = 1) last_week = today - delta begin_date =", "self.nyt_access try: json_url = urllib.request.urlopen(url) articles = json.loads(json_url.read()) except: raise RuntimeError('Failed to retrive", "try: json_url = urllib.request.urlopen(url) articles = json.loads(json_url.read()) except: raise RuntimeError('Failed to retrive New", "articles['response']['docs'][0:num_of_articles - 1], articles['response']['meta']['hits'] else: raise RuntimeError('Failed to find any New York Times", "return articles['response']['docs'][0:num_of_articles - 1], articles['response']['meta']['hits'] else: raise RuntimeError('Failed to find any New York" ]
[ "str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" + str(i)), start_time=start_time + datetime.timedelta(hours=i), end_time=end_time + datetime.timedelta(hours=i), creation_time=creation_time +", "} for i in range(10) ], \"NextToken\": \"100\", }, { \"TrialComponentSummaries\": [ {", "{\"NumberValue\": 1.0}, \"F\": {\"StringValue\": \"G\"}}, \"InputArtifacts\": {\"H\": {\"Value\": \"s3://foo/bar\", \"MediaType\": \"text/plain\"}}, \"OutputArtifacts\": {\"I\":", "display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value = {} obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def test_boto_ignore(): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\")", "assert \"foo\" == obj.trial_component_name assert \"bar\" == obj.display_name assert \"bazz\" == obj.trial_component_arn def", "}, ] expected = [ api_types.TrialComponentSummary( trial_component_name=\"A\" + str(i), trial_component_arn=\"B\" + str(i), display_name=\"C\"", "ANY KIND, either express or implied. See the License for the specific #", "# language governing permissions and limitations under the License. from smexperiments import trial_component,", "\"OutputArtifacts\": {\"I\": {\"Value\": \"s3://whizz/bang\", \"MediaType\": \"text/plain\"}}, \"Metrics\": [ { \"MetricName\": \"J\", \"Count\": 1,", "test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value = {\"TrialComponentSummaries\": []} assert [] == list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def test_list_trial_components_call_args(sagemaker_boto_client): created_before =", "\"G\"}}, \"InputArtifacts\": {\"H\": {\"Value\": \"s3://foo/bar\", \"MediaType\": \"text/plain\"}}, \"OutputArtifacts\": {\"I\": {\"Value\": \"s3://whizz/bang\", \"MediaType\": \"text/plain\"}},", "{} assert [] == list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name, experiment_name=experiment_name, created_before=created_before, created_after=created_after, next_token=next_token, max_results=max_results,", "+ str(i), \"DisplayName\": \"C\" + str(i), \"SourceArn\": \"D\" + str(i), \"Status\": {\"PrimaryStatus\": \"InProgress\",", "\"Min\": 1.0, \"Max\": 2.0, \"Avg\": 3.0, \"StdDev\": 4.0, \"SourceArn\": \"K\", \"Timestamp\": now, }", "obj.trial_component_name assert \"C\" == obj.display_name assert api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") == obj.status assert {\"E\": 1.0,", "\"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"E\" + str(i)}, \"StartTime\": start_time + datetime.timedelta(hours=i), \"EndTime\": end_time", "[ { \"MetricName\": \"J\", \"Count\": 1, \"Min\": 1.0, \"Max\": 2.0, \"Avg\": 3.0, \"StdDev\":", "See the License for the specific # language governing permissions and limitations under", "str(i)}, \"StartTime\": start_time + datetime.timedelta(hours=i), \"EndTime\": end_time + datetime.timedelta(hours=i), \"CreationTime\": creation_time + datetime.timedelta(hours=i),", "\"Max\": 2.0, \"Avg\": 3.0, \"StdDev\": 4.0, \"SourceArn\": \"K\", \"Timestamp\": now, } ], }", "== sagemaker_boto_client.list_trial_components.mock_calls def test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value = {\"TrialComponentSummaries\": []} assert [] == list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def", "the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the", "import trial_component, api_types import datetime import pytest import unittest.mock @pytest.fixture def sagemaker_boto_client(): return", "# # http://aws.amazon.com/apache2.0/ # # or in the \"license\" file accompanying this file.", "obj.trial_component_name assert \"bar\" == obj.display_name assert \"bazz\" == obj.trial_component_arn def test_load(sagemaker_boto_client): now =", ") ] def test_list(sagemaker_boto_client): start_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) end_time = datetime.datetime.now(datetime.timezone.utc) +", "MaxResults=99, ) ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_save(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\",", "\"text/plain\"}}, \"Metrics\": [ { \"MetricName\": \"J\", \"Count\": 1, \"Min\": 1.0, \"Max\": 2.0, \"Avg\":", "{\"Value\": \"s3://foo/bar\", \"MediaType\": \"text/plain\"}}, \"OutputArtifacts\": {\"I\": {\"Value\": \"s3://whizz/bang\", \"MediaType\": \"text/plain\"}}, \"Metrics\": [ {", "created_before=created_before, created_after=created_after, next_token=next_token, max_results=max_results, sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) expected_calls = [ unittest.mock.call( TrialName=\"foo-trial\",", "api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") == obj.status assert {\"E\": 1.0, \"F\": \"G\"} == obj.parameters assert {\"H\":", "\"TrialComponentArn\": \"A\", \"TrialComponentName\": \"B\", \"DisplayName\": \"C\", \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"D\"}, \"Parameters\": {\"E\":", "} obj = trial_component.TrialComponent.create( trial_component_name=\"foo\", display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client ) sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") assert \"foo\" ==", "0) trial_name = \"foo-trial\" experiment_name = \"foo-experiment\" next_token = \"<PASSWORD>\" max_results = 99", "= {} obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") def test_delete(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value", "distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY", "permissions and limitations under the License. from smexperiments import trial_component, api_types import datetime", "= [ unittest.mock.call( TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\", CreatedBefore=created_before, CreatedAfter=created_after, SortBy=\"CreationTime\", SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\", MaxResults=99, ) ]", "+ str(i), source_arn=\"D\" + str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" + str(i)), start_time=start_time + datetime.timedelta(hours=i), end_time=end_time", "[ unittest.mock.call( TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\", CreatedBefore=created_before, CreatedAfter=created_after, SortBy=\"CreationTime\", SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\", MaxResults=99, ) ] assert", "\"s3://foo/bar\", \"MediaType\": \"text/plain\"}}, \"OutputArtifacts\": {\"I\": {\"Value\": \"s3://whizz/bang\", \"MediaType\": \"text/plain\"}}, \"Metrics\": [ { \"MetricName\":", "test_delete(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value = {} obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def test_boto_ignore():", "expected = [ api_types.TrialComponentSummary( trial_component_name=\"A\" + str(i), trial_component_arn=\"B\" + str(i), display_name=\"C\" + str(i),", "\"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"D\"}, \"Parameters\": {\"E\": {\"NumberValue\": 1.0}, \"F\": {\"StringValue\": \"G\"}}, \"InputArtifacts\":", "2.0 (the \"License\"). You # may not use this file except in compliance", "{\"PrimaryStatus\": \"InProgress\", \"Message\": \"E\" + str(i)}, \"StartTime\": start_time + datetime.timedelta(hours=i), \"EndTime\": end_time +", "for the specific # language governing permissions and limitations under the License. from", "SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\", MaxResults=99, ) ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_save(sagemaker_boto_client): obj =", "= datetime.datetime(1990, 10, 12, 0, 0, 0) trial_name = \"foo-trial\" experiment_name = \"foo-experiment\"", "sagemaker_boto_client.list_trial_components.mock_calls def test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value = {\"TrialComponentSummaries\": []} assert [] == list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def test_list_trial_components_call_args(sagemaker_boto_client):", "datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) end_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2) creation_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=3)", "min=1.0, max=2.0, avg=3.0, std_dev=4.0, source_arn=\"K\", timestamp=now ) ] def test_list(sagemaker_boto_client): start_time = datetime.datetime.now(datetime.timezone.utc)", "def test_list_trial_components_call_args(sagemaker_boto_client): created_before = datetime.datetime(1999, 10, 12, 0, 0, 0) created_after = datetime.datetime(1990,", "file accompanying this file. This file is # distributed on an \"AS IS\"", "and limitations under the License. from smexperiments import trial_component, api_types import datetime import", "obj = trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert \"A\" == obj.trial_component_arn assert \"B\" == obj.trial_component_name", "obj.parameters assert {\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")} assert {\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")} assert [ api_types.TrialComponentMetricSummary( metric_name=\"J\",", "sagemaker_boto_client.list_trial_components.return_value = {\"TrialComponentSummaries\": []} assert [] == list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def test_list_trial_components_call_args(sagemaker_boto_client): created_before = datetime.datetime(1999,", "\"C\", \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"D\"}, \"Parameters\": {\"E\": {\"NumberValue\": 1.0}, \"F\": {\"StringValue\": \"G\"}},", "under the Apache License, Version 2.0 (the \"License\"). You # may not use", "list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def test_list_trial_components_call_args(sagemaker_boto_client): created_before = datetime.datetime(1999, 10, 12, 0, 0, 0) created_after =", "timestamp=now ) ] def test_list(sagemaker_boto_client): start_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) end_time = datetime.datetime.now(datetime.timezone.utc)", "this file except in compliance with the License. A copy of # the", "\"A\" + str(i), \"TrialComponentArn\": \"B\" + str(i), \"DisplayName\": \"C\" + str(i), \"SourceArn\": \"D\"", "[ { \"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\": \"B\" + str(i), \"DisplayName\": \"C\" +", "{ \"TrialComponentArn\": \"bazz\", } obj = trial_component.TrialComponent.create( trial_component_name=\"foo\", display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client ) sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\")", "expected_calls = [ unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), ] assert expected_calls", "sagemaker_boto_client.describe_trial_component.return_value = { \"TrialComponentArn\": \"A\", \"TrialComponentName\": \"B\", \"DisplayName\": \"C\", \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\":", "located at # # http://aws.amazon.com/apache2.0/ # # or in the \"license\" file accompanying", "now, } ], } obj = trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert \"A\" == obj.trial_component_arn", "except in compliance with the License. A copy of # the License is", "count=1, min=1.0, max=2.0, avg=3.0, std_dev=4.0, source_arn=\"K\", timestamp=now ) ] def test_list(sagemaker_boto_client): start_time =", "All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the", "the specific # language governing permissions and limitations under the License. from smexperiments", "{} obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") def test_delete(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value =", "+ str(i), \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"E\" + str(i)}, \"StartTime\": start_time + datetime.timedelta(hours=i),", "+ str(i), trial_component_arn=\"B\" + str(i), display_name=\"C\" + str(i), source_arn=\"D\" + str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\"", "sagemaker_boto_client.list_trial_components.mock_calls def test_save(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value = {} obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\",", "api_types.TrialComponentSummary( trial_component_name=\"A\" + str(i), trial_component_arn=\"B\" + str(i), display_name=\"C\" + str(i), source_arn=\"D\" + str(i),", "= \"<PASSWORD>\" max_results = 99 sagemaker_boto_client.list_trial_components.return_value = {} assert [] == list( trial_component.TrialComponent.list(", "obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") def test_delete(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value = {}", "start_time=start_time + datetime.timedelta(hours=i), end_time=end_time + datetime.timedelta(hours=i), creation_time=creation_time + datetime.timedelta(hours=i), last_modified_time=last_modified_time + datetime.timedelta(hours=i), last_modified_by={},", "this file. This file is # distributed on an \"AS IS\" BASIS, WITHOUT", "\"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\": \"B\" + str(i), \"DisplayName\": \"C\"", "+ datetime.timedelta(hours=1) end_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2) creation_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=3) last_modified_time", "{}, } for i in range(10, 20) ] }, ] expected = [", "datetime.timedelta(hours=2) creation_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=3) last_modified_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect =", "== obj.display_name assert \"bazz\" == obj.trial_component_arn def test_load(sagemaker_boto_client): now = datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value =", "str(i), display_name=\"C\" + str(i), source_arn=\"D\" + str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" + str(i)), start_time=start_time +", "assert [ api_types.TrialComponentMetricSummary( metric_name=\"J\", count=1, min=1.0, max=2.0, avg=3.0, std_dev=4.0, source_arn=\"K\", timestamp=now ) ]", "datetime.timedelta(hours=i), \"CreationTime\": creation_time + datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for", "# http://aws.amazon.com/apache2.0/ # # or in the \"license\" file accompanying this file. This", "2.0, \"Avg\": 3.0, \"StdDev\": 4.0, \"SourceArn\": \"K\", \"Timestamp\": now, } ], } obj", "obj.display_name assert api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") == obj.status assert {\"E\": 1.0, \"F\": \"G\"} == obj.parameters", "sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert \"A\" == obj.trial_component_arn assert \"B\" == obj.trial_component_name assert \"C\" == obj.display_name", "\"s3://whizz/bang\", \"MediaType\": \"text/plain\"}}, \"Metrics\": [ { \"MetricName\": \"J\", \"Count\": 1, \"Min\": 1.0, \"Max\":", "compliance with the License. A copy of # the License is located at", "metric_name=\"J\", count=1, min=1.0, max=2.0, avg=3.0, std_dev=4.0, source_arn=\"K\", timestamp=now ) ] def test_list(sagemaker_boto_client): start_time", "sort_order=\"Ascending\", ) ) expected_calls = [ unittest.mock.call( TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\", CreatedBefore=created_before, CreatedAfter=created_after, SortBy=\"CreationTime\", SortOrder=\"Ascending\",", "trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\", sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) assert expected == result expected_calls =", "+ datetime.timedelta(hours=i), \"CreationTime\": creation_time + datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {}, }", "{\"E\": 1.0, \"F\": \"G\"} == obj.parameters assert {\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")} assert {\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\",", "end_time + datetime.timedelta(hours=i), \"CreationTime\": creation_time + datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {},", "str(i), \"DisplayName\": \"C\" + str(i), \"SourceArn\": \"D\" + str(i), \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\":", "\"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in range(10) ], \"NextToken\":", "\"EndTime\": end_time + datetime.timedelta(hours=i), \"CreationTime\": creation_time + datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\":", "DisplayName=\"bar\") assert \"foo\" == obj.trial_component_name assert \"bar\" == obj.display_name assert \"bazz\" == obj.trial_component_arn", "{} obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def test_boto_ignore(): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") assert obj._boto_ignore() ==", "sagemaker_boto_client=sagemaker_boto_client ) sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") assert \"foo\" == obj.trial_component_name assert \"bar\" == obj.display_name assert", "] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_save(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value", "SourceArn=\"foo\"), ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value = {\"TrialComponentSummaries\": []} assert", "trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value = {} obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") def test_delete(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client,", "file is # distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value = {} obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") def test_delete(sagemaker_boto_client):", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied.", "= datetime.datetime(1999, 10, 12, 0, 0, 0) created_after = datetime.datetime(1990, 10, 12, 0,", "on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND,", "\"E\" + str(i)}, \"StartTime\": start_time + datetime.timedelta(hours=i), \"EndTime\": end_time + datetime.timedelta(hours=i), \"CreationTime\": creation_time", "def sagemaker_boto_client(): return unittest.mock.Mock() def test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value = { \"TrialComponentArn\": \"bazz\", } obj", "range(10, 20) ] }, ] expected = [ api_types.TrialComponentSummary( trial_component_name=\"A\" + str(i), trial_component_arn=\"B\"", "\"StartTime\": start_time + datetime.timedelta(hours=i), \"EndTime\": end_time + datetime.timedelta(hours=i), \"CreationTime\": creation_time + datetime.timedelta(hours=i), \"LastModifiedTime\":", "20) ] }, ] expected = [ api_types.TrialComponentSummary( trial_component_name=\"A\" + str(i), trial_component_arn=\"B\" +", "ExperimentName=\"foo-experiment\", CreatedBefore=created_before, CreatedAfter=created_after, SortBy=\"CreationTime\", SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\", MaxResults=99, ) ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls", "i in range(10, 20) ] }, ] expected = [ api_types.TrialComponentSummary( trial_component_name=\"A\" +", "last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in range(10) ], \"NextToken\": \"100\",", "\"D\" + str(i), \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"E\" + str(i)}, \"StartTime\": start_time +", "SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value = {\"TrialComponentSummaries\":", "obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def test_boto_ignore(): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") assert obj._boto_ignore() == [\"ResponseMetadata\",", "License. from smexperiments import trial_component, api_types import datetime import pytest import unittest.mock @pytest.fixture", "SortBy=\"CreationTime\", SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\", MaxResults=99, ) ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_save(sagemaker_boto_client): obj", "\"J\", \"Count\": 1, \"Min\": 1.0, \"Max\": 2.0, \"Avg\": 3.0, \"StdDev\": 4.0, \"SourceArn\": \"K\",", "http://aws.amazon.com/apache2.0/ # # or in the \"license\" file accompanying this file. This file", "\"100\", }, { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\": \"B\" +", "unittest.mock.Mock() def test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value = { \"TrialComponentArn\": \"bazz\", } obj = trial_component.TrialComponent.create( trial_component_name=\"foo\",", "\"LastModifiedBy\": {}, } for i in range(10, 20) ] }, ] expected =", "== obj.trial_component_arn def test_load(sagemaker_boto_client): now = datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value = { \"TrialComponentArn\": \"A\", \"TrialComponentName\":", "end_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2) creation_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=3) last_modified_time = datetime.datetime.now(datetime.timezone.utc)", "trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name, experiment_name=experiment_name, created_before=created_before, created_after=created_after, next_token=next_token, max_results=max_results, sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) expected_calls", "assert \"bazz\" == obj.trial_component_arn def test_load(sagemaker_boto_client): now = datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value = { \"TrialComponentArn\":", "\"TrialComponentArn\": \"B\" + str(i), \"DisplayName\": \"C\" + str(i), \"SourceArn\": \"D\" + str(i), \"Status\":", "trial_name = \"foo-trial\" experiment_name = \"foo-experiment\" next_token = \"<PASSWORD>\" max_results = 99 sagemaker_boto_client.list_trial_components.return_value", "This file is # distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "== obj.trial_component_arn assert \"B\" == obj.trial_component_name assert \"C\" == obj.display_name assert api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\")", "datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=3) last_modified_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect = [ { \"TrialComponentSummaries\":", "test_list_trial_components_call_args(sagemaker_boto_client): created_before = datetime.datetime(1999, 10, 12, 0, 0, 0) created_after = datetime.datetime(1990, 10,", "trial_name=trial_name, experiment_name=experiment_name, created_before=created_before, created_after=created_after, next_token=next_token, max_results=max_results, sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) expected_calls = [", "NextToken=\"<PASSWORD>token\", MaxResults=99, ) ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_save(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client,", "api_types import datetime import pytest import unittest.mock @pytest.fixture def sagemaker_boto_client(): return unittest.mock.Mock() def", "\"D\"}, \"Parameters\": {\"E\": {\"NumberValue\": 1.0}, \"F\": {\"StringValue\": \"G\"}}, \"InputArtifacts\": {\"H\": {\"Value\": \"s3://foo/bar\", \"MediaType\":", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or", "12, 0, 0, 0) created_after = datetime.datetime(1990, 10, 12, 0, 0, 0) trial_name", "== sagemaker_boto_client.list_trial_components.mock_calls def test_save(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value = {} obj.save()", "Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\"). You", "{}, } for i in range(10) ], \"NextToken\": \"100\", }, { \"TrialComponentSummaries\": [", "+ str(i), \"SourceArn\": \"D\" + str(i), \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"E\" + str(i)},", "\"B\", \"DisplayName\": \"C\", \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"D\"}, \"Parameters\": {\"E\": {\"NumberValue\": 1.0}, \"F\":", "\"StdDev\": 4.0, \"SourceArn\": \"K\", \"Timestamp\": now, } ], } obj = trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client)", "\"SourceArn\": \"D\" + str(i), \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"E\" + str(i)}, \"StartTime\": start_time", "== obj.trial_component_name assert \"bar\" == obj.display_name assert \"bazz\" == obj.trial_component_arn def test_load(sagemaker_boto_client): now", "sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) expected_calls = [ unittest.mock.call( TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\", CreatedBefore=created_before, CreatedAfter=created_after, SortBy=\"CreationTime\",", "assert [] == list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def test_list_trial_components_call_args(sagemaker_boto_client): created_before = datetime.datetime(1999, 10, 12, 0, 0,", "datetime.datetime(1999, 10, 12, 0, 0, 0) created_after = datetime.datetime(1990, 10, 12, 0, 0,", "test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value = { \"TrialComponentArn\": \"bazz\", } obj = trial_component.TrialComponent.create( trial_component_name=\"foo\", display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client", "assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value = {\"TrialComponentSummaries\": []} assert [] ==", "\"MediaType\": \"text/plain\"}}, \"OutputArtifacts\": {\"I\": {\"Value\": \"s3://whizz/bang\", \"MediaType\": \"text/plain\"}}, \"Metrics\": [ { \"MetricName\": \"J\",", "datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in range(10) ],", "= { \"TrialComponentArn\": \"bazz\", } obj = trial_component.TrialComponent.create( trial_component_name=\"foo\", display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client ) sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\",", "= datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) end_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2) creation_time = datetime.datetime.now(datetime.timezone.utc) +", "\"InputArtifacts\": {\"H\": {\"Value\": \"s3://foo/bar\", \"MediaType\": \"text/plain\"}}, \"OutputArtifacts\": {\"I\": {\"Value\": \"s3://whizz/bang\", \"MediaType\": \"text/plain\"}}, \"Metrics\":", "Licensed under the Apache License, Version 2.0 (the \"License\"). You # may not", "= { \"TrialComponentArn\": \"A\", \"TrialComponentName\": \"B\", \"DisplayName\": \"C\", \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"D\"},", "[ api_types.TrialComponentMetricSummary( metric_name=\"J\", count=1, min=1.0, max=2.0, avg=3.0, std_dev=4.0, source_arn=\"K\", timestamp=now ) ] def", "status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" + str(i)), start_time=start_time + datetime.timedelta(hours=i), end_time=end_time + datetime.timedelta(hours=i), creation_time=creation_time + datetime.timedelta(hours=i),", "== obj.trial_component_name assert \"C\" == obj.display_name assert api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") == obj.status assert {\"E\":", "limitations under the License. from smexperiments import trial_component, api_types import datetime import pytest", "== obj.parameters assert {\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")} assert {\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")} assert [ api_types.TrialComponentMetricSummary(", "# or in the \"license\" file accompanying this file. This file is #", "\"F\": {\"StringValue\": \"G\"}}, \"InputArtifacts\": {\"H\": {\"Value\": \"s3://foo/bar\", \"MediaType\": \"text/plain\"}}, \"OutputArtifacts\": {\"I\": {\"Value\": \"s3://whizz/bang\",", "= 99 sagemaker_boto_client.list_trial_components.return_value = {} assert [] == list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name, experiment_name=experiment_name,", "= trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value = {} obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") def test_delete(sagemaker_boto_client): obj", "datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value = { \"TrialComponentArn\": \"A\", \"TrialComponentName\": \"B\", \"DisplayName\": \"C\", \"Status\": {\"PrimaryStatus\": \"InProgress\",", "CreatedBefore=created_before, CreatedAfter=created_after, SortBy=\"CreationTime\", SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\", MaxResults=99, ) ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def", "result = list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\", sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) assert expected ==", "= trial_component.TrialComponent.create( trial_component_name=\"foo\", display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client ) sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") assert \"foo\" == obj.trial_component_name assert", "sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") assert \"foo\" == obj.trial_component_name assert \"bar\" == obj.display_name assert \"bazz\" ==", "] def test_list(sagemaker_boto_client): start_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) end_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2)", "trial_component_arn=\"B\" + str(i), display_name=\"C\" + str(i), source_arn=\"D\" + str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" + str(i)),", "sagemaker_boto_client.delete_trial_component.return_value = {} obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def test_boto_ignore(): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") assert", "SortOrder=\"Ascending\", SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_list_empty(sagemaker_boto_client):", "\"text/plain\"}}, \"OutputArtifacts\": {\"I\": {\"Value\": \"s3://whizz/bang\", \"MediaType\": \"text/plain\"}}, \"Metrics\": [ { \"MetricName\": \"J\", \"Count\":", "\"K\", \"Timestamp\": now, } ], } obj = trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert \"A\"", "}, { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\": \"B\" + str(i),", "def test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value = {\"TrialComponentSummaries\": []} assert [] == list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def test_list_trial_components_call_args(sagemaker_boto_client): created_before", "0, 0) trial_name = \"foo-trial\" experiment_name = \"foo-experiment\" next_token = \"<PASSWORD>\" max_results =", "datetime.timedelta(hours=i), end_time=end_time + datetime.timedelta(hours=i), creation_time=creation_time + datetime.timedelta(hours=i), last_modified_time=last_modified_time + datetime.timedelta(hours=i), last_modified_by={}, ) for", "+ datetime.timedelta(hours=i), end_time=end_time + datetime.timedelta(hours=i), creation_time=creation_time + datetime.timedelta(hours=i), last_modified_time=last_modified_time + datetime.timedelta(hours=i), last_modified_by={}, )", "= {\"TrialComponentSummaries\": []} assert [] == list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def test_list_trial_components_call_args(sagemaker_boto_client): created_before = datetime.datetime(1999, 10,", "Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\").", "datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in range(10) ], \"NextToken\": \"100\", }, {", "or its affiliates. All Rights Reserved. # # Licensed under the Apache License,", "[] == list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def test_list_trial_components_call_args(sagemaker_boto_client): created_before = datetime.datetime(1999, 10, 12, 0, 0, 0)", "] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value = {\"TrialComponentSummaries\": []} assert []", "last_modified_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect = [ { \"TrialComponentSummaries\": [ { \"TrialComponentName\":", "[]} assert [] == list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def test_list_trial_components_call_args(sagemaker_boto_client): created_before = datetime.datetime(1999, 10, 12, 0,", "from smexperiments import trial_component, api_types import datetime import pytest import unittest.mock @pytest.fixture def", "in range(20) ] result = list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\", sort_by=\"CreationTime\", sort_order=\"Ascending\", ) )", "in range(10) ], \"NextToken\": \"100\", }, { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" +", "Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache", "] }, ] expected = [ api_types.TrialComponentSummary( trial_component_name=\"A\" + str(i), trial_component_arn=\"B\" + str(i),", "def test_save(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value = {} obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\")", "api_types.TrialComponentMetricSummary( metric_name=\"J\", count=1, min=1.0, max=2.0, avg=3.0, std_dev=4.0, source_arn=\"K\", timestamp=now ) ] def test_list(sagemaker_boto_client):", "\"NextToken\": \"100\", }, { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\": \"B\"", "experiment_name = \"foo-experiment\" next_token = \"<PASSWORD>\" max_results = 99 sagemaker_boto_client.list_trial_components.return_value = {} assert", "assert [] == list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name, experiment_name=experiment_name, created_before=created_before, created_after=created_after, next_token=next_token, max_results=max_results, sort_by=\"CreationTime\",", "WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the", "datetime.timedelta(hours=i), last_modified_time=last_modified_time + datetime.timedelta(hours=i), last_modified_by={}, ) for i in range(20) ] result =", "the \"license\" file accompanying this file. This file is # distributed on an", ") ) expected_calls = [ unittest.mock.call( TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\", CreatedBefore=created_before, CreatedAfter=created_after, SortBy=\"CreationTime\", SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\",", "# # or in the \"license\" file accompanying this file. This file is", "= list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\", sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) assert expected == result", "\"CreationTime\": creation_time + datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i", "+ datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in range(10) ], \"NextToken\": \"100\", },", "# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF #", "datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect = [ { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" +", "api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")} assert {\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")} assert [ api_types.TrialComponentMetricSummary( metric_name=\"J\", count=1, min=1.0, max=2.0,", "message=\"E\" + str(i)), start_time=start_time + datetime.timedelta(hours=i), end_time=end_time + datetime.timedelta(hours=i), creation_time=creation_time + datetime.timedelta(hours=i), last_modified_time=last_modified_time", "(the \"License\"). You # may not use this file except in compliance with", "source_arn=\"K\", timestamp=now ) ] def test_list(sagemaker_boto_client): start_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) end_time =", "datetime.timedelta(hours=3) last_modified_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect = [ { \"TrialComponentSummaries\": [ {", "end_time=end_time + datetime.timedelta(hours=i), creation_time=creation_time + datetime.timedelta(hours=i), last_modified_time=last_modified_time + datetime.timedelta(hours=i), last_modified_by={}, ) for i", "sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert \"A\" == obj.trial_component_arn assert \"B\" == obj.trial_component_name assert \"C\" ==", "\"LastModifiedBy\": {}, } for i in range(10) ], \"NextToken\": \"100\", }, { \"TrialComponentSummaries\":", "== result expected_calls = [ unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), ]", "+ str(i), display_name=\"C\" + str(i), source_arn=\"D\" + str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" + str(i)), start_time=start_time", ") expected_calls = [ unittest.mock.call( TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\", CreatedBefore=created_before, CreatedAfter=created_after, SortBy=\"CreationTime\", SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\", MaxResults=99,", "max=2.0, avg=3.0, std_dev=4.0, source_arn=\"K\", timestamp=now ) ] def test_list(sagemaker_boto_client): start_time = datetime.datetime.now(datetime.timezone.utc) +", "{ \"MetricName\": \"J\", \"Count\": 1, \"Min\": 1.0, \"Max\": 2.0, \"Avg\": 3.0, \"StdDev\": 4.0,", "= {} obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def test_boto_ignore(): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") assert obj._boto_ignore()", "copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # #", "unittest.mock @pytest.fixture def sagemaker_boto_client(): return unittest.mock.Mock() def test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value = { \"TrialComponentArn\": \"bazz\",", "# the License is located at # # http://aws.amazon.com/apache2.0/ # # or in", "assert {\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")} assert [ api_types.TrialComponentMetricSummary( metric_name=\"J\", count=1, min=1.0, max=2.0, avg=3.0, std_dev=4.0,", "\"foo-experiment\" next_token = \"<PASSWORD>\" max_results = 99 sagemaker_boto_client.list_trial_components.return_value = {} assert [] ==", "{\"PrimaryStatus\": \"InProgress\", \"Message\": \"D\"}, \"Parameters\": {\"E\": {\"NumberValue\": 1.0}, \"F\": {\"StringValue\": \"G\"}}, \"InputArtifacts\": {\"H\":", "assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_save(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value =", "99 sagemaker_boto_client.list_trial_components.return_value = {} assert [] == list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name, experiment_name=experiment_name, created_before=created_before,", "sort_order=\"Ascending\", ) ) assert expected == result expected_calls = [ unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"),", "[ { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\": \"B\" + str(i),", "file. This file is # distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES", "\"Count\": 1, \"Min\": 1.0, \"Max\": 2.0, \"Avg\": 3.0, \"StdDev\": 4.0, \"SourceArn\": \"K\", \"Timestamp\":", ") for i in range(20) ] result = list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\", sort_by=\"CreationTime\",", "import unittest.mock @pytest.fixture def sagemaker_boto_client(): return unittest.mock.Mock() def test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value = { \"TrialComponentArn\":", "A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ #", "trial_component_name=\"A\" + str(i), trial_component_arn=\"B\" + str(i), display_name=\"C\" + str(i), source_arn=\"D\" + str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\",", "now = datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value = { \"TrialComponentArn\": \"A\", \"TrialComponentName\": \"B\", \"DisplayName\": \"C\", \"Status\":", "expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value = {\"TrialComponentSummaries\": []} assert [] == list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client))", "is # distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "12, 0, 0, 0) trial_name = \"foo-trial\" experiment_name = \"foo-experiment\" next_token = \"<PASSWORD>\"", "is located at # # http://aws.amazon.com/apache2.0/ # # or in the \"license\" file", "smexperiments import trial_component, api_types import datetime import pytest import unittest.mock @pytest.fixture def sagemaker_boto_client():", "{\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")} assert [ api_types.TrialComponentMetricSummary( metric_name=\"J\", count=1, min=1.0, max=2.0, avg=3.0, std_dev=4.0, source_arn=\"K\",", "\"G\"} == obj.parameters assert {\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")} assert {\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")} assert [", "+ str(i)}, \"StartTime\": start_time + datetime.timedelta(hours=i), \"EndTime\": end_time + datetime.timedelta(hours=i), \"CreationTime\": creation_time +", "\"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\": \"B\" + str(i), \"DisplayName\": \"C\" + str(i), \"SourceArn\":", "assert \"C\" == obj.display_name assert api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") == obj.status assert {\"E\": 1.0, \"F\":", "sagemaker_boto_client(): return unittest.mock.Mock() def test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value = { \"TrialComponentArn\": \"bazz\", } obj =", "\"Timestamp\": now, } ], } obj = trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert \"A\" ==", "test_load(sagemaker_boto_client): now = datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value = { \"TrialComponentArn\": \"A\", \"TrialComponentName\": \"B\", \"DisplayName\": \"C\",", "media_type=\"text/plain\")} assert [ api_types.TrialComponentMetricSummary( metric_name=\"J\", count=1, min=1.0, max=2.0, avg=3.0, std_dev=4.0, source_arn=\"K\", timestamp=now )", "trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value = {} obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def test_boto_ignore(): obj = trial_component.TrialComponent(sagemaker_boto_client,", "# may not use this file except in compliance with the License. A", "datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2) creation_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=3) last_modified_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4)", "sagemaker_boto_client.list_trial_components.return_value = {} assert [] == list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name, experiment_name=experiment_name, created_before=created_before, created_after=created_after,", "def test_list(sagemaker_boto_client): start_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) end_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2) creation_time", "+ datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in range(10,", "\"InProgress\", \"Message\": \"E\" + str(i)}, \"StartTime\": start_time + datetime.timedelta(hours=i), \"EndTime\": end_time + datetime.timedelta(hours=i),", "{ \"TrialComponentArn\": \"A\", \"TrialComponentName\": \"B\", \"DisplayName\": \"C\", \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"D\"}, \"Parameters\":", "datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in range(10, 20)", "expected == result expected_calls = [ unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"),", "Version 2.0 (the \"License\"). You # may not use this file except in", "{\"E\": {\"NumberValue\": 1.0}, \"F\": {\"StringValue\": \"G\"}}, \"InputArtifacts\": {\"H\": {\"Value\": \"s3://foo/bar\", \"MediaType\": \"text/plain\"}}, \"OutputArtifacts\":", "License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/", "1.0, \"Max\": 2.0, \"Avg\": 3.0, \"StdDev\": 4.0, \"SourceArn\": \"K\", \"Timestamp\": now, } ],", "+ datetime.timedelta(hours=2) creation_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=3) last_modified_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect", "std_dev=4.0, source_arn=\"K\", timestamp=now ) ] def test_list(sagemaker_boto_client): start_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) end_time", "created_after = datetime.datetime(1990, 10, 12, 0, 0, 0) trial_name = \"foo-trial\" experiment_name =", "list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name, experiment_name=experiment_name, created_before=created_before, created_after=created_after, next_token=next_token, max_results=max_results, sort_by=\"CreationTime\", sort_order=\"Ascending\", ) )", "{\"I\": {\"Value\": \"s3://whizz/bang\", \"MediaType\": \"text/plain\"}}, \"Metrics\": [ { \"MetricName\": \"J\", \"Count\": 1, \"Min\":", "trial_component.TrialComponent.create( trial_component_name=\"foo\", display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client ) sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") assert \"foo\" == obj.trial_component_name assert \"bar\"", "in compliance with the License. A copy of # the License is located", "\"Parameters\": {\"E\": {\"NumberValue\": 1.0}, \"F\": {\"StringValue\": \"G\"}}, \"InputArtifacts\": {\"H\": {\"Value\": \"s3://foo/bar\", \"MediaType\": \"text/plain\"}},", "1, \"Min\": 1.0, \"Max\": 2.0, \"Avg\": 3.0, \"StdDev\": 4.0, \"SourceArn\": \"K\", \"Timestamp\": now,", "], } obj = trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert \"A\" == obj.trial_component_arn assert \"B\"", "+ datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect = [ { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" + str(i),", "str(i), \"TrialComponentArn\": \"B\" + str(i), \"DisplayName\": \"C\" + str(i), \"SourceArn\": \"D\" + str(i),", "avg=3.0, std_dev=4.0, source_arn=\"K\", timestamp=now ) ] def test_list(sagemaker_boto_client): start_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1)", "\"A\" == obj.trial_component_arn assert \"B\" == obj.trial_component_name assert \"C\" == obj.display_name assert api_types.TrialComponentStatus(primary_status=\"InProgress\",", "in range(10, 20) ] }, ] expected = [ api_types.TrialComponentSummary( trial_component_name=\"A\" + str(i),", "\"bazz\", } obj = trial_component.TrialComponent.create( trial_component_name=\"foo\", display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client ) sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") assert \"foo\"", "assert expected == result expected_calls = [ unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\", SortOrder=\"Ascending\",", "created_before = datetime.datetime(1999, 10, 12, 0, 0, 0) created_after = datetime.datetime(1990, 10, 12,", "assert {\"E\": 1.0, \"F\": \"G\"} == obj.parameters assert {\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")} assert {\"I\":", "the Apache License, Version 2.0 (the \"License\"). You # may not use this", "[ unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls", "datetime import pytest import unittest.mock @pytest.fixture def sagemaker_boto_client(): return unittest.mock.Mock() def test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value", "sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) assert expected == result expected_calls = [ unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\",", "+ datetime.timedelta(hours=i), last_modified_by={}, ) for i in range(20) ] result = list( trial_component.TrialComponent.list(", "= datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=3) last_modified_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect = [ {", "return unittest.mock.Mock() def test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value = { \"TrialComponentArn\": \"bazz\", } obj = trial_component.TrialComponent.create(", "for i in range(10) ], \"NextToken\": \"100\", }, { \"TrialComponentSummaries\": [ { \"TrialComponentName\":", "\"Message\": \"D\"}, \"Parameters\": {\"E\": {\"NumberValue\": 1.0}, \"F\": {\"StringValue\": \"G\"}}, \"InputArtifacts\": {\"H\": {\"Value\": \"s3://foo/bar\",", "} for i in range(10, 20) ] }, ] expected = [ api_types.TrialComponentSummary(", "<gh_stars>0 # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. #", "datetime.timedelta(hours=i), \"EndTime\": end_time + datetime.timedelta(hours=i), \"CreationTime\": creation_time + datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i),", "KIND, either express or implied. See the License for the specific # language", "], \"NextToken\": \"100\", }, { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\":", "+ str(i)), start_time=start_time + datetime.timedelta(hours=i), end_time=end_time + datetime.timedelta(hours=i), creation_time=creation_time + datetime.timedelta(hours=i), last_modified_time=last_modified_time +", "# # Licensed under the Apache License, Version 2.0 (the \"License\"). You #", "== list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name, experiment_name=experiment_name, created_before=created_before, created_after=created_after, next_token=next_token, max_results=max_results, sort_by=\"CreationTime\", sort_order=\"Ascending\", )", "{\"Value\": \"s3://whizz/bang\", \"MediaType\": \"text/plain\"}}, \"Metrics\": [ { \"MetricName\": \"J\", \"Count\": 1, \"Min\": 1.0,", "\"foo-trial\" experiment_name = \"foo-experiment\" next_token = \"<PASSWORD>\" max_results = 99 sagemaker_boto_client.list_trial_components.return_value = {}", "i in range(20) ] result = list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\", sort_by=\"CreationTime\", sort_order=\"Ascending\", )", "{\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")} assert {\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")} assert [ api_types.TrialComponentMetricSummary( metric_name=\"J\", count=1, min=1.0,", "unittest.mock.call( TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\", CreatedBefore=created_before, CreatedAfter=created_after, SortBy=\"CreationTime\", SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\", MaxResults=99, ) ] assert expected_calls", "file except in compliance with the License. A copy of # the License", "\"C\" + str(i), \"SourceArn\": \"D\" + str(i), \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"E\" +", "CreatedAfter=created_after, SortBy=\"CreationTime\", SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\", MaxResults=99, ) ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_save(sagemaker_boto_client):", "creation_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=3) last_modified_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect = [", "unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def", "# Licensed under the Apache License, Version 2.0 (the \"License\"). You # may", "# ANY KIND, either express or implied. See the License for the specific", "sagemaker_boto_client.create_trial_component.return_value = { \"TrialComponentArn\": \"bazz\", } obj = trial_component.TrialComponent.create( trial_component_name=\"foo\", display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client )", "sagemaker_boto_client.list_trial_components.side_effect = [ { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\": \"B\"", "creation_time=creation_time + datetime.timedelta(hours=i), last_modified_time=last_modified_time + datetime.timedelta(hours=i), last_modified_by={}, ) for i in range(20) ]", "== obj.status assert {\"E\": 1.0, \"F\": \"G\"} == obj.parameters assert {\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")}", "sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\", sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) assert expected == result expected_calls = [", "== list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def test_list_trial_components_call_args(sagemaker_boto_client): created_before = datetime.datetime(1999, 10, 12, 0, 0, 0) created_after", "express or implied. See the License for the specific # language governing permissions", "datetime.timedelta(hours=i), creation_time=creation_time + datetime.timedelta(hours=i), last_modified_time=last_modified_time + datetime.timedelta(hours=i), last_modified_by={}, ) for i in range(20)", "\"MetricName\": \"J\", \"Count\": 1, \"Min\": 1.0, \"Max\": 2.0, \"Avg\": 3.0, \"StdDev\": 4.0, \"SourceArn\":", "with the License. A copy of # the License is located at #", "= [ { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\": \"B\" +", "governing permissions and limitations under the License. from smexperiments import trial_component, api_types import", "= [ unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), ] assert expected_calls ==", "} obj = trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert \"A\" == obj.trial_component_arn assert \"B\" ==", "datetime.timedelta(hours=i), last_modified_by={}, ) for i in range(20) ] result = list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client,", "= \"foo-experiment\" next_token = \"<PASSWORD>\" max_results = 99 sagemaker_boto_client.list_trial_components.return_value = {} assert []", "\"bazz\" == obj.trial_component_arn def test_load(sagemaker_boto_client): now = datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value = { \"TrialComponentArn\": \"A\",", "\"DisplayName\": \"C\", \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"D\"}, \"Parameters\": {\"E\": {\"NumberValue\": 1.0}, \"F\": {\"StringValue\":", "\"B\" + str(i), \"DisplayName\": \"C\" + str(i), \"SourceArn\": \"D\" + str(i), \"Status\": {\"PrimaryStatus\":", "= datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2) creation_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=3) last_modified_time = datetime.datetime.now(datetime.timezone.utc) +", "for i in range(20) ] result = list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\", sort_by=\"CreationTime\", sort_order=\"Ascending\",", "list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\", sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) assert expected == result expected_calls", "} ], } obj = trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert \"A\" == obj.trial_component_arn assert", "\"Metrics\": [ { \"MetricName\": \"J\", \"Count\": 1, \"Min\": 1.0, \"Max\": 2.0, \"Avg\": 3.0,", "the License for the specific # language governing permissions and limitations under the", "\"TrialComponentArn\": \"bazz\", } obj = trial_component.TrialComponent.create( trial_component_name=\"foo\", display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client ) sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") assert", "trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value = {} obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def test_boto_ignore(): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\",", "datetime.datetime(1990, 10, 12, 0, 0, 0) trial_name = \"foo-trial\" experiment_name = \"foo-experiment\" next_token", "under the License. from smexperiments import trial_component, api_types import datetime import pytest import", "SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value", "\"TrialComponentName\": \"B\", \"DisplayName\": \"C\", \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"D\"}, \"Parameters\": {\"E\": {\"NumberValue\": 1.0},", "{\"H\": {\"Value\": \"s3://foo/bar\", \"MediaType\": \"text/plain\"}}, \"OutputArtifacts\": {\"I\": {\"Value\": \"s3://whizz/bang\", \"MediaType\": \"text/plain\"}}, \"Metrics\": [", "WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See", "OF # ANY KIND, either express or implied. See the License for the", "source_arn=\"D\" + str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" + str(i)), start_time=start_time + datetime.timedelta(hours=i), end_time=end_time + datetime.timedelta(hours=i),", "= {} assert [] == list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name, experiment_name=experiment_name, created_before=created_before, created_after=created_after, next_token=next_token,", "10, 12, 0, 0, 0) created_after = datetime.datetime(1990, 10, 12, 0, 0, 0)", "or in the \"license\" file accompanying this file. This file is # distributed", "range(20) ] result = list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\", sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) assert", "start_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) end_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2) creation_time = datetime.datetime.now(datetime.timezone.utc)", "0) created_after = datetime.datetime(1990, 10, 12, 0, 0, 0) trial_name = \"foo-trial\" experiment_name", "use this file except in compliance with the License. A copy of #", "CONDITIONS OF # ANY KIND, either express or implied. See the License for", "assert \"bar\" == obj.display_name assert \"bazz\" == obj.trial_component_arn def test_load(sagemaker_boto_client): now = datetime.datetime.now(datetime.timezone.utc)", "last_modified_time=last_modified_time + datetime.timedelta(hours=i), last_modified_by={}, ) for i in range(20) ] result = list(", "created_after=created_after, next_token=next_token, max_results=max_results, sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) expected_calls = [ unittest.mock.call( TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\",", "str(i)), start_time=start_time + datetime.timedelta(hours=i), end_time=end_time + datetime.timedelta(hours=i), creation_time=creation_time + datetime.timedelta(hours=i), last_modified_time=last_modified_time + datetime.timedelta(hours=i),", "unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value =", "result expected_calls = [ unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), ] assert", "\"bar\" == obj.display_name assert \"bazz\" == obj.trial_component_arn def test_load(sagemaker_boto_client): now = datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value", "datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect = [ { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\":", "obj.display_name assert \"bazz\" == obj.trial_component_arn def test_load(sagemaker_boto_client): now = datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value = {", "\"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in range(10, 20) ]", "License is located at # # http://aws.amazon.com/apache2.0/ # # or in the \"license\"", "or implied. See the License for the specific # language governing permissions and", "1.0}, \"F\": {\"StringValue\": \"G\"}}, \"InputArtifacts\": {\"H\": {\"Value\": \"s3://foo/bar\", \"MediaType\": \"text/plain\"}}, \"OutputArtifacts\": {\"I\": {\"Value\":", "str(i), \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"E\" + str(i)}, \"StartTime\": start_time + datetime.timedelta(hours=i), \"EndTime\":", "Apache License, Version 2.0 (the \"License\"). You # may not use this file", "trial_component_name=\"foo\", display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client ) sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") assert \"foo\" == obj.trial_component_name assert \"bar\" ==", "OR CONDITIONS OF # ANY KIND, either express or implied. See the License", "expected_calls = [ unittest.mock.call( TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\", CreatedBefore=created_before, CreatedAfter=created_after, SortBy=\"CreationTime\", SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\", MaxResults=99, )", "obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value = {} obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def test_boto_ignore(): obj", "its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version", "message=\"D\") == obj.status assert {\"E\": 1.0, \"F\": \"G\"} == obj.parameters assert {\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\",", "str(i), trial_component_arn=\"B\" + str(i), display_name=\"C\" + str(i), source_arn=\"D\" + str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" +", "sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def test_boto_ignore(): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") assert obj._boto_ignore() == [\"ResponseMetadata\", \"CreatedBy\"]", "+ str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" + str(i)), start_time=start_time + datetime.timedelta(hours=i), end_time=end_time + datetime.timedelta(hours=i), creation_time=creation_time", "License, Version 2.0 (the \"License\"). You # may not use this file except", "test_list(sagemaker_boto_client): start_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) end_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2) creation_time =", "str(i), \"SourceArn\": \"D\" + str(i), \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"E\" + str(i)}, \"StartTime\":", "specific # language governing permissions and limitations under the License. from smexperiments import", "You # may not use this file except in compliance with the License.", "[ api_types.TrialComponentSummary( trial_component_name=\"A\" + str(i), trial_component_arn=\"B\" + str(i), display_name=\"C\" + str(i), source_arn=\"D\" +", "{ \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\": \"B\" + str(i), \"DisplayName\":", "= trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert \"A\" == obj.trial_component_arn assert \"B\" == obj.trial_component_name assert", "\"C\" == obj.display_name assert api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") == obj.status assert {\"E\": 1.0, \"F\": \"G\"}", "display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value = {} obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") def test_delete(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\",", "not use this file except in compliance with the License. A copy of", "+ datetime.timedelta(hours=3) last_modified_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect = [ { \"TrialComponentSummaries\": [", "creation_time + datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in", ") ) assert expected == result expected_calls = [ unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\",", "= [ api_types.TrialComponentSummary( trial_component_name=\"A\" + str(i), trial_component_arn=\"B\" + str(i), display_name=\"C\" + str(i), source_arn=\"D\"", "TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\", CreatedBefore=created_before, CreatedAfter=created_after, SortBy=\"CreationTime\", SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\", MaxResults=99, ) ] assert expected_calls ==", "obj.status assert {\"E\": 1.0, \"F\": \"G\"} == obj.parameters assert {\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")} assert", "] result = list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\", sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) assert expected", "+ datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in range(10, 20) ] }, ]", "def test_delete(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value = {} obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def", "1.0, \"F\": \"G\"} == obj.parameters assert {\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")} assert {\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")}", "assert {\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")} assert {\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")} assert [ api_types.TrialComponentMetricSummary( metric_name=\"J\", count=1,", "sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name, experiment_name=experiment_name, created_before=created_before, created_after=created_after, next_token=next_token, max_results=max_results, sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) expected_calls =", "the License. A copy of # the License is located at # #", "sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") def test_delete(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value = {} obj.delete()", "= trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value = {} obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def test_boto_ignore(): obj =", "= datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect = [ { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\"", "\"Message\": \"E\" + str(i)}, \"StartTime\": start_time + datetime.timedelta(hours=i), \"EndTime\": end_time + datetime.timedelta(hours=i), \"CreationTime\":", "+ datetime.timedelta(hours=i), last_modified_time=last_modified_time + datetime.timedelta(hours=i), last_modified_by={}, ) for i in range(20) ] result", "i in range(10) ], \"NextToken\": \"100\", }, { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\"", "DisplayName=\"bar\") def test_delete(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value = {} obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\")", "License for the specific # language governing permissions and limitations under the License.", "0, 0, 0) created_after = datetime.datetime(1990, 10, 12, 0, 0, 0) trial_name =", "datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in range(10, 20) ] }, ] expected", "assert api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") == obj.status assert {\"E\": 1.0, \"F\": \"G\"} == obj.parameters assert", "def test_load(sagemaker_boto_client): now = datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value = { \"TrialComponentArn\": \"A\", \"TrialComponentName\": \"B\", \"DisplayName\":", "trial_component, api_types import datetime import pytest import unittest.mock @pytest.fixture def sagemaker_boto_client(): return unittest.mock.Mock()", "def test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value = { \"TrialComponentArn\": \"bazz\", } obj = trial_component.TrialComponent.create( trial_component_name=\"foo\", display_name=\"bar\",", "\"Avg\": 3.0, \"StdDev\": 4.0, \"SourceArn\": \"K\", \"Timestamp\": now, } ], } obj =", "\"MediaType\": \"text/plain\"}}, \"Metrics\": [ { \"MetricName\": \"J\", \"Count\": 1, \"Min\": 1.0, \"Max\": 2.0,", "assert \"A\" == obj.trial_component_arn assert \"B\" == obj.trial_component_name assert \"C\" == obj.display_name assert", "\"<PASSWORD>\" max_results = 99 sagemaker_boto_client.list_trial_components.return_value = {} assert [] == list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client,", "= \"foo-trial\" experiment_name = \"foo-experiment\" next_token = \"<PASSWORD>\" max_results = 99 sagemaker_boto_client.list_trial_components.return_value =", "{\"StringValue\": \"G\"}}, \"InputArtifacts\": {\"H\": {\"Value\": \"s3://foo/bar\", \"MediaType\": \"text/plain\"}}, \"OutputArtifacts\": {\"I\": {\"Value\": \"s3://whizz/bang\", \"MediaType\":", "\"F\": \"G\"} == obj.parameters assert {\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")} assert {\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")} assert", "assert \"B\" == obj.trial_component_name assert \"C\" == obj.display_name assert api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") == obj.status", "\"InProgress\", \"Message\": \"D\"}, \"Parameters\": {\"E\": {\"NumberValue\": 1.0}, \"F\": {\"StringValue\": \"G\"}}, \"InputArtifacts\": {\"H\": {\"Value\":", "sagemaker_boto_client.update_trial_component.return_value = {} obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") def test_delete(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\")", "obj.trial_component_arn assert \"B\" == obj.trial_component_name assert \"C\" == obj.display_name assert api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") ==", "0, 0, 0) trial_name = \"foo-trial\" experiment_name = \"foo-experiment\" next_token = \"<PASSWORD>\" max_results", "trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert \"A\" == obj.trial_component_arn assert \"B\" == obj.trial_component_name assert \"C\"", "+ datetime.timedelta(hours=i), \"EndTime\": end_time + datetime.timedelta(hours=i), \"CreationTime\": creation_time + datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time +", "+ str(i), \"TrialComponentArn\": \"B\" + str(i), \"DisplayName\": \"C\" + str(i), \"SourceArn\": \"D\" +", "in the \"license\" file accompanying this file. This file is # distributed on", "last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in range(10, 20) ] },", "the License. from smexperiments import trial_component, api_types import datetime import pytest import unittest.mock", "{ \"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\": \"B\" + str(i), \"DisplayName\": \"C\" + str(i),", "expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_save(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value = {}", ") assert expected == result expected_calls = [ unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\",", "] expected = [ api_types.TrialComponentSummary( trial_component_name=\"A\" + str(i), trial_component_arn=\"B\" + str(i), display_name=\"C\" +", "last_modified_by={}, ) for i in range(20) ] result = list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\",", "start_time + datetime.timedelta(hours=i), \"EndTime\": end_time + datetime.timedelta(hours=i), \"CreationTime\": creation_time + datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time", "api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")} assert [ api_types.TrialComponentMetricSummary( metric_name=\"J\", count=1, min=1.0, max=2.0, avg=3.0, std_dev=4.0, source_arn=\"K\", timestamp=now", "max_results=max_results, sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) expected_calls = [ unittest.mock.call( TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\", CreatedBefore=created_before, CreatedAfter=created_after,", "\"License\"). You # may not use this file except in compliance with the", ") sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") assert \"foo\" == obj.trial_component_name assert \"bar\" == obj.display_name assert \"bazz\"", "\"A\", \"TrialComponentName\": \"B\", \"DisplayName\": \"C\", \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"D\"}, \"Parameters\": {\"E\": {\"NumberValue\":", "next_token = \"<PASSWORD>\" max_results = 99 sagemaker_boto_client.list_trial_components.return_value = {} assert [] == list(", "language governing permissions and limitations under the License. from smexperiments import trial_component, api_types", "\"SourceArn\": \"K\", \"Timestamp\": now, } ], } obj = trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express", "4.0, \"SourceArn\": \"K\", \"Timestamp\": now, } ], } obj = trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\")", "source_arn=\"foo\", sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) assert expected == result expected_calls = [ unittest.mock.call(SortBy=\"CreationTime\",", "affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0", "may not use this file except in compliance with the License. A copy", "test_save(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value = {} obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") def", "at # # http://aws.amazon.com/apache2.0/ # # or in the \"license\" file accompanying this", "+ datetime.timedelta(hours=i), creation_time=creation_time + datetime.timedelta(hours=i), last_modified_time=last_modified_time + datetime.timedelta(hours=i), last_modified_by={}, ) for i in", "either express or implied. See the License for the specific # language governing", "display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client ) sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") assert \"foo\" == obj.trial_component_name assert \"bar\" == obj.display_name", ") ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_save(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\")", "for i in range(10, 20) ] }, ] expected = [ api_types.TrialComponentSummary( trial_component_name=\"A\"", "display_name=\"C\" + str(i), source_arn=\"D\" + str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" + str(i)), start_time=start_time + datetime.timedelta(hours=i),", "+ datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in range(10)", "# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # #", "= datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value = { \"TrialComponentArn\": \"A\", \"TrialComponentName\": \"B\", \"DisplayName\": \"C\", \"Status\": {\"PrimaryStatus\":", "Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed", "[] == list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name, experiment_name=experiment_name, created_before=created_before, created_after=created_after, next_token=next_token, max_results=max_results, sort_by=\"CreationTime\", sort_order=\"Ascending\",", "2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under", "obj = trial_component.TrialComponent.create( trial_component_name=\"foo\", display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client ) sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") assert \"foo\" == obj.trial_component_name", "datetime.timedelta(hours=1) end_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2) creation_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=3) last_modified_time =", "{\"TrialComponentSummaries\": []} assert [] == list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def test_list_trial_components_call_args(sagemaker_boto_client): created_before = datetime.datetime(1999, 10, 12,", "0, 0) created_after = datetime.datetime(1990, 10, 12, 0, 0, 0) trial_name = \"foo-trial\"", "of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or", "an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either", "obj.trial_component_arn def test_load(sagemaker_boto_client): now = datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value = { \"TrialComponentArn\": \"A\", \"TrialComponentName\": \"B\",", "\"DisplayName\": \"C\" + str(i), \"SourceArn\": \"D\" + str(i), \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"E\"", "3.0, \"StdDev\": 4.0, \"SourceArn\": \"K\", \"Timestamp\": now, } ], } obj = trial_component.TrialComponent.load(trial_component_name=\"foo\",", "\"license\" file accompanying this file. This file is # distributed on an \"AS", "\"B\" == obj.trial_component_name assert \"C\" == obj.display_name assert api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") == obj.status assert", "== obj.display_name assert api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") == obj.status assert {\"E\": 1.0, \"F\": \"G\"} ==", "10, 12, 0, 0, 0) trial_name = \"foo-trial\" experiment_name = \"foo-experiment\" next_token =", "Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the", "\"foo\" == obj.trial_component_name assert \"bar\" == obj.display_name assert \"bazz\" == obj.trial_component_arn def test_load(sagemaker_boto_client):", "media_type=\"text/plain\")} assert {\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")} assert [ api_types.TrialComponentMetricSummary( metric_name=\"J\", count=1, min=1.0, max=2.0, avg=3.0,", "import pytest import unittest.mock @pytest.fixture def sagemaker_boto_client(): return unittest.mock.Mock() def test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value =", "range(10) ], \"NextToken\": \"100\", }, { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" + str(i),", "SortOrder=\"Ascending\", SourceArn=\"foo\"), ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value = {\"TrialComponentSummaries\": []}", "pytest import unittest.mock @pytest.fixture def sagemaker_boto_client(): return unittest.mock.Mock() def test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value = {", "implied. See the License for the specific # language governing permissions and limitations", "str(i), source_arn=\"D\" + str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" + str(i)), start_time=start_time + datetime.timedelta(hours=i), end_time=end_time +", "experiment_name=experiment_name, created_before=created_before, created_after=created_after, next_token=next_token, max_results=max_results, sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) expected_calls = [ unittest.mock.call(", "@pytest.fixture def sagemaker_boto_client(): return unittest.mock.Mock() def test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value = { \"TrialComponentArn\": \"bazz\", }", "max_results = 99 sagemaker_boto_client.list_trial_components.return_value = {} assert [] == list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name,", "accompanying this file. This file is # distributed on an \"AS IS\" BASIS,", "import datetime import pytest import unittest.mock @pytest.fixture def sagemaker_boto_client(): return unittest.mock.Mock() def test_create(sagemaker_boto_client):", "next_token=next_token, max_results=max_results, sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) expected_calls = [ unittest.mock.call( TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\", CreatedBefore=created_before,", "trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value = {} obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") def test_delete(sagemaker_boto_client): obj =" ]
[ "# 1. update preserved oligo length olg5p.incrementLength(new_olg3p.length()) # 2. Remove the old oligo", "oligo length olg5p.incrementLength(old_olg3p.length()) # 2. Remove the old oligo and apply the 5'", "2. install the crossover 3. update the oligo length 4. apply the new", "def def undo(self): part = self._part strand5p = self._strand5p strand5p_idx = self._strand5p_idx strand3p", "the 3' strand old_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p)", "2. restore the modified oligo length olg5p.decrementLength(old_olg3p.length()) # 3. apply the old oligo", "oligo to the 3' strand new_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal", "# 1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._isLoop: olg5p.setLoop(False) olg5p.setStrand5p(strand3p) else: #", "Strand from cadnano import getBatch import cadnano.preferences as prefs import random class CreateXoverCommand(UndoCommand):", "install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p =", "5' oligo to the 3' strand old_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits", "#print('strand5p = %s, connection3p = %s'%(strand5p._name, strand3p._name)) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix()", "5' oligo to the 3' strand new_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits", "and apply the 5' oligo to the 3' strand new_olg3p.removeFromPart() for strand in", "\"\"\" Creates a Xover from the 3' end of strand5p to the 5'", "new_olg3p = self._new_oligo3p # 0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p)", "the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType()", "part self._strand5p = strand5p self._strand5p_idx = strand5p.idx3Prime() self._strand3p = strand3p self._strand3p_idx = strand3p.idx5Prime()", "# end def n_o3p.setStrand5p(strand3p) self._isLoop = strand3p.oligo().isLoop() # end def def redo(self): part", "prefs import random class CreateXoverCommand(UndoCommand): \"\"\" Creates a Xover from the 3' end", "oligo to strand3p new_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, new_olg3p)", "olg5p = strand5p.oligo() new_olg3p = self._new_oligo3p # 0. Deselect the involved strands doc", "the crossover 3. apply the strand5p oligo to the strand3p \"\"\" def __init__(self,", "strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._update_oligo: # Test Loopiness if old_olg3p.isLoop(): old_olg3p.setLoop(False) else: # 2.", "strand5p_idx, strand3p, strand3p_idx, update_oligo=True): super(CreateXoverCommand, self).__init__(\"create xover\") self._part = part self._strand5p = strand5p", "super(RemoveXoverCommand, self).__init__(\"remove xover\") self._part = part self._strand5p = strand5p self._strand5p_idx = strand5p.idx3Prime() self._strand3p", "new strand3p oligo to the strand3p \"\"\" def __init__(self, part, strand5p, strand3p): super(RemoveXoverCommand,", "self).__init__(\"remove xover\") self._part = part self._strand5p = strand5p self._strand5p_idx = strand5p.idx3Prime() self._strand3p =", "the crossover 3. update the oligo length 4. apply the new strand3p oligo", "strand3p, strand3p_idx, update_oligo=True): super(CreateXoverCommand, self).__init__(\"create xover\") self._part = part self._strand5p = strand5p self._strand5p_idx", "= self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() old_olg3p =", "to restore whatever the old Oligo._strand5p was else: # 1. update preserved oligo", "strand new_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # end", "= self._strand5p.oligo() # 0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p)", "apply the old oligo to strand3p new_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits", "part, strand5p, strand3p): super(RemoveXoverCommand, self).__init__(\"remove xover\") self._part = part self._strand5p = strand5p self._strand5p_idx", "strand3p this needs to 1. preserve the old oligo of strand3p 2. install", "import cadnano.preferences as prefs import random class CreateXoverCommand(UndoCommand): \"\"\" Creates a Xover from", "Strand.setOligo(strand, olg5p) # 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) #print('strand5p = %s, connection3p", "strand3p.oligo() self._update_oligo = update_oligo # end def def redo(self): part = self._part strand5p", "= strand5p.idx3Prime() self._strand3p = strand3p self._strand3p_idx = strand3p.idx5Prime() n_o3p = self._new_oligo3p = strand3p.oligo().shallowCopy()", "strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() new_olg3p", "= self._strand3p_idx new_olg3p = self._new_oligo3p olg5p = self._strand5p.oligo() # 0. Deselect the involved", "self._strand5p_idx = strand5p_idx self._strand3p = strand3p self._strand3p_idx = strand3p_idx self._old_oligo3p = strand3p.oligo() self._update_oligo", "def def redo(self): part = self._part strand5p = self._strand5p strand5p_idx = self._strand5p_idx strand3p", "to the strand3p \"\"\" def __init__(self, part, strand5p, strand3p): super(RemoveXoverCommand, self).__init__(\"remove xover\") self._part", "= strand3p self._strand3p_idx = strand3p_idx self._old_oligo3p = strand3p.oligo() self._update_oligo = update_oligo # end", "modified oligo length olg5p.decrementLength(old_olg3p.length()) # 3. apply the old oligo to strand3p old_olg3p.addToPart(part)", "Remove the old oligo and apply the 5' oligo to the 3' strand", "getBatch import cadnano.preferences as prefs import random class CreateXoverCommand(UndoCommand): \"\"\" Creates a Xover", "end of strand5p to the 5' end of strand3p this needs to 1.", "xover\") self._part = part self._strand5p = strand5p self._strand5p_idx = strand5p_idx self._strand3p = strand3p", "oligo length olg5p.incrementLength(new_olg3p.length()) # 2. Remove the old oligo and apply the 5'", "self._strand3p strand3p_idx = self._strand3p_idx new_olg3p = self._new_oligo3p olg5p = self._strand5p.oligo() # 0. Deselect", "emits strandHasNewOligoSignal Strand.setOligo(strand, new_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType()", "self._strand3p_idx = strand3p_idx self._old_oligo3p = strand3p.oligo() self._update_oligo = update_oligo # end def def", "== strand3p.oligo(): olg5p.setLoop(True) else: # 1. update preserved oligo length olg5p.incrementLength(old_olg3p.length()) # 2.", "= strand5p self._strand5p_idx = strand5p.idx3Prime() self._strand3p = strand3p self._strand3p_idx = strand3p.idx5Prime() n_o3p =", "= self._new_oligo3p = strand3p.oligo().shallowCopy() colorList = prefs.STAP_COLORS if strand5p.strandSet().isStaple() \\ else prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name())", "to 1. preserve the old oligo of strand3p 2. install the crossover 3.", "strand in strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength()) # end def n_o3p.setStrand5p(strand3p) self._isLoop = strand3p.oligo().isLoop() # end", "ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self):", "the old oligo and apply the 5' oligo to the 3' strand new_olg3p.removeFromPart()", "Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._isLoop: olg5p.setLoop(False) olg5p.setStrand5p(strand3p) else: # 2. restore the modified", "RemoveXoverCommand(UndoCommand): \"\"\" Removes a Xover from the 3' end of strand5p to the", "Loopiness if olg5p == strand3p.oligo(): olg5p.setLoop(True) else: # 1. update preserved oligo length", "= strand5p_idx self._strand3p = strand3p self._strand3p_idx = strand3p_idx self._old_oligo3p = strand3p.oligo() self._update_oligo =", "part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self): part", "4. apply the new strand3p oligo to the strand3p \"\"\" def __init__(self, part,", "for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, new_olg3p) ss5 = strand5p.strandSet() vh5p", "the old oligo to strand3p new_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal", "# emits strandHasNewOligoSignal Strand.setOligo(strand, new_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p =", "# end def # end class class RemoveXoverCommand(UndoCommand): \"\"\" Removes a Xover from", "old oligo of strand3p 2. install the crossover 3. update the oligo length", "in strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength()) # end def n_o3p.setStrand5p(strand3p) self._isLoop = strand3p.oligo().isLoop() # end def", "end def n_o3p.setStrand5p(strand3p) self._isLoop = strand3p.oligo().isLoop() # end def def redo(self): part =", "the old oligo of strand3p 2. install the crossover 3. update the oligo", "= ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def #", "from the 3' end of strand5p to the 5' end of strand3p this", "vh3p = ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) if self._update_oligo:", "doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._isLoop: olg5p.setLoop(True) # No need to restore whatever the old", "part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def # end class", "update the oligo length 4. apply the new strand3p oligo to the strand3p", "oligo and apply the 5' oligo to the 3' strand new_olg3p.removeFromPart() for strand", "the 3' end of strand5p to the 5' end of strand3p this needs", "= self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() new_olg3p =", "olg5p) # end else # 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) ss5 =", "import UndoCommand from cadnano.strand import Strand from cadnano import getBatch import cadnano.preferences as", "strand3p_idx = self._strand3p_idx old_olg3p = self._old_oligo3p olg5p = strand5p.oligo() # 0. Deselect the", "strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # end else # 3.", "the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._isLoop: olg5p.setLoop(True) # No", "= strand5p self._strand5p_idx = strand5p_idx self._strand3p = strand3p self._strand3p_idx = strand3p_idx self._old_oligo3p =", "xover\") self._part = part self._strand5p = strand5p self._strand5p_idx = strand5p.idx3Prime() self._strand3p = strand3p", "connection3p = %s'%(strand5p._name, strand3p._name)) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType()", "a Xover from the 3' end of strand5p to the 5' end of", "# end def def redo(self): part = self._part strand5p = self._strand5p strand5p_idx =", "in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, new_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix()", "ss3 = strand3p.strandSet() vh3p = ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p,", "olg5p.decrementLength(old_olg3p.length()) # 3. apply the old oligo to strand3p old_olg3p.addToPart(part) for strand in", "uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._isLoop: olg5p.setLoop(False) olg5p.setStrand5p(strand3p) else: # 2. restore", "ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) # if self._update_oligo and not getBatch(): if", "strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, old_olg3p) ss5 = strand5p.strandSet() vh5p =", "Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) #print('strand5p = %s, connection3p = %s'%(strand5p._name, strand3p._name)) ss5 = strand5p.strandSet()", "strand3p 2. install the crossover 3. apply the strand5p oligo to the strand3p", "# emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # end else # 3. install the Xover", "emits strandHasNewOligoSignal Strand.setOligo(strand, old_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType()", "new_olg3p = self._new_oligo3p olg5p = self._strand5p.oligo() # 0. Deselect the involved strands doc", "else: # 1. update preserved oligo length olg5p.incrementLength(old_olg3p.length()) # 2. Remove the old", "self._isLoop = strand3p.oligo().isLoop() # end def def redo(self): part = self._part strand5p =", "vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) # if self._update_oligo and not getBatch(): if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p)", "restore the modified oligo length olg5p.decrementLength(new_olg3p.length()) # 3. apply the old oligo to", "new_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3 = strand3p.strandSet()", "apply the new strand3p oligo to the strand3p \"\"\" def __init__(self, part, strand5p,", "strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self): part = self._part strand5p = self._strand5p strand5p_idx", "else: # 1. update preserved oligo length olg5p.incrementLength(new_olg3p.length()) # 2. Remove the old", "def redo(self): part = self._part strand5p = self._strand5p strand5p_idx = self._strand5p_idx strand3p =", "= self._strand3p_idx olg5p = strand5p.oligo() new_olg3p = self._new_oligo3p # 0. Deselect the involved", "from cadnano import getBatch import cadnano.preferences as prefs import random class CreateXoverCommand(UndoCommand): \"\"\"", "if self._update_oligo: # Test for Loopiness if olg5p == strand3p.oligo(): olg5p.setLoop(True) else: #", "whatever the old Oligo._strand5p was else: # 1. update preserved oligo length olg5p.incrementLength(new_olg3p.length())", "strand3p new_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, new_olg3p) ss5 =", "strand3p_idx self._old_oligo3p = strand3p.oligo() self._update_oligo = update_oligo # end def def redo(self): part", "strand3p_idx = self._strand3p_idx new_olg3p = self._new_oligo3p olg5p = self._strand5p.oligo() # 0. Deselect the", "olg5p = strand5p.oligo() # 0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p)", "strand3p.idx5Prime() n_o3p = self._new_oligo3p = strand3p.oligo().shallowCopy() colorList = prefs.STAP_COLORS if strand5p.strandSet().isStaple() \\ else", "strand3p.setConnection5p(None) if self._isLoop: olg5p.setLoop(False) olg5p.setStrand5p(strand3p) else: # 2. restore the modified oligo length", "involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._update_oligo: # Test for Loopiness", "strand3p): super(RemoveXoverCommand, self).__init__(\"remove xover\") self._part = part self._strand5p = strand5p self._strand5p_idx = strand5p.idx3Prime()", "strand3p = self._strand3p strand3p_idx = self._strand3p_idx new_olg3p = self._new_oligo3p olg5p = self._strand5p.oligo() #", "3' strand old_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) #", "if self._isLoop: olg5p.setLoop(False) olg5p.setStrand5p(strand3p) else: # 2. restore the modified oligo length olg5p.decrementLength(new_olg3p.length())", "strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # end else # 3. install the", "strand5p, strand5p_idx, strand3p, strand3p_idx, update_oligo=True): super(CreateXoverCommand, self).__init__(\"create xover\") self._part = part self._strand5p =", "self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() new_olg3p = self._new_oligo3p # 0. Deselect", "strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() new_olg3p = self._new_oligo3p # 0. Deselect the", "Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1. uninstall the", "# 0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._update_oligo:", "cadnano import getBatch import cadnano.preferences as prefs import random class CreateXoverCommand(UndoCommand): \"\"\" Creates", "Test Loopiness if old_olg3p.isLoop(): old_olg3p.setLoop(False) else: # 2. restore the modified oligo length", "# Test for Loopiness if olg5p == strand3p.oligo(): olg5p.setLoop(True) else: # 1. update", "strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() old_olg3p = self._old_oligo3p # 0. Deselect the", "\\ else prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0) for strand in strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength()) # end def", "the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._update_oligo: # Test Loopiness if old_olg3p.isLoop(): old_olg3p.setLoop(False) else:", "in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, old_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix()", "if olg5p == strand3p.oligo(): olg5p.setLoop(True) else: # 1. update preserved oligo length olg5p.incrementLength(old_olg3p.length())", "cadnano.cnproxy import UndoCommand from cadnano.strand import Strand from cadnano import getBatch import cadnano.preferences", "self._update_oligo = update_oligo # end def def redo(self): part = self._part strand5p =", "end of strand3p this needs to 1. preserve the old oligo of strand3p", "strand3p self._strand3p_idx = strand3p_idx self._old_oligo3p = strand3p.oligo() self._update_oligo = update_oligo # end def", "in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # end else # 3. install", "Strand.setOligo(strand, olg5p) # end else # 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) ss5", "1. update preserved oligo length olg5p.incrementLength(new_olg3p.length()) # 2. Remove the old oligo and", "1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._isLoop: olg5p.setLoop(False) olg5p.setStrand5p(strand3p) else: # 2.", "self._update_oligo: # Test Loopiness if old_olg3p.isLoop(): old_olg3p.setLoop(False) else: # 2. restore the modified", "involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1. uninstall the Xover strand5p.setConnection3p(None)", "3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) #print('strand5p = %s, connection3p = %s'%(strand5p._name, strand3p._name))", "Loopiness if old_olg3p.isLoop(): old_olg3p.setLoop(False) else: # 2. restore the modified oligo length olg5p.decrementLength(old_olg3p.length())", "olg5p.setLoop(True) else: # 1. update preserved oligo length olg5p.incrementLength(old_olg3p.length()) # 2. Remove the", "= self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx new_olg3p = self._new_oligo3p olg5p =", "self._strand5p = strand5p self._strand5p_idx = strand5p_idx self._strand3p = strand3p self._strand3p_idx = strand3p_idx self._old_oligo3p", "vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3 = strand3p.strandSet() vh3p = ss3.virtualHelix() st3p", "# No need to restore whatever the old Oligo._strand5p was else: # 1.", "= ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) #", "self._old_oligo3p # 0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if", "self._part strand5p = self._strand5p strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx", "end class class RemoveXoverCommand(UndoCommand): \"\"\" Removes a Xover from the 3' end of", "strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # end else # 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p)", "Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._update_oligo: # Test Loopiness if old_olg3p.isLoop(): old_olg3p.setLoop(False) else: #", "import random class CreateXoverCommand(UndoCommand): \"\"\" Creates a Xover from the 3' end of", "ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) # if self._update_oligo and", "= self._strand5p strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx old_olg3p =", "old Oligo._strand5p was else: # 1. update preserved oligo length olg5p.incrementLength(new_olg3p.length()) # 2.", "= self._new_oligo3p olg5p = self._strand5p.oligo() # 0. Deselect the involved strands doc =", "3' strand new_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) #", "= ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) # if self._update_oligo", "install the crossover 3. update the oligo length 4. apply the new strand3p", "old oligo to strand3p old_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand,", "strand old_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # 3.", "strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self): part = self._part strand5p = self._strand5p", "strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def # end class class RemoveXoverCommand(UndoCommand): \"\"\" Removes a", "for strand in strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength()) # end def n_o3p.setStrand5p(strand3p) self._isLoop = strand3p.oligo().isLoop() #", "def __init__(self, part, strand5p, strand3p): super(RemoveXoverCommand, self).__init__(\"remove xover\") self._part = part self._strand5p =", "crossover 3. apply the strand5p oligo to the strand3p \"\"\" def __init__(self, part,", "\"\"\" def __init__(self, part, strand5p, strand5p_idx, strand3p, strand3p_idx, update_oligo=True): super(CreateXoverCommand, self).__init__(\"create xover\") self._part", "= self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() new_olg3p = self._new_oligo3p # 0.", "else: # 2. restore the modified oligo length olg5p.decrementLength(old_olg3p.length()) # 3. apply the", "end def def redo(self): part = self._part strand5p = self._strand5p strand5p_idx = self._strand5p_idx", "vh3p = ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) # if", "undo(self): part = self._part strand5p = self._strand5p strand5p_idx = self._strand5p_idx strand3p = self._strand3p", "the 3' strand new_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p)", "the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) #print('strand5p = %s, connection3p = %s'%(strand5p._name, strand3p._name)) ss5 =", "to strand3p old_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, old_olg3p) ss5", "involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._isLoop: olg5p.setLoop(True) # No need", "oligo length 4. apply the new strand3p oligo to the strand3p \"\"\" def", "new_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, new_olg3p) ss5 = strand5p.strandSet()", "part self._strand5p = strand5p self._strand5p_idx = strand5p_idx self._strand3p = strand3p self._strand3p_idx = strand3p_idx", "olg5p = self._strand5p.oligo() # 0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p)", "import Strand from cadnano import getBatch import cadnano.preferences as prefs import random class", "old_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # 3. install", "self._new_oligo3p = strand3p.oligo().shallowCopy() colorList = prefs.STAP_COLORS if strand5p.strandSet().isStaple() \\ else prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0)", "# 1. update preserved oligo length olg5p.incrementLength(old_olg3p.length()) # 2. Remove the old oligo", "3. update the oligo length 4. apply the new strand3p oligo to the", "this needs to 1. preserve the old oligo of strand3p 2. install the", "strand3p_idx, update_oligo=True): super(CreateXoverCommand, self).__init__(\"create xover\") self._part = part self._strand5p = strand5p self._strand5p_idx =", "import getBatch import cadnano.preferences as prefs import random class CreateXoverCommand(UndoCommand): \"\"\" Creates a", "update_oligo # end def def redo(self): part = self._part strand5p = self._strand5p strand5p_idx", "for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, old_olg3p) ss5 = strand5p.strandSet() vh5p", "strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, new_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p", "Strand.setOligo(strand, old_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3 =", "strand3p \"\"\" def __init__(self, part, strand5p, strand5p_idx, strand3p, strand3p_idx, update_oligo=True): super(CreateXoverCommand, self).__init__(\"create xover\")", "self._strand3p strand3p_idx = self._strand3p_idx old_olg3p = self._old_oligo3p olg5p = strand5p.oligo() # 0. Deselect", "self._new_oligo3p # 0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if", "self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx old_olg3p = self._old_oligo3p olg5p = strand5p.oligo()", "n_o3p.setLength(0) for strand in strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength()) # end def n_o3p.setStrand5p(strand3p) self._isLoop = strand3p.oligo().isLoop()", "doc.removeStrandFromSelection(strand3p) if self._update_oligo: # Test for Loopiness if olg5p == strand3p.oligo(): olg5p.setLoop(True) else:", "as prefs import random class CreateXoverCommand(UndoCommand): \"\"\" Creates a Xover from the 3'", "update_oligo=True): super(CreateXoverCommand, self).__init__(\"create xover\") self._part = part self._strand5p = strand5p self._strand5p_idx = strand5p_idx", "1. preserve the old oligo of strand3p 2. install the crossover 3. update", "# end def def undo(self): part = self._part strand5p = self._strand5p strand5p_idx =", "self._isLoop: olg5p.setLoop(True) # No need to restore whatever the old Oligo._strand5p was else:", "part, strand5p, strand5p_idx, strand3p, strand3p_idx, update_oligo=True): super(CreateXoverCommand, self).__init__(\"create xover\") self._part = part self._strand5p", "self._strand5p strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx new_olg3p = self._new_oligo3p", "# Test Loopiness if old_olg3p.isLoop(): old_olg3p.setLoop(False) else: # 2. restore the modified oligo", "old_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, old_olg3p) ss5 = strand5p.strandSet()", "self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def # end class class RemoveXoverCommand(UndoCommand): \"\"\" Removes", "strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3 = strand3p.strandSet() vh3p = ss3.virtualHelix()", "self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() old_olg3p = self._old_oligo3p", "the oligo length 4. apply the new strand3p oligo to the strand3p \"\"\"", "# if self._update_oligo and not getBatch(): if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def", "strand3p.setConnection5p(strand5p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3 = strand3p.strandSet()", "preserve the old oligo of strand3p 2. install the crossover 3. update the", "= %s'%(strand5p._name, strand3p._name)) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3", "strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx old_olg3p = self._old_oligo3p olg5p", "__init__(self, part, strand5p, strand3p): super(RemoveXoverCommand, self).__init__(\"remove xover\") self._part = part self._strand5p = strand5p", "def __init__(self, part, strand5p, strand5p_idx, strand3p, strand3p_idx, update_oligo=True): super(CreateXoverCommand, self).__init__(\"create xover\") self._part =", "to the 3' strand new_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand,", "2. install the crossover 3. apply the strand5p oligo to the strand3p \"\"\"", "olg5p == strand3p.oligo(): olg5p.setLoop(True) else: # 1. update preserved oligo length olg5p.incrementLength(old_olg3p.length()) #", "the old Oligo._strand5p was else: # 1. update preserved oligo length olg5p.incrementLength(new_olg3p.length()) #", "old oligo and apply the 5' oligo to the 3' strand new_olg3p.removeFromPart() for", "old_olg3p = self._old_oligo3p # 0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p)", "apply the strand5p oligo to the strand3p \"\"\" def __init__(self, part, strand5p, strand5p_idx,", "3. apply the strand5p oligo to the strand3p \"\"\" def __init__(self, part, strand5p,", "oligo to strand3p old_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, old_olg3p)", "strand5p.oligo() old_olg3p = self._old_oligo3p # 0. Deselect the involved strands doc = strand5p.document()", "self._strand3p_idx new_olg3p = self._new_oligo3p olg5p = self._strand5p.oligo() # 0. Deselect the involved strands", "def # end class class RemoveXoverCommand(UndoCommand): \"\"\" Removes a Xover from the 3'", "= strand3p self._strand3p_idx = strand3p.idx5Prime() n_o3p = self._new_oligo3p = strand3p.oligo().shallowCopy() colorList = prefs.STAP_COLORS", "Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._update_oligo: # Test", "n_o3p = self._new_oligo3p = strand3p.oligo().shallowCopy() colorList = prefs.STAP_COLORS if strand5p.strandSet().isStaple() \\ else prefs.SCAF_COLORS", "self).__init__(\"create xover\") self._part = part self._strand5p = strand5p self._strand5p_idx = strand5p_idx self._strand3p =", "olg5p.setLoop(False) olg5p.setStrand5p(strand3p) else: # 2. restore the modified oligo length olg5p.decrementLength(new_olg3p.length()) # 3.", "st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) # if self._update_oligo and not", "strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._update_oligo: # Test for Loopiness if", "doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._update_oligo: # Test for Loopiness if olg5p == strand3p.oligo(): olg5p.setLoop(True)", "class CreateXoverCommand(UndoCommand): \"\"\" Creates a Xover from the 3' end of strand5p to", "# strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def # end class", "__init__(self, part, strand5p, strand5p_idx, strand3p, strand3p_idx, update_oligo=True): super(CreateXoverCommand, self).__init__(\"create xover\") self._part = part", "ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end", "= strand3p.oligo().isLoop() # end def def redo(self): part = self._part strand5p = self._strand5p", "= ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) # if self._update_oligo and not getBatch():", "ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3 = strand3p.strandSet() vh3p", "= ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end", "strand3p) # if self._update_oligo and not getBatch(): if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end", "\"\"\" Removes a Xover from the 3' end of strand5p to the 5'", "old_olg3p.isLoop(): old_olg3p.setLoop(False) else: # 2. restore the modified oligo length olg5p.decrementLength(old_olg3p.length()) # 3.", "2. restore the modified oligo length olg5p.decrementLength(new_olg3p.length()) # 3. apply the old oligo", "uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._update_oligo: # Test Loopiness if old_olg3p.isLoop(): old_olg3p.setLoop(False)", "0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._isLoop: olg5p.setLoop(True)", "length olg5p.incrementLength(old_olg3p.length()) # 2. Remove the old oligo and apply the 5' oligo", "strand5p = self._strand5p strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx olg5p", "= strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._isLoop:", "length olg5p.decrementLength(old_olg3p.length()) # 3. apply the old oligo to strand3p old_olg3p.addToPart(part) for strand", "from cadnano.strand import Strand from cadnano import getBatch import cadnano.preferences as prefs import", "strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._isLoop: olg5p.setLoop(False)", "length olg5p.decrementLength(new_olg3p.length()) # 3. apply the old oligo to strand3p new_olg3p.addToPart(part) for strand", "of strand3p 2. install the crossover 3. update the oligo length 4. apply", "the old oligo of strand3p 2. install the crossover 3. apply the strand5p", "= strand3p.oligo().shallowCopy() colorList = prefs.STAP_COLORS if strand5p.strandSet().isStaple() \\ else prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0) for", "if self._update_oligo and not getBatch(): if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def", "olg5p.setLoop(True) # No need to restore whatever the old Oligo._strand5p was else: #", "strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._update_oligo: # Test for Loopiness if olg5p == strand3p.oligo():", "= self._old_oligo3p olg5p = strand5p.oligo() # 0. Deselect the involved strands doc =", "the strand3p \"\"\" def __init__(self, part, strand5p, strand3p): super(RemoveXoverCommand, self).__init__(\"remove xover\") self._part =", "strand3p._name)) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3 = strand3p.strandSet()", "= self._strand3p_idx olg5p = strand5p.oligo() old_olg3p = self._old_oligo3p # 0. Deselect the involved", "prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0) for strand in strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength()) # end def n_o3p.setStrand5p(strand3p) self._isLoop", "cadnano.strand import Strand from cadnano import getBatch import cadnano.preferences as prefs import random", "if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self): part = self._part strand5p", "if self._update_oligo: # Test Loopiness if old_olg3p.isLoop(): old_olg3p.setLoop(False) else: # 2. restore the", "the 5' oligo to the 3' strand old_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): #", "olg5p.incrementLength(new_olg3p.length()) # 2. Remove the old oligo and apply the 5' oligo to", "self._part = part self._strand5p = strand5p self._strand5p_idx = strand5p_idx self._strand3p = strand3p self._strand3p_idx", "in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # 3. install the Xover strand5p.setConnection3p(strand3p)", "= self._new_oligo3p # 0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p)", "doc.removeStrandFromSelection(strand3p) # 1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._update_oligo: # Test Loopiness", "= strand3p.oligo() self._update_oligo = update_oligo # end def def redo(self): part = self._part", "restore whatever the old Oligo._strand5p was else: # 1. update preserved oligo length", "= ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def", "for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # 3. install the", "= self._strand5p strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx olg5p =", "to the 3' strand old_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand,", "apply the 5' oligo to the 3' strand new_olg3p.removeFromPart() for strand in strand3p.generator3pStrand():", "= self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() old_olg3p = self._old_oligo3p # 0.", "strand5p = self._strand5p strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx old_olg3p", "strand3p = self._strand3p strand3p_idx = self._strand3p_idx old_olg3p = self._old_oligo3p olg5p = strand5p.oligo() #", "%s'%(strand5p._name, strand3p._name)) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3 =", "st5p = ss5.strandType() ss3 = strand3p.strandSet() vh3p = ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part,", "preserve the old oligo of strand3p 2. install the crossover 3. apply the", "cadnano.preferences as prefs import random class CreateXoverCommand(UndoCommand): \"\"\" Creates a Xover from the", "# 2. restore the modified oligo length olg5p.decrementLength(old_olg3p.length()) # 3. apply the old", "3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p", "apply the old oligo to strand3p old_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits", "new_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # end else", "strand5p.idx3Prime() self._strand3p = strand3p self._strand3p_idx = strand3p.idx5Prime() n_o3p = self._new_oligo3p = strand3p.oligo().shallowCopy() colorList", "strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._isLoop: olg5p.setLoop(True) # No need to restore whatever the", "self._strand3p_idx olg5p = strand5p.oligo() old_olg3p = self._old_oligo3p # 0. Deselect the involved strands", "# 0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1.", "if self._isLoop: olg5p.setLoop(True) # No need to restore whatever the old Oligo._strand5p was", "strand3p = self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() old_olg3p = self._old_oligo3p #", "strand5p, strand3p): super(RemoveXoverCommand, self).__init__(\"remove xover\") self._part = part self._strand5p = strand5p self._strand5p_idx =", "n_o3p.incrementLength(strand.totalLength()) # end def n_o3p.setStrand5p(strand3p) self._isLoop = strand3p.oligo().isLoop() # end def def redo(self):", "strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._isLoop: olg5p.setLoop(True) # No need to", "part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) # if self._update_oligo and not getBatch(): if self._update_oligo:", "1. preserve the old oligo of strand3p 2. install the crossover 3. apply", "= strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3 = strand3p.strandSet() vh3p =", "the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1. uninstall the Xover", "old_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3 = strand3p.strandSet()", "strand5p = self._strand5p strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx new_olg3p", "the old oligo to strand3p old_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal", "strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() old_olg3p", "strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx new_olg3p = self._new_oligo3p olg5p", "strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) # if self._update_oligo and not getBatch(): if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) #", "= strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._isLoop: olg5p.setLoop(True) # No need to restore whatever", "= self._strand3p strand3p_idx = self._strand3p_idx new_olg3p = self._new_oligo3p olg5p = self._strand5p.oligo() # 0.", "# 3. apply the old oligo to strand3p new_olg3p.addToPart(part) for strand in strand3p.generator3pStrand():", "# emits strandHasNewOligoSignal Strand.setOligo(strand, old_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p =", "self._update_oligo: # Test for Loopiness if olg5p == strand3p.oligo(): olg5p.setLoop(True) else: # 1.", "self._strand5p = strand5p self._strand5p_idx = strand5p.idx3Prime() self._strand3p = strand3p self._strand3p_idx = strand3p.idx5Prime() n_o3p", "strand3p) if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def # end class class RemoveXoverCommand(UndoCommand):", "of strand5p to the 5' end of strand3p this needs to 1. preserve", "strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None)", "old_olg3p.setLoop(False) else: # 2. restore the modified oligo length olg5p.decrementLength(old_olg3p.length()) # 3. apply", "self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx new_olg3p = self._new_oligo3p olg5p = self._strand5p.oligo()", "Oligo._strand5p was else: # 1. update preserved oligo length olg5p.incrementLength(new_olg3p.length()) # 2. Remove", "= prefs.STAP_COLORS if strand5p.strandSet().isStaple() \\ else prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0) for strand in strand3p.generator3pStrand():", "old oligo to strand3p new_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand,", "doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._update_oligo: # Test", "old_olg3p = self._old_oligo3p olg5p = strand5p.oligo() # 0. Deselect the involved strands doc", "if old_olg3p.isLoop(): old_olg3p.setLoop(False) else: # 2. restore the modified oligo length olg5p.decrementLength(old_olg3p.length()) #", "strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._isLoop: olg5p.setLoop(False) olg5p.setStrand5p(strand3p) else: # 2. restore the modified oligo", "vh3p = ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p)", "= self._strand3p_idx old_olg3p = self._old_oligo3p olg5p = strand5p.oligo() # 0. Deselect the involved", "was else: # 1. update preserved oligo length olg5p.incrementLength(new_olg3p.length()) # 2. Remove the", "strand3p.strandUpdateSignal.emit(strand3p) # end def # end class class RemoveXoverCommand(UndoCommand): \"\"\" Removes a Xover", "the strand5p oligo to the strand3p \"\"\" def __init__(self, part, strand5p, strand5p_idx, strand3p,", "Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._isLoop: olg5p.setLoop(True) #", "strand3p.setConnection5p(None) if self._update_oligo: # Test Loopiness if old_olg3p.isLoop(): old_olg3p.setLoop(False) else: # 2. restore", "self._old_oligo3p = strand3p.oligo() self._update_oligo = update_oligo # end def def redo(self): part =", "and not getBatch(): if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self): part", "# 3. apply the old oligo to strand3p old_olg3p.addToPart(part) for strand in strand3p.generator3pStrand():", "1. update preserved oligo length olg5p.incrementLength(old_olg3p.length()) # 2. Remove the old oligo and", "= strand3p.idx5Prime() n_o3p = self._new_oligo3p = strand3p.oligo().shallowCopy() colorList = prefs.STAP_COLORS if strand5p.strandSet().isStaple() \\", "else prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0) for strand in strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength()) # end def n_o3p.setStrand5p(strand3p)", "preserved oligo length olg5p.incrementLength(new_olg3p.length()) # 2. Remove the old oligo and apply the", "# 2. Remove the old oligo and apply the 5' oligo to the", "doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._update_oligo: # Test for Loopiness if olg5p", "# 0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._isLoop:", "oligo and apply the 5' oligo to the 3' strand old_olg3p.removeFromPart() for strand", "self._strand3p = strand3p self._strand3p_idx = strand3p_idx self._old_oligo3p = strand3p.oligo() self._update_oligo = update_oligo #", "strand3p.oligo().shallowCopy() colorList = prefs.STAP_COLORS if strand5p.strandSet().isStaple() \\ else prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0) for strand", "the old oligo and apply the 5' oligo to the 3' strand old_olg3p.removeFromPart()", "self._new_oligo3p olg5p = self._strand5p.oligo() # 0. Deselect the involved strands doc = strand5p.document()", "else # 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) ss5 = strand5p.strandSet() vh5p =", "olg5p = strand5p.oligo() old_olg3p = self._old_oligo3p # 0. Deselect the involved strands doc", "st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def", "strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3 =", "the 5' oligo to the 3' strand new_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): #", "oligo to the strand3p \"\"\" def __init__(self, part, strand5p, strand5p_idx, strand3p, strand3p_idx, update_oligo=True):", "needs to 1. preserve the old oligo of strand3p 2. install the crossover", "update preserved oligo length olg5p.incrementLength(new_olg3p.length()) # 2. Remove the old oligo and apply", "preserved oligo length olg5p.incrementLength(old_olg3p.length()) # 2. Remove the old oligo and apply the", "oligo of strand3p 2. install the crossover 3. apply the strand5p oligo to", "to the 5' end of strand3p this needs to 1. preserve the old", "# 1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._update_oligo: # Test Loopiness if", "3. apply the old oligo to strand3p old_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): #", "strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, old_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p", "doc.removeStrandFromSelection(strand3p) # 1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._isLoop: olg5p.setLoop(False) olg5p.setStrand5p(strand3p) else:", "= update_oligo # end def def redo(self): part = self._part strand5p = self._strand5p", "ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def", "= part self._strand5p = strand5p self._strand5p_idx = strand5p.idx3Prime() self._strand3p = strand3p self._strand3p_idx =", "# 2. restore the modified oligo length olg5p.decrementLength(new_olg3p.length()) # 3. apply the old", "= part self._strand5p = strand5p self._strand5p_idx = strand5p_idx self._strand3p = strand3p self._strand3p_idx =", "= strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._update_oligo:", "and apply the 5' oligo to the 3' strand old_olg3p.removeFromPart() for strand in", "UndoCommand from cadnano.strand import Strand from cadnano import getBatch import cadnano.preferences as prefs", "5' end of strand3p this needs to 1. preserve the old oligo of", "strand3p = self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() new_olg3p = self._new_oligo3p #", "strand3p \"\"\" def __init__(self, part, strand5p, strand3p): super(RemoveXoverCommand, self).__init__(\"remove xover\") self._part = part", "= self._old_oligo3p # 0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p)", "class class RemoveXoverCommand(UndoCommand): \"\"\" Removes a Xover from the 3' end of strand5p", "part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def #", "Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3", "# emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) #print('strand5p", "emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) #print('strand5p =", "1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._update_oligo: # Test Loopiness if old_olg3p.isLoop():", "ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p)", "strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._update_oligo: #", "doc.removeStrandFromSelection(strand3p) if self._isLoop: olg5p.setLoop(True) # No need to restore whatever the old Oligo._strand5p", "vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self): part =", "strand3p old_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, old_olg3p) ss5 =", "Creates a Xover from the 3' end of strand5p to the 5' end", "= strand3p.strandSet() vh3p = ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p)", "random class CreateXoverCommand(UndoCommand): \"\"\" Creates a Xover from the 3' end of strand5p", "Test for Loopiness if olg5p == strand3p.oligo(): olg5p.setLoop(True) else: # 1. update preserved", "strandHasNewOligoSignal Strand.setOligo(strand, new_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3", "self._strand3p_idx olg5p = strand5p.oligo() new_olg3p = self._new_oligo3p # 0. Deselect the involved strands", "# 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) #print('strand5p = %s, connection3p = %s'%(strand5p._name,", "= self._part strand5p = self._strand5p strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx =", "end def # end class class RemoveXoverCommand(UndoCommand): \"\"\" Removes a Xover from the", "strand5p_idx self._strand3p = strand3p self._strand3p_idx = strand3p_idx self._old_oligo3p = strand3p.oligo() self._update_oligo = update_oligo", "redo(self): part = self._part strand5p = self._strand5p strand5p_idx = self._strand5p_idx strand3p = self._strand3p", "for Loopiness if olg5p == strand3p.oligo(): olg5p.setLoop(True) else: # 1. update preserved oligo", "\"\"\" def __init__(self, part, strand5p, strand3p): super(RemoveXoverCommand, self).__init__(\"remove xover\") self._part = part self._strand5p", "self._strand5p_idx = strand5p.idx3Prime() self._strand3p = strand3p self._strand3p_idx = strand3p.idx5Prime() n_o3p = self._new_oligo3p =", "super(CreateXoverCommand, self).__init__(\"create xover\") self._part = part self._strand5p = strand5p self._strand5p_idx = strand5p_idx self._strand3p", "oligo length olg5p.decrementLength(old_olg3p.length()) # 3. apply the old oligo to strand3p old_olg3p.addToPart(part) for", "= ss5.virtualHelix() st5p = ss5.strandType() ss3 = strand3p.strandSet() vh3p = ss3.virtualHelix() st3p =", "strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def # end class class", "self._strand3p_idx old_olg3p = self._old_oligo3p olg5p = strand5p.oligo() # 0. Deselect the involved strands", "of strand3p this needs to 1. preserve the old oligo of strand3p 2.", "self._part = part self._strand5p = strand5p self._strand5p_idx = strand5p.idx3Prime() self._strand3p = strand3p self._strand3p_idx", "length olg5p.incrementLength(new_olg3p.length()) # 2. Remove the old oligo and apply the 5' oligo", "of strand3p 2. install the crossover 3. apply the strand5p oligo to the", "# 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix()", "not getBatch(): if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self): part =", "strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) #print('strand5p = %s,", "self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() old_olg3p = self._old_oligo3p # 0. Deselect", "= self._strand5p strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx new_olg3p =", "strand3p.oligo(): olg5p.setLoop(True) else: # 1. update preserved oligo length olg5p.incrementLength(old_olg3p.length()) # 2. Remove", "CreateXoverCommand(UndoCommand): \"\"\" Creates a Xover from the 3' end of strand5p to the", "strand5p to the 5' end of strand3p this needs to 1. preserve the", "end def def undo(self): part = self._part strand5p = self._strand5p strand5p_idx = self._strand5p_idx", "self._update_oligo and not getBatch(): if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self):", "Removes a Xover from the 3' end of strand5p to the 5' end", "modified oligo length olg5p.decrementLength(new_olg3p.length()) # 3. apply the old oligo to strand3p new_olg3p.addToPart(part)", "= %s, connection3p = %s'%(strand5p._name, strand3p._name)) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p", "ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def # end", "3' end of strand5p to the 5' end of strand3p this needs to", "the 5' end of strand3p this needs to 1. preserve the old oligo", "strandHasNewOligoSignal Strand.setOligo(strand, old_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3", "part = self._part strand5p = self._strand5p strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx", "olg5p.decrementLength(new_olg3p.length()) # 3. apply the old oligo to strand3p new_olg3p.addToPart(part) for strand in", "the strand3p \"\"\" def __init__(self, part, strand5p, strand5p_idx, strand3p, strand3p_idx, update_oligo=True): super(CreateXoverCommand, self).__init__(\"create", "length 4. apply the new strand3p oligo to the strand3p \"\"\" def __init__(self,", "st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) #", "for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # end else #", "to strand3p new_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, new_olg3p) ss5", "strand5p self._strand5p_idx = strand5p.idx3Prime() self._strand3p = strand3p self._strand3p_idx = strand3p.idx5Prime() n_o3p = self._new_oligo3p", "strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength()) # end def n_o3p.setStrand5p(strand3p) self._isLoop = strand3p.oligo().isLoop() # end def def", "from cadnano.cnproxy import UndoCommand from cadnano.strand import Strand from cadnano import getBatch import", "self._old_oligo3p olg5p = strand5p.oligo() # 0. Deselect the involved strands doc = strand5p.document()", "update preserved oligo length olg5p.incrementLength(old_olg3p.length()) # 2. Remove the old oligo and apply", "strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self): part = self._part strand5p =", "need to restore whatever the old Oligo._strand5p was else: # 1. update preserved", "strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, new_olg3p) ss5 = strand5p.strandSet() vh5p =", "= strand3p_idx self._old_oligo3p = strand3p.oligo() self._update_oligo = update_oligo # end def def redo(self):", "strand3p.oligo().isLoop() # end def def redo(self): part = self._part strand5p = self._strand5p strand5p_idx", "if strand5p.strandSet().isStaple() \\ else prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0) for strand in strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength()) #", "def n_o3p.setStrand5p(strand3p) self._isLoop = strand3p.oligo().isLoop() # end def def redo(self): part = self._part", "end else # 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) ss5 = strand5p.strandSet() vh5p", "= strand5p.oligo() old_olg3p = self._old_oligo3p # 0. Deselect the involved strands doc =", "olg5p) # 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) #print('strand5p = %s, connection3p =", "# strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self): part = self._part", "self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self): part = self._part strand5p =", "Xover from the 3' end of strand5p to the 5' end of strand3p", "self._isLoop: olg5p.setLoop(False) olg5p.setStrand5p(strand3p) else: # 2. restore the modified oligo length olg5p.decrementLength(new_olg3p.length()) #", "emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # end else # 3. install the Xover strand5p.setConnection3p(strand3p)", "olg5p.incrementLength(old_olg3p.length()) # 2. Remove the old oligo and apply the 5' oligo to", "getBatch(): if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self): part = self._part", "oligo to the strand3p \"\"\" def __init__(self, part, strand5p, strand3p): super(RemoveXoverCommand, self).__init__(\"remove xover\")", "restore the modified oligo length olg5p.decrementLength(old_olg3p.length()) # 3. apply the old oligo to", "old oligo of strand3p 2. install the crossover 3. apply the strand5p oligo", "self._strand5p.oligo() # 0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) #", "strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) #print('strand5p = %s, connection3p = %s'%(strand5p._name, strand3p._name)) ss5 = strand5p.strandSet() vh5p", "colorList = prefs.STAP_COLORS if strand5p.strandSet().isStaple() \\ else prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0) for strand in", "install the crossover 3. apply the strand5p oligo to the strand3p \"\"\" def", "the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._isLoop: olg5p.setLoop(False) olg5p.setStrand5p(strand3p) else: # 2. restore the", "prefs.STAP_COLORS if strand5p.strandSet().isStaple() \\ else prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0) for strand in strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength())", "0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1. uninstall", "strand3p self._strand3p_idx = strand3p.idx5Prime() n_o3p = self._new_oligo3p = strand3p.oligo().shallowCopy() colorList = prefs.STAP_COLORS if", "strand3p.strandSet() vh3p = ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p)", "0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._update_oligo: #", "install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) #print('strand5p = %s, connection3p = %s'%(strand5p._name, strand3p._name)) ss5", "strand3p.setConnection5p(strand5p) #print('strand5p = %s, connection3p = %s'%(strand5p._name, strand3p._name)) ss5 = strand5p.strandSet() vh5p =", "strand3p.strandSet() vh3p = ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) if", "self._strand3p_idx = strand3p.idx5Prime() n_o3p = self._new_oligo3p = strand3p.oligo().shallowCopy() colorList = prefs.STAP_COLORS if strand5p.strandSet().isStaple()", "%s, connection3p = %s'%(strand5p._name, strand3p._name)) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p =", "= strand5p.oligo() # 0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p)", "= strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._update_oligo: # Test for Loopiness if olg5p ==", "oligo length olg5p.decrementLength(new_olg3p.length()) # 3. apply the old oligo to strand3p new_olg3p.addToPart(part) for", "strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self): part = self._part strand5p", "crossover 3. update the oligo length 4. apply the new strand3p oligo to", "strand5p oligo to the strand3p \"\"\" def __init__(self, part, strand5p, strand5p_idx, strand3p, strand3p_idx,", "self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() new_olg3p = self._new_oligo3p", "if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def # end class class RemoveXoverCommand(UndoCommand): \"\"\"", "strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # 3. install the Xover", "ss5.virtualHelix() st5p = ss5.strandType() ss3 = strand3p.strandSet() vh3p = ss3.virtualHelix() st3p = ss3.strandType()", "strand5p.oligo() # 0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) #", "3. apply the old oligo to strand3p new_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): #", "apply the 5' oligo to the 3' strand old_olg3p.removeFromPart() for strand in strand3p.generator3pStrand():", "self._strand5p strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx old_olg3p = self._old_oligo3p", "Strand.setOligo(strand, new_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3 =", "else: # 2. restore the modified oligo length olg5p.decrementLength(new_olg3p.length()) # 3. apply the", "= self._strand3p strand3p_idx = self._strand3p_idx old_olg3p = self._old_oligo3p olg5p = strand5p.oligo() # 0.", "= ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p)", "self._strand3p = strand3p self._strand3p_idx = strand3p.idx5Prime() n_o3p = self._new_oligo3p = strand3p.oligo().shallowCopy() colorList =", "the new strand3p oligo to the strand3p \"\"\" def __init__(self, part, strand5p, strand3p):", "# strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) # if self._update_oligo and not getBatch(): if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p)", "strand3p oligo to the strand3p \"\"\" def __init__(self, part, strand5p, strand3p): super(RemoveXoverCommand, self).__init__(\"remove", "# end class class RemoveXoverCommand(UndoCommand): \"\"\" Removes a Xover from the 3' end", "class RemoveXoverCommand(UndoCommand): \"\"\" Removes a Xover from the 3' end of strand5p to", "strand5p.strandSet().isStaple() \\ else prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0) for strand in strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength()) # end", "to the strand3p \"\"\" def __init__(self, part, strand5p, strand5p_idx, strand3p, strand3p_idx, update_oligo=True): super(CreateXoverCommand,", "oligo of strand3p 2. install the crossover 3. update the oligo length 4.", "# end else # 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) ss5 = strand5p.strandSet()", "old oligo and apply the 5' oligo to the 3' strand old_olg3p.removeFromPart() for", "the modified oligo length olg5p.decrementLength(old_olg3p.length()) # 3. apply the old oligo to strand3p", "doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._isLoop: olg5p.setLoop(False) olg5p.setStrand5p(strand3p)", "olg5p.setStrand5p(strand3p) else: # 2. restore the modified oligo length olg5p.decrementLength(new_olg3p.length()) # 3. apply", "strand3p.strandSet() vh3p = ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) #", "strand3p 2. install the crossover 3. update the oligo length 4. apply the", "strand5p self._strand5p_idx = strand5p_idx self._strand3p = strand3p self._strand3p_idx = strand3p_idx self._old_oligo3p = strand3p.oligo()", "def undo(self): part = self._part strand5p = self._strand5p strand5p_idx = self._strand5p_idx strand3p =", "oligo to the 3' strand old_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal", "2. Remove the old oligo and apply the 5' oligo to the 3'", "n_o3p.setStrand5p(strand3p) self._isLoop = strand3p.oligo().isLoop() # end def def redo(self): part = self._part strand5p", "self._strand5p strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo()", "n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0) for strand in strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength()) # end def n_o3p.setStrand5p(strand3p) self._isLoop =", "= ss5.strandType() ss3 = strand3p.strandSet() vh3p = ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p)", "= self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx old_olg3p = self._old_oligo3p olg5p =", "vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def # end", "strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p)", "No need to restore whatever the old Oligo._strand5p was else: # 1. update", "the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._update_oligo: # Test for", "doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if", "the modified oligo length olg5p.decrementLength(new_olg3p.length()) # 3. apply the old oligo to strand3p", "ss5.strandType() ss3 = strand3p.strandSet() vh3p = ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) #", "strand5p.oligo() new_olg3p = self._new_oligo3p # 0. Deselect the involved strands doc = strand5p.document()", "doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._isLoop: olg5p.setLoop(True) # No need to restore", "= strand5p.oligo() new_olg3p = self._new_oligo3p # 0. Deselect the involved strands doc =" ]
[ "temperature_in_celsius = sensor.get_temperature() temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units = sensor.get_temperatures([W1ThermSensor.DEGREES_C, W1ThermSensor.DEGREES_F, W1ThermSensor.KELVIN]) print(\"Sensor id:\"", "temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units = sensor.get_temperatures([W1ThermSensor.DEGREES_C, W1ThermSensor.DEGREES_F, W1ThermSensor.KELVIN]) print(\"Sensor id:\" + sensor.id) print(temperature_in_celsius)", "w1thermsensor import W1ThermSensor sensor = W1ThermSensor() temperature_in_celsius = sensor.get_temperature() temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units", "from w1thermsensor import W1ThermSensor sensor = W1ThermSensor() temperature_in_celsius = sensor.get_temperature() temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F)", "W1ThermSensor sensor = W1ThermSensor() temperature_in_celsius = sensor.get_temperature() temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units = sensor.get_temperatures([W1ThermSensor.DEGREES_C,", "sensor.get_temperature() temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units = sensor.get_temperatures([W1ThermSensor.DEGREES_C, W1ThermSensor.DEGREES_F, W1ThermSensor.KELVIN]) print(\"Sensor id:\" + sensor.id)", "import W1ThermSensor sensor = W1ThermSensor() temperature_in_celsius = sensor.get_temperature() temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units =", "= W1ThermSensor() temperature_in_celsius = sensor.get_temperature() temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units = sensor.get_temperatures([W1ThermSensor.DEGREES_C, W1ThermSensor.DEGREES_F, W1ThermSensor.KELVIN])", "sensor = W1ThermSensor() temperature_in_celsius = sensor.get_temperature() temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units = sensor.get_temperatures([W1ThermSensor.DEGREES_C, W1ThermSensor.DEGREES_F,", "= sensor.get_temperature() temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units = sensor.get_temperatures([W1ThermSensor.DEGREES_C, W1ThermSensor.DEGREES_F, W1ThermSensor.KELVIN]) print(\"Sensor id:\" +", "W1ThermSensor() temperature_in_celsius = sensor.get_temperature() temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units = sensor.get_temperatures([W1ThermSensor.DEGREES_C, W1ThermSensor.DEGREES_F, W1ThermSensor.KELVIN]) print(\"Sensor" ]
[ "Generated by Django 3.1.1 on 2020-09-01 17:04 from django.db import migrations, models class", "('tables', '0003_exposure_category'), ] operations = [ migrations.AlterField( model_name='exposure', name='location', field=models.CharField(blank=True, default='', max_length=200), ),", "2020-09-01 17:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tables',", "by Django 3.1.1 on 2020-09-01 17:04 from django.db import migrations, models class Migration(migrations.Migration):", "on 2020-09-01 17:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "Migration(migrations.Migration): dependencies = [ ('tables', '0003_exposure_category'), ] operations = [ migrations.AlterField( model_name='exposure', name='location',", "dependencies = [ ('tables', '0003_exposure_category'), ] operations = [ migrations.AlterField( model_name='exposure', name='location', field=models.CharField(blank=True,", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tables', '0003_exposure_category'), ]", "class Migration(migrations.Migration): dependencies = [ ('tables', '0003_exposure_category'), ] operations = [ migrations.AlterField( model_name='exposure',", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('tables', '0003_exposure_category'), ] operations =", "3.1.1 on 2020-09-01 17:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "Django 3.1.1 on 2020-09-01 17:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies", "'0003_exposure_category'), ] operations = [ migrations.AlterField( model_name='exposure', name='location', field=models.CharField(blank=True, default='', max_length=200), ), ]", "[ ('tables', '0003_exposure_category'), ] operations = [ migrations.AlterField( model_name='exposure', name='location', field=models.CharField(blank=True, default='', max_length=200),", "migrations, models class Migration(migrations.Migration): dependencies = [ ('tables', '0003_exposure_category'), ] operations = [", "= [ ('tables', '0003_exposure_category'), ] operations = [ migrations.AlterField( model_name='exposure', name='location', field=models.CharField(blank=True, default='',", "# Generated by Django 3.1.1 on 2020-09-01 17:04 from django.db import migrations, models", "models class Migration(migrations.Migration): dependencies = [ ('tables', '0003_exposure_category'), ] operations = [ migrations.AlterField(", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tables', '0003_exposure_category'), ] operations", "17:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tables', '0003_exposure_category')," ]
[ "#Copyright ReportLab Europe Ltd. 2000-2016 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/graphics/charts/__init__.py __version__='3.3.0'", "Europe Ltd. 2000-2016 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/graphics/charts/__init__.py __version__='3.3.0' __doc__='''Business charts'''", "ReportLab Europe Ltd. 2000-2016 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/graphics/charts/__init__.py __version__='3.3.0' __doc__='''Business" ]
[ "requirements, but is specifically disallowed for this image. Please try a different value.\".format(username))", "_validate_vm_create_nsg(cmd, namespace): if namespace.nsg: if check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_type = 'existing'", "> 100: if namespace.single_placement_group is None: namespace.single_placement_group = False elif namespace.single_placement_group: raise CLIError(\"usage", "'publicIPAddresses'): namespace.public_ip_address_type = 'existing' logger.debug(\"using existing specified public IP '%s'\", namespace.public_ip_address) else: namespace.public_ip_address_type", "specifically disallowed for this image. Please try a different value.\".format(username)) return username def", "is_linux and re.findall(r'^[$-]+', username): raise CLIError(linux_err) if not is_linux and username.endswith('.'): raise CLIError(win_err)", "and namespace.single_placement_group is False and std_lb_is_available: LBSkuName = cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer_sku is", "else 123 min_length = 12 if len(password) not in range(min_length, max_length + 1):", "exposed yet for VMSS, so use 'getattr' to avoid crash namespace.disk_info = normalize_disk_info(image_data_disks_num=image_data_disks_num,", "'existing' logger.debug(\"using specified existing storage account '%s'\", storage_id['name']) else: # 2 - params", "namespace.vm_sku = 'Standard_DS1_v2' else: namespace.vm_sku = 'Standard_D1_v2' _validate_location(cmd, namespace, namespace.zones, namespace.vm_sku) validate_asg_names_or_ids(cmd, namespace)", "length=8)) def validate_keyvault(cmd, namespace): namespace.keyvault = _get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_vm_secret_format(cmd,", "load balancer will be created') if namespace.load_balancer_type == 'new' and namespace.single_placement_group is False", "CLIError(\"usage error: os type is required to create the image, \" \"please specify", "== 'images': image_info = compute_client.images.get(res['resource_group'], res['name']) namespace.os_type = image_info.storage_profile.os_disk.os_type.value image_data_disks_num = len(image_info.storage_profile.data_disks or", "if 'certificateUrl' not in cert: errors.append(message.format('certificateUrl', idx, jdx, idx_arg)) if is_windows and 'certificateStore'", "subnet: subnet_is_id = is_valid_resource_id(subnet) if (subnet_is_id and vnet) or (not subnet_is_id and not", "namespace.storage_profile == StorageProfile.ManagedCustomImage: required = ['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk']", "required.append('app_gateway_capacity') if namespace.vnet_type != 'new': required.append('app_gateway_subnet_address_prefix') elif namespace.app_gateway_type == 'existing': required.append('backend_pool_name') forbidden =", "def _validate_vmss_create_nsg(cmd, namespace): if namespace.nsg: namespace.nsg = _get_resource_id(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'networkSecurityGroups', 'Microsoft.Network') def", "not in secret['sourceVault']: errors.append( 'Secret is missing sourceVault.id key at index {0} in", "'application_gateway', 'app_gateway_sku', 'app_gateway_capacity'] validate_parameter_set(namespace, required, forbidden, description='network balancer: load balancer') if namespace.load_balancer: rg", "$ or -' win_err = r'admin user name cannot contain special characters \\/\"[]:|<>+=;,?*@#", "is missing sourceVault key at index {0} in arg {1}'.format( idx, idx_arg)) if", "assign system identity\") # keep 'identity_role' for output as logical name is more", "account namespace.storage_account_type = 'new' logger.debug('no suitable storage account found. One will be created.')", "'Standard_E32-16_v3', 'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC', 'Standard_F16_ABC', 'Standard_F32s_v2', 'Standard_D15_v2', 'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested', 'Standard_DS15_v2', 'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested', 'Standard_D40_v3', 'Standard_D40s_v3',", "{} and {}'.format(min_length, max_length)) contains_lower = re.findall('[a-z]+', password) contains_upper = re.findall('[A-Z]+', password) contains_digit", "size = size.lower() # to refresh the list, run 'az vm create --accelerated-networking", "return resource_id(**kwargs) if not missing_kwargs else None def _get_nic_id(cli_ctx, val, resource_group): return _get_resource_id(cli_ctx,", "= resource_id( subscription=subscription_id, resource_group=resource_group, namespace='Microsoft.Network', type='applicationSecurityGroups', name=val ) ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace, 'application_security_groups', ids) def", "array or it is empty at index {0} in ' \\ 'arg {1}", "new_mask): def _convert_to_int(address, bit_mask_len): a, b, c, d = [int(x) for x in", "proper arguments supplied based on the authentication type if namespace.authentication_type == 'password': if", "namespace.resource_group_name, 'images', 'Microsoft.Compute') return 'image_id' except CloudError: err = 'Invalid image \"{}\". Use", "in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]: # pylint: disable=line-too-long namespace.storage_sku = 'Standard_LRS' if for_scale_set else 'Premium_LRS'", "namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, lb_name, 'load_balancers') if not namespace.nat_pool_name: if len(lb.inbound_nat_pools) >", "raise ValueError('Admin password cannot be used with SSH authentication type') validate_ssh_key(namespace) if not", "namespace.os_publisher, namespace.os_offer, namespace.os_sku if not publisher: return publisher, offer, sku = publisher.lower(), offer.lower(),", "string_or_file = (namespace.ssh_key_value or os.path.join(os.path.expanduser('~'), '.ssh', 'id_rsa.pub')) content = string_or_file if os.path.exists(string_or_file): logger.info('Use", "is empty at index {0} in ' \\ 'arg {1} ' errors.append(err.format(idx, idx_arg))", "\"[--admin-username USERNAME] --admin-password PASSWORD\") from knack.prompting import prompt_pass, NoTTYException try: if not namespace.admin_password:", "'new' logger.debug(\"load balancer '%s' not found. It will be created.\", namespace.load_balancer) elif namespace.load_balancer", "resource_group_name, source): from msrestazure.azure_exceptions import CloudError source_blob_uri = None source_disk = None source_snapshot", "try: replica_count = int(parts[1]) except ValueError: raise CLIError(\"usage error: {}'s replica count must", "for_scale_set=False): from msrestazure.tools import parse_resource_id # use minimal parameters to resolve the expected", "ID') def process_disk_or_snapshot_create_namespace(cmd, namespace): from msrestazure.azure_exceptions import CloudError validate_tags(namespace) if namespace.source: usage_error =", "not found and will be created\", storage_id['name']) else: from azure.cli.core.profiles import ResourceType from", "[('canonical', 'UbuntuServer', '^16.04'), ('suse', 'sles', '^12-sp3'), ('redhat', 'rhel', '^7.4'), ('openlogic', 'centos', '^7.4'), ('coreos',", "content def _validate_vm_vmss_msi(cmd, namespace, from_set_command=False): if from_set_command or namespace.assign_identity is not None: identities", "'%s'\", namespace.application_gateway) except CloudError: namespace.app_gateway_type = 'new' logger.debug(\"application gateway '%s' not found. It", "find such locations\".format(namespace.resource_group_name)) # pylint: disable=too-many-branches, too-many-statements def _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False): from msrestazure.tools", "existing storage account specified namespace.storage_account_type = 'existing' logger.debug(\"using specified existing storage account '%s'\",", "out appropriate file names: # 'base_name'(with private keys), and 'base_name.pub'(with public keys) public_key_filepath", "namespace.identity_scope: if identities and MSI_LOCAL_ID not in identities: raise CLIError(\"usage error: '--scope'/'--role' is", "frontend required = [] forbidden = ['app_gateway_subnet_address_prefix', 'application_gateway', 'app_gateway_sku', 'app_gateway_capacity'] validate_parameter_set(namespace, required, forbidden,", "logger.debug('no load balancer will be used') elif namespace.load_balancer is None: namespace.load_balancer_type = 'new'", "is_valid_resource_id(subnet) if (subnet_is_id and vnet) or (not subnet_is_id and not vnet): raise CLIError(\"incorrect", "[] namespace.data_disks = [] namespace.data_snapshots = [] if namespace.data_disk_sources: for data_disk_source in namespace.data_disk_sources:", "--instance-id ID | --size-gb GB') elif bool(namespace.disk) != bool(namespace.instance_id): raise CLIError('usage error: --disk", "image in the marketplace # Ubuntu 16.04, SLES 12 SP3, RHEL 7.4, CentOS", "len(role_defs) > 1: ids = [r.id for r in role_defs] err = \"More", "get_subscription_id if is_valid_resource_id(val): return val kwargs = { 'name': val, 'resource_group': resource_group, 'namespace':", "max_length)) contains_lower = re.findall('[a-z]+', password) contains_upper = re.findall('[A-Z]+', password) contains_digit = re.findall('[0-9]+', password)", "'Invalid image \"{}\". Use a custom image name, id, or pick one from", "val = resource_id( subscription=subscription_id, resource_group=resource_group, namespace='Microsoft.Network', type='applicationSecurityGroups', name=val ) ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace, 'application_security_groups', ids)", "in ' \\ 'arg {1} ' errors.append(err.format(idx, idx_arg)) else: for jdx, cert in", "a capable one. 'az vm list-skus' can be \" \"used to find such", "try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse # pylint:", "# AppGateway frontend required = [] if namespace.app_gateway_type == 'new': required.append('app_gateway_sku') required.append('app_gateway_capacity') if", "== StorageProfile.ManagedCustomImage: # extract additional information from a managed custom image res =", ":param string os_type: the type of OS (linux or windows) :return: errors if", "for new storage account specified namespace.storage_account_type = 'new' logger.debug(\"specified storage account '%s' not", "'Standard_DS15_v2', 'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested', 'Standard_D40_v3', 'Standard_D40s_v3', 'Standard_D15_v2_ABC', 'Standard_M64ms', 'Standard_M64s', 'Standard_M128-64ms', 'Standard_D64_v3', 'Standard_D64s_v3', 'Standard_E64_v3', 'Standard_E64s_v3',", "if namespace.generate_ssh_keys: # figure out appropriate file names: # 'base_name'(with private keys), and", "= StorageProfile.SASpecializedOSDisk else: # STORAGE PROFILE #6 namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk elif namespace.image and", "'Standard_D32_v3', 'Standard_D32s_v3', 'Standard_D64-32s_v3', 'Standard_E32_v3', 'Standard_E32s_v3', 'Standard_E32-8s_v3', 'Standard_E32-16_v3', 'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC', 'Standard_F16_ABC', 'Standard_F32s_v2', 'Standard_D15_v2', 'Standard_D15_v2_Promo',", "in sizes if s.name.lower() == size), None) if size_info is None or size_info.number_of_cores", "OS type. Specify '--os-type' argument.\") if not namespace.authentication_type: # apply default auth type", "= None if urlparse(source).scheme: # a uri? source_blob_uri = source elif '/disks/' in", "_get_resource_id(cmd.cli_ctx, namespace.identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') # TODO move to its own command module", "is not None and namespace.zones is None: raise CLIError('usage error: --platform-fault-domain-count COUNT --zones", "lb.inbound_nat_pools: # Associated scaleset will be missing ssh/rdp, so warn here. logger.warning(\"No inbound", "namespace, namespace.zones, namespace.vm_sku) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=True) _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=True) _validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd,", "CoreOS Linux, Debian \"Stretch\" with backports kernel # Oracle Linux 7.4, Windows Server", "7.4, CoreOS Linux, Debian \"Stretch\" with backports kernel # Oracle Linux 7.4, Windows", "from Azure Marketplace image' elif profile == StorageProfile.ManagedSpecializedOSDisk: return 'attach existing managed OS", "1 - existing storage account specified namespace.storage_account_type = 'existing' logger.debug(\"using specified existing storage", "if v.location == location and v.subnets): # 1 - find a suitable existing", "POLICY]') # endregion # region disk, snapshot, image validators def validate_vm_disk(cmd, namespace): namespace.disk", "in arg {1}'.format( idx, idx_arg)) if 'vaultCertificates' not in secret or not secret['vaultCertificates']:", "load balancer '%s'\", namespace.load_balancer) else: namespace.load_balancer_type = 'new' logger.debug(\"load balancer '%s' not found.", "'create unmanaged OS disk from Azure Marketplace image' elif profile == StorageProfile.SASpecializedOSDisk: return", "resource_id, is_valid_resource_id from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_subscription_id ApplicationSecurityGroup = cmd.get_models('ApplicationSecurityGroup',", "getattr(namespace, 'vm_sku', None) size = size.lower() # to refresh the list, run 'az", "'Standard_D8s_v3'] new_4core_sizes = [x.lower() for x in new_4core_sizes] if size not in new_4core_sizes:", "application gateway '%s'\", namespace.application_gateway) except CloudError: namespace.app_gateway_type = 'new' logger.debug(\"application gateway '%s' not", "- unmanaged vhd based images? if urlparse(namespace.image).scheme: return 'uri' # 4 - attempt", "EXIST_DISK --instance-id ID | --size-gb GB') elif bool(namespace.disk) != bool(namespace.instance_id): raise CLIError('usage error:", "empty\") is_linux = (os_type.lower() == 'linux') # pylint: disable=line-too-long pattern = (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if", "for license information. # -------------------------------------------------------------------------------------------- # pylint:disable=too-many-lines import os try: from urllib.parse import", "2017-03-30), Resource_sku doesn't implement location_info property if not hasattr(temp, 'location_info'): return if not", "existing storage account '%s' will be used\", account.name) else: # 4 - nothing", "error: '--single-placement-group' should be turned off for zonal scale-sets or with\" \" 100+", "lb_name = parse_resource_id(namespace.load_balancer)['name'] lb = get_network_lb(cmd.cli_ctx, namespace.resource_group_name, lb_name) if lb: namespace.load_balancer_type = 'existing'", "'/snapshots/' in source.lower(): source_snapshot = source else: compute_client = _compute_client_factory(cli_ctx) # pylint: disable=no-member", "if check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_type = 'existing' logger.debug(\"using specified NSG '%s'\",", "from azure.cli.core.commands.client_factory import get_subscription_id nics_value = namespace.nics nics = [] if not nics_value:", "_validate_vm_vmss_create_vnet(cmd, namespace) _validate_vm_create_nsg(cmd, namespace) _validate_vm_vmss_create_public_ip(cmd, namespace) _validate_vm_create_nics(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) if namespace.secrets:", "'%s'\", namespace.load_balancer) else: namespace.nat_pool_name = lb.inbound_nat_pools[0].name logger.debug(\"using specified existing load balancer '%s'\", namespace.load_balancer)", "need to be a supported image in the marketplace # Ubuntu 16.04, SLES", "secret ' \\ 'index {1} and vaultCertificate index {2} in arg {3}' if", "namespace.storage_profile in [StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]: return namespace.admin_username = _validate_admin_username(namespace.admin_username, namespace.os_type) if not namespace.os_type: raise", "= {k: v for k, v in kwargs.items() if not v} return resource_id(**kwargs)", "= get_network_client(cmd.cli_ctx).virtual_networks # find VNET in target resource group that matches the VM's", "namespace.nsg_type = 'new' logger.debug('new NSG will be created') def _validate_vmss_create_nsg(cmd, namespace): if namespace.nsg:", "result.name namespace.vnet_name = vnet_match.name namespace.vnet_type = 'existing' logger.debug(\"existing vnet '%s' and subnet '%s'", "be supplied to SSH Key Value. ' 'You can use --generate-ssh-keys to let", "image_version = _get_latest_image_version(cmd.cli_ctx, namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku) else: image_version = namespace.os_version image =", "'windows' or namespace.admin_password) else 'ssh' if namespace.os_type.lower() == 'windows' and namespace.authentication_type == 'ssh':", "subscription_id=res['subscription']) if res['type'].lower() == 'images': image_info = compute_client.images.get(res['resource_group'], res['name']) namespace.os_type = image_info.storage_profile.os_disk.os_type.value image_data_disks_num", "more readable setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role, namespace.identity_scope)) elif namespace.identity_scope or getattr(namespace.identity_role, 'is_default', None)", "namespace.vm_sku is None: from azure.cli.core.cloud import AZURE_US_GOV_CLOUD if cmd.cli_ctx.cloud.name != AZURE_US_GOV_CLOUD.name: namespace.vm_sku =", "'new' and namespace.single_placement_group is False and std_lb_is_available: LBSkuName = cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer_sku", "output as logical name is more readable setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role, namespace.identity_scope)) elif", "disable=no-member namespace.os_type = vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine = res_id if namespace.data_disk_sources: raise CLIError(\"'--data-disk-sources' is not", "or []) else: raise CLIError('usage error: unrecognized image informations \"{}\"'.format(namespace.image)) # pylint: disable=no-member", "def _validate_vmss_create_public_ip(cmd, namespace): if namespace.load_balancer_type is None and namespace.app_gateway_type is None: if namespace.public_ip_address:", "if not for_scale_set: result = next((s for s in vnet_match.subnets if s.name.lower() !=", "'Standard_F8s', 'Standard_M64-16ms', 'Standard_D16_v3', 'Standard_D16s_v3', 'Standard_D32-16s_v3', 'Standard_D64-16s_v3', 'Standard_E16_v3', 'Standard_E16s_v3', 'Standard_E32-16s_v3', 'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC', 'Standard_F8_ABC', 'Standard_F16s_v2',", "region VMSS Create Validators def _get_default_address_pool(cli_ctx, resource_group, balancer_name, balancer_type): option_name = '--backend-pool-name' client", "mask = subnet_cidr.split('/') subnet_bit_mask_len = 32 - int(mask) if vnet_bit_mask_len <= subnet_bit_mask_len: raise", "namespace.public_ip_sku == PublicIPAddressSkuName.standard.value: if not namespace.public_ip_address_allocation: namespace.public_ip_address_allocation = IPAllocationMethod.static.value def _validate_vmss_create_public_ip(cmd, namespace): if", "x in images])) def _get_image_plan_info_if_exists(cmd, namespace): from msrestazure.azure_exceptions import CloudError try: compute_client =", "the list, run 'az vm create --accelerated-networking --size Standard_DS1_v2' and # get it", "== 'existing': required.append('backend_pool_name') forbidden = ['nat_pool_name', 'load_balancer', 'health_probe'] validate_parameter_set(namespace, required, forbidden, description='network balancer:", "ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client storage_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts # find storage account", "if os.path.exists(string_or_file): logger.info('Use existing SSH public key file: %s', string_or_file) with open(string_or_file, 'r')", "key file: %s', string_or_file) with open(string_or_file, 'r') as f: content = f.read() elif", "'password' \\ if (namespace.os_type.lower() == 'windows' or namespace.admin_password) else 'ssh' if namespace.os_type.lower() ==", "being used balancer_type = 'None' if namespace.load_balancer is None and namespace.application_gateway is None:", "'subnets', vnet, 'virtualNetworks') if subnet_is_id and not subnet_exists: raise CLIError(\"Subnet '{}' does not", "VHD' elif profile == StorageProfile.SAPirImage: return 'create unmanaged OS disk from Azure Marketplace", "create a new storage account namespace.storage_account_type = 'new' logger.debug('no suitable storage account found.", "try: compute_client = _compute_client_factory(cmd.cli_ctx) if namespace.os_version.lower() == 'latest': image_version = _get_latest_image_version(cmd.cli_ctx, namespace.location, namespace.os_publisher,", "'{0}' \" \"explicitly.\".format(option_name, ', '.join(values))) elif not values: raise CLIError(\"No existing values found", "return 'create managed OS disk from custom image' elif profile == StorageProfile.ManagedPirImage: return", "'Standard_F4_ABC', 'Standard_F8s_v2', 'Standard_D4_v2', 'Standard_D13_v2', 'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo', 'Standard_DS4_v2', 'Standard_DS13_v2', 'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo', 'Standard_F8',", "required = ['image', 'use_unmanaged_disk'] forbidden = ['os_type', 'attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SACustomImage:", "is supplied for the --image parameter. Updates the namespace and returns the type", "== StorageProfile.SACustomImage: required = ['image', 'os_type', 'use_unmanaged_disk'] forbidden = ['attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile", "if namespace.storage_sku == 'UltraSSD_LRS' and namespace.ultra_ssd_enabled is None: namespace.ultra_ssd_enabled = True # Now", "= keys.generate_ssh_keys(private_key_filepath, public_key_filepath) logger.warning(\"SSH key files '%s' and '%s' have been generated under", "image_info.storage_profile.os_disk.os_type.value image_data_disks_num = len(image_info.storage_profile.data_disks or []) elif res['type'].lower() == 'galleries': image_info = compute_client.gallery_images.get(resource_group_name=res['resource_group'],", "raise CLIError('SSH not supported for Windows VMs.') # validate proper arguments supplied based", "def process_msi_namespace(cmd, namespace): get_default_location_from_resource_group(cmd, namespace) validate_tags(namespace) def process_gallery_image_version_namespace(cmd, namespace): TargetRegion = cmd.get_models('TargetRegion') if", "in arg {3}' if 'certificateUrl' not in cert: errors.append(message.format('certificateUrl', idx, jdx, idx_arg)) if", "'os_caching', 'storage_account', 'storage_container_name', 'use_unmanaged_disk', 'storage_sku'] + auth_params _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.SAPirImage: required", "is None and namespace.application_gateway is None: if std_lb_is_available: balancer_type = 'loadBalancer' else: #", "s in vnet_match.subnets if _check_subnet(s)), None) if not result: continue namespace.subnet = result.name", "found. One will be created.') def _subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision): mask = int(subnet_mask) #", "Windows VM') _validate_vm_vmss_msi(cmd, namespace) if namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage = get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage) # endregion #", "gallery_image_version.lower() in ['latest', '']: image_version_infos = compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) image_version_infos = [x", "resource_type=ResourceType.MGMT_NETWORK) if namespace.public_ip_sku == PublicIPAddressSkuName.standard.value: if not namespace.public_ip_address_allocation: namespace.public_ip_address_allocation = IPAllocationMethod.static.value def _validate_vmss_create_public_ip(cmd,", "aval_sizes = [x.lower() for x in aval_sizes] if size not in aval_sizes: return", "'Standard_DS2_v2', 'Standard_E4_v3', 'Standard_E4s_v3', 'Standard_F2', 'Standard_F2s', 'Standard_F4s_v2', 'Standard_D11_v2', 'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C'] aval_sizes = [x.lower() for", "= urn_match.group(1) namespace.os_offer = urn_match.group(2) namespace.os_sku = urn_match.group(3) namespace.os_version = urn_match.group(4) if not", "mask = vnet_cidr.split('/') vnet_bit_mask_len = 32 - int(mask) vnet_int = _convert_to_int(vnet_ip_address, vnet_bit_mask_len) subnet_ip_address,", "in props_to_remove: if prop in required: required.remove(prop) if prop in forbidden: forbidden.remove(prop) #", "re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role, re.I): role_id = role else: try: uuid.UUID(role) role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id,", "== 'windows' and namespace.authentication_type == 'ssh': raise CLIError('SSH not supported for Windows VMs.')", "def _validate_location(cmd, namespace, zone_info, size_info): from ._vm_utils import list_sku_info if not namespace.location: get_default_location_from_resource_group(cmd,", "logger.debug(\"using specified NSG '%s'\", namespace.nsg) else: namespace.nsg_type = 'new' logger.debug(\"specified NSG '%s' not", "'Microsoft.Compute') res = parse_resource_id(res_id) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) vm_info = compute_client.virtual_machines.get(res['resource_group'], res['name']) #", "raise CLIError(\"admin user name can not be empty\") is_linux = (os_type.lower() == 'linux')", "'--scope' is not provided\".format( namespace.identity_role)) user_assigned_identities = [x for x in identities if", "namespace.location) temp = next((x for x in sku_infos if x.name.lower() == size_info.lower()), None)", "logger.debug('no NSG will be used') elif namespace.nsg is None: namespace.nsg_type = 'new' logger.debug('new", "group from vault name :param str vault_name: name of the key vault :return:", "= ['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku)", "name :param str vault_name: name of the key vault :return: resource group name", "an image ID) if is_valid_resource_id(namespace.image): return 'image_id' # 2 - attempt to match", "application gateway will be used') elif namespace.application_gateway is None: namespace.app_gateway_type = 'new' logger.debug('new", "= \\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def _validate_admin_username(username, os_type): import re if not username: raise CLIError(\"admin", "CLIError(\"This user name '{}' meets the general requirements, but is specifically disallowed for", "is turned off\" raise CLIError('usage error:{}'.format(err)) def get_network_client(cli_ctx): from azure.cli.core.profiles import ResourceType from", "be between {} and {}'.format(min_length, max_length)) contains_lower = re.findall('[a-z]+', password) contains_upper = re.findall('[A-Z]+',", "Windows Server 2016, Windows Server 2012R2 publisher, offer, sku = namespace.os_publisher, namespace.os_offer, namespace.os_sku", "validate_tags(namespace) if namespace.vm_sku is None: from azure.cli.core.cloud import AZURE_US_GOV_CLOUD if cmd.cli_ctx.cloud.name != AZURE_US_GOV_CLOUD.name:", "load balancer is required for scale-sets with 100+ instances\" else: err = \"'Standard'", "endregion # region VMSS Create Validators def _get_default_address_pool(cli_ctx, resource_group, balancer_name, balancer_type): option_name =", "None) # For Stack (compute - 2017-03-30), Resource_sku doesn't implement location_info property if", "['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2', 'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC', 'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4', 'Standard_F4_ABC',", "if vnet_bit_mask_len <= subnet_bit_mask_len: raise CLIError(error_msg) candidate_int = _convert_to_int(subnet_ip_address, subnet_bit_mask_len) + 1 if", "Create Validators def _get_default_address_pool(cli_ctx, resource_group, balancer_name, balancer_type): option_name = '--backend-pool-name' client = getattr(get_network_client(cli_ctx),", "vnet_bit_mask_len = 32 - int(mask) vnet_int = _convert_to_int(vnet_ip_address, vnet_bit_mask_len) subnet_ip_address, mask = subnet_cidr.split('/')", "name or ID namespace.attach_os_disk = _get_resource_id( cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if getattr(namespace,", "exist.\".format(name)) namespace.availability_set = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg, namespace='Microsoft.Compute', type='availabilitySets', name=name) logger.debug(\"adding to specified availability", "balancer is required for zonal scale-sets\" elif namespace.instance_count > 100: err = \"'Standard'", "if namespace.storage_profile == StorageProfile.ManagedPirImage: required = ['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name',", "import MSI_LOCAL_ID for i, _ in enumerate(identities): if identities[i] != MSI_LOCAL_ID: identities[i] =", "IP address will be created') # Public-IP SKU is only exposed for VM.", "or key value must be supplied to SSH Key Value. ' 'You can", "else win_err) if is_linux and re.findall(r'^[$-]+', username): raise CLIError(linux_err) if not is_linux and", "created') def _validate_vmss_create_nsg(cmd, namespace): if namespace.nsg: namespace.nsg = _get_resource_id(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'networkSecurityGroups', 'Microsoft.Network')", "if namespace.secrets: _validate_secrets(namespace.secrets, namespace.os_type) if namespace.license_type and namespace.os_type.lower() != 'windows': raise CLIError('usage error:", "storage SKU '{}': allowed values: '{}'\".format(sku, allowed_skus)) def _validate_location(cmd, namespace, zone_info, size_info): from", "raise CLIError(usage_error) except CloudError: raise CLIError(usage_error) def process_image_create_namespace(cmd, namespace): from msrestazure.tools import parse_resource_id", "validate proper arguments supplied based on the authentication type if namespace.authentication_type == 'password':", "'%s'. Configuring plan settings \" \"will be skipped\", namespace.image, ex.message) # pylint: disable=inconsistent-return-statements", "import urlparse # pylint: disable=import-error from knack.log import get_logger from knack.util import CLIError", "v for k, v in kwargs.items() if not v} return resource_id(**kwargs) if not", "Resource_sku doesn't implement location_info property if not hasattr(temp, 'location_info'): return if not temp", "password) count = len([x for x in [contains_lower, contains_upper, contains_digit, contains_special_char] if x])", "on '%s'\", namespace.load_balancer) else: namespace.nat_pool_name = lb.inbound_nat_pools[0].name logger.debug(\"using specified existing load balancer '%s'\",", "the '--scope' is not provided\".format( namespace.identity_role)) user_assigned_identities = [x for x in identities", "group is disabled\", balancer_type) elif namespace.load_balancer: balancer_type = 'loadBalancer' elif namespace.application_gateway: balancer_type =", "CloudError source_blob_uri = None source_disk = None source_snapshot = None if urlparse(source).scheme: #", "'/disks/' in source.lower(): source_disk = source elif '/snapshots/' in source.lower(): source_snapshot = source", "CentOS 7.4, CoreOS Linux, Debian \"Stretch\" with backports kernel # Oracle Linux 7.4,", "STD LB, defaulting to '%s' under because single placement group is disabled\", balancer_type)", "key at index {0} in arg {1}'.format( idx, idx_arg)) if 'vaultCertificates' not in", "specified - create a new storage account namespace.storage_account_type = 'new' logger.debug('no suitable storage", "i, _ in enumerate(identities): if identities[i] != MSI_LOCAL_ID: identities[i] = _get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name,", "if namespace.zones or namespace.instance_count > 100: if namespace.single_placement_group is None: namespace.single_placement_group = False", "CLIError('Error decoding secrets: {0}'.format(err)) for idx_arg, narg_secret in enumerate(loaded_secret): for idx, secret in", "else: def _check_subnet(s): if s.name.lower() == 'gatewaysubnet': return False subnet_mask = s.address_prefix.split('/')[-1] return", "else: raise CLIError('Unrecognized storage profile: {}'.format(namespace.storage_profile)) logger.debug(\"storage profile '%s'\", namespace.storage_profile) if for_scale_set: #", "== StorageProfile.ManagedPirImage: required = ['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if", "as_id['name'] rg = as_id.get('resource_group', namespace.resource_group_name) if not check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute', 'availabilitySets'): raise", "'location_info'): return if not temp or not [x for x in (temp.location_info or", "= 'existing' logger.debug(\"using specified vnet '%s' and subnet '%s'\", namespace.vnet_name, namespace.subnet) return #", "i = 0 for i in range(24, 16, -1): if _subnet_capacity_check(i, namespace.instance_count, not", "= _convert_to_int(subnet_ip_address, subnet_bit_mask_len) + 1 if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int:", "'id': n if '/' in n else resource_id(name=n, resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)), 'properties':", "following: 1 lower case character, 1 upper case character, 1 number and 1", "'': namespace.nsg_type = None logger.debug('no NSG will be used') elif namespace.nsg is None:", "one first and try \" \"again.\".format(option_name)) return values[0] def _validate_vmss_single_placement_group(namespace): if namespace.platform_fault_domain_count is", "values[0] def _validate_vmss_single_placement_group(namespace): if namespace.platform_fault_domain_count is not None and namespace.zones is None: raise", "new_mask) def _validate_vm_create_nsg(cmd, namespace): if namespace.nsg: if check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_type", "not namespace.image: if namespace.use_unmanaged_disk: # STORAGE PROFILE #3 namespace.storage_profile = StorageProfile.SASpecializedOSDisk else: #", "created.\", namespace.nsg) elif namespace.nsg == '': namespace.nsg_type = None logger.debug('no NSG will be", "= next((x for x in images if x['urnAlias'].lower() == namespace.image.lower()), None) if matched:", "[]) elif res['type'].lower() == 'galleries': image_info = compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) namespace.os_type = image_info.os_type.value", "= _compute_client_factory(cmd.cli_ctx) if namespace.os_version.lower() == 'latest': image_version = _get_latest_image_version(cmd.cli_ctx, namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku)", "_validate_vm_vmss_create_auth(namespace): if namespace.storage_profile in [StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]: return namespace.admin_username = _validate_admin_username(namespace.admin_username, namespace.os_type) if not", "'%s' and '%s' have been generated under ~/.ssh to \" \"allow SSH access", "'Standard_F32s_v2', 'Standard_D15_v2', 'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested', 'Standard_DS15_v2', 'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested', 'Standard_D40_v3', 'Standard_D40s_v3', 'Standard_D15_v2_ABC', 'Standard_M64ms', 'Standard_M64s', 'Standard_M128-64ms',", "username.lower() in disallowed_user_names: raise CLIError(\"This user name '{}' meets the general requirements, but", "from azure.cli.command_modules.vm._vm_utils import check_existence, get_target_network_api, get_storage_blob_uri from azure.cli.command_modules.vm._template_builder import StorageProfile import azure.cli.core.keys as", "next((x for x in sku_infos if x.name.lower() == size_info.lower()), None) # For Stack", "image_info.os_type.value gallery_image_version = res.get('child_name_2', '') if gallery_image_version.lower() in ['latest', '']: image_version_infos = compute_client.gallery_image_versions.list_by_gallery_image(", "CLIError(error_msg) # format back to the cidr candaidate_str = '{0:32b}'.format(candidate_int << subnet_bit_mask_len) return", "# Public-IP SKU is only exposed for VM. VMSS has no such needs", "without \" \"permanent storage, back up your keys to a safe location.\", private_key_filepath,", "identity\") # keep 'identity_role' for output as logical name is more readable setattr(namespace,", "identities[i] != MSI_LOCAL_ID: identities[i] = _get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') if not namespace.identity_scope", "._actions import _get_latest_image_version logger = get_logger(__name__) def validate_asg_names_or_ids(cmd, namespace): from msrestazure.tools import resource_id,", "namespace.load_balancer_type = None logger.debug('no load balancer will be used') elif namespace.load_balancer is None:", "namespace.authentication_type = 'password' \\ if (namespace.os_type.lower() == 'windows' or namespace.admin_password) else 'ssh' if", "== StorageProfile.SAPirImage: return 'create unmanaged OS disk from Azure Marketplace image' elif profile", "been generated under ~/.ssh to \" \"allow SSH access to the VM. If", "getattr(namespace, 'attach_data_disks', None): if not namespace.use_unmanaged_disk: namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name, 'disks', 'Microsoft.Compute')", "namespace.public_ip_per_vm and namespace.vm_domain_name: raise CLIError('Usage error: --vm-domain-name can only be used when --public-ip-per-vm", "4 - attempt to match an URN alias (most likely) from azure.cli.command_modules.vm._actions import", "= get_network_lb(cmd.cli_ctx, namespace.resource_group_name, lb_name) if lb: namespace.load_balancer_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or", "or [] from ._vm_utils import MSI_LOCAL_ID for i, _ in enumerate(identities): if identities[i]", "msrestazure.azure_exceptions import CloudError import re # 1 - check if a fully-qualified ID", "key vault :return: resource group name or None :rtype: str \"\"\" from azure.cli.core.profiles", "distros: if p.lower() == publisher and (o is None or o.lower() == offer)", "namespace='Microsoft.Compute', type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name = namespace.network_security_group_name \\ or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8)) def validate_keyvault(cmd,", "candaidate_str = '{0:32b}'.format(candidate_int << subnet_bit_mask_len) return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2), int(candaidate_str[8:16], 2), int(candaidate_str[16:24], 2), int(candaidate_str[24:32],", "val, resource_group, resource_type, resource_namespace): from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.commands.client_factory import get_subscription_id", "start with the required/forbidden parameters for VM if namespace.storage_profile == StorageProfile.ManagedPirImage: required =", "get_logger from knack.util import CLIError from azure.cli.core.commands.validators import ( get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set, validate_tags)", "resource group that matches the VM's location with a matching subnet for vnet_match", "return ((1 << (32 - mask)) - 2) > int(vmss_instance_count * factor) def", "< 16: err = \"instance count '{}' is out of range of 2^16", "examining the OS type namespace.authentication_type = 'password' \\ if (namespace.os_type.lower() == 'windows' or", "azure.cli.core.keys as keys from ._client_factory import _compute_client_factory from ._actions import _get_latest_image_version logger =", "1: regions_info.append(TargetRegion(name=parts[0])) else: try: replica_count = int(parts[1]) except ValueError: raise CLIError(\"usage error: {}'s", "'/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id, role) except ValueError: pass if not role_id: # retrieve role id", "CloudError import re # 1 - check if a fully-qualified ID (assumes it", "} missing_kwargs = {k: v for k, v in kwargs.items() if not v}", "compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) if res['type'].lower() == 'images': image_info = compute_client.images.get(res['resource_group'], res['name']) namespace.os_type", "'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SASpecializedOSDisk: required = ['os_type', 'attach_os_disk', 'use_unmanaged_disk'] forbidden = ['os_disk_name',", "namespace.image, ex.message) # pylint: disable=inconsistent-return-statements def _get_storage_profile_description(profile): if profile == StorageProfile.SACustomImage: return 'create", "Ubuntu 16.04, SLES 12 SP3, RHEL 7.4, CentOS 7.4, CoreOS Linux, Debian \"Stretch\"", "from azure.cli.command_modules.vm._actions import load_images_from_aliases_doc images = load_images_from_aliases_doc(cmd.cli_ctx) matched = next((x for x in", "None or re.match(s, sku, re.I)): namespace.accelerated_networking = True def _validate_vmss_create_subnet(namespace): if namespace.vnet_type ==", "# extract vnet information needed to verify the defaults we are coming out", "'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: required", "namespace.public_ip_address == '': namespace.public_ip_address_type = None logger.debug('no public IP address will be used')", "supplied to SSH Key Value. ' 'You can use --generate-ssh-keys to let CLI", "= re.findall('[A-Z]+', password) contains_digit = re.findall('[0-9]+', password) contains_special_char = re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password) count", "found. It will be created.\", namespace.application_gateway) elif namespace.application_gateway == '': namespace.app_gateway_type = None", "if x.name.lower() == size_info.lower()), None) # For Stack (compute - 2017-03-30), Resource_sku doesn't", "'Standard_LRS' if for_scale_set else 'Premium_LRS' if namespace.storage_sku == 'UltraSSD_LRS' and namespace.ultra_ssd_enabled is None:", "None): if not namespace.use_unmanaged_disk: namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name, 'disks', 'Microsoft.Compute') for d", "source_blob_uri, source_disk, source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, data_disk_source) if source_blob_uri: namespace.data_blob_uris.append(source_blob_uri) if source_disk:", "from msrestazure.azure_exceptions import CloudError try: compute_client = _compute_client_factory(cmd.cli_ctx) if namespace.os_version.lower() == 'latest': image_version", "vaultCertificate index {2} in arg {3}' if 'certificateUrl' not in cert: errors.append(message.format('certificateUrl', idx,", "in role_defs] err = \"More than one role matches the given name '{}'.", "ValueError: raise CLIError(\"usage error: {}'s replica count must be an integer\".format(parts[0])) regions_info.append(TargetRegion(name=parts[0], regional_replica_count=replica_count))", "['latest', '']: image_version_infos = compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) image_version_infos = [x for x", "{}'s replica count must be an integer\".format(parts[0])) regions_info.append(TargetRegion(name=parts[0], regional_replica_count=replica_count)) namespace.target_regions = regions_info #", "verify that the status of required and forbidden parameters validate_parameter_set( namespace, required, forbidden,", "= namespace.resource_group_name subscription_id = get_subscription_id(cmd.cli_ctx) names_or_ids = getattr(namespace, 'application_security_groups') ids = [] if", "to existing unmanaged OS disk' elif profile == StorageProfile.ManagedCustomImage: return 'create managed OS", "get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults for vault in client.list(): id_comps = parse_resource_id(vault.id) if id_comps['name'] == vault_name:", "StorageProfile.ManagedSpecializedOSDisk: return 'attach existing managed OS disk' def _validate_managed_disk_sku(sku): allowed_skus = ['Premium_LRS', 'Standard_LRS',", "msrestazure.azure_exceptions import CloudError from msrestazure.tools import parse_resource_id from azure.cli.core.profiles import ResourceType std_lb_is_available =", "elif namespace.load_balancer is None: namespace.load_balancer_type = 'new' logger.debug('new load balancer will be created')", "= get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts # find storage account in target resource group that matches", "image_plan: namespace.plan_name = image_plan.name namespace.plan_product = image_plan.product namespace.plan_publisher = image_plan.publisher return 'urn' #", "import StorageProfile import azure.cli.core.keys as keys from ._client_factory import _compute_client_factory from ._actions import", "identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') if not namespace.identity_scope and getattr(namespace.identity_role, 'is_default', None) is None:", "'single placement group' is turned off\" raise CLIError('usage error:{}'.format(err)) def get_network_client(cli_ctx): from azure.cli.core.profiles", "\"cert store name (only on windows)\" }] }] :param dict secrets: Dict fitting", "== '': namespace.public_ip_address_type = None logger.debug('no public IP address will be used') elif", "def process_disk_or_snapshot_create_namespace(cmd, namespace): from msrestazure.azure_exceptions import CloudError validate_tags(namespace) if namespace.source: usage_error = 'usage", "n, rg)) namespace.nics = nic_ids if hasattr(namespace, 'primary_nic') and namespace.primary_nic: namespace.primary_nic = _get_nic_id(cmd.cli_ctx,", "idx, jdx, idx_arg)) if errors: raise CLIError('\\n'.join(errors)) # region VM Create Validators def", "from {}' raise CLIError(err.format(namespace.image, [x['urnAlias'] for x in images])) def _get_image_plan_info_if_exists(cmd, namespace): from", "of range of 2^16 subnet size'\" raise CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix = '{}/{}'.format(cidr, i) if", "raise CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify '{0}' \" \"explicitly.\".format(option_name, ', '.join(values)))", "from msrestazure.azure_exceptions import CloudError import re # 1 - check if a fully-qualified", "if len(lb.inbound_nat_pools) > 1: raise CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify '{0}'", "namespace.public_ip_address is None: namespace.public_ip_address_type = 'new' logger.debug('new public IP address will be created')", "from urllib.parse import urlparse except ImportError: from urlparse import urlparse # pylint: disable=import-error", "namespace.nsg, namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_type = 'existing' logger.debug(\"using specified NSG '%s'\", namespace.nsg) else:", "'attach_os_disk'] forbidden = ['os_disk_name', 'os_caching', 'storage_account', 'storage_container_name', 'use_unmanaged_disk', 'storage_sku'] + auth_params _validate_managed_disk_sku(namespace.storage_sku) elif", "\"incorrect usage for authentication-type 'password': \" \"[--admin-username USERNAME] --admin-password PASSWORD\") from knack.prompting import", "namespace.image = _get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name, 'images', 'Microsoft.Compute') return 'image_id' except CloudError: err =", ".' if re.findall(pattern, username): raise CLIError(linux_err if is_linux else win_err) if is_linux and", "\" \"permanent storage, back up your keys to a safe location.\", private_key_filepath, public_key_filepath)", "managed disk image resource compute_client = _compute_client_factory(cmd.cli_ctx) try: compute_client.images.get(namespace.resource_group_name, namespace.image) namespace.image = _get_resource_id(cmd.cli_ctx,", "expected storage profile if getattr(namespace, 'attach_os_disk', None) and not namespace.image: if namespace.use_unmanaged_disk: #", "subnet_is_id and not vnet): raise CLIError(\"incorrect '--subnet' usage: --subnet SUBNET_ID | \" \"--subnet", "image_info = compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) namespace.os_type = image_info.os_type.value gallery_image_version = res.get('child_name_2', '') if", "a safe location.\", private_key_filepath, public_key_filepath) else: raise CLIError('An RSA key file or key", "= candidate_int - 2 # try the other way around if (candidate_int >>", "disabled\", balancer_type) elif namespace.load_balancer: balancer_type = 'loadBalancer' elif namespace.application_gateway: balancer_type = 'applicationGateway' if", "location = namespace.location nics = getattr(namespace, 'nics', None) if not vnet and not", "getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError(\"usage error: '--role {}' is not applicable", "exposed for VM. VMSS has no such needs so far if getattr(namespace, 'public_ip_sku',", ") ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace, 'application_security_groups', ids) def validate_nsg_name(cmd, namespace): from msrestazure.tools import resource_id from", "= namespace.network_security_group_name \\ or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8)) def validate_keyvault(cmd, namespace): namespace.keyvault = _get_resource_id(cmd.cli_ctx,", "if s.name.lower() == size), None) if size_info is None or size_info.number_of_cores < 8:", "2 - user specified existing vnet/subnet namespace.vnet_type = 'existing' logger.debug(\"using specified vnet '%s'", "available under profile ' 'with minimum Compute API version of 2017-12-01') if namespace.identity_scope:", "used balancer_type = 'None' if namespace.load_balancer is None and namespace.application_gateway is None: if", "namespace, for_scale_set=True) _validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace) _validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd, namespace) _validate_vmss_create_nsg(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace)", "publisher, offer, sku = publisher.lower(), offer.lower(), sku.lower() distros = [('canonical', 'UbuntuServer', '^16.04'), ('suse',", "in disallowed_user_names: raise CLIError(\"This user name '{}' meets the general requirements, but is", "lb = get_network_lb(cmd.cli_ctx, namespace.resource_group_name, lb_name) if lb: namespace.load_balancer_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name", "else: image_version = namespace.os_version image = compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku, image_version) # pylint:", "elif profile == StorageProfile.ManagedSpecializedOSDisk: return 'attach existing managed OS disk' def _validate_managed_disk_sku(sku): allowed_skus", "azure.cli.core.commands.client_factory import get_mgmt_service_client from msrestazure.tools import parse_resource_id client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults for vault", "an existing Vnet and subnet...') # if nothing specified, try to find an", "forbidden.remove(prop) # set default storage SKU if not provided and using an image", "'Microsoft.Compute') if getattr(namespace, 'attach_data_disks', None): if not namespace.use_unmanaged_disk: namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name,", "from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client storage_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts #", "# overflows? candidate_int = candidate_int - 2 # try the other way around", "if not namespace.os_type: raise CLIError(\"Unable to resolve OS type. Specify '--os-type' argument.\") if", "than one role matches the given name '{}'. Please pick an id from", "knack.util import CLIError from azure.cli.core.commands.validators import ( get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set, validate_tags) from azure.cli.core.util", "_check_subnet(s): if s.name.lower() == 'gatewaysubnet': return False subnet_mask = s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask, namespace.instance_count,", "i) if namespace.app_gateway_type and namespace.app_gateway_subnet_address_prefix is None: namespace.app_gateway_subnet_address_prefix = _get_next_subnet_addr_suffix( namespace.vnet_address_prefix, namespace.subnet_address_prefix, 24)", "check if a fully-qualified ID (assumes it is an image ID) if is_valid_resource_id(namespace.image):", "vnet information needed to verify the defaults we are coming out vnet_ip_address, mask", "error: --subnet-address-prefix value should be a subrange of --vnet-address-prefix's\" # extract vnet information", "based OS if not namespace.storage_sku and namespace.storage_profile in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]: # pylint: disable=line-too-long", "{1}\\nSpecify '{0}' explicitly.\".format( # pylint: disable=line-too-long '--nat-pool-name', ', '.join([n.name for n in lb.inbound_nat_pools])))", "from ._actions import _get_latest_image_version logger = get_logger(__name__) def validate_asg_names_or_ids(cmd, namespace): from msrestazure.tools import", "(os_type.lower() == 'linux') max_length = 72 if is_linux else 123 min_length = 12", "'Standard_F16', 'Standard_F16s', 'Standard_M64-32ms', 'Standard_M128-32ms', 'Standard_D32_v3', 'Standard_D32s_v3', 'Standard_D64-32s_v3', 'Standard_E32_v3', 'Standard_E32s_v3', 'Standard_E32-8s_v3', 'Standard_E32-16_v3', 'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC',", "= _get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') if namespace.key_encryption_keyvault: if not namespace.key_encryption_key: raise CLIError(\"Incorrect", "way around if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: raise CLIError(error_msg) #", "that matches the VM's location with a matching subnet for vnet_match in (v", "check_existence(cmd.cli_ctx, storage_id['name'], rg, 'Microsoft.Storage', 'storageAccounts'): # 1 - existing storage account specified namespace.storage_account_type", "based images? if urlparse(namespace.image).scheme: return 'uri' # 4 - attempt to match an", "is not provided\".format( namespace.identity_role)) user_assigned_identities = [x for x in identities if x", "It will be created.\", namespace.public_ip_address) elif namespace.public_ip_address == '': namespace.public_ip_address_type = None logger.debug('no", "validate_tags(namespace) if namespace.source: usage_error = 'usage error: --source {SNAPSHOT | DISK} | --source", "idx_arg)) if errors: raise CLIError('\\n'.join(errors)) # region VM Create Validators def _parse_image_argument(cmd, namespace):", "SP3, RHEL 7.4, CentOS 7.4, CoreOS Linux, Debian \"Stretch\" with backports kernel #", "namespace.target_regions: parts = t.split('=', 1) if len(parts) == 1: regions_info.append(TargetRegion(name=parts[0])) else: try: replica_count", "rg, ag_name, 'application_gateways') logger.debug(\"using specified existing application gateway '%s'\", namespace.application_gateway) except CloudError: namespace.app_gateway_type", "not namespace.disable_overprovision) result = next((s for s in vnet_match.subnets if _check_subnet(s)), None) if", "namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, ag_name, 'application_gateways') logger.debug(\"using specified existing application gateway '%s'\",", "CLIError(\"Availability set '{}' does not exist.\".format(name)) namespace.availability_set = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg, namespace='Microsoft.Compute', type='availabilitySets',", "in range(min_length, max_length + 1): raise CLIError('The password length must be between {}", "namespace.source_virtual_machine = res_id if namespace.data_disk_sources: raise CLIError(\"'--data-disk-sources' is not allowed when capturing \"", "rg, lb_name, 'load_balancers') if not namespace.nat_pool_name: if len(lb.inbound_nat_pools) > 1: raise CLIError(\"Multiple possible", "if not namespace.ssh_dest_key_path: namespace.ssh_dest_key_path = \\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def _validate_admin_username(username, os_type): import re if", "next((s for s in sizes if s.name.lower() == size), None) if size_info is", "if is_windows and 'certificateStore' not in cert: errors.append(message.format('certificateStore', idx, jdx, idx_arg)) if errors:", "# STORAGE PROFILE #6 namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk elif namespace.image and not getattr(namespace, 'attach_os_disk',", "exist.\".format(subnet)) elif subnet_exists: # 2 - user specified existing vnet/subnet namespace.vnet_type = 'existing'", "IPAllocationMethod.static.value def _validate_vmss_create_public_ip(cmd, namespace): if namespace.load_balancer_type is None and namespace.app_gateway_type is None: if", "= 'existing' namespace.public_ip_address_type = None logger.debug('existing NIC(s) will be used') def _validate_vm_vmss_create_auth(namespace): if", "sku as single placement group is turned off\") elif namespace.load_balancer_sku == LBSkuName.basic.value: if", "return _get_resource_id(cli_ctx, val, resource_group, 'networkInterfaces', 'Microsoft.Network') def validate_vm_nic(cmd, namespace): namespace.nic = _get_nic_id(cmd.cli_ctx, namespace.nic,", "COUNT --zones ZONES') if namespace.zones or namespace.instance_count > 100: if namespace.single_placement_group is None:", "an id from '{}'\" raise CLIError(err.format(role, ids)) role_id = role_defs[0].id return role_id def", "STORAGE PROFILE #3 namespace.storage_profile = StorageProfile.SASpecializedOSDisk else: # STORAGE PROFILE #6 namespace.storage_profile =", "subnet_bit_mask_len: raise CLIError(error_msg) candidate_int = _convert_to_int(subnet_ip_address, subnet_bit_mask_len) + 1 if (candidate_int >> (vnet_bit_mask_len", "PASSWORD\") from knack.prompting import prompt_pass, NoTTYException try: if not namespace.admin_password: namespace.admin_password = prompt_pass('Admin", "= matched['publisher'] namespace.os_offer = matched['offer'] namespace.os_sku = matched['sku'] namespace.os_version = matched['version'] return 'urn'", "storage account found. One will be created.') def _validate_vm_create_availability_set(cmd, namespace): from msrestazure.tools import", "# if nothing specified, try to find an existing vnet and subnet in", "storage_id['name']) else: from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client storage_client = get_mgmt_service_client(cmd.cli_ctx,", "rg = namespace.resource_group_name nic_ids = [] for n in namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg))", "'^12-sp3'), ('redhat', 'rhel', '^7.4'), ('openlogic', 'centos', '^7.4'), ('coreos', 'coreos', None), ('credativ', 'debian', '-backports'),", "error: '--scope'/'--role' is only applicable when assign system identity\") # keep 'identity_role' for", "= ['image', 'use_unmanaged_disk'] forbidden = ['os_type', 'attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SACustomImage: required", "sku, re.I)): namespace.accelerated_networking = True def _validate_vmss_create_subnet(namespace): if namespace.vnet_type == 'new': if namespace.subnet_address_prefix", "will be created') # Public-IP SKU is only exposed for VM. VMSS has", "# Resolve the type of balancer (if any) being used balancer_type = 'None'", "resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer and namespace.application_gateway: raise CLIError('incorrect usage: --load-balancer NAME_OR_ID | ' '--application-gateway", "validation for the specific storage profile # start with the required/forbidden parameters for", "namespace.nsg is None: namespace.nsg_type = 'new' logger.debug('new NSG will be created') def _validate_vmss_create_nsg(cmd,", "for x in images])) def _get_image_plan_info_if_exists(cmd, namespace): from msrestazure.azure_exceptions import CloudError try: compute_client", "pylint: disable=no-member try: info = compute_client.snapshots.get(resource_group_name, source) source_snapshot = info.id except CloudError: info", ":return: resource group name or None :rtype: str \"\"\" from azure.cli.core.profiles import ResourceType", "'Standard_D8s_v3', 'Standard_D32-8s_v3', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC', 'Standard_F4_ABC', 'Standard_F8s_v2', 'Standard_D4_v2', 'Standard_D13_v2', 'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo', 'Standard_DS4_v2',", "not in secret: errors.append( 'Secret is missing sourceVault key at index {0} in", "process_gallery_image_version_namespace(cmd, namespace): TargetRegion = cmd.get_models('TargetRegion') if namespace.target_regions: regions_info = [] for t in", "namespace): from msrestazure.azure_exceptions import CloudError try: compute_client = _compute_client_factory(cmd.cli_ctx) if namespace.os_version.lower() == 'latest':", "namespace.nics = nic_ids if hasattr(namespace, 'primary_nic') and namespace.primary_nic: namespace.primary_nic = _get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg)", "keep 'identity_role' for output as logical name is more readable setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx,", "import CloudError validate_tags(namespace) if namespace.source: usage_error = 'usage error: --source {SNAPSHOT | DISK}", "# keep 'identity_role' for output as logical name is more readable setattr(namespace, 'identity_role_id',", "= 'new' logger.debug('new NIC will be created') return if not isinstance(nics_value, list): nics_value", "= role_defs[0].id return role_id def process_vm_create_namespace(cmd, namespace): validate_tags(namespace) _validate_location(cmd, namespace, namespace.zone, namespace.size) validate_asg_names_or_ids(cmd,", "`~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password) count = len([x for x in [contains_lower, contains_upper, contains_digit, contains_special_char] if", "import CloudError network_client = get_network_client(cli_ctx) try: return network_client.load_balancers.get(resource_group_name, lb_name) except CloudError: return None", "the status of required and forbidden parameters validate_parameter_set( namespace, required, forbidden, description='storage profile:", "else 'Standard' account = next( (a for a in storage_client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value ==", "\"adm\", \"admin2\", \"aspnet\", \"backup\", \"console\", \"guest\", \"owner\", \"root\", \"server\", \"sql\", \"support\", \"support_388945a0\", \"sys\",", "enumerate(identities): if identities[i] != MSI_LOCAL_ID: identities[i] = _get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') if", "namespace.app_gateway_type == 'existing': required.append('backend_pool_name') forbidden = ['nat_pool_name', 'load_balancer', 'health_probe'] validate_parameter_set(namespace, required, forbidden, description='network", "--disk EXIST_DISK --instance-id ID') def process_disk_or_snapshot_create_namespace(cmd, namespace): from msrestazure.azure_exceptions import CloudError validate_tags(namespace) if", "subnet_ip_address, mask = subnet_cidr.split('/') subnet_bit_mask_len = 32 - int(mask) if vnet_bit_mask_len <= subnet_bit_mask_len:", "'new' logger.debug('new NIC will be created') return if not isinstance(nics_value, list): nics_value =", "break if i < 16: err = \"instance count '{}' is out of", "'Standard_D13_v2', 'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo', 'Standard_DS4_v2', 'Standard_DS13_v2', 'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo', 'Standard_F8', 'Standard_F8s', 'Standard_M64-16ms', 'Standard_D16_v3',", "try a different value.\".format(username)) return username def _validate_admin_password(password, os_type): import re is_linux =", "if image_type == 'uri': # STORAGE PROFILE #2 namespace.storage_profile = StorageProfile.SACustomImage elif image_type", "'Microsoft.Compute') return 'image_id' except CloudError: err = 'Invalid image \"{}\". Use a custom", "location sku_tier = 'Premium' if 'Premium' in namespace.storage_sku else 'Standard' account = next(", "--source {SNAPSHOT | DISK} | --source VHD_BLOB_URI [--source-storage-account-id ID]' try: namespace.source_blob_uri, namespace.source_disk, namespace.source_snapshot", "parameters, so scrub these out props_to_remove = ['attach_os_disk', 'storage_account'] for prop in props_to_remove:", "sku and sku.lower() not in [x.lower() for x in allowed_skus]: raise CLIError(\"invalid storage", "= 'new' logger.debug(\"specified public IP '%s' not found. It will be created.\", namespace.public_ip_address)", "not applicable as the '--scope' is not provided\".format( namespace.identity_role)) user_assigned_identities = [x for", "' '--application-gateway NAME_OR_ID') # Resolve the type of balancer (if any) being used", "namespace.keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_vm_secret_format(cmd, namespace): from msrestazure.tools import is_valid_resource_id keyvault_usage =", "image_data_disks_num = len(image_info.storage_profile.data_disks or []) elif res['type'].lower() == 'galleries': image_info = compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'],", "crash namespace.disk_info = normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace, 'attach_data_disks', []), storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching) def _validate_vm_create_storage_account(cmd,", "For Stack (compute - 2017-03-30), Resource_sku doesn't implement location_info property if not hasattr(temp,", "namespace.subnet rg = namespace.resource_group_name location = namespace.location nics = getattr(namespace, 'nics', None) if", "username): raise CLIError(linux_err) if not is_linux and username.endswith('.'): raise CLIError(win_err) disallowed_user_names = [", "def process_vm_secret_format(cmd, namespace): from msrestazure.tools import is_valid_resource_id keyvault_usage = CLIError('usage error: [--keyvault NAME", "to SSH Key Value. ' 'You can use --generate-ssh-keys to let CLI generate", "'gatewaysubnet': return False subnet_mask = s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask, namespace.instance_count, not namespace.disable_overprovision) result =", "'': namespace.app_gateway_type = None logger.debug('no application gateway will be used') elif namespace.application_gateway is", "be created.\", namespace.application_gateway) elif namespace.application_gateway == '': namespace.app_gateway_type = None logger.debug('no application gateway", "_compute_client_factory(cli_ctx) # pylint: disable=no-member try: info = compute_client.snapshots.get(resource_group_name, source) source_snapshot = info.id except", "azure.cli.command_modules.vm._vm_utils import check_existence, get_target_network_api, get_storage_blob_uri from azure.cli.command_modules.vm._template_builder import StorageProfile import azure.cli.core.keys as keys", "use in VM Creation Secrets JSON structure [{ \"sourceVault\": { \"id\": \"value\" },", "for the --image parameter. Updates the namespace and returns the type for subsequent", "if sku and sku.lower() not in [x.lower() for x in allowed_skus]: raise CLIError(\"invalid", "OS disk' def _validate_managed_disk_sku(sku): allowed_skus = ['Premium_LRS', 'Standard_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS'] if sku and", "= parse_resource_id(vault.id) if id_comps['name'] == vault_name: return id_comps['resource_group'] return None def _get_resource_id(cli_ctx, val,", "100: if namespace.single_placement_group is None: namespace.single_placement_group = False elif namespace.single_placement_group: raise CLIError(\"usage error:", "raise CLIError(\"usage error: os type is required to create the image, \" \"please", "array at secret ' \\ 'index {1} and vaultCertificate index {2} in arg", "'Secret is missing sourceVault.id key at index {0} in arg {1}'.format( idx, idx_arg))", "namespace.os_type = 'windows' if 'windows' in namespace.os_offer.lower() else 'linux' from ._vm_utils import normalize_disk_info", "= get_network_client(cli_ctx) try: return network_client.load_balancers.get(resource_group_name, lb_name) except CloudError: return None def process_vmss_create_namespace(cmd, namespace):", "namespace.os_type) if not namespace.os_type: raise CLIError(\"Unable to resolve OS type. Specify '--os-type' argument.\")", "if (subnet_is_id and vnet) or (not subnet_is_id and not vnet): raise CLIError(\"incorrect '--subnet'", "rg = parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name) lb_name = parse_resource_id(namespace.load_balancer)['name'] lb = get_network_lb(cmd.cli_ctx, namespace.resource_group_name, lb_name) if", "from msrestazure.tools import parse_resource_id client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults for vault in client.list(): id_comps", "'create unmanaged OS disk created from generalized VHD' elif profile == StorageProfile.SAPirImage: return", "def _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False): from msrestazure.tools import parse_resource_id # use minimal parameters to", "disable=no-member try: info = compute_client.snapshots.get(resource_group_name, source) source_snapshot = info.id except CloudError: info =", "StorageProfile.SACustomImage elif image_type == 'image_id': # STORAGE PROFILE #5 namespace.storage_profile = StorageProfile.ManagedCustomImage elif", "address.split('.')] result = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b, c, d) return int(result[:-bit_mask_len], 2) error_msg = \"usage", "from '{}'\" raise CLIError(err.format(role, ids)) role_id = role_defs[0].id return role_id def process_vm_create_namespace(cmd, namespace):", "have the 3 of the following: 1 lower case character, 1 upper case", "_resolve_role_id(cli_ctx, role, scope): import re import uuid from azure.cli.core.commands.client_factory import get_mgmt_service_client from azure.cli.core.profiles", "'Standard_D14_v2_ABC', 'Standard_F16_ABC', 'Standard_F32s_v2', 'Standard_D15_v2', 'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested', 'Standard_DS15_v2', 'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested', 'Standard_D40_v3', 'Standard_D40s_v3', 'Standard_D15_v2_ABC', 'Standard_M64ms',", "_get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg) def _validate_secrets(secrets, os_type): \"\"\" Validates a parsed JSON array containing", "for x in allowed_skus]: raise CLIError(\"invalid storage SKU '{}': allowed values: '{}'\".format(sku, allowed_skus))", "azure.cli.core.commands.client_factory import get_mgmt_service_client storage_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts # find storage account in target", "for s in sizes if s.name.lower() == size), None) if size_info is None", "= [x.lower() for x in aval_sizes] if size not in aval_sizes: return new_4core_sizes", "'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: required = ['os_type', 'attach_os_disk']", "if not namespace.os_type: raise CLIError(\"usage error: os type is required to create the", "if namespace.data_disk_sources: for data_disk_source in namespace.data_disk_sources: source_blob_uri, source_disk, source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name,", "for '{0}'. Create one first and try \" \"again.\".format(option_name)) return values[0] def _validate_vmss_single_placement_group(namespace):", "msrestazure.azure_exceptions import CloudError try: compute_client = _compute_client_factory(cmd.cli_ctx) if namespace.os_version.lower() == 'latest': image_version =", "None and namespace.app_gateway_type is None: if namespace.public_ip_address: raise CLIError('--public-ip-address can only be used", "namespace) _validate_vm_vmss_create_public_ip(cmd, namespace) _validate_vm_create_nics(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) if namespace.secrets: _validate_secrets(namespace.secrets, namespace.os_type) if", "namespace.plan_product, namespace.plan_publisher]): image_plan = _get_image_plan_info_if_exists(cmd, namespace) if image_plan: namespace.plan_name = image_plan.name namespace.plan_product =", "namespace.authentication_type: # apply default auth type (password for Windows, ssh for Linux) by", "namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id vm_id = resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name,", "= compute_client.virtual_machine_sizes.list(namespace.location) size_info = next((s for s in sizes if s.name.lower() == size),", "- 2 # try the other way around if (candidate_int >> (vnet_bit_mask_len -", "namespace.load_balancer_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, lb_name, 'load_balancers') if", "= parse_resource_id(namespace.load_balancer)['name'] lb = get_network_lb(cmd.cli_ctx, namespace.resource_group_name, lb_name) if lb: namespace.load_balancer_type = 'existing' namespace.backend_pool_name", "# STORAGE PROFILE #1 namespace.storage_profile = StorageProfile.SAPirImage else: # STORAGE PROFILE #4 namespace.storage_profile", "'WindowsServer', '^2016'), ('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')] import re for p, o, s in distros:", "scale-sets\" elif namespace.instance_count > 100: err = \"'Standard' load balancer is required for", "validate_nsg_name(cmd, namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id vm_id = resource_id(name=namespace.vm_name,", "cidr candaidate_str = '{0:32b}'.format(candidate_int << subnet_bit_mask_len) return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2), int(candaidate_str[8:16], 2), int(candaidate_str[16:24], 2),", "from azure.cli.core.commands.client_factory import get_mgmt_service_client from msrestazure.tools import parse_resource_id client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults for", "'resource_group': resource_group, 'namespace': resource_namespace, 'type': resource_type, 'subscription': get_subscription_id(cli_ctx) } missing_kwargs = {k: v", "(vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: # overflows? candidate_int = candidate_int - 2 #", "if profile == StorageProfile.SACustomImage: return 'create unmanaged OS disk created from generalized VHD'", "logger.debug('new public IP address will be created') # Public-IP SKU is only exposed", "'balancer or application gateway frontend.') namespace.public_ip_address = '' _validate_vm_vmss_create_public_ip(cmd, namespace) def _validate_vm_create_nics(cmd, namespace):", "\" \"images from virtual machines\") except CloudError: namespace.os_blob_uri, namespace.os_disk, namespace.os_snapshot = _figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name,", "if urlparse(namespace.image).scheme: return 'uri' # 4 - attempt to match an URN alias", "subnet, rg, 'Microsoft.Network', 'subnets', vnet, 'virtualNetworks') if subnet_is_id and not subnet_exists: raise CLIError(\"Subnet", "return 'create managed OS disk from Azure Marketplace image' elif profile == StorageProfile.ManagedSpecializedOSDisk:", "secret['vaultCertificates']: err = 'Secret is missing vaultCertificates array or it is empty at", "namespace.zones, namespace.vm_sku) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=True) _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=True) _validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace)", "'use_unmanaged_disk'] forbidden = ['os_type', 'attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SACustomImage: required = ['image',", "\"\"\" is_windows = os_type == 'windows' errors = [] try: loaded_secret = [validate_file_or_dict(secret)", "{}' raise CLIError(err.format(namespace.image, [x['urnAlias'] for x in images])) def _get_image_plan_info_if_exists(cmd, namespace): from msrestazure.azure_exceptions", "'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo', 'Standard_F8', 'Standard_F8s', 'Standard_M64-16ms', 'Standard_D16_v3', 'Standard_D16s_v3', 'Standard_D32-16s_v3', 'Standard_D64-16s_v3', 'Standard_E16_v3', 'Standard_E16s_v3',", "extract additional information from a managed custom image res = parse_resource_id(namespace.image) compute_client =", "= result.name namespace.vnet_name = vnet_match.name namespace.vnet_type = 'existing' logger.debug(\"existing vnet '%s' and subnet", "namespace.data_disks.append(source_disk) if source_snapshot: namespace.data_snapshots.append(source_snapshot) if not namespace.os_type: raise CLIError(\"usage error: os type is", "vaultCertificates array at secret ' \\ 'index {1} and vaultCertificate index {2} in", "ResourceType from azure.cli.core.commands.client_factory import get_subscription_id ApplicationSecurityGroup = cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK) resource_group = namespace.resource_group_name subscription_id", "'Premium' if 'Premium' in namespace.storage_sku else 'Standard' account = next( (a for a", "'usage error: --source {SNAPSHOT | DISK} | --source VHD_BLOB_URI [--source-storage-account-id ID]' try: namespace.source_blob_uri,", "used') def _validate_vm_vmss_create_auth(namespace): if namespace.storage_profile in [StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]: return namespace.admin_username = _validate_admin_username(namespace.admin_username, namespace.os_type)", "CLI generate one for you') namespace.ssh_key_value = content def _validate_vm_vmss_msi(cmd, namespace, from_set_command=False): if", "if namespace.identity_scope: if identities and MSI_LOCAL_ID not in identities: raise CLIError(\"usage error: '--scope'/'--role'", "to find an existing Vnet and subnet...') # if nothing specified, try to", "CLIError(\"'--data-disk-sources' is not allowed when capturing \" \"images from virtual machines\") except CloudError:", "account '%s' will be used\", account.name) else: # 4 - nothing specified -", "ROLE]') def _resolve_role_id(cli_ctx, role, scope): import re import uuid from azure.cli.core.commands.client_factory import get_mgmt_service_client", "namespace.boot_diagnostics_storage = get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage) # endregion # region VMSS Create Validators def _get_default_address_pool(cli_ctx,", "_get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') if namespace.key_encryption_keyvault: if not namespace.key_encryption_key: raise CLIError(\"Incorrect usage", "if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: raise CLIError(error_msg) # format back", "urlparse # pylint: disable=import-error from knack.log import get_logger from knack.util import CLIError from", "_check_subnet(s)), None) if not result: continue namespace.subnet = result.name namespace.vnet_name = vnet_match.name namespace.vnet_type", "is_linux and username.endswith('.'): raise CLIError(win_err) disallowed_user_names = [ \"administrator\", \"admin\", \"user\", \"user1\", \"test\",", "namespace) _validate_vm_create_nics(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) if namespace.secrets: _validate_secrets(namespace.secrets, namespace.os_type) if namespace.license_type and", "'Standard_D15_v2_Nested', 'Standard_DS15_v2', 'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested', 'Standard_D40_v3', 'Standard_D40s_v3', 'Standard_D15_v2_ABC', 'Standard_M64ms', 'Standard_M64s', 'Standard_M128-64ms', 'Standard_D64_v3', 'Standard_D64s_v3', 'Standard_E64_v3',", "\"certificateUrl\": \"value\", \"certificateStore\": \"cert store name (only on windows)\" }] }] :param dict", "#6 namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk elif namespace.image and not getattr(namespace, 'attach_os_disk', None): image_type =", "replica_count = int(parts[1]) except ValueError: raise CLIError(\"usage error: {}'s replica count must be", "= 'Secret is missing {0} within vaultCertificates array at secret ' \\ 'index", "namespace.os_type: namespace.os_type = 'windows' if 'windows' in namespace.os_offer.lower() else 'linux' from ._vm_utils import", "so use 'getattr' to avoid crash namespace.disk_info = normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace, 'attach_data_disks', []),", "with open(string_or_file, 'r') as f: content = f.read() elif not keys.is_valid_ssh_rsa_public_key(content): if namespace.generate_ssh_keys:", "errors.append( 'Secret is missing sourceVault key at index {0} in arg {1}'.format( idx,", "load ' 'balancer or application gateway frontend.') namespace.public_ip_address = '' _validate_vm_vmss_create_public_ip(cmd, namespace) def", "None) is None: raise CLIError(\"usage error: '--role {}' is not applicable as the", "VMSS, so use 'getattr' to avoid crash namespace.disk_info = normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace, 'attach_data_disks',", "_get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name, 'images', 'Microsoft.Compute') return 'image_id' except CloudError: err = 'Invalid image", "'{0:32b}'.format(candidate_int << subnet_bit_mask_len) return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2), int(candaidate_str[8:16], 2), int(candaidate_str[16:24], 2), int(candaidate_str[24:32], 2), new_mask)", "to specify a capable one. 'az vm list-skus' can be \" \"used to", "required, forbidden, description='network balancer: application gateway') elif balancer_type == 'loadBalancer': # LoadBalancer frontend", "'--nat-pool-name', ', '.join([n.name for n in lb.inbound_nat_pools]))) elif not lb.inbound_nat_pools: # Associated scaleset", "\" \"will be skipped\", namespace.image, ex.message) # pylint: disable=inconsistent-return-statements def _get_storage_profile_description(profile): if profile", "# pylint: disable=line-too-long namespace.storage_sku = 'Standard_LRS' if for_scale_set else 'Premium_LRS' if namespace.storage_sku ==", "from msrestazure.azure_exceptions import CloudError network_client = get_network_client(cli_ctx) try: return network_client.load_balancers.get(resource_group_name, lb_name) except CloudError:", "= ['os_type', 'attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SACustomImage: required = ['image', 'os_type', 'use_unmanaged_disk']", "16.04, SLES 12 SP3, RHEL 7.4, CentOS 7.4, CoreOS Linux, Debian \"Stretch\" with", "int(subnet_mask) # '2' are the reserved broadcasting addresses # '*1.5' so we have", "if names_or_ids == [\"\"] or not names_or_ids: return for val in names_or_ids: if", "in allowed_skus]: raise CLIError(\"invalid storage SKU '{}': allowed values: '{}'\".format(sku, allowed_skus)) def _validate_location(cmd,", "namespace.subnet) return if subnet: subnet_is_id = is_valid_resource_id(subnet) if (subnet_is_id and vnet) or (not", "#1 namespace.storage_profile = StorageProfile.SAPirImage else: # STORAGE PROFILE #4 namespace.storage_profile = StorageProfile.ManagedPirImage else:", "type is required to create the image, \" \"please specify '--os-type OS_TYPE'\") def", "else: raise CLIError('usage error: unrecognized image informations \"{}\"'.format(namespace.image)) # pylint: disable=no-member elif namespace.storage_profile", "'app_gateway_capacity'] validate_parameter_set(namespace, required, forbidden, description='network balancer: load balancer') if namespace.load_balancer: rg = parse_resource_id(namespace.load_balancer).get('resource_group',", "created') if namespace.load_balancer_type == 'new' and namespace.single_placement_group is False and std_lb_is_available: LBSkuName =", "# 4 - attempt to match an URN alias (most likely) from azure.cli.command_modules.vm._actions", "out vnet_ip_address, mask = vnet_cidr.split('/') vnet_bit_mask_len = 32 - int(mask) vnet_int = _convert_to_int(vnet_ip_address,", "error: '--role {}' is not applicable as the '--scope' is not provided\".format( namespace.identity_role))", "x in images if x['urnAlias'].lower() == namespace.image.lower()), None) if matched: namespace.os_publisher = matched['publisher']", "raise CLIError('incorrect usage: --image IMAGE | --attach-os-disk DISK') auth_params = ['<PASSWORD>_password', 'admin_username', 'authentication_type',", "elif namespace.application_gateway: balancer_type = 'applicationGateway' if balancer_type == 'applicationGateway': if namespace.application_gateway: client =", "== namespace.location), None) if account: # 3 - nothing specified - find viable", "CLIError('usage error: --license-type is only applicable on Windows VM scaleset') if not namespace.public_ip_per_vm", "Windows VMs.') # validate proper arguments supplied based on the authentication type if", "== StorageProfile.ManagedSpecializedOSDisk: required = ['os_type', 'attach_os_disk'] forbidden = ['os_disk_name', 'os_caching', 'storage_account', 'storage_container_name', 'use_unmanaged_disk',", "if errors: raise CLIError('\\n'.join(errors)) # region VM Create Validators def _parse_image_argument(cmd, namespace): \"\"\"", "- attempt to match an URN pattern urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image) if urn_match:", "#3 namespace.storage_profile = StorageProfile.SASpecializedOSDisk else: # STORAGE PROFILE #6 namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk elif", "namespace.resource_group_name, 'disks', 'Microsoft.Compute') if getattr(namespace, 'attach_data_disks', None): if not namespace.use_unmanaged_disk: namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx,", "'Standard_D12_v2_ABC', 'Standard_F4_ABC', 'Standard_F8s_v2', 'Standard_D4_v2', 'Standard_D13_v2', 'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo', 'Standard_DS4_v2', 'Standard_DS13_v2', 'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo',", "{1} and vaultCertificate index {2} in arg {3}' if 'certificateUrl' not in cert:", "# perform parameter validation for the specific storage profile # start with the", "namespace.os_type = image_info.storage_profile.os_disk.os_type.value image_data_disks_num = len(image_info.storage_profile.data_disks or []) elif res['type'].lower() == 'galleries': image_info", "use --generate-ssh-keys to let CLI generate one for you') namespace.ssh_key_value = content def", "ids = [r.id for r in role_defs] err = \"More than one role", "nics_value = [nics_value] for n in nics_value: nics.append({ 'id': n if '/' in", "group is turned off\") elif namespace.load_balancer_sku == LBSkuName.basic.value: if namespace.zones: err = \"'Standard'", "= vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine = res_id if namespace.data_disk_sources: raise CLIError(\"'--data-disk-sources' is not allowed when", "not namespace.os_type: namespace.os_type = 'windows' if 'windows' in namespace.os_offer.lower() else 'linux' from ._vm_utils", "capable one. 'az vm list-skus' can be \" \"used to find such locations\".format(namespace.resource_group_name))", "parse_resource_id if namespace.storage_account: storage_id = parse_resource_id(namespace.storage_account) rg = storage_id.get('resource_group', namespace.resource_group_name) if check_existence(cmd.cli_ctx, storage_id['name'],", "# 1 - existing storage account specified namespace.storage_account_type = 'existing' logger.debug(\"using specified existing", "'application_security_groups', ids) def validate_nsg_name(cmd, namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id", "in balancer.backend_address_pools] if len(values) > 1: raise CLIError(\"Multiple possible values found for '{0}':", "missing {0} within vaultCertificates array at secret ' \\ 'index {1} and vaultCertificate", "keys from ._client_factory import _compute_client_factory from ._actions import _get_latest_image_version logger = get_logger(__name__) def", "is None: cidr = namespace.vnet_address_prefix.split('/', 1)[0] i = 0 for i in range(24,", "rg = namespace.resource_group_name if rg: if not kv or is_valid_resource_id(kv): raise keyvault_usage validate_keyvault(cmd,", "= 'loadBalancer' else: # needed for Stack profile 2017_03_09 balancer_type = 'loadBalancer' if", "source_snapshot) def process_disk_encryption_namespace(cmd, namespace): namespace.disk_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') if namespace.key_encryption_keyvault:", "_validate_vm_vmss_create_public_ip(cmd, namespace) _validate_vm_create_nics(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) if namespace.secrets: _validate_secrets(namespace.secrets, namespace.os_type) if namespace.license_type", "structure [{ \"sourceVault\": { \"id\": \"value\" }, \"vaultCertificates\": [{ \"certificateUrl\": \"value\", \"certificateStore\": \"cert", "namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') def validate_vmss_disk(cmd, namespace): if namespace.disk: namespace.disk", "informations \"{}\"'.format(namespace.image)) # pylint: disable=no-member elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: # accept disk name", "Marketplace image' elif profile == StorageProfile.ManagedSpecializedOSDisk: return 'attach existing managed OS disk' def", "'Standard_E4s_v3', 'Standard_F2', 'Standard_F2s', 'Standard_F4s_v2', 'Standard_D11_v2', 'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C'] aval_sizes = [x.lower() for x in", "namespace.nic, namespace.resource_group_name) def validate_vm_nics(cmd, namespace): rg = namespace.resource_group_name nic_ids = [] for n", "check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute', 'availabilitySets'): raise CLIError(\"Availability set '{}' does not exist.\".format(name)) namespace.availability_set", "= 'usage error: --source {SNAPSHOT | DISK} | --source VHD_BLOB_URI [--source-storage-account-id ID]' try:", "in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd, namespace) _validate_vm_create_availability_set(cmd, namespace) _validate_vm_vmss_create_vnet(cmd, namespace) _validate_vm_create_nsg(cmd, namespace) _validate_vm_vmss_create_public_ip(cmd, namespace)", "elif '/disks/' in source.lower(): source_disk = source elif '/snapshots/' in source.lower(): source_snapshot =", "# region VM Create Validators def _parse_image_argument(cmd, namespace): \"\"\" Systematically determines what type", "storage SKU if not provided and using an image based OS if not", "DISK') auth_params = ['<PASSWORD>_password', 'admin_username', 'authentication_type', 'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value'] # perform parameter validation", "VM. VMSS has no such needs so far if getattr(namespace, 'public_ip_sku', None): from", "resource_type, resource_namespace): from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.commands.client_factory import get_subscription_id if is_valid_resource_id(val):", "image_version_info = compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2']) image_data_disks_num = len(image_version_info.storage_profile.data_disk_images or []) else:", "for VM. VMSS has no such needs so far if getattr(namespace, 'public_ip_sku', None):", "size = getattr(namespace, 'size', None) or getattr(namespace, 'vm_sku', None) size = size.lower() #", "from knack.log import get_logger from knack.util import CLIError from azure.cli.core.commands.validators import ( get_default_location_from_resource_group,", "for v in client.list(rg) if v.location == location and v.subnets): # 1 -", "the given name '{}'. Please pick an id from '{}'\" raise CLIError(err.format(role, ids))", "rg, 'Microsoft.Compute', 'availabilitySets'): raise CLIError(\"Availability set '{}' does not exist.\".format(name)) namespace.availability_set = resource_id(", "type='applicationSecurityGroups', name=val ) ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace, 'application_security_groups', ids) def validate_nsg_name(cmd, namespace): from msrestazure.tools import", "processing. \"\"\" from msrestazure.tools import is_valid_resource_id from msrestazure.azure_exceptions import CloudError import re #", "else: # STORAGE PROFILE #6 namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk elif namespace.image and not getattr(namespace,", "raise CLIError(\"Incorrect usage '--key-encryption-keyvault': \" \"'--key-encryption-key' is required\") namespace.key_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault, namespace.resource_group_name,", "storage account in target resource group namespace.storage_account = account.name namespace.storage_account_type = 'existing' logger.debug(\"suitable", "'use_unmanaged_disk', 'storage_sku'] + auth_params _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.SAPirImage: required = ['image', 'use_unmanaged_disk']", "= ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile ==", "'existing' logger.debug(\"using specified vnet '%s' and subnet '%s'\", namespace.vnet_name, namespace.subnet) return # 3", "the type of OS (linux or windows) :return: errors if any were found", "and (s is None or re.match(s, sku, re.I)): namespace.accelerated_networking = True def _validate_vmss_create_subnet(namespace):", "'Standard_D8_v3', 'Standard_D8s_v3', 'Standard_D32-8s_v3', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC', 'Standard_F4_ABC', 'Standard_F8s_v2', 'Standard_D4_v2', 'Standard_D13_v2', 'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo',", "'vaultCertificates' not in secret or not secret['vaultCertificates']: err = 'Secret is missing vaultCertificates", "if not provided and using an image based OS if not namespace.storage_sku and", "'storage_sku'] + auth_params _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.SAPirImage: required = ['image', 'use_unmanaged_disk'] forbidden", "= namespace.location nics = getattr(namespace, 'nics', None) if not vnet and not subnet", "matching subnet for vnet_match in (v for v in client.list(rg) if v.location ==", "vnet_match in (v for v in client.list(rg) if v.location == location and v.subnets):", "\"server\", \"sql\", \"support\", \"support_388945a0\", \"sys\", \"test2\", \"test3\", \"user4\", \"user5\"] if username.lower() in disallowed_user_names:", "_get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_assign_identity_namespace(cmd, namespace): _validate_vm_vmss_msi(cmd, namespace, from_set_command=True) def process_remove_identity_namespace(cmd,", "password cannot be used with SSH authentication type') validate_ssh_key(namespace) if not namespace.ssh_dest_key_path: namespace.ssh_dest_key_path", "= namespace.vnet_name subnet = namespace.subnet rg = namespace.resource_group_name location = namespace.location nics =", "namespace.storage_account = account.name namespace.storage_account_type = 'existing' logger.debug(\"suitable existing storage account '%s' will be", "namespace.storage_profile = StorageProfile.SAPirImage else: # STORAGE PROFILE #4 namespace.storage_profile = StorageProfile.ManagedPirImage else: raise", "vnet_match.subnets if s.name.lower() != 'gatewaysubnet'), None) else: def _check_subnet(s): if s.name.lower() == 'gatewaysubnet':", "= compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku, image_version) # pylint: disable=no-member return image.plan except CloudError", "and # get it from the error aval_sizes = ['Standard_D3_v2', 'Standard_D12_v2', 'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo',", "or it is empty at index {0} in ' \\ 'arg {1} '", "._vm_utils import MSI_LOCAL_ID for i in range(len(namespace.identities)): if namespace.identities[i] != MSI_LOCAL_ID: namespace.identities[i] =", "raise CLIError(\"'--data-disk-sources' is not allowed when capturing \" \"images from virtual machines\") except", "be used') elif namespace.load_balancer is None: namespace.load_balancer_type = 'new' logger.debug('new load balancer will", "= 'existing' logger.debug(\"using specified NSG '%s'\", namespace.nsg) else: namespace.nsg_type = 'new' logger.debug(\"specified NSG", "it is an image ID) if is_valid_resource_id(namespace.image): return 'image_id' # 2 - attempt", "arg {3}' if 'certificateUrl' not in cert: errors.append(message.format('certificateUrl', idx, jdx, idx_arg)) if is_windows", "= True # Now verify that the status of required and forbidden parameters", "= 'new' logger.debug('no suitable storage account found. One will be created.') def _validate_vm_create_availability_set(cmd,", "suitable storage account found. One will be created.') def _validate_vm_create_availability_set(cmd, namespace): from msrestazure.tools", "32 - int(mask) if vnet_bit_mask_len <= subnet_bit_mask_len: raise CLIError(error_msg) candidate_int = _convert_to_int(subnet_ip_address, subnet_bit_mask_len)", "namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd, namespace) if namespace.license_type and namespace.os_type.lower() != 'windows': raise", "if namespace.authentication_type == 'password': if namespace.ssh_key_value or namespace.ssh_dest_key_path: raise ValueError( \"incorrect usage for", "under because single placement group is disabled\", balancer_type) elif namespace.load_balancer: balancer_type = 'loadBalancer'", "= 'loadBalancer' if namespace.single_placement_group is not False else 'applicationGateway' logger.debug(\"W/o STD LB, defaulting", "for use in VM Creation Secrets JSON structure [{ \"sourceVault\": { \"id\": \"value\"", "urn_match.group(4) if not any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]): image_plan = _get_image_plan_info_if_exists(cmd, namespace) if image_plan: namespace.plan_name", "if not is_linux and username.endswith('.'): raise CLIError(win_err) disallowed_user_names = [ \"administrator\", \"admin\", \"user\",", "namespace.identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') # TODO move to its own command module https://github.com/Azure/azure-cli/issues/5105", "namespace='Microsoft.Compute', type='availabilitySets', name=name) logger.debug(\"adding to specified availability set '%s'\", namespace.availability_set) def _validate_vm_vmss_create_vnet(cmd, namespace,", "if not any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]): image_plan = _get_image_plan_info_if_exists(cmd, namespace) if image_plan: namespace.plan_name =", "_get_default_address_pool(cmd.cli_ctx, rg, lb_name, 'load_balancers') if not namespace.nat_pool_name: if len(lb.inbound_nat_pools) > 1: raise CLIError(\"Multiple", "_validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False): from msrestazure.tools import is_valid_resource_id vnet = namespace.vnet_name subnet = namespace.subnet", "if prop in forbidden: forbidden.remove(prop) # set default storage SKU if not provided", "for n in nics_value: nics.append({ 'id': n if '/' in n else resource_id(name=n,", "applicable on Windows VM') _validate_vm_vmss_msi(cmd, namespace) if namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage = get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage) #", "error: [--keyvault NAME --resource-group NAME | --keyvault ID]') kv = namespace.keyvault rg =", "{0} in arg {1}'.format( idx, idx_arg)) if 'vaultCertificates' not in secret or not", "for a in storage_client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value == sku_tier and a.location == namespace.location), None)", "\" \"[--admin-username USERNAME] --admin-password PASSWORD\") from knack.prompting import prompt_pass, NoTTYException try: if not", "vm list-skus' can be \" \"used to find such locations\".format(namespace.resource_group_name)) # pylint: disable=too-many-branches,", "1) if len(parts) == 1: regions_info.append(TargetRegion(name=parts[0])) else: try: replica_count = int(parts[1]) except ValueError:", "namespace, for_scale_set=False): from msrestazure.tools import is_valid_resource_id vnet = namespace.vnet_name subnet = namespace.subnet rg", "string_or_file if public_key_filepath[-4:].lower() == '.pub': private_key_filepath = public_key_filepath[:-4] else: private_key_filepath = public_key_filepath +", "in enumerate(narg_secret): if 'sourceVault' not in secret: errors.append( 'Secret is missing sourceVault key", "_validate_vm_create_storage_account(cmd, namespace): from msrestazure.tools import parse_resource_id if namespace.storage_account: storage_id = parse_resource_id(namespace.storage_account) rg =", "or is_valid_resource_id(kv): raise keyvault_usage validate_keyvault(cmd, namespace) else: if kv and not is_valid_resource_id(kv): raise", "2), int(candaidate_str[16:24], 2), int(candaidate_str[24:32], 2), new_mask) def _validate_vm_create_nsg(cmd, namespace): if namespace.nsg: if check_existence(cmd.cli_ctx,", "required.remove(prop) if prop in forbidden: forbidden.remove(prop) # set default storage SKU if not", "and vnet) or (not subnet_is_id and not vnet): raise CLIError(\"incorrect '--subnet' usage: --subnet", "if not is_valid_resource_id(val): val = resource_id( subscription=subscription_id, resource_group=resource_group, namespace='Microsoft.Network', type='applicationSecurityGroups', name=val ) ids.append(ApplicationSecurityGroup(id=val))", "= vnet_match.name namespace.vnet_type = 'existing' logger.debug(\"existing vnet '%s' and subnet '%s' found\", namespace.vnet_name,", "is only exposed for VM. VMSS has no such needs so far if", "'primary_nic') and namespace.primary_nic: namespace.primary_nic = _get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg) def _validate_secrets(secrets, os_type): \"\"\" Validates", "elif profile == StorageProfile.SAPirImage: return 'create unmanaged OS disk from Azure Marketplace image'", "n in namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg)) namespace.nics = nic_ids if hasattr(namespace, 'primary_nic') and", "namespace.storage_sku and namespace.storage_profile in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]: # pylint: disable=line-too-long namespace.storage_sku = 'Standard_LRS' if", "nothing specified, try to find an existing vnet and subnet in the target", "StorageProfile.ManagedCustomImage: required = ['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if for_scale_set:", "aval_sizes] if size not in aval_sizes: return new_4core_sizes = ['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2',", "gallery_name=res['name'], gallery_image_name=res['child_name_1']) namespace.os_type = image_info.os_type.value gallery_image_version = res.get('child_name_2', '') if gallery_image_version.lower() in ['latest',", "urllib.parse import urlparse except ImportError: from urlparse import urlparse # pylint: disable=import-error from", "this image. Please try a different value.\".format(username)) return username def _validate_admin_password(password, os_type): import", "'{0}' explicitly.\".format( # pylint: disable=line-too-long '--nat-pool-name', ', '.join([n.name for n in lb.inbound_nat_pools]))) elif", "namespace.key_encryption_key: raise CLIError(\"Incorrect usage '--key-encryption-keyvault': \" \"'--key-encryption-key' is required\") namespace.key_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault,", "an existing vnet and subnet in the target resource group client = get_network_client(cmd.cli_ctx).virtual_networks", "None): image_type = _parse_image_argument(cmd, namespace) if image_type == 'uri': # STORAGE PROFILE #2", "'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo', 'Standard_F8', 'Standard_F8s', 'Standard_M64-16ms', 'Standard_D16_v3', 'Standard_D16s_v3', 'Standard_D32-16s_v3', 'Standard_D64-16s_v3', 'Standard_E16_v3', 'Standard_E16s_v3', 'Standard_E32-16s_v3', 'Standard_D4_v2_ABC',", "the authentication type if namespace.authentication_type == 'password': if namespace.ssh_key_value or namespace.ssh_dest_key_path: raise ValueError(", "if 'vaultCertificates' not in secret or not secret['vaultCertificates']: err = 'Secret is missing", "'Standard_D64s_v3', 'Standard_E64_v3', 'Standard_E64s_v3', 'Standard_E64-16s_v3', 'Standard_E64-32s_v3', 'Standard_F64s_v2', 'Standard_F72s_v2', 'Standard_M128s', 'Standard_M128ms', 'Standard_L8s_v2', 'Standard_L16s_v2', 'Standard_L32s_v2', 'Standard_L64s_v2',", "password) contains_upper = re.findall('[A-Z]+', password) contains_digit = re.findall('[0-9]+', password) contains_special_char = re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+',", "raise CLIError('unrecognized balancer type: {}'.format(balancer_type)) balancer = client.get(resource_group, balancer_name) values = [x.name for", "gateway will be created') # AppGateway frontend required = [] if namespace.app_gateway_type ==", "def _validate_vmss_create_subnet(namespace): if namespace.vnet_type == 'new': if namespace.subnet_address_prefix is None: cidr = namespace.vnet_address_prefix.split('/',", "rg = parse_resource_id(namespace.application_gateway).get( 'resource_group', namespace.resource_group_name) ag_name = parse_resource_id(namespace.application_gateway)['name'] client.get(rg, ag_name) namespace.app_gateway_type = 'existing'", "== 'urn': if namespace.use_unmanaged_disk: # STORAGE PROFILE #1 namespace.storage_profile = StorageProfile.SAPirImage else: #", "CLIError('Usage error: --vm-domain-name can only be used when --public-ip-per-vm is enabled') if namespace.eviction_policy", "if not namespace.use_unmanaged_disk: namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name, 'disks', 'Microsoft.Compute') for d in", "get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set, validate_tags) from azure.cli.core.util import hash_string from azure.cli.command_modules.vm._vm_utils import check_existence, get_target_network_api,", "is out of range of 2^16 subnet size'\" raise CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix = '{}/{}'.format(cidr,", "ValueError: pass if not role_id: # retrieve role id role_defs = list(client.list(scope, \"roleName", "validate_parameter_set(namespace, required, forbidden, description='network balancer: application gateway') elif balancer_type == 'loadBalancer': # LoadBalancer", "props_to_remove = ['attach_os_disk', 'storage_account'] for prop in props_to_remove: if prop in required: required.remove(prop)", "for vnet_match in (v for v in client.list(rg) if v.location == location and", "= 'new' logger.debug('new public IP address will be created') # Public-IP SKU is", "\"certificateStore\": \"cert store name (only on windows)\" }] }] :param dict secrets: Dict", "'windows' errors = [] try: loaded_secret = [validate_file_or_dict(secret) for secret in secrets] except", "namespace.storage_profile = StorageProfile.SACustomImage elif image_type == 'image_id': # STORAGE PROFILE #5 namespace.storage_profile =", "else: try: uuid.UUID(role) role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id, role) except ValueError: pass if not", "option_name = '--backend-pool-name' client = getattr(get_network_client(cli_ctx), balancer_type, None) if not client: raise CLIError('unrecognized", "\"id\": \"value\" }, \"vaultCertificates\": [{ \"certificateUrl\": \"value\", \"certificateStore\": \"cert store name (only on", "is None: if std_lb_is_available: balancer_type = 'loadBalancer' else: # needed for Stack profile", "None source_disk = None source_snapshot = None if urlparse(source).scheme: # a uri? source_blob_uri", "= False elif namespace.single_placement_group: raise CLIError(\"usage error: '--single-placement-group' should be turned off for", "\"\"\" Fetch resource group from vault name :param str vault_name: name of the", "}) namespace.nics = nics namespace.nic_type = 'existing' namespace.public_ip_address_type = None logger.debug('existing NIC(s) will", "'debian', '-backports'), ('oracle', 'oracle-linux', '^7.4'), ('MicrosoftWindowsServer', 'WindowsServer', '^2016'), ('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')] import re", "scale-sets with 100+ instances\" else: err = \"'Standard' load balancer is required because", "namespace) _validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd, namespace) if namespace.license_type and namespace.os_type.lower() != 'windows': raise CLIError('usage error:", "a new storage account namespace.storage_account_type = 'new' logger.debug('no suitable storage account found. One", "import AZURE_US_GOV_CLOUD if cmd.cli_ctx.cloud.name != AZURE_US_GOV_CLOUD.name: namespace.vm_sku = 'Standard_DS1_v2' else: namespace.vm_sku = 'Standard_D1_v2'", "namespace.identities[i] != MSI_LOCAL_ID: namespace.identities[i] = _get_resource_id(cmd.cli_ctx, namespace.identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') # TODO move", "URN alias (most likely) from azure.cli.command_modules.vm._actions import load_images_from_aliases_doc images = load_images_from_aliases_doc(cmd.cli_ctx) matched =", "to avoid crash namespace.disk_info = normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace, 'attach_data_disks', []), storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching)", "if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role, re.I): role_id = role else: try: uuid.UUID(role) role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format(", "'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3', 'Standard_D8s_v3'] new_4core_sizes = [x.lower() for x in new_4core_sizes] if size", "rg)) namespace.nics = nic_ids if hasattr(namespace, 'primary_nic') and namespace.primary_nic: namespace.primary_nic = _get_nic_id(cmd.cli_ctx, namespace.primary_nic,", "SKU is only exposed for VM. VMSS has no such needs so far", "ex: logger.warning(\"Querying the image of '%s' failed for an error '%s'. Configuring plan", "if namespace.identities: from ._vm_utils import MSI_LOCAL_ID for i in range(len(namespace.identities)): if namespace.identities[i] !=", "else None def _get_nic_id(cli_ctx, val, resource_group): return _get_resource_id(cli_ctx, val, resource_group, 'networkInterfaces', 'Microsoft.Network') def", "if check_existence(cmd.cli_ctx, namespace.public_ip_address, namespace.resource_group_name, 'Microsoft.Network', 'publicIPAddresses'): namespace.public_ip_address_type = 'existing' logger.debug(\"using existing specified public", "= namespace.keyvault rg = namespace.resource_group_name if rg: if not kv or is_valid_resource_id(kv): raise", "'password': \" \"[--admin-username USERNAME] --admin-password PASSWORD\") from knack.prompting import prompt_pass, NoTTYException try: if", "win_err) if is_linux and re.findall(r'^[$-]+', username): raise CLIError(linux_err) if not is_linux and username.endswith('.'):", "version exists for \"{}\"'.format(namespace.image)) image_version_info = sorted(image_version_infos, key=lambda x: x.publishing_profile.published_date)[-1] else: image_version_info =", "vnet): raise CLIError(\"incorrect '--subnet' usage: --subnet SUBNET_ID | \" \"--subnet SUBNET_NAME --vnet-name VNET_NAME\")", "_validate_vmss_create_nsg(cmd, namespace): if namespace.nsg: namespace.nsg = _get_resource_id(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'networkSecurityGroups', 'Microsoft.Network') def _validate_vm_vmss_create_public_ip(cmd,", "if namespace.disk: namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if bool(namespace.disk) == bool(namespace.size_gb):", "from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_subscription_id", "not found. It will be created.\", namespace.nsg) elif namespace.nsg == '': namespace.nsg_type =", "s in sizes if s.name.lower() == size), None) if size_info is None or", "ApplicationSecurityGroup = cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK) resource_group = namespace.resource_group_name subscription_id = get_subscription_id(cmd.cli_ctx) names_or_ids = getattr(namespace,", "data_disk_cachings=namespace.data_caching) def _validate_vm_create_storage_account(cmd, namespace): from msrestazure.tools import parse_resource_id if namespace.storage_account: storage_id = parse_resource_id(namespace.storage_account)", "namespace.network_security_group_name = namespace.network_security_group_name \\ or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8)) def validate_keyvault(cmd, namespace): namespace.keyvault =", "def _subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision): mask = int(subnet_mask) # '2' are the reserved broadcasting", "val kwargs = { 'name': val, 'resource_group': resource_group, 'namespace': resource_namespace, 'type': resource_type, 'subscription':", "type is supplied for the --image parameter. Updates the namespace and returns the", "new storage account namespace.storage_account_type = 'new' logger.debug('no suitable storage account found. One will", "'Standard_DS5_v2', 'Standard_DS14_v2', 'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo', 'Standard_F16', 'Standard_F16s', 'Standard_M64-32ms', 'Standard_M128-32ms', 'Standard_D32_v3', 'Standard_D32s_v3', 'Standard_D64-32s_v3', 'Standard_E32_v3', 'Standard_E32s_v3',", "from msrestazure.azure_exceptions import CloudError source_blob_uri = None source_disk = None source_snapshot = None", "can't be used to create the VM/VMSS because availablity zone is not yet", "to find such locations\".format(namespace.resource_group_name)) # pylint: disable=too-many-branches, too-many-statements def _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False): from", "elif namespace.application_gateway == '': namespace.app_gateway_type = None logger.debug('no application gateway will be used')", "MSI_LOCAL_ID for i, _ in enumerate(identities): if identities[i] != MSI_LOCAL_ID: identities[i] = _get_resource_id(cmd.cli_ctx,", "3 - nothing specified - find viable storage account in target resource group", "raise CLIError(\"This user name '{}' meets the general requirements, but is specifically disallowed", "raise CLIError(err.format(role, ids)) role_id = role_defs[0].id return role_id def process_vm_create_namespace(cmd, namespace): validate_tags(namespace) _validate_location(cmd,", "using an image based OS if not namespace.storage_sku and namespace.storage_profile in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]:", "balancer_type, None) if not client: raise CLIError('unrecognized balancer type: {}'.format(balancer_type)) balancer = client.get(resource_group,", "length must be between {} and {}'.format(min_length, max_length)) contains_lower = re.findall('[a-z]+', password) contains_upper", "[--eviction-policy POLICY]') # endregion # region disk, snapshot, image validators def validate_vm_disk(cmd, namespace):", "= 'Premium' if 'Premium' in namespace.storage_sku else 'Standard' account = next( (a for", "namespace): if namespace.nsg: namespace.nsg = _get_resource_id(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'networkSecurityGroups', 'Microsoft.Network') def _validate_vm_vmss_create_public_ip(cmd, namespace):", "namespace): if namespace.identities: from ._vm_utils import MSI_LOCAL_ID for i in range(len(namespace.identities)): if namespace.identities[i]", "namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if bool(namespace.disk) == bool(namespace.size_gb): raise CLIError('usage error: --disk EXIST_DISK", "forbidden = ['os_disk_name', 'os_caching', 'storage_account', 'storage_container_name', 'use_unmanaged_disk', 'storage_sku'] + auth_params _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile", "'vaults', 'Microsoft.KeyVault') def process_vm_secret_format(cmd, namespace): from msrestazure.tools import is_valid_resource_id keyvault_usage = CLIError('usage error:", "err = 'Invalid image \"{}\". Use a custom image name, id, or pick", "LBSkuName.basic.value: if namespace.zones: err = \"'Standard' load balancer is required for zonal scale-sets\"", "msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id nics_value = namespace.nics nics = []", "for r in role_defs] err = \"More than one role matches the given", "IPAllocationMethod = cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK) if namespace.public_ip_sku == PublicIPAddressSkuName.standard.value: if not namespace.public_ip_address_allocation: namespace.public_ip_address_allocation", "== 'latest': image_version = _get_latest_image_version(cmd.cli_ctx, namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku) else: image_version = namespace.os_version", "validate_tags(namespace) _validate_location(cmd, namespace, namespace.zone, namespace.size) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace) if namespace.storage_profile in [StorageProfile.SACustomImage,", "'%s' will be used\", account.name) else: # 4 - nothing specified - create", "namespace.nic_type = 'new' logger.debug('new NIC will be created') return if not isinstance(nics_value, list):", "elif namespace.app_gateway_type == 'existing': required.append('backend_pool_name') forbidden = ['nat_pool_name', 'load_balancer', 'health_probe'] validate_parameter_set(namespace, required, forbidden,", "image, \" \"please specify '--os-type OS_TYPE'\") def _figure_out_storage_source(cli_ctx, resource_group_name, source): from msrestazure.azure_exceptions import", "'storage_account', 'storage_container_name', 'use_unmanaged_disk', 'storage_sku'] + auth_params _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.SAPirImage: required =", "and will be created\", storage_id['name']) else: from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import", "for x in sku_infos if x.name.lower() == size_info.lower()), None) # For Stack (compute", "implement location_info property if not hasattr(temp, 'location_info'): return if not temp or not", "'networkSecurityGroups'): namespace.nsg_type = 'existing' logger.debug(\"using specified NSG '%s'\", namespace.nsg) else: namespace.nsg_type = 'new'", "\"admin2\", \"aspnet\", \"backup\", \"console\", \"guest\", \"owner\", \"root\", \"server\", \"sql\", \"support\", \"support_388945a0\", \"sys\", \"test2\",", "namespace.storage_account_type = 'existing' logger.debug(\"using specified existing storage account '%s'\", storage_id['name']) else: # 2", "None: namespace.ultra_ssd_enabled = True # Now verify that the status of required and", "special character') def validate_ssh_key(namespace): string_or_file = (namespace.ssh_key_value or os.path.join(os.path.expanduser('~'), '.ssh', 'id_rsa.pub')) content =", "return role_id def process_vm_create_namespace(cmd, namespace): validate_tags(namespace) _validate_location(cmd, namespace, namespace.zone, namespace.size) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd,", "err: raise CLIError('Error decoding secrets: {0}'.format(err)) for idx_arg, narg_secret in enumerate(loaded_secret): for idx,", "public IP '%s' not found. It will be created.\", namespace.public_ip_address) elif namespace.public_ip_address ==", "value must be supplied to SSH Key Value. ' 'You can use --generate-ssh-keys", "not for_scale_set: result = next((s for s in vnet_match.subnets if s.name.lower() != 'gatewaysubnet'),", "user_assigned_identities = [x for x in identities if x != MSI_LOCAL_ID] if user_assigned_identities", "namespace.os_disk, namespace.os_snapshot = _figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name, namespace.source) # pylint: disable=line-too-long namespace.data_blob_uris = [] namespace.data_disks", "--keyvault ID]') kv = namespace.keyvault rg = namespace.resource_group_name if rg: if not kv", "custom image' elif profile == StorageProfile.ManagedPirImage: return 'create managed OS disk from Azure", "ImportError: from urlparse import urlparse # pylint: disable=import-error from knack.log import get_logger from", "gallery_image_name=res['child_name_1']) namespace.os_type = image_info.os_type.value gallery_image_version = res.get('child_name_2', '') if gallery_image_version.lower() in ['latest', '']:", "namespace.authentication_type == 'ssh': raise CLIError('SSH not supported for Windows VMs.') # validate proper", "from ._vm_utils import list_sku_info if not namespace.location: get_default_location_from_resource_group(cmd, namespace) if zone_info: sku_infos =", "namespace.public_ip_address_allocation: namespace.public_ip_address_allocation = IPAllocationMethod.static.value def _validate_vmss_create_public_ip(cmd, namespace): if namespace.load_balancer_type is None and namespace.app_gateway_type", "compute_client.virtual_machines.get(res['resource_group'], res['name']) # pylint: disable=no-member namespace.os_type = vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine = res_id if namespace.data_disk_sources:", "\"value\" }, \"vaultCertificates\": [{ \"certificateUrl\": \"value\", \"certificateStore\": \"cert store name (only on windows)\"", "storage account in target resource group that matches the VM's location sku_tier =", "= 'new' logger.debug(\"specified NSG '%s' not found. It will be created.\", namespace.nsg) elif", "= publisher.lower(), offer.lower(), sku.lower() distros = [('canonical', 'UbuntuServer', '^16.04'), ('suse', 'sles', '^12-sp3'), ('redhat',", "elif not keys.is_valid_ssh_rsa_public_key(content): if namespace.generate_ssh_keys: # figure out appropriate file names: # 'base_name'(with", "assigned identity is only available under profile ' 'with minimum Compute API version", "'existing': required.append('backend_pool_name') forbidden = ['nat_pool_name', 'load_balancer', 'health_probe'] validate_parameter_set(namespace, required, forbidden, description='network balancer: application", "balancer: load balancer') if namespace.load_balancer: rg = parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name) lb_name = parse_resource_id(namespace.load_balancer)['name'] lb", "import resource_id from azure.cli.core.commands.client_factory import get_subscription_id vm_id = resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx))", "namespace, from_set_command=False): if from_set_command or namespace.assign_identity is not None: identities = namespace.assign_identity or", "len(image_info.storage_profile.data_disks or []) elif res['type'].lower() == 'galleries': image_info = compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) namespace.os_type", "parse_resource_id(namespace.storage_account) rg = storage_id.get('resource_group', namespace.resource_group_name) if check_existence(cmd.cli_ctx, storage_id['name'], rg, 'Microsoft.Storage', 'storageAccounts'): # 1", "namespace.source_blob_uri and namespace.source_storage_account_id: raise CLIError(usage_error) except CloudError: raise CLIError(usage_error) def process_image_create_namespace(cmd, namespace): from", "disk from Azure Marketplace image' elif profile == StorageProfile.ManagedSpecializedOSDisk: return 'attach existing managed", "namespace.attach_os_disk = _get_resource_id( cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if getattr(namespace, 'attach_data_disks', None): if", "not [x for x in (temp.location_info or []) if x.zones]: raise CLIError(\"{}'s location", "instances\" else: err = \"'Standard' load balancer is required because 'single placement group'", "namespace.storage_profile == StorageProfile.SACustomImage: required = ['image', 'os_type', 'use_unmanaged_disk'] forbidden = ['attach_os_disk', 'data_disk_sizes_gb'] elif", "None) if not vnet and not subnet and not nics: logger.debug('no subnet specified.", "'arg {1} ' errors.append(err.format(idx, idx_arg)) else: for jdx, cert in enumerate(secret['vaultCertificates']): message =", "namespace.os_snapshot = _figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name, namespace.source) # pylint: disable=line-too-long namespace.data_blob_uris = [] namespace.data_disks =", "bit_mask_len): a, b, c, d = [int(x) for x in address.split('.')] result =", "data_disk_source) if source_blob_uri: namespace.data_blob_uris.append(source_blob_uri) if source_disk: namespace.data_disks.append(source_disk) if source_snapshot: namespace.data_snapshots.append(source_snapshot) if not namespace.os_type:", "if not temp or not [x for x in (temp.location_info or []) if", "'^7.4'), ('MicrosoftWindowsServer', 'WindowsServer', '^2016'), ('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')] import re for p, o, s", "image validators def validate_vm_disk(cmd, namespace): namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') def", "\"root\", \"server\", \"sql\", \"support\", \"support_388945a0\", \"sys\", \"test2\", \"test3\", \"user4\", \"user5\"] if username.lower() in", "import CloudError import re # 1 - check if a fully-qualified ID (assumes", "parse_resource_id(res_id) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) vm_info = compute_client.virtual_machines.get(res['resource_group'], res['name']) # pylint: disable=no-member namespace.os_type", "= 'new' logger.debug(\"load balancer '%s' not found. It will be created.\", namespace.load_balancer) elif", "secret['sourceVault']: errors.append( 'Secret is missing sourceVault.id key at index {0} in arg {1}'.format(", "namespace) _validate_vm_create_storage_profile(cmd, namespace) if namespace.storage_profile in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd, namespace) _validate_vm_create_availability_set(cmd, namespace) _validate_vm_vmss_create_vnet(cmd,", "return if subnet: subnet_is_id = is_valid_resource_id(subnet) if (subnet_is_id and vnet) or (not subnet_is_id", "' 'balancer or application gateway frontend.') namespace.public_ip_address = '' _validate_vm_vmss_create_public_ip(cmd, namespace) def _validate_vm_create_nics(cmd,", "names_or_ids: if not is_valid_resource_id(val): val = resource_id( subscription=subscription_id, resource_group=resource_group, namespace='Microsoft.Network', type='applicationSecurityGroups', name=val )", "IP '%s'\", namespace.public_ip_address) else: namespace.public_ip_address_type = 'new' logger.debug(\"specified public IP '%s' not found.", "\"\"\" Validates a parsed JSON array containing secrets for use in VM Creation", "n if '/' in n else resource_id(name=n, resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)), 'properties': {", "getattr(namespace, 'application_security_groups') ids = [] if names_or_ids == [\"\"] or not names_or_ids: return", "narg_secret in enumerate(loaded_secret): for idx, secret in enumerate(narg_secret): if 'sourceVault' not in secret:", "'%s' have been generated under ~/.ssh to \" \"allow SSH access to the", "VMSS has no such needs so far if getattr(namespace, 'public_ip_sku', None): from azure.cli.core.profiles", "kwargs.items() if not v} return resource_id(**kwargs) if not missing_kwargs else None def _get_nic_id(cli_ctx,", "specify a capable one. 'az vm list-skus' can be \" \"used to find", "as_id.get('resource_group', namespace.resource_group_name) if not check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute', 'availabilitySets'): raise CLIError(\"Availability set '{}'", "Fetch resource group from vault name :param str vault_name: name of the key", "if is_valid_resource_id(namespace.image): return 'image_id' # 2 - attempt to match an URN pattern", "'Standard_M64ms', 'Standard_M64s', 'Standard_M128-64ms', 'Standard_D64_v3', 'Standard_D64s_v3', 'Standard_E64_v3', 'Standard_E64s_v3', 'Standard_E64-16s_v3', 'Standard_E64-32s_v3', 'Standard_F64s_v2', 'Standard_F72s_v2', 'Standard_M128s', 'Standard_M128ms',", "balancer_name) values = [x.name for x in balancer.backend_address_pools] if len(values) > 1: raise", "and 'id' not in secret['sourceVault']: errors.append( 'Secret is missing sourceVault.id key at index", "the reserved broadcasting addresses # '*1.5' so we have enough leeway for over-provision", "namespace) else: if kv and not is_valid_resource_id(kv): raise keyvault_usage def _get_resource_group_from_vault_name(cli_ctx, vault_name): \"\"\"", "NSG '%s'\", namespace.nsg) else: namespace.nsg_type = 'new' logger.debug(\"specified NSG '%s' not found. It", "role_id = role_defs[0].id return role_id def process_vm_create_namespace(cmd, namespace): validate_tags(namespace) _validate_location(cmd, namespace, namespace.zone, namespace.size)", "forbidden = ['nat_pool_name', 'load_balancer', 'health_probe'] validate_parameter_set(namespace, required, forbidden, description='network balancer: application gateway') elif", "import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx)) def get_network_lb(cli_ctx, resource_group_name,", "[] forbidden = ['app_gateway_subnet_address_prefix', 'application_gateway', 'app_gateway_sku', 'app_gateway_capacity'] validate_parameter_set(namespace, required, forbidden, description='network balancer: load", "errors.append(message.format('certificateStore', idx, jdx, idx_arg)) if errors: raise CLIError('\\n'.join(errors)) # region VM Create Validators", "PROFILE #6 namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk elif namespace.image and not getattr(namespace, 'attach_os_disk', None): image_type", "for_scale_set=False): from msrestazure.tools import is_valid_resource_id vnet = namespace.vnet_name subnet = namespace.subnet rg =", "One will be created.') def _subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision): mask = int(subnet_mask) # '2'", "= [r.id for r in role_defs] err = \"More than one role matches", "namespace.app_gateway_type = 'new' logger.debug(\"application gateway '%s' not found. It will be created.\", namespace.application_gateway)", "def validate_asg_names_or_ids(cmd, namespace): from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.profiles import ResourceType from", "profile == StorageProfile.SACustomImage: return 'create unmanaged OS disk created from generalized VHD' elif", "[x.lower() for x in allowed_skus]: raise CLIError(\"invalid storage SKU '{}': allowed values: '{}'\".format(sku,", "a suitable existing vnet/subnet result = None if not for_scale_set: result = next((s", "import get_mgmt_service_client storage_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts # find storage account in target resource", "= ['Standard_D3_v2', 'Standard_D12_v2', 'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo', 'Standard_DS3_v2', 'Standard_DS12_v2', 'Standard_DS13-4_v2', 'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo',", "\"aspnet\", \"backup\", \"console\", \"guest\", \"owner\", \"root\", \"server\", \"sql\", \"support\", \"support_388945a0\", \"sys\", \"test2\", \"test3\",", "type: {}'.format(balancer_type)) balancer = client.get(resource_group, balancer_name) values = [x.name for x in balancer.backend_address_pools]", "\"user5\"] if username.lower() in disallowed_user_names: raise CLIError(\"This user name '{}' meets the general", "placement group' is turned off\" raise CLIError('usage error:{}'.format(err)) def get_network_client(cli_ctx): from azure.cli.core.profiles import", "from urlparse import urlparse # pylint: disable=import-error from knack.log import get_logger from knack.util", "elif namespace.identity_scope or getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError('usage error: --assign-identity [--scope", "get_default_location_from_resource_group(cmd, namespace) if zone_info: sku_infos = list_sku_info(cmd.cli_ctx, namespace.location) temp = next((x for x", "', '.join(values))) elif not values: raise CLIError(\"No existing values found for '{0}'. Create", "if balancer_type == 'applicationGateway': if namespace.application_gateway: client = get_network_client(cmd.cli_ctx).application_gateways try: rg = parse_resource_id(namespace.application_gateway).get(", "VNET in target resource group that matches the VM's location with a matching", "find a suitable existing vnet/subnet result = None if not for_scale_set: result =", "parse_resource_id from azure.cli.core.profiles import ResourceType std_lb_is_available = cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer and namespace.application_gateway:", "regions_info.append(TargetRegion(name=parts[0])) else: try: replica_count = int(parts[1]) except ValueError: raise CLIError(\"usage error: {}'s replica", "in [contains_lower, contains_upper, contains_digit, contains_special_char] if x]) # pylint: disable=line-too-long if count <", "'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo', 'Standard_F4', 'Standard_F4s', 'Standard_D8_v3', 'Standard_D8s_v3', 'Standard_D32-8s_v3', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC', 'Standard_F4_ABC',", "_validate_admin_username(namespace.admin_username, namespace.os_type) if not namespace.os_type: raise CLIError(\"Unable to resolve OS type. Specify '--os-type'", "['os_disk_name', 'os_caching', 'image', 'storage_account', 'storage_container_name', 'data_disk_sizes_gb', 'storage_sku'] + auth_params else: raise CLIError('Unrecognized storage", "None and namespace.zones is None: raise CLIError('usage error: --platform-fault-domain-count COUNT --zones ZONES') if", "size_info.lower()), None) # For Stack (compute - 2017-03-30), Resource_sku doesn't implement location_info property", "windows) :return: errors if any were found :rtype: list \"\"\" is_windows = os_type", "'new' logger.debug('no suitable storage account found. One will be created.') def _validate_vm_create_availability_set(cmd, namespace):", "unrecognized image informations \"{}\"'.format(namespace.image)) # pylint: disable=no-member elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: # accept", "namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, ag_name, 'application_gateways') logger.debug(\"using specified existing application", "import CloudError try: compute_client = _compute_client_factory(cmd.cli_ctx) if namespace.os_version.lower() == 'latest': image_version = _get_latest_image_version(cmd.cli_ctx,", "name=val ) ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace, 'application_security_groups', ids) def validate_nsg_name(cmd, namespace): from msrestazure.tools import resource_id", "def validate_vm_disk(cmd, namespace): namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') def validate_vmss_disk(cmd, namespace):", "OS if not namespace.storage_sku and namespace.storage_profile in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]: # pylint: disable=line-too-long namespace.storage_sku", "alias (most likely) from azure.cli.command_modules.vm._actions import load_images_from_aliases_doc images = load_images_from_aliases_doc(cmd.cli_ctx) matched = next((x", "'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C'] aval_sizes = [x.lower() for x in aval_sizes] if size not in", "val, resource_group, 'networkInterfaces', 'Microsoft.Network') def validate_vm_nic(cmd, namespace): namespace.nic = _get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name) def", "namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk elif namespace.image and not getattr(namespace, 'attach_os_disk', None): image_type = _parse_image_argument(cmd,", "will be created\", storage_id['name']) else: from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client", "'sles', '^12-sp3'), ('redhat', 'rhel', '^7.4'), ('openlogic', 'centos', '^7.4'), ('coreos', 'coreos', None), ('credativ', 'debian',", "namespace.public_ip_address_type = None logger.debug('existing NIC(s) will be used') def _validate_vm_vmss_create_auth(namespace): if namespace.storage_profile in", "missing_kwargs = {k: v for k, v in kwargs.items() if not v} return", "region VM Create Validators def _parse_image_argument(cmd, namespace): \"\"\" Systematically determines what type is", "for x in image_version_infos if not x.publishing_profile.exclude_from_latest] if not image_version_infos: raise CLIError('There is", "', confirm=True) except NoTTYException: raise CLIError('Please specify password in non-interactive mode.') # validate", "namespace.authentication_type == 'ssh': if namespace.admin_password: raise ValueError('Admin password cannot be used with SSH", "error: --license-type is only applicable on Windows VM') _validate_vm_vmss_msi(cmd, namespace) if namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage", "= None logger.debug('no load balancer will be used') elif namespace.load_balancer is None: namespace.load_balancer_type", "validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=True) _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=True) _validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace) _validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd,", "create the VM/VMSS because availablity zone is not yet \" \"supported. Please use", "values found for '{0}': {1}\\nSpecify '{0}' \" \"explicitly.\".format(option_name, ', '.join(values))) elif not values:", "[]), storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching) def _validate_vm_create_storage_account(cmd, namespace): from msrestazure.tools import parse_resource_id if namespace.storage_account:", "enabled') if namespace.eviction_policy and not namespace.priority: raise CLIError('Usage error: --priority PRIORITY [--eviction-policy POLICY]')", "in kwargs.items() if not v} return resource_id(**kwargs) if not missing_kwargs else None def", "the namespace and returns the type for subsequent processing. \"\"\" from msrestazure.tools import", "that the status of required and forbidden parameters validate_parameter_set( namespace, required, forbidden, description='storage", "for Windows VMs.') # validate proper arguments supplied based on the authentication type", "CLIError(linux_err if is_linux else win_err) if is_linux and re.findall(r'^[$-]+', username): raise CLIError(linux_err) if", "logger.debug(\"using specified existing storage account '%s'\", storage_id['name']) else: # 2 - params for", "Windows Server 2012R2 publisher, offer, sku = namespace.os_publisher, namespace.os_offer, namespace.os_sku if not publisher:", "size'\" raise CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix = '{}/{}'.format(cidr, i) if namespace.app_gateway_type and namespace.app_gateway_subnet_address_prefix is None:", "were found :rtype: list \"\"\" is_windows = os_type == 'windows' errors = []", "--attach-os-disk DISK') auth_params = ['<PASSWORD>_password', 'admin_username', 'authentication_type', 'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value'] # perform parameter", "to be a supported image in the marketplace # Ubuntu 16.04, SLES 12", "index {0} in ' \\ 'arg {1} ' errors.append(err.format(idx, idx_arg)) else: for jdx,", "for x in (temp.location_info or []) if x.zones]: raise CLIError(\"{}'s location can't be", "not check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute', 'availabilitySets'): raise CLIError(\"Availability set '{}' does not exist.\".format(name))", "raise ValueError( \"incorrect usage for authentication-type 'password': \" \"[--admin-username USERNAME] --admin-password PASSWORD\") from", "namespace) _validate_vm_create_nsg(cmd, namespace) _validate_vm_vmss_create_public_ip(cmd, namespace) _validate_vm_create_nics(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) if namespace.secrets: _validate_secrets(namespace.secrets,", "import get_subscription_id nics_value = namespace.nics nics = [] if not nics_value: namespace.nic_type =", "'new' logger.debug(\"specified storage account '%s' not found and will be created\", storage_id['name']) else:", "be created') if namespace.load_balancer_type == 'new' and namespace.single_placement_group is False and std_lb_is_available: LBSkuName", "= next((s for s in vnet_match.subnets if s.name.lower() != 'gatewaysubnet'), None) else: def", "in identities if x != MSI_LOCAL_ID] if user_assigned_identities and not cmd.supported_api_version(min_api='2017-12-01'): raise CLIError('usage", "[{ \"sourceVault\": { \"id\": \"value\" }, \"vaultCertificates\": [{ \"certificateUrl\": \"value\", \"certificateStore\": \"cert store", "_ in enumerate(identities): if identities[i] != MSI_LOCAL_ID: identities[i] = _get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name, 'userAssignedIdentities',", "or ID namespace.attach_os_disk = _get_resource_id( cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if getattr(namespace, 'attach_data_disks',", "= 'existing' logger.debug(\"using specified existing storage account '%s'\", storage_id['name']) else: # 2 -", "> 1: raise CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify '{0}' \" \"explicitly.\".format(option_name,", "SCOPE] [--role ROLE]') def _resolve_role_id(cli_ctx, role, scope): import re import uuid from azure.cli.core.commands.client_factory", "in the marketplace # Ubuntu 16.04, SLES 12 SP3, RHEL 7.4, CentOS 7.4,", "elif image_type == 'image_id': # STORAGE PROFILE #5 namespace.storage_profile = StorageProfile.ManagedCustomImage elif image_type", "import get_logger from knack.util import CLIError from azure.cli.core.commands.validators import ( get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set,", "'rhel', '^7.4'), ('openlogic', 'centos', '^7.4'), ('coreos', 'coreos', None), ('credativ', 'debian', '-backports'), ('oracle', 'oracle-linux',", "= len([x for x in [contains_lower, contains_upper, contains_digit, contains_special_char] if x]) # pylint:", "from_set_command or namespace.assign_identity is not None: identities = namespace.assign_identity or [] from ._vm_utils", "StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd, namespace) _validate_vm_create_availability_set(cmd, namespace) _validate_vm_vmss_create_vnet(cmd, namespace) _validate_vm_create_nsg(cmd, namespace) _validate_vm_vmss_create_public_ip(cmd, namespace) _validate_vm_create_nics(cmd, namespace)", "'': namespace.public_ip_address_type = None logger.debug('no public IP address will be used') elif namespace.public_ip_address", "= StorageProfile.ManagedCustomImage elif image_type == 'urn': if namespace.use_unmanaged_disk: # STORAGE PROFILE #1 namespace.storage_profile", "auth_params _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.SAPirImage: required = ['image', 'use_unmanaged_disk'] forbidden = ['os_type',", "or namespace.admin_password) else 'ssh' if namespace.os_type.lower() == 'windows' and namespace.authentication_type == 'ssh': raise", "= 'Standard_DS1_v2' else: namespace.vm_sku = 'Standard_D1_v2' _validate_location(cmd, namespace, namespace.zones, namespace.vm_sku) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd,", "= namespace.resource_group_name if rg: if not kv or is_valid_resource_id(kv): raise keyvault_usage validate_keyvault(cmd, namespace)", "required = [] if namespace.app_gateway_type == 'new': required.append('app_gateway_sku') required.append('app_gateway_capacity') if namespace.vnet_type != 'new':", "namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') if not namespace.identity_scope and getattr(namespace.identity_role, 'is_default', None) is None: raise", "return None def process_vmss_create_namespace(cmd, namespace): validate_tags(namespace) if namespace.vm_sku is None: from azure.cli.core.cloud import", "'{}' is out of range of 2^16 subnet size'\" raise CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix =", "resource group from vault name :param str vault_name: name of the key vault", "'Standard_D15_v2_ABC', 'Standard_M64ms', 'Standard_M64s', 'Standard_M128-64ms', 'Standard_D64_v3', 'Standard_D64s_v3', 'Standard_E64_v3', 'Standard_E64s_v3', 'Standard_E64-16s_v3', 'Standard_E64-32s_v3', 'Standard_F64s_v2', 'Standard_F72s_v2', 'Standard_M128s',", "for x in address.split('.')] result = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b, c, d) return int(result[:-bit_mask_len], 2)", "character, 1 upper case character, 1 number and 1 special character') def validate_ssh_key(namespace):", "uuid from azure.cli.core.commands.client_factory import get_mgmt_service_client from azure.cli.core.profiles import ResourceType client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions", "an URN pattern urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image) if urn_match: namespace.os_publisher = urn_match.group(1) namespace.os_offer", "file names: # 'base_name'(with private keys), and 'base_name.pub'(with public keys) public_key_filepath = string_or_file", "nic_ids = [] for n in namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg)) namespace.nics = nic_ids", "namespace.app_gateway_subnet_address_prefix is None: namespace.app_gateway_subnet_address_prefix = _get_next_subnet_addr_suffix( namespace.vnet_address_prefix, namespace.subnet_address_prefix, 24) def _get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr, new_mask):", "{0}'.format(err)) for idx_arg, narg_secret in enumerate(loaded_secret): for idx, secret in enumerate(narg_secret): if 'sourceVault'", "are coming out vnet_ip_address, mask = vnet_cidr.split('/') vnet_bit_mask_len = 32 - int(mask) vnet_int", "from azure.cli.core.commands.client_factory import get_subscription_id if is_valid_resource_id(val): return val kwargs = { 'name': val,", "load balancer will be used') elif namespace.load_balancer is None: namespace.load_balancer_type = 'new' logger.debug('new", "~/.ssh to \" \"allow SSH access to the VM. If using machines without", "namespace.os_type: raise CLIError(\"usage error: os type is required to create the image, \"", "[] try: loaded_secret = [validate_file_or_dict(secret) for secret in secrets] except Exception as err:", "(32 - mask)) - 2) > int(vmss_instance_count * factor) def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace): if", "'disks', 'Microsoft.Compute') def validate_vmss_disk(cmd, namespace): if namespace.disk: namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks',", "'--key-encryption-keyvault': \" \"'--key-encryption-key' is required\") namespace.key_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def", "image_plan.product namespace.plan_publisher = image_plan.publisher return 'urn' # 3 - unmanaged vhd based images?", "if nothing specified, try to find an existing vnet and subnet in the", "1): raise CLIError('The password length must be between {} and {}'.format(min_length, max_length)) contains_lower", "namespace.target_regions: regions_info = [] for t in namespace.target_regions: parts = t.split('=', 1) if", "+ auth_params else: raise CLIError('Unrecognized storage profile: {}'.format(namespace.storage_profile)) logger.debug(\"storage profile '%s'\", namespace.storage_profile) if", "load balancer is required because 'single placement group' is turned off\" raise CLIError('usage", "= _get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name, 'images', 'Microsoft.Compute') return 'image_id' except CloudError: err = 'Invalid", "nic_ids if hasattr(namespace, 'primary_nic') and namespace.primary_nic: namespace.primary_nic = _get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg) def _validate_secrets(secrets,", "resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2']) image_data_disks_num = len(image_version_info.storage_profile.data_disk_images or []) else: raise CLIError('usage error:", "int(vmss_instance_count * factor) def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace): if namespace.accelerated_networking is None: size = getattr(namespace,", "{k: v for k, v in kwargs.items() if not v} return resource_id(**kwargs) if", "if urn_match: namespace.os_publisher = urn_match.group(1) namespace.os_offer = urn_match.group(2) namespace.os_sku = urn_match.group(3) namespace.os_version =", "_validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.SAPirImage: required = ['image', 'use_unmanaged_disk'] forbidden = ['os_type', 'attach_os_disk',", "StorageProfile.SAPirImage: required = ['image', 'use_unmanaged_disk'] forbidden = ['os_type', 'attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile ==", "8: return # VMs need to be a supported image in the marketplace", "verify the defaults we are coming out vnet_ip_address, mask = vnet_cidr.split('/') vnet_bit_mask_len =", "avoid crash namespace.disk_info = normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace, 'attach_data_disks', []), storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching) def", "sku_tier and a.location == namespace.location), None) if account: # 3 - nothing specified", "= ['<PASSWORD>_password', 'admin_username', 'authentication_type', 'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value'] # perform parameter validation for the", "if x]) # pylint: disable=line-too-long if count < 3: raise CLIError('Password must have", "import ResourceType client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions role_id = None if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role, re.I):", "('credativ', 'debian', '-backports'), ('oracle', 'oracle-linux', '^7.4'), ('MicrosoftWindowsServer', 'WindowsServer', '^2016'), ('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')] import", "was configured on '%s'\", namespace.load_balancer) else: namespace.nat_pool_name = lb.inbound_nat_pools[0].name logger.debug(\"using specified existing load", "MSI_LOCAL_ID for i in range(len(namespace.identities)): if namespace.identities[i] != MSI_LOCAL_ID: namespace.identities[i] = _get_resource_id(cmd.cli_ctx, namespace.identities[i],", "is an image ID) if is_valid_resource_id(namespace.image): return 'image_id' # 2 - attempt to", "!= MSI_LOCAL_ID: namespace.identities[i] = _get_resource_id(cmd.cli_ctx, namespace.identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') # TODO move to", "'{}' does not exist.\".format(subnet)) elif subnet_exists: # 2 - user specified existing vnet/subnet", "PROFILE #1 namespace.storage_profile = StorageProfile.SAPirImage else: # STORAGE PROFILE #4 namespace.storage_profile = StorageProfile.ManagedPirImage", "== sku_tier and a.location == namespace.location), None) if account: # 3 - nothing", "not exist.\".format(subnet)) elif subnet_exists: # 2 - user specified existing vnet/subnet namespace.vnet_type =", "default auth type (password for Windows, ssh for Linux) by examining the OS", "not lb.inbound_nat_pools: # Associated scaleset will be missing ssh/rdp, so warn here. logger.warning(\"No", "= [x for x in identities if x != MSI_LOCAL_ID] if user_assigned_identities and", "parse_resource_id(namespace.load_balancer)['name'] lb = get_network_lb(cmd.cli_ctx, namespace.resource_group_name, lb_name) if lb: namespace.load_balancer_type = 'existing' namespace.backend_pool_name =", "Systematically determines what type is supplied for the --image parameter. Updates the namespace", "is required for zonal scale-sets\" elif namespace.instance_count > 100: err = \"'Standard' load", "Value. ' 'You can use --generate-ssh-keys to let CLI generate one for you')", "namespace.os_type) if namespace.license_type and namespace.os_type.lower() != 'windows': raise CLIError('usage error: --license-type is only", "namespace): namespace.nic = _get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name) def validate_vm_nics(cmd, namespace): rg = namespace.resource_group_name nic_ids", "upper case character A-Z, special characters \\/\"[]:|<>+=;,?*@#()! or start with $ or -'", "x in [contains_lower, contains_upper, contains_digit, contains_special_char] if x]) # pylint: disable=line-too-long if count", "generalized VHD' elif profile == StorageProfile.SAPirImage: return 'create unmanaged OS disk from Azure", "._vm_utils import normalize_disk_info # attach_data_disks are not exposed yet for VMSS, so use", "except CloudError as ex: logger.warning(\"Querying the image of '%s' failed for an error", "= _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) vm_info = compute_client.virtual_machines.get(res['resource_group'], res['name']) # pylint: disable=no-member namespace.os_type = vm_info.storage_profile.os_disk.os_type.value", "CLIError('unrecognized balancer type: {}'.format(balancer_type)) balancer = client.get(resource_group, balancer_name) values = [x.name for x", "namespace.nic = _get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name) def validate_vm_nics(cmd, namespace): rg = namespace.resource_group_name nic_ids =", "string os_type: the type of OS (linux or windows) :return: errors if any", "_figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, data_disk_source) if source_blob_uri: namespace.data_blob_uris.append(source_blob_uri) if source_disk: namespace.data_disks.append(source_disk) if source_snapshot: namespace.data_snapshots.append(source_snapshot)", "cert: errors.append(message.format('certificateStore', idx, jdx, idx_arg)) if errors: raise CLIError('\\n'.join(errors)) # region VM Create", "namespace.os_sku, image_version) # pylint: disable=no-member return image.plan except CloudError as ex: logger.warning(\"Querying the", "lacks some parameters, so scrub these out props_to_remove = ['attach_os_disk', 'storage_account'] for prop", "not values: raise CLIError(\"No existing values found for '{0}'. Create one first and", "storage account '%s'\", storage_id['name']) else: # 2 - params for new storage account", "JSON structure [{ \"sourceVault\": { \"id\": \"value\" }, \"vaultCertificates\": [{ \"certificateUrl\": \"value\", \"certificateStore\":", "for x in aval_sizes] if size not in aval_sizes: return new_4core_sizes = ['Standard_D3_v2',", "re # 1 - check if a fully-qualified ID (assumes it is an", "[\"\"] or not names_or_ids: return for val in names_or_ids: if not is_valid_resource_id(val): val", "return if not isinstance(nics_value, list): nics_value = [nics_value] for n in nics_value: nics.append({", "image informations \"{}\"'.format(namespace.image)) # pylint: disable=no-member elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: # accept disk", "# 1 - find a suitable existing vnet/subnet result = None if not", "the other way around if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: raise", "source_disk: namespace.data_disks.append(source_disk) if source_snapshot: namespace.data_snapshots.append(source_snapshot) if not namespace.os_type: raise CLIError(\"usage error: os type", "# VMs need to be a supported image in the marketplace # Ubuntu", "MSI_LOCAL_ID] if user_assigned_identities and not cmd.supported_api_version(min_api='2017-12-01'): raise CLIError('usage error: user assigned identity is", "\"admin1\", \"1\", \"123\", \"a\", \"actuser\", \"adm\", \"admin2\", \"aspnet\", \"backup\", \"console\", \"guest\", \"owner\", \"root\",", "loaded_secret = [validate_file_or_dict(secret) for secret in secrets] except Exception as err: raise CLIError('Error", "namespace.os_version = matched['version'] return 'urn' # 5 - check if an existing managed", "namespace.public_ip_address) else: namespace.public_ip_address_type = 'new' logger.debug(\"specified public IP '%s' not found. It will", "CLIError('usage error: --platform-fault-domain-count COUNT --zones ZONES') if namespace.zones or namespace.instance_count > 100: if", "rights reserved. # Licensed under the MIT License. See License.txt in the project", "\"'Standard' load balancer is required for scale-sets with 100+ instances\" else: err =", "for k, v in kwargs.items() if not v} return resource_id(**kwargs) if not missing_kwargs", "if kv and not is_valid_resource_id(kv): raise keyvault_usage def _get_resource_group_from_vault_name(cli_ctx, vault_name): \"\"\" Fetch resource", "namespace.storage_profile in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]: # pylint: disable=line-too-long namespace.storage_sku = 'Standard_LRS' if for_scale_set else", "_convert_to_int(address, bit_mask_len): a, b, c, d = [int(x) for x in address.split('.')] result", "applicable as the '--scope' is not provided\".format( namespace.identity_role)) user_assigned_identities = [x for x", "[r.id for r in role_defs] err = \"More than one role matches the", "# pylint: disable=line-too-long pattern = (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if is_linux else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err = r'admin", "Standard sku as single placement group is turned off\") elif namespace.load_balancer_sku == LBSkuName.basic.value:", "= True def _validate_vmss_create_subnet(namespace): if namespace.vnet_type == 'new': if namespace.subnet_address_prefix is None: cidr", "import get_subscription_id if is_valid_resource_id(val): return val kwargs = { 'name': val, 'resource_group': resource_group,", "if (namespace.os_type.lower() == 'windows' or namespace.admin_password) else 'ssh' if namespace.os_type.lower() == 'windows' and", "'Microsoft.Network') def _validate_vm_vmss_create_public_ip(cmd, namespace): if namespace.public_ip_address: if check_existence(cmd.cli_ctx, namespace.public_ip_address, namespace.resource_group_name, 'Microsoft.Network', 'publicIPAddresses'): namespace.public_ip_address_type", "= _get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_vm_secret_format(cmd, namespace): from msrestazure.tools import is_valid_resource_id", "res = parse_resource_id(namespace.image) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) if res['type'].lower() == 'images': image_info =", "contains_lower = re.findall('[a-z]+', password) contains_upper = re.findall('[A-Z]+', password) contains_digit = re.findall('[0-9]+', password) contains_special_char", "leeway for over-provision factor = 1.5 if over_provision else 1 return ((1 <<", "from msrestazure.azure_exceptions import CloudError from msrestazure.tools import parse_resource_id from azure.cli.core.profiles import ResourceType std_lb_is_available", "CloudError: namespace.app_gateway_type = 'new' logger.debug(\"application gateway '%s' not found. It will be created.\",", "= 'password' \\ if (namespace.os_type.lower() == 'windows' or namespace.admin_password) else 'ssh' if namespace.os_type.lower()", "msrestazure.tools import is_valid_resource_id vnet = namespace.vnet_name subnet = namespace.subnet rg = namespace.resource_group_name location", "for an error '%s'. Configuring plan settings \" \"will be skipped\", namespace.image, ex.message)", "(vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: raise CLIError(error_msg) # format back to the cidr", "group name or None :rtype: str \"\"\" from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory", "- nothing specified - create a new storage account namespace.storage_account_type = 'new' logger.debug('no", "'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo', 'Standard_F16', 'Standard_F16s', 'Standard_M64-32ms', 'Standard_M128-32ms', 'Standard_D32_v3', 'Standard_D32s_v3', 'Standard_D64-32s_v3', 'Standard_E32_v3', 'Standard_E32s_v3', 'Standard_E32-8s_v3', 'Standard_E32-16_v3',", "CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify '{0}' explicitly.\".format( # pylint: disable=line-too-long '--nat-pool-name',", "\"console\", \"guest\", \"owner\", \"root\", \"server\", \"sql\", \"support\", \"support_388945a0\", \"sys\", \"test2\", \"test3\", \"user4\", \"user5\"]", "'Standard_E64s_v3', 'Standard_E64-16s_v3', 'Standard_E64-32s_v3', 'Standard_F64s_v2', 'Standard_F72s_v2', 'Standard_M128s', 'Standard_M128ms', 'Standard_L8s_v2', 'Standard_L16s_v2', 'Standard_L32s_v2', 'Standard_L64s_v2', 'Standard_L96s_v2', 'SQLGL',", "CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify '{0}' \" \"explicitly.\".format(option_name, ', '.join(values))) elif", "namespace.zones is None: raise CLIError('usage error: --platform-fault-domain-count COUNT --zones ZONES') if namespace.zones or", "the error aval_sizes = ['Standard_D3_v2', 'Standard_D12_v2', 'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo', 'Standard_DS3_v2', 'Standard_DS12_v2', 'Standard_DS13-4_v2', 'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo',", "elif namespace.load_balancer == '': namespace.load_balancer_type = None logger.debug('no load balancer will be used')", "contains_upper = re.findall('[A-Z]+', password) contains_digit = re.findall('[0-9]+', password) contains_special_char = re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password)", "-' win_err = r'admin user name cannot contain special characters \\/\"[]:|<>+=;,?*@# or ends", "VM's location sku_tier = 'Premium' if 'Premium' in namespace.storage_sku else 'Standard' account =", "= [int(x) for x in address.split('.')] result = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b, c, d) return", "source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, data_disk_source) if source_blob_uri: namespace.data_blob_uris.append(source_blob_uri) if source_disk: namespace.data_disks.append(source_disk) if", "= urn_match.group(4) if not any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]): image_plan = _get_image_plan_info_if_exists(cmd, namespace) if image_plan:", "from msrestazure.tools import parse_resource_id, resource_id from azure.cli.core.commands.client_factory import get_subscription_id if namespace.availability_set: as_id =", "'attach_data_disks', []), storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching) def _validate_vm_create_storage_account(cmd, namespace): from msrestazure.tools import parse_resource_id if", "except ImportError: from urlparse import urlparse # pylint: disable=import-error from knack.log import get_logger", "'Standard_D40s_v3', 'Standard_D15_v2_ABC', 'Standard_M64ms', 'Standard_M64s', 'Standard_M128-64ms', 'Standard_D64_v3', 'Standard_D64s_v3', 'Standard_E64_v3', 'Standard_E64s_v3', 'Standard_E64-16s_v3', 'Standard_E64-32s_v3', 'Standard_F64s_v2', 'Standard_F72s_v2',", "\"More than one role matches the given name '{}'. Please pick an id", "= 'Standard_D1_v2' _validate_location(cmd, namespace, namespace.zones, namespace.vm_sku) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=True) _validate_vm_vmss_create_vnet(cmd, namespace,", "virtual machines\") except CloudError: namespace.os_blob_uri, namespace.os_disk, namespace.os_snapshot = _figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name, namespace.source) # pylint:", "storage_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts # find storage account in target resource group that", "_get_nic_id(cli_ctx, val, resource_group): return _get_resource_id(cli_ctx, val, resource_group, 'networkInterfaces', 'Microsoft.Network') def validate_vm_nic(cmd, namespace): namespace.nic", "namespace.disk_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') if namespace.key_encryption_keyvault: if not namespace.key_encryption_key: raise CLIError(\"Incorrect usage '--key-encryption-keyvault':", "== offer) and (s is None or re.match(s, sku, re.I)): namespace.accelerated_networking = True", "o, s in distros: if p.lower() == publisher and (o is None or", "elif not lb.inbound_nat_pools: # Associated scaleset will be missing ssh/rdp, so warn here.", "# endregion # region disk, snapshot, image validators def validate_vm_disk(cmd, namespace): namespace.disk =", "= urn_match.group(3) namespace.os_version = urn_match.group(4) if not any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]): image_plan = _get_image_plan_info_if_exists(cmd,", "'Standard_E32_v3', 'Standard_E32s_v3', 'Standard_E32-8s_v3', 'Standard_E32-16_v3', 'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC', 'Standard_F16_ABC', 'Standard_F32s_v2', 'Standard_D15_v2', 'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested', 'Standard_DS15_v2', 'Standard_DS15_v2_Promo',", "def _validate_admin_password(password, os_type): import re is_linux = (os_type.lower() == 'linux') max_length = 72", "Validators def _parse_image_argument(cmd, namespace): \"\"\" Systematically determines what type is supplied for the", "--image IMAGE | --attach-os-disk DISK') auth_params = ['<PASSWORD>_password', 'admin_username', 'authentication_type', 'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value']", "be created.') def _validate_vm_create_availability_set(cmd, namespace): from msrestazure.tools import parse_resource_id, resource_id from azure.cli.core.commands.client_factory import", "password length must be between {} and {}'.format(min_length, max_length)) contains_lower = re.findall('[a-z]+', password)", "if not result: continue namespace.subnet = result.name namespace.vnet_name = vnet_match.name namespace.vnet_type = 'existing'", "vnet and subnet in the target resource group client = get_network_client(cmd.cli_ctx).virtual_networks # find", "client.get(resource_group, balancer_name) values = [x.name for x in balancer.backend_address_pools] if len(values) > 1:", "'sourceVault' not in secret: errors.append( 'Secret is missing sourceVault key at index {0}", "'%s' not found. It will be created.\", namespace.nsg) elif namespace.nsg == '': namespace.nsg_type", "if namespace.nsg: if check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_type = 'existing' logger.debug(\"using specified", "generated under ~/.ssh to \" \"allow SSH access to the VM. If using", "be turned off for zonal scale-sets or with\" \" 100+ instances\") def _validate_vmss_create_load_balancer_or_app_gateway(cmd,", "'disks', 'Microsoft.Compute') if bool(namespace.disk) == bool(namespace.size_gb): raise CLIError('usage error: --disk EXIST_DISK --instance-id ID", "{}'.format(image_type)) else: # did not specify image XOR attach-os-disk raise CLIError('incorrect usage: --image", "not publisher: return publisher, offer, sku = publisher.lower(), offer.lower(), sku.lower() distros = [('canonical',", "from a managed custom image res = parse_resource_id(namespace.image) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) if", "[validate_file_or_dict(secret) for secret in secrets] except Exception as err: raise CLIError('Error decoding secrets:", "or namespace.assign_identity is not None: identities = namespace.assign_identity or [] from ._vm_utils import", "size not in new_4core_sizes: compute_client = _compute_client_factory(cli_ctx) sizes = compute_client.virtual_machine_sizes.list(namespace.location) size_info = next((s", "namespace.attach_data_disks] if not namespace.os_type: namespace.os_type = 'windows' if 'windows' in namespace.os_offer.lower() else 'linux'", "= parse_resource_id(namespace.application_gateway)['name'] client.get(rg, ag_name) namespace.app_gateway_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx,", "elif '/snapshots/' in source.lower(): source_snapshot = source else: compute_client = _compute_client_factory(cli_ctx) # pylint:", "= 32 - int(mask) if vnet_bit_mask_len <= subnet_bit_mask_len: raise CLIError(error_msg) candidate_int = _convert_to_int(subnet_ip_address,", "namespace.subnet = result.name namespace.vnet_name = vnet_match.name namespace.vnet_type = 'existing' logger.debug(\"existing vnet '%s' and", "getattr(namespace, 'size', None) or getattr(namespace, 'vm_sku', None) size = size.lower() # to refresh", "and try \" \"again.\".format(option_name)) return values[0] def _validate_vmss_single_placement_group(namespace): if namespace.platform_fault_domain_count is not None", "= _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') def validate_vmss_disk(cmd, namespace): if namespace.disk: namespace.disk =", "matches the VM's location with a matching subnet for vnet_match in (v for", "URN pattern urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image) if urn_match: namespace.os_publisher = urn_match.group(1) namespace.os_offer =", "err = \"'Standard' load balancer is required because 'single placement group' is turned", "!= bool(namespace.instance_id): raise CLIError('usage error: --disk EXIST_DISK --instance-id ID') def process_disk_or_snapshot_create_namespace(cmd, namespace): from", "2012R2 publisher, offer, sku = namespace.os_publisher, namespace.os_offer, namespace.os_sku if not publisher: return publisher,", "raise CLIError(\"Unable to resolve OS type. Specify '--os-type' argument.\") if not namespace.authentication_type: #", "namespace) if image_type == 'uri': # STORAGE PROFILE #2 namespace.storage_profile = StorageProfile.SACustomImage elif", "'vaults', 'Microsoft.KeyVault') if namespace.key_encryption_keyvault: if not namespace.key_encryption_key: raise CLIError(\"Incorrect usage '--key-encryption-keyvault': \" \"'--key-encryption-key'", "'Standard_D64_v3', 'Standard_D64s_v3', 'Standard_E64_v3', 'Standard_E64s_v3', 'Standard_E64-16s_v3', 'Standard_E64-32s_v3', 'Standard_F64s_v2', 'Standard_F72s_v2', 'Standard_M128s', 'Standard_M128ms', 'Standard_L8s_v2', 'Standard_L16s_v2', 'Standard_L32s_v2',", "password _validate_admin_password(namespace.admin_password, namespace.os_type) elif namespace.authentication_type == 'ssh': if namespace.admin_password: raise ValueError('Admin password cannot", "= resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name = namespace.network_security_group_name \\ or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id,", "v in kwargs.items() if not v} return resource_id(**kwargs) if not missing_kwargs else None", "elif namespace.storage_profile == StorageProfile.ManagedCustomImage: required = ['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name',", "'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC', 'Standard_F4_ABC', 'Standard_F8s_v2', 'Standard_D4_v2', 'Standard_D13_v2', 'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo', 'Standard_DS4_v2', 'Standard_DS13_v2', 'Standard_DS14-8_v2',", "error: {}'s replica count must be an integer\".format(parts[0])) regions_info.append(TargetRegion(name=parts[0], regional_replica_count=replica_count)) namespace.target_regions = regions_info", "error: --source {SNAPSHOT | DISK} | --source VHD_BLOB_URI [--source-storage-account-id ID]' try: namespace.source_blob_uri, namespace.source_disk,", "not hasattr(temp, 'location_info'): return if not temp or not [x for x in", "'Standard_D13_v2_Promo', 'Standard_DS4_v2', 'Standard_DS13_v2', 'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo', 'Standard_F8', 'Standard_F8s', 'Standard_M64-16ms', 'Standard_D16_v3', 'Standard_D16s_v3', 'Standard_D32-16s_v3',", "_validate_vmss_create_public_ip(cmd, namespace) _validate_vmss_create_nsg(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd, namespace) if namespace.license_type and namespace.os_type.lower()", "None and namespace.application_gateway is None: if std_lb_is_available: balancer_type = 'loadBalancer' else: # needed", "OS disk from Azure Marketplace image' elif profile == StorageProfile.SASpecializedOSDisk: return 'attach to", "and namespace.application_gateway is None: if std_lb_is_available: balancer_type = 'loadBalancer' else: # needed for", "'load_balancer', 'health_probe'] validate_parameter_set(namespace, required, forbidden, description='network balancer: application gateway') elif balancer_type == 'loadBalancer':", "\" 100+ instances\") def _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace): from msrestazure.azure_exceptions import CloudError from msrestazure.tools import", "scenario res_id = _get_resource_id(cmd.cli_ctx, namespace.source, namespace.resource_group_name, 'virtualMachines', 'Microsoft.Compute') res = parse_resource_id(res_id) compute_client =", "in namespace.attach_data_disks] if not namespace.os_type: namespace.os_type = 'windows' if 'windows' in namespace.os_offer.lower() else", "namespace.zones: err = \"'Standard' load balancer is required for zonal scale-sets\" elif namespace.instance_count", "nics_value: nics.append({ 'id': n if '/' in n else resource_id(name=n, resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkInterfaces',", "VM if namespace.storage_profile == StorageProfile.ManagedPirImage: required = ['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account',", "contains_special_char] if x]) # pylint: disable=line-too-long if count < 3: raise CLIError('Password must", "| DISK} | --source VHD_BLOB_URI [--source-storage-account-id ID]' try: namespace.source_blob_uri, namespace.source_disk, namespace.source_snapshot = _figure_out_storage_source(", "up your keys to a safe location.\", private_key_filepath, public_key_filepath) else: raise CLIError('An RSA", "image' elif profile == StorageProfile.SASpecializedOSDisk: return 'attach to existing unmanaged OS disk' elif", "is_valid_resource_id(namespace.image): return 'image_id' # 2 - attempt to match an URN pattern urn_match", "== LBSkuName.basic.value: if namespace.zones: err = \"'Standard' load balancer is required for zonal", "count = len([x for x in [contains_lower, contains_upper, contains_digit, contains_special_char] if x]) #", "character, 1 number and 1 special character') def validate_ssh_key(namespace): string_or_file = (namespace.ssh_key_value or", "existing SSH public key file: %s', string_or_file) with open(string_or_file, 'r') as f: content", "def process_vmss_create_namespace(cmd, namespace): validate_tags(namespace) if namespace.vm_sku is None: from azure.cli.core.cloud import AZURE_US_GOV_CLOUD if", "regions_info = [] for t in namespace.target_regions: parts = t.split('=', 1) if len(parts)", "missing sourceVault key at index {0} in arg {1}'.format( idx, idx_arg)) if 'sourceVault'", "'Standard_E64_v3', 'Standard_E64s_v3', 'Standard_E64-16s_v3', 'Standard_E64-32s_v3', 'Standard_F64s_v2', 'Standard_F72s_v2', 'Standard_M128s', 'Standard_M128ms', 'Standard_L8s_v2', 'Standard_L16s_v2', 'Standard_L32s_v2', 'Standard_L64s_v2', 'Standard_L96s_v2',", "network_client = get_network_client(cli_ctx) try: return network_client.load_balancers.get(resource_group_name, lb_name) except CloudError: return None def process_vmss_create_namespace(cmd,", "def validate_nsg_name(cmd, namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id vm_id =", "existing specified public IP '%s'\", namespace.public_ip_address) else: namespace.public_ip_address_type = 'new' logger.debug(\"specified public IP", "'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedCustomImage: required =", "supplied based on the authentication type if namespace.authentication_type == 'password': if namespace.ssh_key_value or", "namespace.os_type) elif namespace.authentication_type == 'ssh': if namespace.admin_password: raise ValueError('Admin password cannot be used", "return 'image_id' # 2 - attempt to match an URN pattern urn_match =", "'Standard_D4_v2', 'Standard_D13_v2', 'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo', 'Standard_DS4_v2', 'Standard_DS13_v2', 'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo', 'Standard_F8', 'Standard_F8s', 'Standard_M64-16ms',", "'base_name.pub'(with public keys) public_key_filepath = string_or_file if public_key_filepath[-4:].lower() == '.pub': private_key_filepath = public_key_filepath[:-4]", "key files '%s' and '%s' have been generated under ~/.ssh to \" \"allow", "ID]' try: namespace.source_blob_uri, namespace.source_disk, namespace.source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, namespace.source) if not namespace.source_blob_uri", "not namespace.use_unmanaged_disk: namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name, 'disks', 'Microsoft.Compute') for d in namespace.attach_data_disks]", "else 1 return ((1 << (32 - mask)) - 2) > int(vmss_instance_count *", "reserved broadcasting addresses # '*1.5' so we have enough leeway for over-provision factor", "contains_special_char = re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password) count = len([x for x in [contains_lower, contains_upper,", "= compute_client.snapshots.get(resource_group_name, source) source_snapshot = info.id except CloudError: info = compute_client.disks.get(resource_group_name, source) source_disk", "namespace.disable_overprovision) result = next((s for s in vnet_match.subnets if _check_subnet(s)), None) if not", "namespace.admin_password = prompt_pass('Admin Password: ', confirm=True) except NoTTYException: raise CLIError('Please specify password in", "7.4, Windows Server 2016, Windows Server 2012R2 publisher, offer, sku = namespace.os_publisher, namespace.os_offer,", "namespace): if namespace.disk: namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if bool(namespace.disk) ==", "ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace, 'application_security_groups', ids) def validate_nsg_name(cmd, namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory", "params for new storage account specified namespace.storage_account_type = 'new' logger.debug(\"specified storage account '%s'", "is None: namespace.load_balancer_sku = LBSkuName.standard.value logger.debug(\"use Standard sku as single placement group is", "._vm_utils import list_sku_info if not namespace.location: get_default_location_from_resource_group(cmd, namespace) if zone_info: sku_infos = list_sku_info(cmd.cli_ctx,", "'Microsoft.Compute', 'availabilitySets'): raise CLIError(\"Availability set '{}' does not exist.\".format(name)) namespace.availability_set = resource_id( subscription=get_subscription_id(cmd.cli_ctx),", "disable=line-too-long '--nat-pool-name', ', '.join([n.name for n in lb.inbound_nat_pools]))) elif not lb.inbound_nat_pools: # Associated", "subnet_mask = s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask, namespace.instance_count, not namespace.disable_overprovision) result = next((s for s", "not specify image XOR attach-os-disk raise CLIError('incorrect usage: --image IMAGE | --attach-os-disk DISK')", "err = \"'Standard' load balancer is required for zonal scale-sets\" elif namespace.instance_count >", "# Ubuntu 16.04, SLES 12 SP3, RHEL 7.4, CentOS 7.4, CoreOS Linux, Debian", "created') return if not isinstance(nics_value, list): nics_value = [nics_value] for n in nics_value:", "If using machines without \" \"permanent storage, back up your keys to a", "prompt_pass('Admin Password: ', confirm=True) except NoTTYException: raise CLIError('Please specify password in non-interactive mode.')", "getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError('usage error: --assign-identity [--scope SCOPE] [--role ROLE]')", "{0} within vaultCertificates array at secret ' \\ 'index {1} and vaultCertificate index", "[nics_value] for n in nics_value: nics.append({ 'id': n if '/' in n else", "command module https://github.com/Azure/azure-cli/issues/5105 def process_msi_namespace(cmd, namespace): get_default_location_from_resource_group(cmd, namespace) validate_tags(namespace) def process_gallery_image_version_namespace(cmd, namespace): TargetRegion", "x in identities if x != MSI_LOCAL_ID] if user_assigned_identities and not cmd.supported_api_version(min_api='2017-12-01'): raise", "3 of the following: 1 lower case character, 1 upper case character, 1", "Please use '--location' to specify a capable one. 'az vm list-skus' can be", "or o.lower() == offer) and (s is None or re.match(s, sku, re.I)): namespace.accelerated_networking", "address will be created') # Public-IP SKU is only exposed for VM. VMSS", "= [x.lower() for x in new_4core_sizes] if size not in new_4core_sizes: compute_client =", "for you') namespace.ssh_key_value = content def _validate_vm_vmss_msi(cmd, namespace, from_set_command=False): if from_set_command or namespace.assign_identity", "\\ _get_default_address_pool(cmd.cli_ctx, rg, ag_name, 'application_gateways') logger.debug(\"using specified existing application gateway '%s'\", namespace.application_gateway) except", "re for p, o, s in distros: if p.lower() == publisher and (o", "'%s' failed for an error '%s'. Configuring plan settings \" \"will be skipped\",", "factor = 1.5 if over_provision else 1 return ((1 << (32 - mask))", "namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: # accept disk name or ID namespace.attach_os_disk = _get_resource_id( cmd.cli_ctx,", "other way around if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: raise CLIError(error_msg)", "result = next((s for s in vnet_match.subnets if s.name.lower() != 'gatewaysubnet'), None) else:", "not any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]): image_plan = _get_image_plan_info_if_exists(cmd, namespace) if image_plan: namespace.plan_name = image_plan.name", "not v} return resource_id(**kwargs) if not missing_kwargs else None def _get_nic_id(cli_ctx, val, resource_group):", "STORAGE PROFILE #5 namespace.storage_profile = StorageProfile.ManagedCustomImage elif image_type == 'urn': if namespace.use_unmanaged_disk: #", "[x['urnAlias'] for x in images])) def _get_image_plan_info_if_exists(cmd, namespace): from msrestazure.azure_exceptions import CloudError try:", "resource_type=ResourceType.MGMT_NETWORK) resource_group = namespace.resource_group_name subscription_id = get_subscription_id(cmd.cli_ctx) names_or_ids = getattr(namespace, 'application_security_groups') ids =", "None logger.debug('no public IP address will be used') elif namespace.public_ip_address is None: namespace.public_ip_address_type", "not provided\".format( namespace.identity_role)) user_assigned_identities = [x for x in identities if x !=", "can use --generate-ssh-keys to let CLI generate one for you') namespace.ssh_key_value = content", "error: --priority PRIORITY [--eviction-policy POLICY]') # endregion # region disk, snapshot, image validators", "namespace.assign_identity or [] from ._vm_utils import MSI_LOCAL_ID for i, _ in enumerate(identities): if", "s in vnet_match.subnets if s.name.lower() != 'gatewaysubnet'), None) else: def _check_subnet(s): if s.name.lower()", "props_to_remove: if prop in required: required.remove(prop) if prop in forbidden: forbidden.remove(prop) # set", "= ['os_type', 'attach_os_disk', 'use_unmanaged_disk'] forbidden = ['os_disk_name', 'os_caching', 'image', 'storage_account', 'storage_container_name', 'data_disk_sizes_gb', 'storage_sku']", "image \"{}\". Use a custom image name, id, or pick one from {}'", "= ['os_disk_name', 'os_caching', 'storage_account', 'storage_container_name', 'use_unmanaged_disk', 'storage_sku'] + auth_params _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile ==", "'new' logger.debug('new application gateway will be created') # AppGateway frontend required = []", "'disks', 'Microsoft.Compute') if getattr(namespace, 'attach_data_disks', None): if not namespace.use_unmanaged_disk: namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx, d,", "error: os type is required to create the image, \" \"please specify '--os-type", "for secret in secrets] except Exception as err: raise CLIError('Error decoding secrets: {0}'.format(err))", "'data_disk_sizes_gb', 'storage_sku'] + auth_params else: raise CLIError('Unrecognized storage profile: {}'.format(namespace.storage_profile)) logger.debug(\"storage profile '%s'\",", "azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client from msrestazure.tools import parse_resource_id client =", "'Standard_E8s_v3', 'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC', 'Standard_F4_ABC', 'Standard_F8s_v2', 'Standard_D4_v2', 'Standard_D13_v2', 'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo', 'Standard_DS4_v2', 'Standard_DS13_v2', 'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo',", "jdx, idx_arg)) if errors: raise CLIError('\\n'.join(errors)) # region VM Create Validators def _parse_image_argument(cmd,", "(s is None or re.match(s, sku, re.I)): namespace.accelerated_networking = True def _validate_vmss_create_subnet(namespace): if", "application gateway frontend.') namespace.public_ip_address = '' _validate_vm_vmss_create_public_ip(cmd, namespace) def _validate_vm_create_nics(cmd, namespace): from msrestazure.tools", "'new' logger.debug(\"specified public IP '%s' not found. It will be created.\", namespace.public_ip_address) elif", "'attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SACustomImage: required = ['image', 'os_type', 'use_unmanaged_disk'] forbidden =", "== 'password': if namespace.ssh_key_value or namespace.ssh_dest_key_path: raise ValueError( \"incorrect usage for authentication-type 'password':", "as logical name is more readable setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role, namespace.identity_scope)) elif namespace.identity_scope", "role) except ValueError: pass if not role_id: # retrieve role id role_defs =", "!= 'gatewaysubnet'), None) else: def _check_subnet(s): if s.name.lower() == 'gatewaysubnet': return False subnet_mask", "_validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace): from msrestazure.azure_exceptions import CloudError from msrestazure.tools import parse_resource_id from azure.cli.core.profiles import", "the VM's location sku_tier = 'Premium' if 'Premium' in namespace.storage_sku else 'Standard' account", "\"owner\", \"root\", \"server\", \"sql\", \"support\", \"support_388945a0\", \"sys\", \"test2\", \"test3\", \"user4\", \"user5\"] if username.lower()", "from vault name :param str vault_name: name of the key vault :return: resource", "be used when --public-ip-per-vm is enabled') if namespace.eviction_policy and not namespace.priority: raise CLIError('Usage", "in ['latest', '']: image_version_infos = compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) image_version_infos = [x for", "required, forbidden, description='network balancer: load balancer') if namespace.load_balancer: rg = parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name) lb_name", "> int(vmss_instance_count * factor) def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace): if namespace.accelerated_networking is None: size =", "= StorageProfile.SACustomImage elif image_type == 'image_id': # STORAGE PROFILE #5 namespace.storage_profile = StorageProfile.ManagedCustomImage", "STORAGE PROFILE #6 namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk elif namespace.image and not getattr(namespace, 'attach_os_disk', None):", "# set default storage SKU if not provided and using an image based", "storage_client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value == sku_tier and a.location == namespace.location), None) if account: #", "namespace.app_gateway_type = 'new' logger.debug('new application gateway will be created') # AppGateway frontend required", "'application_gateways') logger.debug(\"using specified existing application gateway '%s'\", namespace.application_gateway) except CloudError: namespace.app_gateway_type = 'new'", "None logger.debug('existing NIC(s) will be used') def _validate_vm_vmss_create_auth(namespace): if namespace.storage_profile in [StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]:", "def _get_image_plan_info_if_exists(cmd, namespace): from msrestazure.azure_exceptions import CloudError try: compute_client = _compute_client_factory(cmd.cli_ctx) if namespace.os_version.lower()", "zone_info, size_info): from ._vm_utils import list_sku_info if not namespace.location: get_default_location_from_resource_group(cmd, namespace) if zone_info:", "x in aval_sizes] if size not in aval_sizes: return new_4core_sizes = ['Standard_D3_v2', 'Standard_D3_v2_Promo',", "based on the authentication type if namespace.authentication_type == 'password': if namespace.ssh_key_value or namespace.ssh_dest_key_path:", "'attach_os_disk', None) and not namespace.image: if namespace.use_unmanaged_disk: # STORAGE PROFILE #3 namespace.storage_profile =", "SUBNET_NAME --vnet-name VNET_NAME\") subnet_exists = \\ check_existence(cmd.cli_ctx, subnet, rg, 'Microsoft.Network', 'subnets', vnet, 'virtualNetworks')", "argument.\") if not namespace.authentication_type: # apply default auth type (password for Windows, ssh", "vault :return: resource group name or None :rtype: str \"\"\" from azure.cli.core.profiles import", "if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: required = ['os_type', 'attach_os_disk'] forbidden", "- params for new storage account specified namespace.storage_account_type = 'new' logger.debug(\"specified storage account", "required and forbidden parameters validate_parameter_set( namespace, required, forbidden, description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num =", "| --keyvault ID]') kv = namespace.keyvault rg = namespace.resource_group_name if rg: if not", "account: # 3 - nothing specified - find viable storage account in target", "not in range(min_length, max_length + 1): raise CLIError('The password length must be between", "one for you') namespace.ssh_key_value = content def _validate_vm_vmss_msi(cmd, namespace, from_set_command=False): if from_set_command or", "for s in vnet_match.subnets if s.name.lower() != 'gatewaysubnet'), None) else: def _check_subnet(s): if", "and MSI_LOCAL_ID not in identities: raise CLIError(\"usage error: '--scope'/'--role' is only applicable when", "not namespace.location: get_default_location_from_resource_group(cmd, namespace) if zone_info: sku_infos = list_sku_info(cmd.cli_ctx, namespace.location) temp = next((x", "(assumes it is an image ID) if is_valid_resource_id(namespace.image): return 'image_id' # 2 -", "['attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SASpecializedOSDisk: required = ['os_type', 'attach_os_disk', 'use_unmanaged_disk'] forbidden =", "\" \"--subnet SUBNET_NAME --vnet-name VNET_NAME\") subnet_exists = \\ check_existence(cmd.cli_ctx, subnet, rg, 'Microsoft.Network', 'subnets',", "idx, secret in enumerate(narg_secret): if 'sourceVault' not in secret: errors.append( 'Secret is missing", "publisher.lower(), offer.lower(), sku.lower() distros = [('canonical', 'UbuntuServer', '^16.04'), ('suse', 'sles', '^12-sp3'), ('redhat', 'rhel',", "namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_type = 'existing' logger.debug(\"using specified NSG '%s'\", namespace.nsg) else: namespace.nsg_type", "only applicable when assign system identity\") # keep 'identity_role' for output as logical", "single placement group is disabled\", balancer_type) elif namespace.load_balancer: balancer_type = 'loadBalancer' elif namespace.application_gateway:", "index {0} in arg {1}'.format( idx, idx_arg)) if 'vaultCertificates' not in secret or", "subnet_exists: # 2 - user specified existing vnet/subnet namespace.vnet_type = 'existing' logger.debug(\"using specified", "required to create the image, \" \"please specify '--os-type OS_TYPE'\") def _figure_out_storage_source(cli_ctx, resource_group_name,", "'Standard_M64-32ms', 'Standard_M128-32ms', 'Standard_D32_v3', 'Standard_D32s_v3', 'Standard_D64-32s_v3', 'Standard_E32_v3', 'Standard_E32s_v3', 'Standard_E32-8s_v3', 'Standard_E32-16_v3', 'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC', 'Standard_F16_ABC', 'Standard_F32s_v2',", "'--scope'/'--role' is only applicable when assign system identity\") # keep 'identity_role' for output", "- int(mask) vnet_int = _convert_to_int(vnet_ip_address, vnet_bit_mask_len) subnet_ip_address, mask = subnet_cidr.split('/') subnet_bit_mask_len = 32", "Please try a different value.\".format(username)) return username def _validate_admin_password(password, os_type): import re is_linux", "any were found :rtype: list \"\"\" is_windows = os_type == 'windows' errors =", "for output as logical name is more readable setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role, namespace.identity_scope))", "'Standard_DS15_v2_Nested', 'Standard_D40_v3', 'Standard_D40s_v3', 'Standard_D15_v2_ABC', 'Standard_M64ms', 'Standard_M64s', 'Standard_M128-64ms', 'Standard_D64_v3', 'Standard_D64s_v3', 'Standard_E64_v3', 'Standard_E64s_v3', 'Standard_E64-16s_v3', 'Standard_E64-32s_v3',", "None def _get_nic_id(cli_ctx, val, resource_group): return _get_resource_id(cli_ctx, val, resource_group, 'networkInterfaces', 'Microsoft.Network') def validate_vm_nic(cmd,", "\"support_388945a0\", \"sys\", \"test2\", \"test3\", \"user4\", \"user5\"] if username.lower() in disallowed_user_names: raise CLIError(\"This user", "cmd.cli_ctx.cloud.name != AZURE_US_GOV_CLOUD.name: namespace.vm_sku = 'Standard_DS1_v2' else: namespace.vm_sku = 'Standard_D1_v2' _validate_location(cmd, namespace, namespace.zones,", "if _subnet_capacity_check(i, namespace.instance_count, not namespace.disable_overprovision): break if i < 16: err = \"instance", "pylint: disable=line-too-long pattern = (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if is_linux else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err = r'admin user", "use 'getattr' to avoid crash namespace.disk_info = normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace, 'attach_data_disks', []), storage_sku=namespace.storage_sku,", "will be created.\", namespace.application_gateway) elif namespace.application_gateway == '': namespace.app_gateway_type = None logger.debug('no application", "check_existence, get_target_network_api, get_storage_blob_uri from azure.cli.command_modules.vm._template_builder import StorageProfile import azure.cli.core.keys as keys from ._client_factory", "first and try \" \"again.\".format(option_name)) return values[0] def _validate_vmss_single_placement_group(namespace): if namespace.platform_fault_domain_count is not", "= int(parts[1]) except ValueError: raise CLIError(\"usage error: {}'s replica count must be an", "# TODO move to its own command module https://github.com/Azure/azure-cli/issues/5105 def process_msi_namespace(cmd, namespace): get_default_location_from_resource_group(cmd,", "== '': namespace.nsg_type = None logger.debug('no NSG will be used') elif namespace.nsg is", "CLIError(\"No existing values found for '{0}'. Create one first and try \" \"again.\".format(option_name))", "= prompt_pass('Admin Password: ', confirm=True) except NoTTYException: raise CLIError('Please specify password in non-interactive", "'%s'\", namespace.storage_profile) if for_scale_set: # VMSS lacks some parameters, so scrub these out", "start with $ or -' win_err = r'admin user name cannot contain special", "only be used when --public-ip-per-vm is enabled') if namespace.eviction_policy and not namespace.priority: raise", "secrets: Dict fitting the JSON description above :param string os_type: the type of", "logger.debug('new application gateway will be created') # AppGateway frontend required = [] if", "elif namespace.load_balancer: balancer_type = 'loadBalancer' elif namespace.application_gateway: balancer_type = 'applicationGateway' if balancer_type ==", "namespace.identities[i] = _get_resource_id(cmd.cli_ctx, namespace.identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') # TODO move to its own", "balancer_type) elif namespace.load_balancer: balancer_type = 'loadBalancer' elif namespace.application_gateway: balancer_type = 'applicationGateway' if balancer_type", "'{}/{}'.format(cidr, i) if namespace.app_gateway_type and namespace.app_gateway_subnet_address_prefix is None: namespace.app_gateway_subnet_address_prefix = _get_next_subnet_addr_suffix( namespace.vnet_address_prefix, namespace.subnet_address_prefix,", "the general requirements, but is specifically disallowed for this image. Please try a", "= _compute_client_factory(cli_ctx) # pylint: disable=no-member try: info = compute_client.snapshots.get(resource_group_name, source) source_snapshot = info.id", "import re is_linux = (os_type.lower() == 'linux') max_length = 72 if is_linux else", "'Microsoft.ManagedIdentity') # TODO move to its own command module https://github.com/Azure/azure-cli/issues/5105 def process_msi_namespace(cmd, namespace):", "'Premium_LRS' if namespace.storage_sku == 'UltraSSD_LRS' and namespace.ultra_ssd_enabled is None: namespace.ultra_ssd_enabled = True #", "int(parts[1]) except ValueError: raise CLIError(\"usage error: {}'s replica count must be an integer\".format(parts[0]))", "if zone_info: sku_infos = list_sku_info(cmd.cli_ctx, namespace.location) temp = next((x for x in sku_infos", "StorageProfile.SASpecializedOSDisk: required = ['os_type', 'attach_os_disk', 'use_unmanaged_disk'] forbidden = ['os_disk_name', 'os_caching', 'image', 'storage_account', 'storage_container_name',", "new load ' 'balancer or application gateway frontend.') namespace.public_ip_address = '' _validate_vm_vmss_create_public_ip(cmd, namespace)", "['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedCustomImage:", "as ex: logger.warning(\"Querying the image of '%s' failed for an error '%s'. Configuring", "information from a managed custom image res = parse_resource_id(namespace.image) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription'])", "find storage account in target resource group that matches the VM's location sku_tier", "files '%s' and '%s' have been generated under ~/.ssh to \" \"allow SSH", "client = get_network_client(cmd.cli_ctx).application_gateways try: rg = parse_resource_id(namespace.application_gateway).get( 'resource_group', namespace.resource_group_name) ag_name = parse_resource_id(namespace.application_gateway)['name'] client.get(rg,", "NSG will be used') elif namespace.nsg is None: namespace.nsg_type = 'new' logger.debug('new NSG", "process_vm_secret_format(cmd, namespace): from msrestazure.tools import is_valid_resource_id keyvault_usage = CLIError('usage error: [--keyvault NAME --resource-group", "res['name']) # pylint: disable=no-member namespace.os_type = vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine = res_id if namespace.data_disk_sources: raise", "raise CLIError(\"invalid storage SKU '{}': allowed values: '{}'\".format(sku, allowed_skus)) def _validate_location(cmd, namespace, zone_info,", "and not vnet): raise CLIError(\"incorrect '--subnet' usage: --subnet SUBNET_ID | \" \"--subnet SUBNET_NAME", "if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: # overflows? candidate_int = candidate_int", "azure.cli.core.profiles import ResourceType PublicIPAddressSkuName, IPAllocationMethod = cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK) if namespace.public_ip_sku == PublicIPAddressSkuName.standard.value:", "'coreos', None), ('credativ', 'debian', '-backports'), ('oracle', 'oracle-linux', '^7.4'), ('MicrosoftWindowsServer', 'WindowsServer', '^2016'), ('MicrosoftWindowsServer', 'WindowsServer',", "import uuid from azure.cli.core.commands.client_factory import get_mgmt_service_client from azure.cli.core.profiles import ResourceType client = get_mgmt_service_client(cli_ctx,", "for vault in client.list(): id_comps = parse_resource_id(vault.id) if id_comps['name'] == vault_name: return id_comps['resource_group']", "resource_id, is_valid_resource_id from azure.cli.core.commands.client_factory import get_subscription_id if is_valid_resource_id(val): return val kwargs = {", "'Secret is missing {0} within vaultCertificates array at secret ' \\ 'index {1}", "if namespace.storage_account: storage_id = parse_resource_id(namespace.storage_account) rg = storage_id.get('resource_group', namespace.resource_group_name) if check_existence(cmd.cli_ctx, storage_id['name'], rg,", "# pylint: disable=line-too-long '--nat-pool-name', ', '.join([n.name for n in lb.inbound_nat_pools]))) elif not lb.inbound_nat_pools:", "# try capturing from VM, a most common scenario res_id = _get_resource_id(cmd.cli_ctx, namespace.source,", "| --attach-os-disk DISK') auth_params = ['<PASSWORD>_password', 'admin_username', 'authentication_type', 'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value'] # perform", "'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo', 'Standard_F8', 'Standard_F8s', 'Standard_M64-16ms', 'Standard_D16_v3', 'Standard_D16s_v3', 'Standard_D32-16s_v3', 'Standard_D64-16s_v3', 'Standard_E16_v3', 'Standard_E16s_v3', 'Standard_E32-16s_v3',", "or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8)) def validate_keyvault(cmd, namespace): namespace.keyvault = _get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name, 'vaults',", "disable=no-member return image.plan except CloudError as ex: logger.warning(\"Querying the image of '%s' failed", "return 'uri' # 4 - attempt to match an URN alias (most likely)", "['os_type', 'attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SACustomImage: required = ['image', 'os_type', 'use_unmanaged_disk'] forbidden", "in (v for v in client.list(rg) if v.location == location and v.subnets): #", "# pylint: disable=line-too-long if count < 3: raise CLIError('Password must have the 3", "private keys), and 'base_name.pub'(with public keys) public_key_filepath = string_or_file if public_key_filepath[-4:].lower() == '.pub':", "balancer '%s'\", namespace.load_balancer) else: namespace.load_balancer_type = 'new' logger.debug(\"load balancer '%s' not found. It", "not secret['vaultCertificates']: err = 'Secret is missing vaultCertificates array or it is empty", "= _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, data_disk_source) if source_blob_uri: namespace.data_blob_uris.append(source_blob_uri) if source_disk: namespace.data_disks.append(source_disk) if source_snapshot:", "'Standard_DS13_v2', 'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo', 'Standard_F8', 'Standard_F8s', 'Standard_M64-16ms', 'Standard_D16_v3', 'Standard_D16s_v3', 'Standard_D32-16s_v3', 'Standard_D64-16s_v3', 'Standard_E16_v3',", "urlparse import urlparse # pylint: disable=import-error from knack.log import get_logger from knack.util import", "= _validate_admin_username(namespace.admin_username, namespace.os_type) if not namespace.os_type: raise CLIError(\"Unable to resolve OS type. Specify", "[] from ._vm_utils import MSI_LOCAL_ID for i, _ in enumerate(identities): if identities[i] !=", "information. # -------------------------------------------------------------------------------------------- # pylint:disable=too-many-lines import os try: from urllib.parse import urlparse except", "'oracle-linux', '^7.4'), ('MicrosoftWindowsServer', 'WindowsServer', '^2016'), ('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')] import re for p, o,", "found. One will be created.') def _validate_vm_create_availability_set(cmd, namespace): from msrestazure.tools import parse_resource_id, resource_id", "elif namespace.public_ip_address is None: namespace.public_ip_address_type = 'new' logger.debug('new public IP address will be", "not is_valid_resource_id(val): val = resource_id( subscription=subscription_id, resource_group=resource_group, namespace='Microsoft.Network', type='applicationSecurityGroups', name=val ) ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace,", "of balancer (if any) being used balancer_type = 'None' if namespace.load_balancer is None", "std_lb_is_available: LBSkuName = cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer_sku is None: namespace.load_balancer_sku = LBSkuName.standard.value logger.debug(\"use", "namespace.public_ip_address_type = 'existing' logger.debug(\"using existing specified public IP '%s'\", namespace.public_ip_address) else: namespace.public_ip_address_type =", "public IP address will be created') # Public-IP SKU is only exposed for", "error: --platform-fault-domain-count COUNT --zones ZONES') if namespace.zones or namespace.instance_count > 100: if namespace.single_placement_group", "error: --disk EXIST_DISK --instance-id ID') def process_disk_or_snapshot_create_namespace(cmd, namespace): from msrestazure.azure_exceptions import CloudError validate_tags(namespace)", "not namespace.public_ip_address_allocation: namespace.public_ip_address_allocation = IPAllocationMethod.static.value def _validate_vmss_create_public_ip(cmd, namespace): if namespace.load_balancer_type is None and", "if namespace.identities[i] != MSI_LOCAL_ID: namespace.identities[i] = _get_resource_id(cmd.cli_ctx, namespace.identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') # TODO", "_get_image_plan_info_if_exists(cmd, namespace) if image_plan: namespace.plan_name = image_plan.name namespace.plan_product = image_plan.product namespace.plan_publisher = image_plan.publisher", "vnet_int = _convert_to_int(vnet_ip_address, vnet_bit_mask_len) subnet_ip_address, mask = subnet_cidr.split('/') subnet_bit_mask_len = 32 - int(mask)", "n } }) namespace.nics = nics namespace.nic_type = 'existing' namespace.public_ip_address_type = None logger.debug('existing", "namespace.os_offer, namespace.os_sku) else: image_version = namespace.os_version image = compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku, image_version)", "None: cidr = namespace.vnet_address_prefix.split('/', 1)[0] i = 0 for i in range(24, 16,", "'with minimum Compute API version of 2017-12-01') if namespace.identity_scope: if identities and MSI_LOCAL_ID", "validators def validate_vm_disk(cmd, namespace): namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') def validate_vmss_disk(cmd,", "= [validate_file_or_dict(secret) for secret in secrets] except Exception as err: raise CLIError('Error decoding", "and a.location == namespace.location), None) if account: # 3 - nothing specified -", "vnet_bit_mask_len <= subnet_bit_mask_len: raise CLIError(error_msg) candidate_int = _convert_to_int(subnet_ip_address, subnet_bit_mask_len) + 1 if (candidate_int", "None: if std_lb_is_available: balancer_type = 'loadBalancer' else: # needed for Stack profile 2017_03_09", "did not specify image XOR attach-os-disk raise CLIError('incorrect usage: --image IMAGE | --attach-os-disk", "offer, sku = publisher.lower(), offer.lower(), sku.lower() distros = [('canonical', 'UbuntuServer', '^16.04'), ('suse', 'sles',", "matched['sku'] namespace.os_version = matched['version'] return 'urn' # 5 - check if an existing", "source) source_disk = info.id return (source_blob_uri, source_disk, source_snapshot) def process_disk_encryption_namespace(cmd, namespace): namespace.disk_encryption_keyvault =", "hash_string from azure.cli.command_modules.vm._vm_utils import check_existence, get_target_network_api, get_storage_blob_uri from azure.cli.command_modules.vm._template_builder import StorageProfile import azure.cli.core.keys", "\\ or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8)) def validate_keyvault(cmd, namespace): namespace.keyvault = _get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name,", "{0} in arg {1}'.format( idx, idx_arg)) if 'sourceVault' in secret and 'id' not", "namespace.application_gateway: raise CLIError('incorrect usage: --load-balancer NAME_OR_ID | ' '--application-gateway NAME_OR_ID') # Resolve the", "logical name is more readable setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role, namespace.identity_scope)) elif namespace.identity_scope or", "'^2016'), ('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')] import re for p, o, s in distros: if", "for x in [contains_lower, contains_upper, contains_digit, contains_special_char] if x]) # pylint: disable=line-too-long if", "logger.debug('no application gateway will be used') elif namespace.application_gateway is None: namespace.app_gateway_type = 'new'", "for d in namespace.attach_data_disks] if not namespace.os_type: namespace.os_type = 'windows' if 'windows' in", "jdx, idx_arg)) if is_windows and 'certificateStore' not in cert: errors.append(message.format('certificateStore', idx, jdx, idx_arg))", "'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_type = 'existing' logger.debug(\"using specified NSG '%s'\", namespace.nsg) else: namespace.nsg_type =", "used') elif namespace.nsg is None: namespace.nsg_type = 'new' logger.debug('new NSG will be created')", "}] }] :param dict secrets: Dict fitting the JSON description above :param string", "'loadBalancer': # LoadBalancer frontend required = [] forbidden = ['app_gateway_subnet_address_prefix', 'application_gateway', 'app_gateway_sku', 'app_gateway_capacity']", "[] for n in namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg)) namespace.nics = nic_ids if hasattr(namespace,", "['image', 'os_type', 'use_unmanaged_disk'] forbidden = ['attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SASpecializedOSDisk: required =", "'Standard_D2_v2', 'Standard_DS2_v2', 'Standard_E4_v3', 'Standard_E4s_v3', 'Standard_F2', 'Standard_F2s', 'Standard_F4s_v2', 'Standard_D11_v2', 'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C'] aval_sizes = [x.lower()", "on Windows VM scaleset') if not namespace.public_ip_per_vm and namespace.vm_domain_name: raise CLIError('Usage error: --vm-domain-name", "of required and forbidden parameters validate_parameter_set( namespace, required, forbidden, description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num", "_validate_vm_create_storage_account(cmd, namespace) _validate_vm_create_availability_set(cmd, namespace) _validate_vm_vmss_create_vnet(cmd, namespace) _validate_vm_create_nsg(cmd, namespace) _validate_vm_vmss_create_public_ip(cmd, namespace) _validate_vm_create_nics(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx,", "matched = next((x for x in images if x['urnAlias'].lower() == namespace.image.lower()), None) if", "else 'linux' from ._vm_utils import normalize_disk_info # attach_data_disks are not exposed yet for", "count '{}' is out of range of 2^16 subnet size'\" raise CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix", "if namespace.storage_profile == StorageProfile.ManagedCustomImage: # extract additional information from a managed custom image", "'Standard_E32s_v3', 'Standard_E32-8s_v3', 'Standard_E32-16_v3', 'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC', 'Standard_F16_ABC', 'Standard_F32s_v2', 'Standard_D15_v2', 'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested', 'Standard_DS15_v2', 'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested',", "raise CLIError('The password length must be between {} and {}'.format(min_length, max_length)) contains_lower =", "namespace.assign_identity is not None: identities = namespace.assign_identity or [] from ._vm_utils import MSI_LOCAL_ID", "client.config.subscription_id, role) except ValueError: pass if not role_id: # retrieve role id role_defs", "1: ids = [r.id for r in role_defs] err = \"More than one", "what type is supplied for the --image parameter. Updates the namespace and returns", "will be used') elif namespace.application_gateway is None: namespace.app_gateway_type = 'new' logger.debug('new application gateway", "= '--backend-pool-name' client = getattr(get_network_client(cli_ctx), balancer_type, None) if not client: raise CLIError('unrecognized balancer", "CloudError: err = 'Invalid image \"{}\". Use a custom image name, id, or", "error:{}'.format(err)) def get_network_client(cli_ctx): from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client return get_mgmt_service_client(cli_ctx,", "# pylint: disable=no-member namespace.os_type = vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine = res_id if namespace.data_disk_sources: raise CLIError(\"'--data-disk-sources'", "namespace.resource_group_name, data_disk_source) if source_blob_uri: namespace.data_blob_uris.append(source_blob_uri) if source_disk: namespace.data_disks.append(source_disk) if source_snapshot: namespace.data_snapshots.append(source_snapshot) if not", "if namespace.admin_password: raise ValueError('Admin password cannot be used with SSH authentication type') validate_ssh_key(namespace)", "is None: if namespace.public_ip_address: raise CLIError('--public-ip-address can only be used when creating a", "- create a new vnet/subnet namespace.vnet_type = 'new' logger.debug('no suitable subnet found. One", "if res['type'].lower() == 'images': image_info = compute_client.images.get(res['resource_group'], res['name']) namespace.os_type = image_info.storage_profile.os_disk.os_type.value image_data_disks_num =", "rg = namespace.resource_group_name location = namespace.location nics = getattr(namespace, 'nics', None) if not", "non-interactive mode.') # validate password _validate_admin_password(namespace.admin_password, namespace.os_type) elif namespace.authentication_type == 'ssh': if namespace.admin_password:", "CLIError(linux_err) if not is_linux and username.endswith('.'): raise CLIError(win_err) disallowed_user_names = [ \"administrator\", \"admin\",", "PROFILE #2 namespace.storage_profile = StorageProfile.SACustomImage elif image_type == 'image_id': # STORAGE PROFILE #5", "parameters for VM if namespace.storage_profile == StorageProfile.ManagedPirImage: required = ['image'] forbidden = ['os_type',", "a supported image in the marketplace # Ubuntu 16.04, SLES 12 SP3, RHEL", "image_data_disks_num = 0 if namespace.storage_profile == StorageProfile.ManagedCustomImage: # extract additional information from a", "def _figure_out_storage_source(cli_ctx, resource_group_name, source): from msrestazure.azure_exceptions import CloudError source_blob_uri = None source_disk =", "type of balancer (if any) being used balancer_type = 'None' if namespace.load_balancer is", "Stack (compute - 2017-03-30), Resource_sku doesn't implement location_info property if not hasattr(temp, 'location_info'):", "get_default_location_from_resource_group(cmd, namespace) validate_tags(namespace) def process_gallery_image_version_namespace(cmd, namespace): TargetRegion = cmd.get_models('TargetRegion') if namespace.target_regions: regions_info =", "in target resource group that matches the VM's location with a matching subnet", "subnet_exists: raise CLIError(\"Subnet '{}' does not exist.\".format(subnet)) elif subnet_exists: # 2 - user", "= parse_resource_id(namespace.application_gateway).get( 'resource_group', namespace.resource_group_name) ag_name = parse_resource_id(namespace.application_gateway)['name'] client.get(rg, ag_name) namespace.app_gateway_type = 'existing' namespace.backend_pool_name", "!= AZURE_US_GOV_CLOUD.name: namespace.vm_sku = 'Standard_DS1_v2' else: namespace.vm_sku = 'Standard_D1_v2' _validate_location(cmd, namespace, namespace.zones, namespace.vm_sku)", "the VM. If using machines without \" \"permanent storage, back up your keys", "ID]') kv = namespace.keyvault rg = namespace.resource_group_name if rg: if not kv or", "'storageAccounts'): # 1 - existing storage account specified namespace.storage_account_type = 'existing' logger.debug(\"using specified", "in sku_infos if x.name.lower() == size_info.lower()), None) # For Stack (compute - 2017-03-30),", "'*1.5' so we have enough leeway for over-provision factor = 1.5 if over_provision", "namespace.admin_password) else 'ssh' if namespace.os_type.lower() == 'windows' and namespace.authentication_type == 'ssh': raise CLIError('SSH", "elif len(role_defs) > 1: ids = [r.id for r in role_defs] err =", "from azure.cli.core.commands.client_factory import get_mgmt_service_client return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx)) def get_network_lb(cli_ctx, resource_group_name, lb_name): from", "raise CLIError('usage error: --license-type is only applicable on Windows VM scaleset') if not", "except CloudError: info = compute_client.disks.get(resource_group_name, source) source_disk = info.id return (source_blob_uri, source_disk, source_snapshot)", "NAME --resource-group NAME | --keyvault ID]') kv = namespace.keyvault rg = namespace.resource_group_name if", "used to create the VM/VMSS because availablity zone is not yet \" \"supported.", "subnet_cidr, new_mask): def _convert_to_int(address, bit_mask_len): a, b, c, d = [int(x) for x", "= _get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name) def validate_vm_nics(cmd, namespace): rg = namespace.resource_group_name nic_ids = []", "'windows' in namespace.os_offer.lower() else 'linux' from ._vm_utils import normalize_disk_info # attach_data_disks are not", "'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2', 'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC', 'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4', 'Standard_F4_ABC', 'Standard_F4s',", "not missing_kwargs else None def _get_nic_id(cli_ctx, val, resource_group): return _get_resource_id(cli_ctx, val, resource_group, 'networkInterfaces',", "in forbidden: forbidden.remove(prop) # set default storage SKU if not provided and using", "namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') if namespace.key_encryption_keyvault: if not namespace.key_encryption_key: raise CLIError(\"Incorrect usage '--key-encryption-keyvault': \"", "validate_parameter_set, validate_tags) from azure.cli.core.util import hash_string from azure.cli.command_modules.vm._vm_utils import check_existence, get_target_network_api, get_storage_blob_uri from", "if 'Premium' in namespace.storage_sku else 'Standard' account = next( (a for a in", "# pylint:disable=too-many-lines import os try: from urllib.parse import urlparse except ImportError: from urlparse", "in identities: raise CLIError(\"usage error: '--scope'/'--role' is only applicable when assign system identity\")", "error: --assign-identity [--scope SCOPE] [--role ROLE]') def _resolve_role_id(cli_ctx, role, scope): import re import", "in images])) def _get_image_plan_info_if_exists(cmd, namespace): from msrestazure.azure_exceptions import CloudError try: compute_client = _compute_client_factory(cmd.cli_ctx)", "namespace, for_scale_set=False): from msrestazure.tools import parse_resource_id # use minimal parameters to resolve the", "identity is only available under profile ' 'with minimum Compute API version of", "'Standard_L96s_v2', 'SQLGL', 'SQLGLCore', 'Standard_D4_v3', 'Standard_D4s_v3', 'Standard_D2_v2', 'Standard_DS2_v2', 'Standard_E4_v3', 'Standard_E4s_v3', 'Standard_F2', 'Standard_F2s', 'Standard_F4s_v2', 'Standard_D11_v2',", "role_id def process_vm_create_namespace(cmd, namespace): validate_tags(namespace) _validate_location(cmd, namespace, namespace.zone, namespace.size) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace)", "compute_client.images.get(namespace.resource_group_name, namespace.image) namespace.image = _get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name, 'images', 'Microsoft.Compute') return 'image_id' except CloudError:", "for_scale_set: result = next((s for s in vnet_match.subnets if s.name.lower() != 'gatewaysubnet'), None)", "--vnet-address-prefix's\" # extract vnet information needed to verify the defaults we are coming", "namespace.data_disk_sources: raise CLIError(\"'--data-disk-sources' is not allowed when capturing \" \"images from virtual machines\")", "source.lower(): source_snapshot = source else: compute_client = _compute_client_factory(cli_ctx) # pylint: disable=no-member try: info", "elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: # accept disk name or ID namespace.attach_os_disk = _get_resource_id(", "created.') def _validate_vm_create_availability_set(cmd, namespace): from msrestazure.tools import parse_resource_id, resource_id from azure.cli.core.commands.client_factory import get_subscription_id", "_figure_out_storage_source(cli_ctx, resource_group_name, source): from msrestazure.azure_exceptions import CloudError source_blob_uri = None source_disk = None", "elif not values: raise CLIError(\"No existing values found for '{0}'. Create one first", "the key vault :return: resource group name or None :rtype: str \"\"\" from", "\"admin\", \"user\", \"user1\", \"test\", \"user2\", \"test1\", \"user3\", \"admin1\", \"1\", \"123\", \"a\", \"actuser\", \"adm\",", "role_id = role else: try: uuid.UUID(role) role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id, role) except ValueError:", "'Standard_D64-16s_v3', 'Standard_E16_v3', 'Standard_E16s_v3', 'Standard_E32-16s_v3', 'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC', 'Standard_F8_ABC', 'Standard_F16s_v2', 'Standard_D5_v2', 'Standard_D14_v2', 'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo', 'Standard_DS5_v2',", "raise CLIError('An RSA key file or key value must be supplied to SSH", "StorageProfile.ManagedPirImage: return 'create managed OS disk from Azure Marketplace image' elif profile ==", "namespace, zone_info, size_info): from ._vm_utils import list_sku_info if not namespace.location: get_default_location_from_resource_group(cmd, namespace) if", "namespace.disk: namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if bool(namespace.disk) == bool(namespace.size_gb): raise", "val in names_or_ids: if not is_valid_resource_id(val): val = resource_id( subscription=subscription_id, resource_group=resource_group, namespace='Microsoft.Network', type='applicationSecurityGroups',", "'--single-placement-group' should be turned off for zonal scale-sets or with\" \" 100+ instances\")", "for_scale_set=True) _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=True) _validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace) _validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd, namespace) _validate_vmss_create_nsg(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx,", "public IP address will be used') elif namespace.public_ip_address is None: namespace.public_ip_address_type = 'new'", "namespace.priority: raise CLIError('Usage error: --priority PRIORITY [--eviction-policy POLICY]') # endregion # region disk,", "False and std_lb_is_available: LBSkuName = cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer_sku is None: namespace.load_balancer_sku =", "does not exist.\".format(subnet)) elif subnet_exists: # 2 - user specified existing vnet/subnet namespace.vnet_type", "namespace.storage_profile = StorageProfile.ManagedCustomImage elif image_type == 'urn': if namespace.use_unmanaged_disk: # STORAGE PROFILE #1", "using machines without \" \"permanent storage, back up your keys to a safe", "and namespace.ultra_ssd_enabled is None: namespace.ultra_ssd_enabled = True # Now verify that the status", "namespace) _validate_vm_vmss_create_vnet(cmd, namespace) _validate_vm_create_nsg(cmd, namespace) _validate_vm_vmss_create_public_ip(cmd, namespace) _validate_vm_create_nics(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) if", "'Microsoft.Network') def validate_vm_nic(cmd, namespace): namespace.nic = _get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name) def validate_vm_nics(cmd, namespace): rg", "compute_client.snapshots.get(resource_group_name, source) source_snapshot = info.id except CloudError: info = compute_client.disks.get(resource_group_name, source) source_disk =", "'vm_sku', None) size = size.lower() # to refresh the list, run 'az vm", "x.publishing_profile.exclude_from_latest] if not image_version_infos: raise CLIError('There is no latest image version exists for", "required = ['os_type', 'attach_os_disk', 'use_unmanaged_disk'] forbidden = ['os_disk_name', 'os_caching', 'image', 'storage_account', 'storage_container_name', 'data_disk_sizes_gb',", "OS disk' elif profile == StorageProfile.ManagedCustomImage: return 'create managed OS disk from custom", "returns the type for subsequent processing. \"\"\" from msrestazure.tools import is_valid_resource_id from msrestazure.azure_exceptions", "namespace.availability_set) def _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False): from msrestazure.tools import is_valid_resource_id vnet = namespace.vnet_name subnet", "'Standard_DS13-4_v2', 'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo', 'Standard_F4', 'Standard_F4s', 'Standard_D8_v3', 'Standard_D8s_v3', 'Standard_D32-8s_v3', 'Standard_E8_v3', 'Standard_E8s_v3',", "not vnet): raise CLIError(\"incorrect '--subnet' usage: --subnet SUBNET_ID | \" \"--subnet SUBNET_NAME --vnet-name", "namespace.nsg) elif namespace.nsg == '': namespace.nsg_type = None logger.debug('no NSG will be used')", "= cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer_sku is None: namespace.load_balancer_sku = LBSkuName.standard.value logger.debug(\"use Standard sku", "namespace.vm_sku) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=True) _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=True) _validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace) _validate_vmss_create_subnet(namespace)", "user_assigned_identities and not cmd.supported_api_version(min_api='2017-12-01'): raise CLIError('usage error: user assigned identity is only available", "= StorageProfile.ManagedPirImage else: raise CLIError('Unrecognized image type: {}'.format(image_type)) else: # did not specify", "set default storage SKU if not provided and using an image based OS", "'WindowsServer', '^2012-R2')] import re for p, o, s in distros: if p.lower() ==", "required = [] forbidden = ['app_gateway_subnet_address_prefix', 'application_gateway', 'app_gateway_sku', 'app_gateway_capacity'] validate_parameter_set(namespace, required, forbidden, description='network", "from_set_command=True) def process_remove_identity_namespace(cmd, namespace): if namespace.identities: from ._vm_utils import MSI_LOCAL_ID for i in", "None: namespace.app_gateway_subnet_address_prefix = _get_next_subnet_addr_suffix( namespace.vnet_address_prefix, namespace.subnet_address_prefix, 24) def _get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr, new_mask): def _convert_to_int(address,", "namespace): from msrestazure.tools import is_valid_resource_id keyvault_usage = CLIError('usage error: [--keyvault NAME --resource-group NAME", "client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions role_id = None if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role, re.I): role_id =", "_get_storage_profile_description(profile): if profile == StorageProfile.SACustomImage: return 'create unmanaged OS disk created from generalized", "= resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg, namespace='Microsoft.Compute', type='availabilitySets', name=name) logger.debug(\"adding to specified availability set '%s'\",", "Create one first and try \" \"again.\".format(option_name)) return values[0] def _validate_vmss_single_placement_group(namespace): if namespace.platform_fault_domain_count", "[StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]: return namespace.admin_username = _validate_admin_username(namespace.admin_username, namespace.os_type) if not namespace.os_type: raise CLIError(\"Unable to", "raise CLIError(err.format(namespace.image, [x['urnAlias'] for x in images])) def _get_image_plan_info_if_exists(cmd, namespace): from msrestazure.azure_exceptions import", "namespace.keyvault rg = namespace.resource_group_name if rg: if not kv or is_valid_resource_id(kv): raise keyvault_usage", "the OS type namespace.authentication_type = 'password' \\ if (namespace.os_type.lower() == 'windows' or namespace.admin_password)", "get_network_client(cmd.cli_ctx).application_gateways try: rg = parse_resource_id(namespace.application_gateway).get( 'resource_group', namespace.resource_group_name) ag_name = parse_resource_id(namespace.application_gateway)['name'] client.get(rg, ag_name) namespace.app_gateway_type", "will be missing ssh/rdp, so warn here. logger.warning(\"No inbound nat pool was configured", "'virtualMachines', 'Microsoft.Compute') res = parse_resource_id(res_id) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) vm_info = compute_client.virtual_machines.get(res['resource_group'], res['name'])", "IP address will be used') elif namespace.public_ip_address is None: namespace.public_ip_address_type = 'new' logger.debug('new", "12 SP3, RHEL 7.4, CentOS 7.4, CoreOS Linux, Debian \"Stretch\" with backports kernel", "%s', string_or_file) with open(string_or_file, 'r') as f: content = f.read() elif not keys.is_valid_ssh_rsa_public_key(content):", "lb.inbound_nat_pools]))) elif not lb.inbound_nat_pools: # Associated scaleset will be missing ssh/rdp, so warn", "kv and not is_valid_resource_id(kv): raise keyvault_usage def _get_resource_group_from_vault_name(cli_ctx, vault_name): \"\"\" Fetch resource group", "is None: namespace.single_placement_group = False elif namespace.single_placement_group: raise CLIError(\"usage error: '--single-placement-group' should be", "CLIError(\"usage error: {}'s replica count must be an integer\".format(parts[0])) regions_info.append(TargetRegion(name=parts[0], regional_replica_count=replica_count)) namespace.target_regions =", "attach_data_disks=getattr(namespace, 'attach_data_disks', []), storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching) def _validate_vm_create_storage_account(cmd, namespace): from msrestazure.tools import parse_resource_id", "set '%s'\", namespace.availability_set) def _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False): from msrestazure.tools import is_valid_resource_id vnet =", "if not publisher: return publisher, offer, sku = publisher.lower(), offer.lower(), sku.lower() distros =", "'virtualNetworks') if subnet_is_id and not subnet_exists: raise CLIError(\"Subnet '{}' does not exist.\".format(subnet)) elif", "'new' logger.debug(\"application gateway '%s' not found. It will be created.\", namespace.application_gateway) elif namespace.application_gateway", "2) > int(vmss_instance_count * factor) def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace): if namespace.accelerated_networking is None: size", "'Standard_F2', 'Standard_F2s', 'Standard_F4s_v2', 'Standard_D11_v2', 'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C'] aval_sizes = [x.lower() for x in aval_sizes]", "Linux) by examining the OS type namespace.authentication_type = 'password' \\ if (namespace.os_type.lower() ==", "'ssh_key_value'] # perform parameter validation for the specific storage profile # start with", "= [ \"administrator\", \"admin\", \"user\", \"user1\", \"test\", \"user2\", \"test1\", \"user3\", \"admin1\", \"1\", \"123\",", "scaleset will be missing ssh/rdp, so warn here. logger.warning(\"No inbound nat pool was", "validate_tags(namespace) try: # try capturing from VM, a most common scenario res_id =", "msrestazure.tools import parse_resource_id if namespace.storage_account: storage_id = parse_resource_id(namespace.storage_account) rg = storage_id.get('resource_group', namespace.resource_group_name) if", "existing unmanaged OS disk' elif profile == StorageProfile.ManagedCustomImage: return 'create managed OS disk", "errors.append(err.format(idx, idx_arg)) else: for jdx, cert in enumerate(secret['vaultCertificates']): message = 'Secret is missing", "namespace.subnet_address_prefix, 24) def _get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr, new_mask): def _convert_to_int(address, bit_mask_len): a, b, c, d", "\"backup\", \"console\", \"guest\", \"owner\", \"root\", \"server\", \"sql\", \"support\", \"support_388945a0\", \"sys\", \"test2\", \"test3\", \"user4\",", "> 100: err = \"'Standard' load balancer is required for scale-sets with 100+", "region disk, snapshot, image validators def validate_vm_disk(cmd, namespace): namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name,", "create --accelerated-networking --size Standard_DS1_v2' and # get it from the error aval_sizes =", "from azure.cli.core.commands.validators import ( get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set, validate_tags) from azure.cli.core.util import hash_string from", "namespace.app_gateway_type = None logger.debug('no application gateway will be used') elif namespace.application_gateway is None:", "def _validate_admin_username(username, os_type): import re if not username: raise CLIError(\"admin user name can", "storage profile if getattr(namespace, 'attach_os_disk', None) and not namespace.image: if namespace.use_unmanaged_disk: # STORAGE", "profile if getattr(namespace, 'attach_os_disk', None) and not namespace.image: if namespace.use_unmanaged_disk: # STORAGE PROFILE", "'namespace': resource_namespace, 'type': resource_type, 'subscription': get_subscription_id(cli_ctx) } missing_kwargs = {k: v for k,", "availablity zone is not yet \" \"supported. Please use '--location' to specify a", "storage_id.get('resource_group', namespace.resource_group_name) if check_existence(cmd.cli_ctx, storage_id['name'], rg, 'Microsoft.Storage', 'storageAccounts'): # 1 - existing storage", "from azure.cli.core.util import hash_string from azure.cli.command_modules.vm._vm_utils import check_existence, get_target_network_api, get_storage_blob_uri from azure.cli.command_modules.vm._template_builder import", "existing storage account '%s'\", storage_id['name']) else: # 2 - params for new storage", "in namespace.data_disk_sources: source_blob_uri, source_disk, source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, data_disk_source) if source_blob_uri: namespace.data_blob_uris.append(source_blob_uri)", "b, c, d) return int(result[:-bit_mask_len], 2) error_msg = \"usage error: --subnet-address-prefix value should", "ids) def validate_nsg_name(cmd, namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id vm_id", "kv or is_valid_resource_id(kv): raise keyvault_usage validate_keyvault(cmd, namespace) else: if kv and not is_valid_resource_id(kv):", "_compute_client_factory from ._actions import _get_latest_image_version logger = get_logger(__name__) def validate_asg_names_or_ids(cmd, namespace): from msrestazure.tools", "'2' are the reserved broadcasting addresses # '*1.5' so we have enough leeway", "lb_name): from msrestazure.azure_exceptions import CloudError network_client = get_network_client(cli_ctx) try: return network_client.load_balancers.get(resource_group_name, lb_name) except", "secret: errors.append( 'Secret is missing sourceVault key at index {0} in arg {1}'.format(", "100: err = \"'Standard' load balancer is required for scale-sets with 100+ instances\"", "image_plan.name namespace.plan_product = image_plan.product namespace.plan_publisher = image_plan.publisher return 'urn' # 3 - unmanaged", "rg: if not kv or is_valid_resource_id(kv): raise keyvault_usage validate_keyvault(cmd, namespace) else: if kv", "raise CLIError('usage error: user assigned identity is only available under profile ' 'with", "NAME_OR_ID | ' '--application-gateway NAME_OR_ID') # Resolve the type of balancer (if any)", "_validate_admin_username(username, os_type): import re if not username: raise CLIError(\"admin user name can not", "root for license information. # -------------------------------------------------------------------------------------------- # pylint:disable=too-many-lines import os try: from urllib.parse", "def get_network_client(cli_ctx): from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK,", "_compute_client_factory(cmd.cli_ctx) if namespace.os_version.lower() == 'latest': image_version = _get_latest_image_version(cmd.cli_ctx, namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku) else:", "'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC', 'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4', 'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3', 'Standard_D8s_v3']", "namespace.storage_account_type = 'new' logger.debug(\"specified storage account '%s' not found and will be created\",", "password) contains_digit = re.findall('[0-9]+', password) contains_special_char = re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password) count = len([x", "# '*1.5' so we have enough leeway for over-provision factor = 1.5 if", "will be created') if namespace.load_balancer_type == 'new' and namespace.single_placement_group is False and std_lb_is_available:", "= '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b, c, d) return int(result[:-bit_mask_len], 2) error_msg = \"usage error: --subnet-address-prefix", "= 'applicationGateway' if balancer_type == 'applicationGateway': if namespace.application_gateway: client = get_network_client(cmd.cli_ctx).application_gateways try: rg", "fitting the JSON description above :param string os_type: the type of OS (linux", "balancer_type == 'loadBalancer': # LoadBalancer frontend required = [] forbidden = ['app_gateway_subnet_address_prefix', 'application_gateway',", "viable storage account in target resource group namespace.storage_account = account.name namespace.storage_account_type = 'existing'", "sku = publisher.lower(), offer.lower(), sku.lower() distros = [('canonical', 'UbuntuServer', '^16.04'), ('suse', 'sles', '^12-sp3'),", "'You can use --generate-ssh-keys to let CLI generate one for you') namespace.ssh_key_value =", "in new_4core_sizes] if size not in new_4core_sizes: compute_client = _compute_client_factory(cli_ctx) sizes = compute_client.virtual_machine_sizes.list(namespace.location)", "specific storage profile # start with the required/forbidden parameters for VM if namespace.storage_profile", "name, rg, 'Microsoft.Compute', 'availabilitySets'): raise CLIError(\"Availability set '{}' does not exist.\".format(name)) namespace.availability_set =", "'loadBalancer' if namespace.single_placement_group is not False else 'applicationGateway' logger.debug(\"W/o STD LB, defaulting to", "= normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace, 'attach_data_disks', []), storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching) def _validate_vm_create_storage_account(cmd, namespace): from", "= parse_resource_id(res_id) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) vm_info = compute_client.virtual_machines.get(res['resource_group'], res['name']) # pylint: disable=no-member", "for authentication-type 'password': \" \"[--admin-username USERNAME] --admin-password PASSWORD\") from knack.prompting import prompt_pass, NoTTYException", "from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx)) def", "namespace.load_balancer_sku = LBSkuName.standard.value logger.debug(\"use Standard sku as single placement group is turned off\")", "None: raise CLIError('usage error: --platform-fault-domain-count COUNT --zones ZONES') if namespace.zones or namespace.instance_count >", "for val in names_or_ids: if not is_valid_resource_id(val): val = resource_id( subscription=subscription_id, resource_group=resource_group, namespace='Microsoft.Network',", "2 # try the other way around if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len))", "not is_valid_resource_id(kv): raise keyvault_usage def _get_resource_group_from_vault_name(cli_ctx, vault_name): \"\"\" Fetch resource group from vault", "# validate password _validate_admin_password(namespace.admin_password, namespace.os_type) elif namespace.authentication_type == 'ssh': if namespace.admin_password: raise ValueError('Admin", "new storage account specified namespace.storage_account_type = 'new' logger.debug(\"specified storage account '%s' not found", "pylint: disable=too-many-branches, too-many-statements def _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False): from msrestazure.tools import parse_resource_id # use", "def _validate_vm_vmss_create_public_ip(cmd, namespace): if namespace.public_ip_address: if check_existence(cmd.cli_ctx, namespace.public_ip_address, namespace.resource_group_name, 'Microsoft.Network', 'publicIPAddresses'): namespace.public_ip_address_type =", "= 1.5 if over_provision else 1 return ((1 << (32 - mask)) -", "upper case character, 1 number and 1 special character') def validate_ssh_key(namespace): string_or_file =", "_get_resource_id( cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if getattr(namespace, 'attach_data_disks', None): if not namespace.use_unmanaged_disk:", "a matching subnet for vnet_match in (v for v in client.list(rg) if v.location", "logger.debug(\"specified public IP '%s' not found. It will be created.\", namespace.public_ip_address) elif namespace.public_ip_address", "if not check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute', 'availabilitySets'): raise CLIError(\"Availability set '{}' does not", "'Standard_M128s', 'Standard_M128ms', 'Standard_L8s_v2', 'Standard_L16s_v2', 'Standard_L32s_v2', 'Standard_L64s_v2', 'Standard_L96s_v2', 'SQLGL', 'SQLGLCore', 'Standard_D4_v3', 'Standard_D4s_v3', 'Standard_D2_v2', 'Standard_DS2_v2',", "if not namespace.key_encryption_key: raise CLIError(\"Incorrect usage '--key-encryption-keyvault': \" \"'--key-encryption-key' is required\") namespace.key_encryption_keyvault =", "is only available under profile ' 'with minimum Compute API version of 2017-12-01')", "secrets: {0}'.format(err)) for idx_arg, narg_secret in enumerate(loaded_secret): for idx, secret in enumerate(narg_secret): if", "must be supplied to SSH Key Value. ' 'You can use --generate-ssh-keys to", "or []) elif res['type'].lower() == 'galleries': image_info = compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) namespace.os_type =", "subnet_bit_mask_len) return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2), int(candaidate_str[8:16], 2), int(candaidate_str[16:24], 2), int(candaidate_str[24:32], 2), new_mask) def _validate_vm_create_nsg(cmd,", "= cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK) if namespace.public_ip_sku == PublicIPAddressSkuName.standard.value: if not namespace.public_ip_address_allocation: namespace.public_ip_address_allocation =", "missing sourceVault.id key at index {0} in arg {1}'.format( idx, idx_arg)) if 'vaultCertificates'", "16: err = \"instance count '{}' is out of range of 2^16 subnet", "PRIORITY [--eviction-policy POLICY]') # endregion # region disk, snapshot, image validators def validate_vm_disk(cmd,", "NAME | --keyvault ID]') kv = namespace.keyvault rg = namespace.resource_group_name if rg: if", "or re.match(s, sku, re.I)): namespace.accelerated_networking = True def _validate_vmss_create_subnet(namespace): if namespace.vnet_type == 'new':", "# pylint: disable=inconsistent-return-statements def _get_storage_profile_description(profile): if profile == StorageProfile.SACustomImage: return 'create unmanaged OS", "x: x.publishing_profile.published_date)[-1] else: image_version_info = compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2']) image_data_disks_num = len(image_version_info.storage_profile.data_disk_images", "created.') def _subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision): mask = int(subnet_mask) # '2' are the reserved", "len([x for x in [contains_lower, contains_upper, contains_digit, contains_special_char] if x]) # pylint: disable=line-too-long", "role_defs[0].id return role_id def process_vm_create_namespace(cmd, namespace): validate_tags(namespace) _validate_location(cmd, namespace, namespace.zone, namespace.size) validate_asg_names_or_ids(cmd, namespace)", "in VM Creation Secrets JSON structure [{ \"sourceVault\": { \"id\": \"value\" }, \"vaultCertificates\":", "try capturing from VM, a most common scenario res_id = _get_resource_id(cmd.cli_ctx, namespace.source, namespace.resource_group_name,", "if prop in required: required.remove(prop) if prop in forbidden: forbidden.remove(prop) # set default", "'Standard_E8s_v3', 'Standard_D8_v3', 'Standard_D8s_v3'] new_4core_sizes = [x.lower() for x in new_4core_sizes] if size not", "errors = [] try: loaded_secret = [validate_file_or_dict(secret) for secret in secrets] except Exception", "None), ('credativ', 'debian', '-backports'), ('oracle', 'oracle-linux', '^7.4'), ('MicrosoftWindowsServer', 'WindowsServer', '^2016'), ('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')]", "string_or_file) with open(string_or_file, 'r') as f: content = f.read() elif not keys.is_valid_ssh_rsa_public_key(content): if", "of the following: 1 lower case character, 1 upper case character, 1 number", "balancer_type = 'loadBalancer' if namespace.single_placement_group is not False else 'applicationGateway' logger.debug(\"W/o STD LB,", "key at index {0} in arg {1}'.format( idx, idx_arg)) if 'sourceVault' in secret", "'applicationGateway' if balancer_type == 'applicationGateway': if namespace.application_gateway: client = get_network_client(cmd.cli_ctx).application_gateways try: rg =", "and '%s' have been generated under ~/.ssh to \" \"allow SSH access to", "_validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd, namespace) if namespace.license_type and namespace.os_type.lower() != 'windows': raise CLIError('usage", "= info.id return (source_blob_uri, source_disk, source_snapshot) def process_disk_encryption_namespace(cmd, namespace): namespace.disk_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault,", "else: raise CLIError('An RSA key file or key value must be supplied to", "== 'ssh': if namespace.admin_password: raise ValueError('Admin password cannot be used with SSH authentication", "namespace.nsg_type = 'existing' logger.debug(\"using specified NSG '%s'\", namespace.nsg) else: namespace.nsg_type = 'new' logger.debug(\"specified", "'{0}': {1}\\nSpecify '{0}' \" \"explicitly.\".format(option_name, ', '.join(values))) elif not values: raise CLIError(\"No existing", "disk' elif profile == StorageProfile.ManagedCustomImage: return 'create managed OS disk from custom image'", "= re.findall('[a-z]+', password) contains_upper = re.findall('[A-Z]+', password) contains_digit = re.findall('[0-9]+', password) contains_special_char =", "== StorageProfile.ManagedCustomImage: return 'create managed OS disk from custom image' elif profile ==", "turned off\" raise CLIError('usage error:{}'.format(err)) def get_network_client(cli_ctx): from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory", "resource_group=rg, namespace='Microsoft.Compute', type='availabilitySets', name=name) logger.debug(\"adding to specified availability set '%s'\", namespace.availability_set) def _validate_vm_vmss_create_vnet(cmd,", "vm_id = resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name = namespace.network_security_group_name \\ or '{}_NSG_{}'.format(namespace.vm_name,", "in storage_client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value == sku_tier and a.location == namespace.location), None) if account:", "special characters \\/\"[]:|<>+=;,?*@#()! or start with $ or -' win_err = r'admin user", "format back to the cidr candaidate_str = '{0:32b}'.format(candidate_int << subnet_bit_mask_len) return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2),", "os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching) def _validate_vm_create_storage_account(cmd, namespace): from msrestazure.tools import parse_resource_id if namespace.storage_account: storage_id =", "if not vnet and not subnet and not nics: logger.debug('no subnet specified. Attempting", "'Standard_F16s_v2', 'Standard_D5_v2', 'Standard_D14_v2', 'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo', 'Standard_DS5_v2', 'Standard_DS14_v2', 'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo', 'Standard_F16', 'Standard_F16s', 'Standard_M64-32ms', 'Standard_M128-32ms',", "- find viable storage account in target resource group namespace.storage_account = account.name namespace.storage_account_type", "be used\", account.name) else: # 4 - nothing specified - create a new", "def _get_nic_id(cli_ctx, val, resource_group): return _get_resource_id(cli_ctx, val, resource_group, 'networkInterfaces', 'Microsoft.Network') def validate_vm_nic(cmd, namespace):", "= compute_client.virtual_machines.get(res['resource_group'], res['name']) # pylint: disable=no-member namespace.os_type = vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine = res_id if", "resource_id( subscription=subscription_id, resource_group=resource_group, namespace='Microsoft.Network', type='applicationSecurityGroups', name=val ) ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace, 'application_security_groups', ids) def validate_nsg_name(cmd,", "msrestazure.azure_exceptions import CloudError validate_tags(namespace) if namespace.source: usage_error = 'usage error: --source {SNAPSHOT |", "--size-gb GB') elif bool(namespace.disk) != bool(namespace.instance_id): raise CLIError('usage error: --disk EXIST_DISK --instance-id ID')", "( get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set, validate_tags) from azure.cli.core.util import hash_string from azure.cli.command_modules.vm._vm_utils import check_existence,", "True # Now verify that the status of required and forbidden parameters validate_parameter_set(", "- 2017-03-30), Resource_sku doesn't implement location_info property if not hasattr(temp, 'location_info'): return if", "_validate_vm_create_storage_profile(cmd, namespace) if namespace.storage_profile in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd, namespace) _validate_vm_create_availability_set(cmd, namespace) _validate_vm_vmss_create_vnet(cmd, namespace)", "'Standard_D32s_v3', 'Standard_D64-32s_v3', 'Standard_E32_v3', 'Standard_E32s_v3', 'Standard_E32-8s_v3', 'Standard_E32-16_v3', 'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC', 'Standard_F16_ABC', 'Standard_F32s_v2', 'Standard_D15_v2', 'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested',", "subsequent processing. \"\"\" from msrestazure.tools import is_valid_resource_id from msrestazure.azure_exceptions import CloudError import re", "sku.lower() not in [x.lower() for x in allowed_skus]: raise CLIError(\"invalid storage SKU '{}':", "used') elif namespace.public_ip_address is None: namespace.public_ip_address_type = 'new' logger.debug('new public IP address will", "Debian \"Stretch\" with backports kernel # Oracle Linux 7.4, Windows Server 2016, Windows", "namespace.authentication_type == 'password': if namespace.ssh_key_value or namespace.ssh_dest_key_path: raise ValueError( \"incorrect usage for authentication-type", "'base_name'(with private keys), and 'base_name.pub'(with public keys) public_key_filepath = string_or_file if public_key_filepath[-4:].lower() ==", "uuid.UUID(role) role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id, role) except ValueError: pass if not role_id: #", "namespace.resource_group_name) lb_name = parse_resource_id(namespace.load_balancer)['name'] lb = get_network_lb(cmd.cli_ctx, namespace.resource_group_name, lb_name) if lb: namespace.load_balancer_type =", "= '{}/{}'.format(cidr, i) if namespace.app_gateway_type and namespace.app_gateway_subnet_address_prefix is None: namespace.app_gateway_subnet_address_prefix = _get_next_subnet_addr_suffix( namespace.vnet_address_prefix,", "logger.debug(\"specified storage account '%s' not found and will be created\", storage_id['name']) else: from", "and not cmd.supported_api_version(min_api='2017-12-01'): raise CLIError('usage error: user assigned identity is only available under", "namespace.attach_os_disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if getattr(namespace, 'attach_data_disks', None): if not namespace.use_unmanaged_disk: namespace.attach_data_disks =", "msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_subscription_id ApplicationSecurityGroup", "required for zonal scale-sets\" elif namespace.instance_count > 100: err = \"'Standard' load balancer", "--platform-fault-domain-count COUNT --zones ZONES') if namespace.zones or namespace.instance_count > 100: if namespace.single_placement_group is", "namespace.public_ip_address_allocation = IPAllocationMethod.static.value def _validate_vmss_create_public_ip(cmd, namespace): if namespace.load_balancer_type is None and namespace.app_gateway_type is", "usage_error = 'usage error: --source {SNAPSHOT | DISK} | --source VHD_BLOB_URI [--source-storage-account-id ID]'", "None: namespace.public_ip_address_type = 'new' logger.debug('new public IP address will be created') # Public-IP", "import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client from msrestazure.tools import parse_resource_id client = get_mgmt_service_client(cli_ctx,", "characters \\/\"[]:|<>+=;,?*@# or ends with .' if re.findall(pattern, username): raise CLIError(linux_err if is_linux", "'applicationGateway' logger.debug(\"W/o STD LB, defaulting to '%s' under because single placement group is", "'Standard_D16s_v3', 'Standard_D32-16s_v3', 'Standard_D64-16s_v3', 'Standard_E16_v3', 'Standard_E16s_v3', 'Standard_E32-16s_v3', 'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC', 'Standard_F8_ABC', 'Standard_F16s_v2', 'Standard_D5_v2', 'Standard_D14_v2', 'Standard_D5_v2_Promo',", "if namespace.app_gateway_type and namespace.app_gateway_subnet_address_prefix is None: namespace.app_gateway_subnet_address_prefix = _get_next_subnet_addr_suffix( namespace.vnet_address_prefix, namespace.subnet_address_prefix, 24) def", "# 2 - attempt to match an URN pattern urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image)", "AZURE_US_GOV_CLOUD if cmd.cli_ctx.cloud.name != AZURE_US_GOV_CLOUD.name: namespace.vm_sku = 'Standard_DS1_v2' else: namespace.vm_sku = 'Standard_D1_v2' _validate_location(cmd,", "== vault_name: return id_comps['resource_group'] return None def _get_resource_id(cli_ctx, val, resource_group, resource_type, resource_namespace): from", "= compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2']) image_data_disks_num = len(image_version_info.storage_profile.data_disk_images or []) else: raise", "= 'Secret is missing vaultCertificates array or it is empty at index {0}", "| ' '--application-gateway NAME_OR_ID') # Resolve the type of balancer (if any) being", "def _validate_vm_create_nics(cmd, namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id nics_value =", "account in target resource group namespace.storage_account = account.name namespace.storage_account_type = 'existing' logger.debug(\"suitable existing", "getattr(namespace, 'nics', None) if not vnet and not subnet and not nics: logger.debug('no", "'health_probe'] validate_parameter_set(namespace, required, forbidden, description='network balancer: application gateway') elif balancer_type == 'loadBalancer': #", "zone is not yet \" \"supported. Please use '--location' to specify a capable", "single placement group is turned off\") elif namespace.load_balancer_sku == LBSkuName.basic.value: if namespace.zones: err", "\"'Standard' load balancer is required for zonal scale-sets\" elif namespace.instance_count > 100: err", "refresh the list, run 'az vm create --accelerated-networking --size Standard_DS1_v2' and # get", "disallowed_user_names: raise CLIError(\"This user name '{}' meets the general requirements, but is specifically", "elif namespace.nsg is None: namespace.nsg_type = 'new' logger.debug('new NSG will be created') def", "Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt", "and not is_valid_resource_id(kv): raise keyvault_usage def _get_resource_group_from_vault_name(cli_ctx, vault_name): \"\"\" Fetch resource group from", "try: if not namespace.admin_password: namespace.admin_password = prompt_pass('Admin Password: ', confirm=True) except NoTTYException: raise", "'linux') # pylint: disable=line-too-long pattern = (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if is_linux else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err =", "'windows': raise CLIError('usage error: --license-type is only applicable on Windows VM scaleset') if", "namespace.os_publisher, namespace.os_offer, namespace.os_sku, image_version) # pylint: disable=no-member return image.plan except CloudError as ex:", "size.lower() # to refresh the list, run 'az vm create --accelerated-networking --size Standard_DS1_v2'", "'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value'] # perform parameter validation for the specific storage profile #", "specified availability set '%s'\", namespace.availability_set) def _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False): from msrestazure.tools import is_valid_resource_id", "error aval_sizes = ['Standard_D3_v2', 'Standard_D12_v2', 'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo', 'Standard_DS3_v2', 'Standard_DS12_v2', 'Standard_DS13-4_v2', 'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo',", "around if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: raise CLIError(error_msg) # format", "= 'new' logger.debug('no suitable subnet found. One will be created.') def _subnet_capacity_check(subnet_mask, vmss_instance_count,", "supplied for the --image parameter. Updates the namespace and returns the type for", "lb: namespace.load_balancer_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, lb_name, 'load_balancers')", "to resolve the expected storage profile if getattr(namespace, 'attach_os_disk', None) and not namespace.image:", "StorageProfile.SACustomImage: required = ['image', 'os_type', 'use_unmanaged_disk'] forbidden = ['attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile ==", "'name': val, 'resource_group': resource_group, 'namespace': resource_namespace, 'type': resource_type, 'subscription': get_subscription_id(cli_ctx) } missing_kwargs =", "< 8: return # VMs need to be a supported image in the", "'Standard_D16_v3', 'Standard_D16s_v3', 'Standard_D32-16s_v3', 'Standard_D64-16s_v3', 'Standard_E16_v3', 'Standard_E16s_v3', 'Standard_E32-16s_v3', 'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC', 'Standard_F8_ABC', 'Standard_F16s_v2', 'Standard_D5_v2', 'Standard_D14_v2',", "# needed for Stack profile 2017_03_09 balancer_type = 'loadBalancer' if namespace.single_placement_group is not", "allowed values: '{}'\".format(sku, allowed_skus)) def _validate_location(cmd, namespace, zone_info, size_info): from ._vm_utils import list_sku_info", "x in (temp.location_info or []) if x.zones]: raise CLIError(\"{}'s location can't be used", "names_or_ids = getattr(namespace, 'application_security_groups') ids = [] if names_or_ids == [\"\"] or not", "in n else resource_id(name=n, resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)), 'properties': { 'primary': nics_value[0] ==", "temp = next((x for x in sku_infos if x.name.lower() == size_info.lower()), None) #", "_validate_location(cmd, namespace, zone_info, size_info): from ._vm_utils import list_sku_info if not namespace.location: get_default_location_from_resource_group(cmd, namespace)", "_validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd, namespace) _validate_vmss_create_nsg(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd, namespace) if namespace.license_type and", "unmanaged vhd based images? if urlparse(namespace.image).scheme: return 'uri' # 4 - attempt to", "private_key_filepath, public_key_filepath) else: raise CLIError('An RSA key file or key value must be", "x in new_4core_sizes] if size not in new_4core_sizes: compute_client = _compute_client_factory(cli_ctx) sizes =", "list, run 'az vm create --accelerated-networking --size Standard_DS1_v2' and # get it from", "= as_id['name'] rg = as_id.get('resource_group', namespace.resource_group_name) if not check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute', 'availabilitySets'):", "not role_id: # retrieve role id role_defs = list(client.list(scope, \"roleName eq '{}'\".format(role))) if", "is not yet \" \"supported. Please use '--location' to specify a capable one.", "b, c, d = [int(x) for x in address.split('.')] result = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b,", "= matched['offer'] namespace.os_sku = matched['sku'] namespace.os_version = matched['version'] return 'urn' # 5 -", "namespace): if namespace.public_ip_address: if check_existence(cmd.cli_ctx, namespace.public_ip_address, namespace.resource_group_name, 'Microsoft.Network', 'publicIPAddresses'): namespace.public_ip_address_type = 'existing' logger.debug(\"using", "'Standard_F16_ABC', 'Standard_F32s_v2', 'Standard_D15_v2', 'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested', 'Standard_DS15_v2', 'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested', 'Standard_D40_v3', 'Standard_D40s_v3', 'Standard_D15_v2_ABC', 'Standard_M64ms', 'Standard_M64s',", "namespace.public_ip_address, namespace.resource_group_name, 'Microsoft.Network', 'publicIPAddresses'): namespace.public_ip_address_type = 'existing' logger.debug(\"using existing specified public IP '%s'\",", "--license-type is only applicable on Windows VM') _validate_vm_vmss_msi(cmd, namespace) if namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage =", "LoadBalancer frontend required = [] forbidden = ['app_gateway_subnet_address_prefix', 'application_gateway', 'app_gateway_sku', 'app_gateway_capacity'] validate_parameter_set(namespace, required,", "idx_arg)) else: for jdx, cert in enumerate(secret['vaultCertificates']): message = 'Secret is missing {0}", "be used') elif namespace.public_ip_address is None: namespace.public_ip_address_type = 'new' logger.debug('new public IP address", "storage_id['name'], rg, 'Microsoft.Storage', 'storageAccounts'): # 1 - existing storage account specified namespace.storage_account_type =", "\"usage error: --subnet-address-prefix value should be a subrange of --vnet-address-prefix's\" # extract vnet", "NIC(s) will be used') def _validate_vm_vmss_create_auth(namespace): if namespace.storage_profile in [StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]: return namespace.admin_username", "specified existing vnet/subnet namespace.vnet_type = 'existing' logger.debug(\"using specified vnet '%s' and subnet '%s'\",", "'r') as f: content = f.read() elif not keys.is_valid_ssh_rsa_public_key(content): if namespace.generate_ssh_keys: # figure", "'Standard_F8s_v2', 'Standard_F4', 'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3', 'Standard_D8s_v3'] new_4core_sizes = [x.lower() for x", "return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx)) def get_network_lb(cli_ctx, resource_group_name, lb_name): from msrestazure.azure_exceptions import CloudError network_client", "[contains_lower, contains_upper, contains_digit, contains_special_char] if x]) # pylint: disable=line-too-long if count < 3:", "# extract additional information from a managed custom image res = parse_resource_id(namespace.image) compute_client", "'Standard_D64-32s_v3', 'Standard_E32_v3', 'Standard_E32s_v3', 'Standard_E32-8s_v3', 'Standard_E32-16_v3', 'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC', 'Standard_F16_ABC', 'Standard_F32s_v2', 'Standard_D15_v2', 'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested', 'Standard_DS15_v2',", "not exist.\".format(name)) namespace.availability_set = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg, namespace='Microsoft.Compute', type='availabilitySets', name=name) logger.debug(\"adding to specified", "identities[i] = _get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') if not namespace.identity_scope and getattr(namespace.identity_role, 'is_default',", "process_disk_or_snapshot_create_namespace(cmd, namespace): from msrestazure.azure_exceptions import CloudError validate_tags(namespace) if namespace.source: usage_error = 'usage error:", "Create Validators def _parse_image_argument(cmd, namespace): \"\"\" Systematically determines what type is supplied for", "return # VMs need to be a supported image in the marketplace #", "'^16.04'), ('suse', 'sles', '^12-sp3'), ('redhat', 'rhel', '^7.4'), ('openlogic', 'centos', '^7.4'), ('coreos', 'coreos', None),", "validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace) if namespace.storage_profile in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd, namespace) _validate_vm_create_availability_set(cmd, namespace)", "= _get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_assign_identity_namespace(cmd, namespace): _validate_vm_vmss_msi(cmd, namespace, from_set_command=True) def", "plan settings \" \"will be skipped\", namespace.image, ex.message) # pylint: disable=inconsistent-return-statements def _get_storage_profile_description(profile):", "16, -1): if _subnet_capacity_check(i, namespace.instance_count, not namespace.disable_overprovision): break if i < 16: err", "knack.log import get_logger from knack.util import CLIError from azure.cli.core.commands.validators import ( get_default_location_from_resource_group, validate_file_or_dict,", "'admin_username', 'authentication_type', 'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value'] # perform parameter validation for the specific storage", "\"instance count '{}' is out of range of 2^16 subnet size'\" raise CLIError(err.format(namespace.instance_count))", "and 1 special character') def validate_ssh_key(namespace): string_or_file = (namespace.ssh_key_value or os.path.join(os.path.expanduser('~'), '.ssh', 'id_rsa.pub'))", "x != MSI_LOCAL_ID] if user_assigned_identities and not cmd.supported_api_version(min_api='2017-12-01'): raise CLIError('usage error: user assigned", "100+ instances\") def _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace): from msrestazure.azure_exceptions import CloudError from msrestazure.tools import parse_resource_id", "compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) image_version_infos = [x for x in image_version_infos if not", "from ._client_factory import _compute_client_factory from ._actions import _get_latest_image_version logger = get_logger(__name__) def validate_asg_names_or_ids(cmd,", "x]) # pylint: disable=line-too-long if count < 3: raise CLIError('Password must have the", "under profile ' 'with minimum Compute API version of 2017-12-01') if namespace.identity_scope: if", "'{}'\" raise CLIError(err.format(role, ids)) role_id = role_defs[0].id return role_id def process_vm_create_namespace(cmd, namespace): validate_tags(namespace)", "namespace.public_ip_address) elif namespace.public_ip_address == '': namespace.public_ip_address_type = None logger.debug('no public IP address will", "# 5 - check if an existing managed disk image resource compute_client =", "in aval_sizes: return new_4core_sizes = ['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2', 'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC',", "is None: namespace.nsg_type = 'new' logger.debug('new NSG will be created') def _validate_vmss_create_nsg(cmd, namespace):", "not nics: logger.debug('no subnet specified. Attempting to find an existing Vnet and subnet...')", "not found. It will be created.\", namespace.load_balancer) elif namespace.load_balancer == '': namespace.load_balancer_type =", "namespace, for_scale_set=True) _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=True) _validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace) _validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd, namespace) _validate_vmss_create_nsg(cmd, namespace)", "re is_linux = (os_type.lower() == 'linux') max_length = 72 if is_linux else 123", "is None: namespace.public_ip_address_type = 'new' logger.debug('new public IP address will be created') #", "type') validate_ssh_key(namespace) if not namespace.ssh_dest_key_path: namespace.ssh_dest_key_path = \\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def _validate_admin_username(username, os_type): import", "in enumerate(loaded_secret): for idx, secret in enumerate(narg_secret): if 'sourceVault' not in secret: errors.append(", "= \"More than one role matches the given name '{}'. Please pick an", "required.append('app_gateway_sku') required.append('app_gateway_capacity') if namespace.vnet_type != 'new': required.append('app_gateway_subnet_address_prefix') elif namespace.app_gateway_type == 'existing': required.append('backend_pool_name') forbidden", "from ._vm_utils import normalize_disk_info # attach_data_disks are not exposed yet for VMSS, so", "if namespace.platform_fault_domain_count is not None and namespace.zones is None: raise CLIError('usage error: --platform-fault-domain-count", "= nics namespace.nic_type = 'existing' namespace.public_ip_address_type = None logger.debug('existing NIC(s) will be used')", "namespace.source_disk, namespace.source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, namespace.source) if not namespace.source_blob_uri and namespace.source_storage_account_id: raise", "public_key_filepath) else: raise CLIError('An RSA key file or key value must be supplied", "azure.cli.core.util import hash_string from azure.cli.command_modules.vm._vm_utils import check_existence, get_target_network_api, get_storage_blob_uri from azure.cli.command_modules.vm._template_builder import StorageProfile", "user name '{}' meets the general requirements, but is specifically disallowed for this", "azure.cli.core.commands.client_factory import get_mgmt_service_client from azure.cli.core.profiles import ResourceType client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions role_id =", "CLIError(\"Unable to resolve OS type. Specify '--os-type' argument.\") if not namespace.authentication_type: # apply", "created from generalized VHD' elif profile == StorageProfile.SAPirImage: return 'create unmanaged OS disk", "vault_name: name of the key vault :return: resource group name or None :rtype:", "if check_existence(cmd.cli_ctx, storage_id['name'], rg, 'Microsoft.Storage', 'storageAccounts'): # 1 - existing storage account specified", "out of range of 2^16 subnet size'\" raise CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix = '{}/{}'.format(cidr, i)", "import get_subscription_id if namespace.availability_set: as_id = parse_resource_id(namespace.availability_set) name = as_id['name'] rg = as_id.get('resource_group',", "is_linux = (os_type.lower() == 'linux') max_length = 72 if is_linux else 123 min_length", "'Standard_D14_v2_Promo', 'Standard_DS5_v2', 'Standard_DS14_v2', 'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo', 'Standard_F16', 'Standard_F16s', 'Standard_M64-32ms', 'Standard_M128-32ms', 'Standard_D32_v3', 'Standard_D32s_v3', 'Standard_D64-32s_v3', 'Standard_E32_v3',", "api_version=get_target_network_api(cli_ctx)) def get_network_lb(cli_ctx, resource_group_name, lb_name): from msrestazure.azure_exceptions import CloudError network_client = get_network_client(cli_ctx) try:", "public IP '%s'\", namespace.public_ip_address) else: namespace.public_ip_address_type = 'new' logger.debug(\"specified public IP '%s' not", "is turned off\") elif namespace.load_balancer_sku == LBSkuName.basic.value: if namespace.zones: err = \"'Standard' load", "images])) def _get_image_plan_info_if_exists(cmd, namespace): from msrestazure.azure_exceptions import CloudError try: compute_client = _compute_client_factory(cmd.cli_ctx) if", "client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults for vault in client.list(): id_comps = parse_resource_id(vault.id) if id_comps['name']", "= None source_disk = None source_snapshot = None if urlparse(source).scheme: # a uri?", "= content def _validate_vm_vmss_msi(cmd, namespace, from_set_command=False): if from_set_command or namespace.assign_identity is not None:", "msrestazure.azure_exceptions import CloudError validate_tags(namespace) try: # try capturing from VM, a most common", "storage profile # start with the required/forbidden parameters for VM if namespace.storage_profile ==", "gallery_image_version = res.get('child_name_2', '') if gallery_image_version.lower() in ['latest', '']: image_version_infos = compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'],", "namespace.storage_account_type = 'existing' logger.debug(\"suitable existing storage account '%s' will be used\", account.name) else:", "defaults we are coming out vnet_ip_address, mask = vnet_cidr.split('/') vnet_bit_mask_len = 32 -", "or size_info.number_of_cores < 8: return # VMs need to be a supported image", "_subnet_capacity_check(i, namespace.instance_count, not namespace.disable_overprovision): break if i < 16: err = \"instance count", "'new' logger.debug('new load balancer will be created') if namespace.load_balancer_type == 'new' and namespace.single_placement_group", "matched['version'] return 'urn' # 5 - check if an existing managed disk image", "so we have enough leeway for over-provision factor = 1.5 if over_provision else", "the VM/VMSS because availablity zone is not yet \" \"supported. Please use '--location'", "= image_plan.publisher return 'urn' # 3 - unmanaged vhd based images? if urlparse(namespace.image).scheme:", "role_defs] err = \"More than one role matches the given name '{}'. Please", "'id' not in secret['sourceVault']: errors.append( 'Secret is missing sourceVault.id key at index {0}", "{}' is not applicable as the '--scope' is not provided\".format( namespace.identity_role)) user_assigned_identities =", "def validate_vmss_disk(cmd, namespace): if namespace.disk: namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if", "balancer_type == 'applicationGateway': if namespace.application_gateway: client = get_network_client(cmd.cli_ctx).application_gateways try: rg = parse_resource_id(namespace.application_gateway).get( 'resource_group',", "of --vnet-address-prefix's\" # extract vnet information needed to verify the defaults we are", "# Licensed under the MIT License. See License.txt in the project root for", "rg = storage_id.get('resource_group', namespace.resource_group_name) if check_existence(cmd.cli_ctx, storage_id['name'], rg, 'Microsoft.Storage', 'storageAccounts'): # 1 -", "x in address.split('.')] result = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b, c, d) return int(result[:-bit_mask_len], 2) error_msg", "if identities[i] != MSI_LOCAL_ID: identities[i] = _get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') if not", "the image of '%s' failed for an error '%s'. Configuring plan settings \"", "disable=too-many-branches, too-many-statements def _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False): from msrestazure.tools import parse_resource_id # use minimal", "scale-sets or with\" \" 100+ instances\") def _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace): from msrestazure.azure_exceptions import CloudError", "_figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, namespace.source) if not namespace.source_blob_uri and namespace.source_storage_account_id: raise CLIError(usage_error) except CloudError:", "- create a new storage account namespace.storage_account_type = 'new' logger.debug('no suitable storage account", "lb.inbound_nat_pools[0].name logger.debug(\"using specified existing load balancer '%s'\", namespace.load_balancer) else: namespace.load_balancer_type = 'new' logger.debug(\"load", "from msrestazure.azure_exceptions import CloudError validate_tags(namespace) try: # try capturing from VM, a most", "'attach to existing unmanaged OS disk' elif profile == StorageProfile.ManagedCustomImage: return 'create managed", "== StorageProfile.ManagedSpecializedOSDisk: return 'attach existing managed OS disk' def _validate_managed_disk_sku(sku): allowed_skus = ['Premium_LRS',", "is None: namespace.ultra_ssd_enabled = True # Now verify that the status of required", "auth type (password for Windows, ssh for Linux) by examining the OS type", "if namespace.vm_sku is None: from azure.cli.core.cloud import AZURE_US_GOV_CLOUD if cmd.cli_ctx.cloud.name != AZURE_US_GOV_CLOUD.name: namespace.vm_sku", "'Standard_D12_v2_ABC', 'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4', 'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3', 'Standard_D8s_v3'] new_4core_sizes =", "# 'base_name'(with private keys), and 'base_name.pub'(with public keys) public_key_filepath = string_or_file if public_key_filepath[-4:].lower()", "elif namespace.application_gateway is None: namespace.app_gateway_type = 'new' logger.debug('new application gateway will be created')", "the --image parameter. Updates the namespace and returns the type for subsequent processing.", "parsed JSON array containing secrets for use in VM Creation Secrets JSON structure", "'certificateStore' not in cert: errors.append(message.format('certificateStore', idx, jdx, idx_arg)) if errors: raise CLIError('\\n'.join(errors)) #", "is_linux else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err = r'admin user name cannot contain upper case character", "0 if namespace.storage_profile == StorageProfile.ManagedCustomImage: # extract additional information from a managed custom", "namespace.os_blob_uri, namespace.os_disk, namespace.os_snapshot = _figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name, namespace.source) # pylint: disable=line-too-long namespace.data_blob_uris = []", "id_comps['resource_group'] return None def _get_resource_id(cli_ctx, val, resource_group, resource_type, resource_namespace): from msrestazure.tools import resource_id,", "return False subnet_mask = s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask, namespace.instance_count, not namespace.disable_overprovision) result = next((s", "= 0 if namespace.storage_profile == StorageProfile.ManagedCustomImage: # extract additional information from a managed", "[--scope SCOPE] [--role ROLE]') def _resolve_role_id(cli_ctx, role, scope): import re import uuid from", "= _get_latest_image_version(cmd.cli_ctx, namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku) else: image_version = namespace.os_version image = compute_client.virtual_machine_images.get(namespace.location,", "balancer type: {}'.format(balancer_type)) balancer = client.get(resource_group, balancer_name) values = [x.name for x in", "compute_client = _compute_client_factory(cmd.cli_ctx) if namespace.os_version.lower() == 'latest': image_version = _get_latest_image_version(cmd.cli_ctx, namespace.location, namespace.os_publisher, namespace.os_offer,", "= len(image_version_info.storage_profile.data_disk_images or []) else: raise CLIError('usage error: unrecognized image informations \"{}\"'.format(namespace.image)) #", "import CloudError from msrestazure.tools import parse_resource_id from azure.cli.core.profiles import ResourceType std_lb_is_available = cmd.supported_api_version(min_api='2017-08-01',", "namespace.license_type and namespace.os_type.lower() != 'windows': raise CLIError('usage error: --license-type is only applicable on", "secret in enumerate(narg_secret): if 'sourceVault' not in secret: errors.append( 'Secret is missing sourceVault", "group that matches the VM's location sku_tier = 'Premium' if 'Premium' in namespace.storage_sku", "None: raise CLIError('usage error: --assign-identity [--scope SCOPE] [--role ROLE]') def _resolve_role_id(cli_ctx, role, scope):", "3 - create a new vnet/subnet namespace.vnet_type = 'new' logger.debug('no suitable subnet found.", "under ~/.ssh to \" \"allow SSH access to the VM. If using machines", "result = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b, c, d) return int(result[:-bit_mask_len], 2) error_msg = \"usage error:", "resource group name or None :rtype: str \"\"\" from azure.cli.core.profiles import ResourceType from", "= next((s for s in vnet_match.subnets if _check_subnet(s)), None) if not result: continue", "2^16 subnet size'\" raise CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix = '{}/{}'.format(cidr, i) if namespace.app_gateway_type and namespace.app_gateway_subnet_address_prefix", "= f.read() elif not keys.is_valid_ssh_rsa_public_key(content): if namespace.generate_ssh_keys: # figure out appropriate file names:", "error: --license-type is only applicable on Windows VM scaleset') if not namespace.public_ip_per_vm and", "return values[0] def _validate_vmss_single_placement_group(namespace): if namespace.platform_fault_domain_count is not None and namespace.zones is None:", "errors if any were found :rtype: list \"\"\" is_windows = os_type == 'windows'", "perform parameter validation for the specific storage profile # start with the required/forbidden", "namespace.os_version.lower() == 'latest': image_version = _get_latest_image_version(cmd.cli_ctx, namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku) else: image_version =", "namespace.ssh_dest_key_path: namespace.ssh_dest_key_path = \\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def _validate_admin_username(username, os_type): import re if not username:", "logger = get_logger(__name__) def validate_asg_names_or_ids(cmd, namespace): from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.profiles", "'{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b, c, d) return int(result[:-bit_mask_len], 2) error_msg = \"usage error: --subnet-address-prefix value", "'{}' doesn't exist.\".format(role)) elif len(role_defs) > 1: ids = [r.id for r in", "images = load_images_from_aliases_doc(cmd.cli_ctx) matched = next((x for x in images if x['urnAlias'].lower() ==", "get_storage_blob_uri from azure.cli.command_modules.vm._template_builder import StorageProfile import azure.cli.core.keys as keys from ._client_factory import _compute_client_factory", "index {0} in arg {1}'.format( idx, idx_arg)) if 'sourceVault' in secret and 'id'", "'Standard_F2s', 'Standard_F4s_v2', 'Standard_D11_v2', 'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C'] aval_sizes = [x.lower() for x in aval_sizes] if", "= storage_id.get('resource_group', namespace.resource_group_name) if check_existence(cmd.cli_ctx, storage_id['name'], rg, 'Microsoft.Storage', 'storageAccounts'): # 1 - existing", "if namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage = get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage) # endregion # region VMSS Create Validators", "import get_mgmt_service_client from azure.cli.core.profiles import ResourceType client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions role_id = None", "try: info = compute_client.snapshots.get(resource_group_name, source) source_snapshot = info.id except CloudError: info = compute_client.disks.get(resource_group_name,", "== 'linux') # pylint: disable=line-too-long pattern = (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if is_linux else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err", "generate one for you') namespace.ssh_key_value = content def _validate_vm_vmss_msi(cmd, namespace, from_set_command=False): if from_set_command", "namespace.vm_sku = 'Standard_D1_v2' _validate_location(cmd, namespace, namespace.zones, namespace.vm_sku) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=True) _validate_vm_vmss_create_vnet(cmd,", "be empty\") is_linux = (os_type.lower() == 'linux') # pylint: disable=line-too-long pattern = (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+'", "required = ['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name')", "'Standard_D40_v3', 'Standard_D40s_v3', 'Standard_D15_v2_ABC', 'Standard_M64ms', 'Standard_M64s', 'Standard_M128-64ms', 'Standard_D64_v3', 'Standard_D64s_v3', 'Standard_E64_v3', 'Standard_E64s_v3', 'Standard_E64-16s_v3', 'Standard_E64-32s_v3', 'Standard_F64s_v2',", "namespace.admin_username = _validate_admin_username(namespace.admin_username, namespace.os_type) if not namespace.os_type: raise CLIError(\"Unable to resolve OS type.", "_get_resource_id(cmd.cli_ctx, namespace.source, namespace.resource_group_name, 'virtualMachines', 'Microsoft.Compute') res = parse_resource_id(res_id) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) vm_info", "if getattr(namespace, 'attach_data_disks', None): if not namespace.use_unmanaged_disk: namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name, 'disks',", "raise CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify '{0}' explicitly.\".format( # pylint: disable=line-too-long", "namespace.nics nics = [] if not nics_value: namespace.nic_type = 'new' logger.debug('new NIC will", "'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4', 'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3', 'Standard_D8s_v3'] new_4core_sizes = [x.lower()", "image_version = namespace.os_version image = compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku, image_version) # pylint: disable=no-member", "in names_or_ids: if not is_valid_resource_id(val): val = resource_id( subscription=subscription_id, resource_group=resource_group, namespace='Microsoft.Network', type='applicationSecurityGroups', name=val", "disk created from generalized VHD' elif profile == StorageProfile.SAPirImage: return 'create unmanaged OS", "= \"instance count '{}' is out of range of 2^16 subnet size'\" raise", "account specified namespace.storage_account_type = 'existing' logger.debug(\"using specified existing storage account '%s'\", storage_id['name']) else:", "a.sku.tier.value == sku_tier and a.location == namespace.location), None) if account: # 3 -", "'--role {}' is not applicable as the '--scope' is not provided\".format( namespace.identity_role)) user_assigned_identities", "get_network_client(cli_ctx): from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx))", "image_version_infos = compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) image_version_infos = [x for x in image_version_infos", "IP '%s' not found. It will be created.\", namespace.public_ip_address) elif namespace.public_ip_address == '':", "namespace.ssh_key_value or namespace.ssh_dest_key_path: raise ValueError( \"incorrect usage for authentication-type 'password': \" \"[--admin-username USERNAME]", "and sku.lower() not in [x.lower() for x in allowed_skus]: raise CLIError(\"invalid storage SKU", "len(password) not in range(min_length, max_length + 1): raise CLIError('The password length must be", "and namespace.source_storage_account_id: raise CLIError(usage_error) except CloudError: raise CLIError(usage_error) def process_image_create_namespace(cmd, namespace): from msrestazure.tools", "compute_client = _compute_client_factory(cmd.cli_ctx) try: compute_client.images.get(namespace.resource_group_name, namespace.image) namespace.image = _get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name, 'images', 'Microsoft.Compute')", "is enabled') if namespace.eviction_policy and not namespace.priority: raise CLIError('Usage error: --priority PRIORITY [--eviction-policy", "None logger.debug('no load balancer will be used') elif namespace.load_balancer is None: namespace.load_balancer_type =", "DISK} | --source VHD_BLOB_URI [--source-storage-account-id ID]' try: namespace.source_blob_uri, namespace.source_disk, namespace.source_snapshot = _figure_out_storage_source( cmd.cli_ctx,", "SSH authentication type') validate_ssh_key(namespace) if not namespace.ssh_dest_key_path: namespace.ssh_dest_key_path = \\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def _validate_admin_username(username,", "namespace.instance_count > 100: if namespace.single_placement_group is None: namespace.single_placement_group = False elif namespace.single_placement_group: raise", "raise CLIError('usage error: --disk EXIST_DISK --instance-id ID | --size-gb GB') elif bool(namespace.disk) !=", "3 - unmanaged vhd based images? if urlparse(namespace.image).scheme: return 'uri' # 4 -", "username): raise CLIError(linux_err if is_linux else win_err) if is_linux and re.findall(r'^[$-]+', username): raise", "get_network_lb(cli_ctx, resource_group_name, lb_name): from msrestazure.azure_exceptions import CloudError network_client = get_network_client(cli_ctx) try: return network_client.load_balancers.get(resource_group_name,", "such locations\".format(namespace.resource_group_name)) # pylint: disable=too-many-branches, too-many-statements def _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False): from msrestazure.tools import", "'Standard_F4', 'Standard_F4s', 'Standard_D8_v3', 'Standard_D8s_v3', 'Standard_D32-8s_v3', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC', 'Standard_F4_ABC', 'Standard_F8s_v2', 'Standard_D4_v2', 'Standard_D13_v2',", "needed to verify the defaults we are coming out vnet_ip_address, mask = vnet_cidr.split('/')", "if source_disk: namespace.data_disks.append(source_disk) if source_snapshot: namespace.data_snapshots.append(source_snapshot) if not namespace.os_type: raise CLIError(\"usage error: os", "CLIError('--public-ip-address can only be used when creating a new load ' 'balancer or", "keyvault_usage = CLIError('usage error: [--keyvault NAME --resource-group NAME | --keyvault ID]') kv =", "'Standard_D4s_v3', 'Standard_D2_v2', 'Standard_DS2_v2', 'Standard_E4_v3', 'Standard_E4s_v3', 'Standard_F2', 'Standard_F2s', 'Standard_F4s_v2', 'Standard_D11_v2', 'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C'] aval_sizes =", "is_valid_resource_id from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_subscription_id ApplicationSecurityGroup = cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK)", "if not nics_value: namespace.nic_type = 'new' logger.debug('new NIC will be created') return if", "PublicIPAddressSkuName, IPAllocationMethod = cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK) if namespace.public_ip_sku == PublicIPAddressSkuName.standard.value: if not namespace.public_ip_address_allocation:", "namespace.nsg_type = 'new' logger.debug(\"specified NSG '%s' not found. It will be created.\", namespace.nsg)", "# For Stack (compute - 2017-03-30), Resource_sku doesn't implement location_info property if not", "None source_snapshot = None if urlparse(source).scheme: # a uri? source_blob_uri = source elif", "CLIError('usage error: --disk EXIST_DISK --instance-id ID | --size-gb GB') elif bool(namespace.disk) != bool(namespace.instance_id):", "CloudError validate_tags(namespace) try: # try capturing from VM, a most common scenario res_id", "namespace) _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=True) _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=True) _validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace) _validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd, namespace)", "= get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions role_id = None if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role, re.I): role_id = role", "\"actuser\", \"adm\", \"admin2\", \"aspnet\", \"backup\", \"console\", \"guest\", \"owner\", \"root\", \"server\", \"sql\", \"support\", \"support_388945a0\",", "_validate_vm_vmss_msi(cmd, namespace) if namespace.license_type and namespace.os_type.lower() != 'windows': raise CLIError('usage error: --license-type is", "if x.zones]: raise CLIError(\"{}'s location can't be used to create the VM/VMSS because", "is None: size = getattr(namespace, 'size', None) or getattr(namespace, 'vm_sku', None) size =", "used when creating a new load ' 'balancer or application gateway frontend.') namespace.public_ip_address", "= parse_resource_id(namespace.availability_set) name = as_id['name'] rg = as_id.get('resource_group', namespace.resource_group_name) if not check_existence(cmd.cli_ctx, name,", "empty at index {0} in ' \\ 'arg {1} ' errors.append(err.format(idx, idx_arg)) else:", "None logger.debug('no NSG will be used') elif namespace.nsg is None: namespace.nsg_type = 'new'", "len(image_version_info.storage_profile.data_disk_images or []) else: raise CLIError('usage error: unrecognized image informations \"{}\"'.format(namespace.image)) # pylint:", "= parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name) lb_name = parse_resource_id(namespace.load_balancer)['name'] lb = get_network_lb(cmd.cli_ctx, namespace.resource_group_name, lb_name) if lb:", "is_valid_resource_id(kv): raise keyvault_usage def _get_resource_group_from_vault_name(cli_ctx, vault_name): \"\"\" Fetch resource group from vault name", "'attach_os_disk', None): image_type = _parse_image_argument(cmd, namespace) if image_type == 'uri': # STORAGE PROFILE", "= ['attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SASpecializedOSDisk: required = ['os_type', 'attach_os_disk', 'use_unmanaged_disk'] forbidden", "key=lambda x: x.publishing_profile.published_date)[-1] else: image_version_info = compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2']) image_data_disks_num =", "if not namespace.os_type: namespace.os_type = 'windows' if 'windows' in namespace.os_offer.lower() else 'linux' from", "try the other way around if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int:", "balancer is required for scale-sets with 100+ instances\" else: err = \"'Standard' load", "if _check_subnet(s)), None) if not result: continue namespace.subnet = result.name namespace.vnet_name = vnet_match.name", "public keys) public_key_filepath = string_or_file if public_key_filepath[-4:].lower() == '.pub': private_key_filepath = public_key_filepath[:-4] else:", "candidate_int = candidate_int - 2 # try the other way around if (candidate_int", "namespace.load_balancer_type = 'new' logger.debug('new load balancer will be created') if namespace.load_balancer_type == 'new'", "auth_params else: raise CLIError('Unrecognized storage profile: {}'.format(namespace.storage_profile)) logger.debug(\"storage profile '%s'\", namespace.storage_profile) if for_scale_set:", "x in sku_infos if x.name.lower() == size_info.lower()), None) # For Stack (compute -", "# 3 - unmanaged vhd based images? if urlparse(namespace.image).scheme: return 'uri' # 4", "namespace.nsg: if check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_type = 'existing' logger.debug(\"using specified NSG", "namespace.nsg) else: namespace.nsg_type = 'new' logger.debug(\"specified NSG '%s' not found. It will be", "if not image_version_infos: raise CLIError('There is no latest image version exists for \"{}\"'.format(namespace.image))", "elif namespace.public_ip_address == '': namespace.public_ip_address_type = None logger.debug('no public IP address will be", "namespace): if namespace.load_balancer_type is None and namespace.app_gateway_type is None: if namespace.public_ip_address: raise CLIError('--public-ip-address", "win_err = r'admin user name cannot contain special characters \\/\"[]:|<>+=;,?*@# or ends with", "It will be created.\", namespace.nsg) elif namespace.nsg == '': namespace.nsg_type = None logger.debug('no", "import re import uuid from azure.cli.core.commands.client_factory import get_mgmt_service_client from azure.cli.core.profiles import ResourceType client", "if namespace.app_gateway_type == 'new': required.append('app_gateway_sku') required.append('app_gateway_capacity') if namespace.vnet_type != 'new': required.append('app_gateway_subnet_address_prefix') elif namespace.app_gateway_type", "import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client storage_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts # find storage", "new vnet/subnet namespace.vnet_type = 'new' logger.debug('no suitable subnet found. One will be created.')", "max_length + 1): raise CLIError('The password length must be between {} and {}'.format(min_length,", "'linux') max_length = 72 if is_linux else 123 min_length = 12 if len(password)", "import parse_resource_id from azure.cli.core.profiles import ResourceType std_lb_is_available = cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer and", "namespace.vm_domain_name: raise CLIError('Usage error: --vm-domain-name can only be used when --public-ip-per-vm is enabled')", "compute_client.disks.get(resource_group_name, source) source_disk = info.id return (source_blob_uri, source_disk, source_snapshot) def process_disk_encryption_namespace(cmd, namespace): namespace.disk_encryption_keyvault", "'image_id': # STORAGE PROFILE #5 namespace.storage_profile = StorageProfile.ManagedCustomImage elif image_type == 'urn': if", "RHEL 7.4, CentOS 7.4, CoreOS Linux, Debian \"Stretch\" with backports kernel # Oracle", "found. It will be created.\", namespace.public_ip_address) elif namespace.public_ip_address == '': namespace.public_ip_address_type = None", "gallery_name=res['name'], gallery_image_name=res['child_name_1']) image_version_infos = [x for x in image_version_infos if not x.publishing_profile.exclude_from_latest] if", "location and v.subnets): # 1 - find a suitable existing vnet/subnet result =", "'windows': raise CLIError('usage error: --license-type is only applicable on Windows VM') _validate_vm_vmss_msi(cmd, namespace)", "namespace.resource_group_name) ag_name = parse_resource_id(namespace.application_gateway)['name'] client.get(rg, ag_name) namespace.app_gateway_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or", "ValueError( \"incorrect usage for authentication-type 'password': \" \"[--admin-username USERNAME] --admin-password PASSWORD\") from knack.prompting", "re.findall('[a-z]+', password) contains_upper = re.findall('[A-Z]+', password) contains_digit = re.findall('[0-9]+', password) contains_special_char = re.findall(r'[", "location.\", private_key_filepath, public_key_filepath) else: raise CLIError('An RSA key file or key value must", "vm_info = compute_client.virtual_machines.get(res['resource_group'], res['name']) # pylint: disable=no-member namespace.os_type = vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine = res_id", "'%s'\", namespace.nsg) else: namespace.nsg_type = 'new' logger.debug(\"specified NSG '%s' not found. It will", "if matched: namespace.os_publisher = matched['publisher'] namespace.os_offer = matched['offer'] namespace.os_sku = matched['sku'] namespace.os_version =", "'Standard_M128-32ms', 'Standard_D32_v3', 'Standard_D32s_v3', 'Standard_D64-32s_v3', 'Standard_E32_v3', 'Standard_E32s_v3', 'Standard_E32-8s_v3', 'Standard_E32-16_v3', 'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC', 'Standard_F16_ABC', 'Standard_F32s_v2', 'Standard_D15_v2',", "namespace.nat_pool_name = lb.inbound_nat_pools[0].name logger.debug(\"using specified existing load balancer '%s'\", namespace.load_balancer) else: namespace.load_balancer_type =", "'Standard_F4', 'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3', 'Standard_D8s_v3'] new_4core_sizes = [x.lower() for x in", "from generalized VHD' elif profile == StorageProfile.SAPirImage: return 'create unmanaged OS disk from", "from msrestazure.tools import is_valid_resource_id from msrestazure.azure_exceptions import CloudError import re # 1 -", "(c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See", "jdx, cert in enumerate(secret['vaultCertificates']): message = 'Secret is missing {0} within vaultCertificates array", "image_plan = _get_image_plan_info_if_exists(cmd, namespace) if image_plan: namespace.plan_name = image_plan.name namespace.plan_product = image_plan.product namespace.plan_publisher", "StorageProfile.ManagedSpecializedOSDisk elif namespace.image and not getattr(namespace, 'attach_os_disk', None): image_type = _parse_image_argument(cmd, namespace) if", "x in allowed_skus]: raise CLIError(\"invalid storage SKU '{}': allowed values: '{}'\".format(sku, allowed_skus)) def", "sorted(image_version_infos, key=lambda x: x.publishing_profile.published_date)[-1] else: image_version_info = compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2']) image_data_disks_num", "try: compute_client.images.get(namespace.resource_group_name, namespace.image) namespace.image = _get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name, 'images', 'Microsoft.Compute') return 'image_id' except", "azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client storage_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts # find", "'size', None) or getattr(namespace, 'vm_sku', None) size = size.lower() # to refresh the", "error '%s'. Configuring plan settings \" \"will be skipped\", namespace.image, ex.message) # pylint:", "if namespace.load_balancer and namespace.application_gateway: raise CLIError('incorrect usage: --load-balancer NAME_OR_ID | ' '--application-gateway NAME_OR_ID')", "so far if getattr(namespace, 'public_ip_sku', None): from azure.cli.core.profiles import ResourceType PublicIPAddressSkuName, IPAllocationMethod =", "[x for x in (temp.location_info or []) if x.zones]: raise CLIError(\"{}'s location can't", "import resource_id from azure.cli.core.commands.client_factory import get_subscription_id nics_value = namespace.nics nics = [] if", "logger.debug(\"specified NSG '%s' not found. It will be created.\", namespace.nsg) elif namespace.nsg ==", "None) if not result: continue namespace.subnet = result.name namespace.vnet_name = vnet_match.name namespace.vnet_type =", "in image_version_infos if not x.publishing_profile.exclude_from_latest] if not image_version_infos: raise CLIError('There is no latest", "'Standard_E64-16s_v3', 'Standard_E64-32s_v3', 'Standard_F64s_v2', 'Standard_F72s_v2', 'Standard_M128s', 'Standard_M128ms', 'Standard_L8s_v2', 'Standard_L16s_v2', 'Standard_L32s_v2', 'Standard_L64s_v2', 'Standard_L96s_v2', 'SQLGL', 'SQLGLCore',", "disallowed_user_names = [ \"administrator\", \"admin\", \"user\", \"user1\", \"test\", \"user2\", \"test1\", \"user3\", \"admin1\", \"1\",", "\" \"explicitly.\".format(option_name, ', '.join(values))) elif not values: raise CLIError(\"No existing values found for", "cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer and namespace.application_gateway: raise CLIError('incorrect usage: --load-balancer NAME_OR_ID | '", "namespace.source_blob_uri, namespace.source_disk, namespace.source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, namespace.source) if not namespace.source_blob_uri and namespace.source_storage_account_id:", "None) size = size.lower() # to refresh the list, run 'az vm create", "and not namespace.priority: raise CLIError('Usage error: --priority PRIORITY [--eviction-policy POLICY]') # endregion #", "= None logger.debug('no NSG will be used') elif namespace.nsg is None: namespace.nsg_type =", "= public_key_filepath[:-4] else: private_key_filepath = public_key_filepath + '.private' content = keys.generate_ssh_keys(private_key_filepath, public_key_filepath) logger.warning(\"SSH", "# retrieve role id role_defs = list(client.list(scope, \"roleName eq '{}'\".format(role))) if not role_defs:", "CLIError('usage error: --disk EXIST_DISK --instance-id ID') def process_disk_or_snapshot_create_namespace(cmd, namespace): from msrestazure.azure_exceptions import CloudError", "raise CLIError('\\n'.join(errors)) # region VM Create Validators def _parse_image_argument(cmd, namespace): \"\"\" Systematically determines", "not namespace.os_type: raise CLIError(\"usage error: os type is required to create the image,", "found. It will be created.\", namespace.nsg) elif namespace.nsg == '': namespace.nsg_type = None", "[int(x) for x in address.split('.')] result = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b, c, d) return int(result[:-bit_mask_len],", "AZURE_US_GOV_CLOUD.name: namespace.vm_sku = 'Standard_DS1_v2' else: namespace.vm_sku = 'Standard_D1_v2' _validate_location(cmd, namespace, namespace.zones, namespace.vm_sku) validate_asg_names_or_ids(cmd,", "'Microsoft.Compute') for d in namespace.attach_data_disks] if not namespace.os_type: namespace.os_type = 'windows' if 'windows'", "location with a matching subnet for vnet_match in (v for v in client.list(rg)", "if getattr(namespace, 'public_ip_sku', None): from azure.cli.core.profiles import ResourceType PublicIPAddressSkuName, IPAllocationMethod = cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod',", "'Microsoft.Compute') def validate_vmss_disk(cmd, namespace): if namespace.disk: namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute')", "contains_digit, contains_special_char] if x]) # pylint: disable=line-too-long if count < 3: raise CLIError('Password", "\"images from virtual machines\") except CloudError: namespace.os_blob_uri, namespace.os_disk, namespace.os_snapshot = _figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name, namespace.source)", "specified existing load balancer '%s'\", namespace.load_balancer) else: namespace.load_balancer_type = 'new' logger.debug(\"load balancer '%s'", "'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedCustomImage: required = ['image'] forbidden", "for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedCustomImage: required = ['image'] forbidden = ['os_type',", "raise CLIError(usage_error) def process_image_create_namespace(cmd, namespace): from msrestazure.tools import parse_resource_id from msrestazure.azure_exceptions import CloudError", "for prop in props_to_remove: if prop in required: required.remove(prop) if prop in forbidden:", "LBSkuName = cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer_sku is None: namespace.load_balancer_sku = LBSkuName.standard.value logger.debug(\"use Standard", "'' _validate_vm_vmss_create_public_ip(cmd, namespace) def _validate_vm_create_nics(cmd, namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import", "group that matches the VM's location with a matching subnet for vnet_match in", "def process_vm_create_namespace(cmd, namespace): validate_tags(namespace) _validate_location(cmd, namespace, namespace.zone, namespace.size) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace) if", "None def process_vmss_create_namespace(cmd, namespace): validate_tags(namespace) if namespace.vm_sku is None: from azure.cli.core.cloud import AZURE_US_GOV_CLOUD", "forbidden = ['os_type', 'attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SACustomImage: required = ['image', 'os_type',", "'Standard_D1_v2' _validate_location(cmd, namespace, namespace.zones, namespace.vm_sku) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=True) _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=True)", "an error '%s'. Configuring plan settings \" \"will be skipped\", namespace.image, ex.message) #", "else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err = r'admin user name cannot contain upper case character A-Z,", "safe location.\", private_key_filepath, public_key_filepath) else: raise CLIError('An RSA key file or key value", "import hash_string from azure.cli.command_modules.vm._vm_utils import check_existence, get_target_network_api, get_storage_blob_uri from azure.cli.command_modules.vm._template_builder import StorageProfile import", "or []) if x.zones]: raise CLIError(\"{}'s location can't be used to create the", "CLIError(win_err) disallowed_user_names = [ \"administrator\", \"admin\", \"user\", \"user1\", \"test\", \"user2\", \"test1\", \"user3\", \"admin1\",", "source_snapshot = None if urlparse(source).scheme: # a uri? source_blob_uri = source elif '/disks/'", "import parse_resource_id from msrestazure.azure_exceptions import CloudError validate_tags(namespace) try: # try capturing from VM,", "minimal parameters to resolve the expected storage profile if getattr(namespace, 'attach_os_disk', None) and", "namespace.network_security_group_name \\ or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8)) def validate_keyvault(cmd, namespace): namespace.keyvault = _get_resource_id(cmd.cli_ctx, namespace.keyvault,", "size_info.number_of_cores < 8: return # VMs need to be a supported image in", "{ 'name': val, 'resource_group': resource_group, 'namespace': resource_namespace, 'type': resource_type, 'subscription': get_subscription_id(cli_ctx) } missing_kwargs", "skipped\", namespace.image, ex.message) # pylint: disable=inconsistent-return-statements def _get_storage_profile_description(profile): if profile == StorageProfile.SACustomImage: return", "account.name) else: # 4 - nothing specified - create a new storage account", "namespace.storage_profile = StorageProfile.SASpecializedOSDisk else: # STORAGE PROFILE #6 namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk elif namespace.image", "if for_scale_set: # VMSS lacks some parameters, so scrub these out props_to_remove =", "# start with the required/forbidden parameters for VM if namespace.storage_profile == StorageProfile.ManagedPirImage: required", "if p.lower() == publisher and (o is None or o.lower() == offer) and", "vmss_instance_count, over_provision): mask = int(subnet_mask) # '2' are the reserved broadcasting addresses #", "password) contains_special_char = re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password) count = len([x for x in [contains_lower,", "is None: raise CLIError(\"usage error: '--role {}' is not applicable as the '--scope'", "'Standard_E4_v3', 'Standard_E4s_v3', 'Standard_F2', 'Standard_F2s', 'Standard_F4s_v2', 'Standard_D11_v2', 'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C'] aval_sizes = [x.lower() for x", "image_version_infos: raise CLIError('There is no latest image version exists for \"{}\"'.format(namespace.image)) image_version_info =", "[x for x in identities if x != MSI_LOCAL_ID] if user_assigned_identities and not", "'Standard_DS14-4_v2_Promo', 'Standard_F4', 'Standard_F4s', 'Standard_D8_v3', 'Standard_D8s_v3', 'Standard_D32-8s_v3', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC', 'Standard_F4_ABC', 'Standard_F8s_v2', 'Standard_D4_v2',", "ID) if is_valid_resource_id(namespace.image): return 'image_id' # 2 - attempt to match an URN", "be used when creating a new load ' 'balancer or application gateway frontend.')", "to '%s' under because single placement group is disabled\", balancer_type) elif namespace.load_balancer: balancer_type", "match an URN pattern urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image) if urn_match: namespace.os_publisher = urn_match.group(1)", "== publisher and (o is None or o.lower() == offer) and (s is", "role_id = None if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role, re.I): role_id = role else: try: uuid.UUID(role)", "Linux 7.4, Windows Server 2016, Windows Server 2012R2 publisher, offer, sku = namespace.os_publisher,", "to the VM. If using machines without \" \"permanent storage, back up your", "list \"\"\" is_windows = os_type == 'windows' errors = [] try: loaded_secret =", "if namespace.availability_set: as_id = parse_resource_id(namespace.availability_set) name = as_id['name'] rg = as_id.get('resource_group', namespace.resource_group_name) if", "'{}': allowed values: '{}'\".format(sku, allowed_skus)) def _validate_location(cmd, namespace, zone_info, size_info): from ._vm_utils import", "'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC', 'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4', 'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3', 'Standard_D8s_v3'] new_4core_sizes", "namespace.public_ip_address_type = 'new' logger.debug(\"specified public IP '%s' not found. It will be created.\",", "from knack.prompting import prompt_pass, NoTTYException try: if not namespace.admin_password: namespace.admin_password = prompt_pass('Admin Password:", "None: namespace.app_gateway_type = 'new' logger.debug('new application gateway will be created') # AppGateway frontend", "namespace.zone, namespace.size) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace) if namespace.storage_profile in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd, namespace)", "'Microsoft.KeyVault') def process_assign_identity_namespace(cmd, namespace): _validate_vm_vmss_msi(cmd, namespace, from_set_command=True) def process_remove_identity_namespace(cmd, namespace): if namespace.identities: from", "subnet...') # if nothing specified, try to find an existing vnet and subnet", "vnet/subnet namespace.vnet_type = 'new' logger.debug('no suitable subnet found. One will be created.') def", "= _get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') if not namespace.identity_scope and getattr(namespace.identity_role, 'is_default', None)", "get_mgmt_service_client return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx)) def get_network_lb(cli_ctx, resource_group_name, lb_name): from msrestazure.azure_exceptions import CloudError", "'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC', 'Standard_F4_ABC', 'Standard_F8s_v2', 'Standard_D4_v2', 'Standard_D13_v2', 'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo', 'Standard_DS4_v2', 'Standard_DS13_v2', 'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo',", "and v.subnets): # 1 - find a suitable existing vnet/subnet result = None", "is_valid_resource_id(val): val = resource_id( subscription=subscription_id, resource_group=resource_group, namespace='Microsoft.Network', type='applicationSecurityGroups', name=val ) ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace, 'application_security_groups',", "msrestazure.tools import parse_resource_id client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults for vault in client.list(): id_comps =", "+ '.private' content = keys.generate_ssh_keys(private_key_filepath, public_key_filepath) logger.warning(\"SSH key files '%s' and '%s' have", "Use a custom image name, id, or pick one from {}' raise CLIError(err.format(namespace.image,", "def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace): if namespace.accelerated_networking is None: size = getattr(namespace, 'size', None) or", "idx_arg)) if is_windows and 'certificateStore' not in cert: errors.append(message.format('certificateStore', idx, jdx, idx_arg)) if", "created.\", namespace.application_gateway) elif namespace.application_gateway == '': namespace.app_gateway_type = None logger.debug('no application gateway will", "(candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: raise CLIError(error_msg) # format back to", "def _validate_vm_create_availability_set(cmd, namespace): from msrestazure.tools import parse_resource_id, resource_id from azure.cli.core.commands.client_factory import get_subscription_id if", "so warn here. logger.warning(\"No inbound nat pool was configured on '%s'\", namespace.load_balancer) else:", "= compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) namespace.os_type = image_info.os_type.value gallery_image_version = res.get('child_name_2', '') if gallery_image_version.lower()", "CloudError: namespace.os_blob_uri, namespace.os_disk, namespace.os_snapshot = _figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name, namespace.source) # pylint: disable=line-too-long namespace.data_blob_uris =", "unmanaged OS disk' elif profile == StorageProfile.ManagedCustomImage: return 'create managed OS disk from", "vault in client.list(): id_comps = parse_resource_id(vault.id) if id_comps['name'] == vault_name: return id_comps['resource_group'] return", "str \"\"\" from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client from msrestazure.tools import", "forbidden, description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num = 0 if namespace.storage_profile == StorageProfile.ManagedCustomImage: # extract", "== 'uri': # STORAGE PROFILE #2 namespace.storage_profile = StorageProfile.SACustomImage elif image_type == 'image_id':", "namespace.vnet_name subnet = namespace.subnet rg = namespace.resource_group_name location = namespace.location nics = getattr(namespace,", "p, o, s in distros: if p.lower() == publisher and (o is None", "= re.findall('[0-9]+', password) contains_special_char = re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password) count = len([x for x", "TargetRegion = cmd.get_models('TargetRegion') if namespace.target_regions: regions_info = [] for t in namespace.target_regions: parts", "namespace.location: get_default_location_from_resource_group(cmd, namespace) if zone_info: sku_infos = list_sku_info(cmd.cli_ctx, namespace.location) temp = next((x for", "\"guest\", \"owner\", \"root\", \"server\", \"sql\", \"support\", \"support_388945a0\", \"sys\", \"test2\", \"test3\", \"user4\", \"user5\"] if", "hash_string(vm_id, length=8)) def validate_keyvault(cmd, namespace): namespace.keyvault = _get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def", "get_target_network_api, get_storage_blob_uri from azure.cli.command_modules.vm._template_builder import StorageProfile import azure.cli.core.keys as keys from ._client_factory import", "target resource group that matches the VM's location sku_tier = 'Premium' if 'Premium'", "if not namespace.admin_password: namespace.admin_password = prompt_pass('Admin Password: ', confirm=True) except NoTTYException: raise CLIError('Please", "return network_client.load_balancers.get(resource_group_name, lb_name) except CloudError: return None def process_vmss_create_namespace(cmd, namespace): validate_tags(namespace) if namespace.vm_sku", "type for subsequent processing. \"\"\" from msrestazure.tools import is_valid_resource_id from msrestazure.azure_exceptions import CloudError", "profile '%s'\", namespace.storage_profile) if for_scale_set: # VMSS lacks some parameters, so scrub these", "c, d) return int(result[:-bit_mask_len], 2) error_msg = \"usage error: --subnet-address-prefix value should be", "r'admin user name cannot contain special characters \\/\"[]:|<>+=;,?*@# or ends with .' if", "if namespace.storage_profile in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd, namespace) _validate_vm_create_availability_set(cmd, namespace) _validate_vm_vmss_create_vnet(cmd, namespace) _validate_vm_create_nsg(cmd, namespace)", "'galleries': image_info = compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) namespace.os_type = image_info.os_type.value gallery_image_version = res.get('child_name_2', '')", "._vm_utils import MSI_LOCAL_ID for i, _ in enumerate(identities): if identities[i] != MSI_LOCAL_ID: identities[i]", "account '%s' not found and will be created\", storage_id['name']) else: from azure.cli.core.profiles import", "_validate_vm_vmss_create_auth(namespace) if namespace.secrets: _validate_secrets(namespace.secrets, namespace.os_type) if namespace.license_type and namespace.os_type.lower() != 'windows': raise CLIError('usage", "if namespace.os_version.lower() == 'latest': image_version = _get_latest_image_version(cmd.cli_ctx, namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku) else: image_version", "= _get_resource_id( cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if getattr(namespace, 'attach_data_disks', None): if not", "from azure.cli.core.profiles import ResourceType client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions role_id = None if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/',", "from azure.cli.core.commands.client_factory import get_subscription_id vm_id = resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name =", "get_mgmt_service_client storage_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts # find storage account in target resource group", "'UbuntuServer', '^16.04'), ('suse', 'sles', '^12-sp3'), ('redhat', 'rhel', '^7.4'), ('openlogic', 'centos', '^7.4'), ('coreos', 'coreos',", "profile == StorageProfile.ManagedSpecializedOSDisk: return 'attach existing managed OS disk' def _validate_managed_disk_sku(sku): allowed_skus =", "pylint: disable=line-too-long namespace.data_blob_uris = [] namespace.data_disks = [] namespace.data_snapshots = [] if namespace.data_disk_sources:", "== 'new' and namespace.single_placement_group is False and std_lb_is_available: LBSkuName = cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK) if", "and 'certificateStore' not in cert: errors.append(message.format('certificateStore', idx, jdx, idx_arg)) if errors: raise CLIError('\\n'.join(errors))", "frontend required = [] if namespace.app_gateway_type == 'new': required.append('app_gateway_sku') required.append('app_gateway_capacity') if namespace.vnet_type !=", "'Standard_F8s_v2', 'Standard_D4_v2', 'Standard_D13_v2', 'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo', 'Standard_DS4_v2', 'Standard_DS13_v2', 'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo', 'Standard_F8', 'Standard_F8s',", "Please pick an id from '{}'\" raise CLIError(err.format(role, ids)) role_id = role_defs[0].id return", "under the MIT License. See License.txt in the project root for license information.", "' 'You can use --generate-ssh-keys to let CLI generate one for you') namespace.ssh_key_value", "= get_logger(__name__) def validate_asg_names_or_ids(cmd, namespace): from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.profiles import", "' errors.append(err.format(idx, idx_arg)) else: for jdx, cert in enumerate(secret['vaultCertificates']): message = 'Secret is", "urn_match.group(3) namespace.os_version = urn_match.group(4) if not any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]): image_plan = _get_image_plan_info_if_exists(cmd, namespace)", "logger.debug('new load balancer will be created') if namespace.load_balancer_type == 'new' and namespace.single_placement_group is", "return 'create unmanaged OS disk from Azure Marketplace image' elif profile == StorageProfile.SASpecializedOSDisk:", "namespace.resource_group_name nic_ids = [] for n in namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg)) namespace.nics =", "'windows' and namespace.authentication_type == 'ssh': raise CLIError('SSH not supported for Windows VMs.') #", "balancer_type = 'loadBalancer' else: # needed for Stack profile 2017_03_09 balancer_type = 'loadBalancer'", "next((s for s in vnet_match.subnets if s.name.lower() != 'gatewaysubnet'), None) else: def _check_subnet(s):", "missing_kwargs else None def _get_nic_id(cli_ctx, val, resource_group): return _get_resource_id(cli_ctx, val, resource_group, 'networkInterfaces', 'Microsoft.Network')", "12 if len(password) not in range(min_length, max_length + 1): raise CLIError('The password length", "matched['offer'] namespace.os_sku = matched['sku'] namespace.os_version = matched['version'] return 'urn' # 5 - check", "at secret ' \\ 'index {1} and vaultCertificate index {2} in arg {3}'", "= compute_client.images.get(res['resource_group'], res['name']) namespace.os_type = image_info.storage_profile.os_disk.os_type.value image_data_disks_num = len(image_info.storage_profile.data_disks or []) elif res['type'].lower()", "'-backports'), ('oracle', 'oracle-linux', '^7.4'), ('MicrosoftWindowsServer', 'WindowsServer', '^2016'), ('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')] import re for", "confirm=True) except NoTTYException: raise CLIError('Please specify password in non-interactive mode.') # validate password", "\"user3\", \"admin1\", \"1\", \"123\", \"a\", \"actuser\", \"adm\", \"admin2\", \"aspnet\", \"backup\", \"console\", \"guest\", \"owner\",", "specified vnet '%s' and subnet '%s'\", namespace.vnet_name, namespace.subnet) return # 3 - create", "= 'new' logger.debug(\"specified storage account '%s' not found and will be created\", storage_id['name'])", "namespace.nat_pool_name: if len(lb.inbound_nat_pools) > 1: raise CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify", "'Standard_D15_v2', 'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested', 'Standard_DS15_v2', 'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested', 'Standard_D40_v3', 'Standard_D40s_v3', 'Standard_D15_v2_ABC', 'Standard_M64ms', 'Standard_M64s', 'Standard_M128-64ms', 'Standard_D64_v3',", "if namespace.license_type and namespace.os_type.lower() != 'windows': raise CLIError('usage error: --license-type is only applicable", "raise keyvault_usage validate_keyvault(cmd, namespace) else: if kv and not is_valid_resource_id(kv): raise keyvault_usage def", "try: # try capturing from VM, a most common scenario res_id = _get_resource_id(cmd.cli_ctx,", "not namespace.key_encryption_key: raise CLIError(\"Incorrect usage '--key-encryption-keyvault': \" \"'--key-encryption-key' is required\") namespace.key_encryption_keyvault = _get_resource_id(cmd.cli_ctx,", "s in distros: if p.lower() == publisher and (o is None or o.lower()", "is specifically disallowed for this image. Please try a different value.\".format(username)) return username", "subscription=get_subscription_id(cmd.cli_ctx)), 'properties': { 'primary': nics_value[0] == n } }) namespace.nics = nics namespace.nic_type", "found for '{0}'. Create one first and try \" \"again.\".format(option_name)) return values[0] def", "'new' logger.debug(\"specified NSG '%s' not found. It will be created.\", namespace.nsg) elif namespace.nsg", "'existing' logger.debug(\"using existing specified public IP '%s'\", namespace.public_ip_address) else: namespace.public_ip_address_type = 'new' logger.debug(\"specified", "storage_id = parse_resource_id(namespace.storage_account) rg = storage_id.get('resource_group', namespace.resource_group_name) if check_existence(cmd.cli_ctx, storage_id['name'], rg, 'Microsoft.Storage', 'storageAccounts'):", "== 'new': required.append('app_gateway_sku') required.append('app_gateway_capacity') if namespace.vnet_type != 'new': required.append('app_gateway_subnet_address_prefix') elif namespace.app_gateway_type == 'existing':", "cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer_sku is None: namespace.load_balancer_sku = LBSkuName.standard.value logger.debug(\"use Standard sku as", "file or key value must be supplied to SSH Key Value. ' 'You", "subnet = namespace.subnet rg = namespace.resource_group_name location = namespace.location nics = getattr(namespace, 'nics',", "existing values found for '{0}'. Create one first and try \" \"again.\".format(option_name)) return", "be created.\", namespace.public_ip_address) elif namespace.public_ip_address == '': namespace.public_ip_address_type = None logger.debug('no public IP", "any) being used balancer_type = 'None' if namespace.load_balancer is None and namespace.application_gateway is", "image_type == 'uri': # STORAGE PROFILE #2 namespace.storage_profile = StorageProfile.SACustomImage elif image_type ==", "image version exists for \"{}\"'.format(namespace.image)) image_version_info = sorted(image_version_infos, key=lambda x: x.publishing_profile.published_date)[-1] else: image_version_info", "err = \"'Standard' load balancer is required for scale-sets with 100+ instances\" else:", "source_blob_uri = None source_disk = None source_snapshot = None if urlparse(source).scheme: # a", "placement group is disabled\", balancer_type) elif namespace.load_balancer: balancer_type = 'loadBalancer' elif namespace.application_gateway: balancer_type", "else: private_key_filepath = public_key_filepath + '.private' content = keys.generate_ssh_keys(private_key_filepath, public_key_filepath) logger.warning(\"SSH key files", "# Now verify that the status of required and forbidden parameters validate_parameter_set( namespace,", "pylint: disable=line-too-long '--nat-pool-name', ', '.join([n.name for n in lb.inbound_nat_pools]))) elif not lb.inbound_nat_pools: #", "it from the error aval_sizes = ['Standard_D3_v2', 'Standard_D12_v2', 'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo', 'Standard_DS3_v2', 'Standard_DS12_v2', 'Standard_DS13-4_v2',", "scope): import re import uuid from azure.cli.core.commands.client_factory import get_mgmt_service_client from azure.cli.core.profiles import ResourceType", "# get it from the error aval_sizes = ['Standard_D3_v2', 'Standard_D12_v2', 'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo', 'Standard_DS3_v2',", "# STORAGE PROFILE #3 namespace.storage_profile = StorageProfile.SASpecializedOSDisk else: # STORAGE PROFILE #6 namespace.storage_profile", "namespace.platform_fault_domain_count is not None and namespace.zones is None: raise CLIError('usage error: --platform-fault-domain-count COUNT", "_parse_image_argument(cmd, namespace): \"\"\" Systematically determines what type is supplied for the --image parameter.", "# Oracle Linux 7.4, Windows Server 2016, Windows Server 2012R2 publisher, offer, sku", "vm create --accelerated-networking --size Standard_DS1_v2' and # get it from the error aval_sizes", "namespace.storage_sku == 'UltraSSD_LRS' and namespace.ultra_ssd_enabled is None: namespace.ultra_ssd_enabled = True # Now verify", "mask)) - 2) > int(vmss_instance_count * factor) def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace): if namespace.accelerated_networking is", "be a supported image in the marketplace # Ubuntu 16.04, SLES 12 SP3,", "info = compute_client.snapshots.get(resource_group_name, source) source_snapshot = info.id except CloudError: info = compute_client.disks.get(resource_group_name, source)", "is_valid_resource_id keyvault_usage = CLIError('usage error: [--keyvault NAME --resource-group NAME | --keyvault ID]') kv", "balancer_type): option_name = '--backend-pool-name' client = getattr(get_network_client(cli_ctx), balancer_type, None) if not client: raise", "_validate_vm_create_storage_profile(cmd, namespace, for_scale_set=True) _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=True) _validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace) _validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd, namespace) _validate_vmss_create_nsg(cmd,", "Azure Marketplace image' elif profile == StorageProfile.ManagedSpecializedOSDisk: return 'attach existing managed OS disk'", "parse_resource_id # use minimal parameters to resolve the expected storage profile if getattr(namespace,", "== 'linux') max_length = 72 if is_linux else 123 min_length = 12 if", "public_key_filepath[:-4] else: private_key_filepath = public_key_filepath + '.private' content = keys.generate_ssh_keys(private_key_filepath, public_key_filepath) logger.warning(\"SSH key", "def process_gallery_image_version_namespace(cmd, namespace): TargetRegion = cmd.get_models('TargetRegion') if namespace.target_regions: regions_info = [] for t", "namespace.availability_set = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg, namespace='Microsoft.Compute', type='availabilitySets', name=name) logger.debug(\"adding to specified availability set", "not found. It will be created.\", namespace.application_gateway) elif namespace.application_gateway == '': namespace.app_gateway_type =", "disable=no-member elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: # accept disk name or ID namespace.attach_os_disk =", "namespace.identity_scope)) elif namespace.identity_scope or getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError('usage error: --assign-identity", "balancer_name, balancer_type): option_name = '--backend-pool-name' client = getattr(get_network_client(cli_ctx), balancer_type, None) if not client:", "vnet_bit_mask_len) subnet_ip_address, mask = subnet_cidr.split('/') subnet_bit_mask_len = 32 - int(mask) if vnet_bit_mask_len <=", "'Microsoft.KeyVault') def process_vm_secret_format(cmd, namespace): from msrestazure.tools import is_valid_resource_id keyvault_usage = CLIError('usage error: [--keyvault", "CLIError(\"{}'s location can't be used to create the VM/VMSS because availablity zone is", "= [] forbidden = ['app_gateway_subnet_address_prefix', 'application_gateway', 'app_gateway_sku', 'app_gateway_capacity'] validate_parameter_set(namespace, required, forbidden, description='network balancer:", "raise CLIError('Unrecognized storage profile: {}'.format(namespace.storage_profile)) logger.debug(\"storage profile '%s'\", namespace.storage_profile) if for_scale_set: # VMSS", "raise CLIError(\"Subnet '{}' does not exist.\".format(subnet)) elif subnet_exists: # 2 - user specified", "parse_resource_id client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults for vault in client.list(): id_comps = parse_resource_id(vault.id) if", "msrestazure.tools import parse_resource_id from azure.cli.core.profiles import ResourceType std_lb_is_available = cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer", "ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx)) def get_network_lb(cli_ctx, resource_group_name, lb_name): from msrestazure.azure_exceptions import CloudError network_client = get_network_client(cli_ctx)", "Resolve the type of balancer (if any) being used balancer_type = 'None' if", "if namespace.use_unmanaged_disk: # STORAGE PROFILE #1 namespace.storage_profile = StorageProfile.SAPirImage else: # STORAGE PROFILE", "gateway frontend.') namespace.public_ip_address = '' _validate_vm_vmss_create_public_ip(cmd, namespace) def _validate_vm_create_nics(cmd, namespace): from msrestazure.tools import", "of OS (linux or windows) :return: errors if any were found :rtype: list", "StorageProfile.SASpecializedOSDisk else: # STORAGE PROFILE #6 namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk elif namespace.image and not", "namespace.nic_type = 'existing' namespace.public_ip_address_type = None logger.debug('existing NIC(s) will be used') def _validate_vm_vmss_create_auth(namespace):", "--zones ZONES') if namespace.zones or namespace.instance_count > 100: if namespace.single_placement_group is None: namespace.single_placement_group", "[StorageProfile.SAPirImage, StorageProfile.SACustomImage]: # pylint: disable=line-too-long namespace.storage_sku = 'Standard_LRS' if for_scale_set else 'Premium_LRS' if", "'{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8)) def validate_keyvault(cmd, namespace): namespace.keyvault = _get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault')", "to resolve OS type. Specify '--os-type' argument.\") if not namespace.authentication_type: # apply default", "= next((x for x in sku_infos if x.name.lower() == size_info.lower()), None) # For", "existing vnet/subnet namespace.vnet_type = 'existing' logger.debug(\"using specified vnet '%s' and subnet '%s'\", namespace.vnet_name,", "client = getattr(get_network_client(cli_ctx), balancer_type, None) if not client: raise CLIError('unrecognized balancer type: {}'.format(balancer_type))", "_validate_vm_create_nics(cmd, namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id nics_value = namespace.nics", "a parsed JSON array containing secrets for use in VM Creation Secrets JSON", "raise CLIError('Please specify password in non-interactive mode.') # validate password _validate_admin_password(namespace.admin_password, namespace.os_type) elif", "name can not be empty\") is_linux = (os_type.lower() == 'linux') # pylint: disable=line-too-long", "and forbidden parameters validate_parameter_set( namespace, required, forbidden, description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num = 0", "# did not specify image XOR attach-os-disk raise CLIError('incorrect usage: --image IMAGE |", "be created\", storage_id['name']) else: from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client storage_client", "for this image. Please try a different value.\".format(username)) return username def _validate_admin_password(password, os_type):", "= size.lower() # to refresh the list, run 'az vm create --accelerated-networking --size", "if not namespace.nat_pool_name: if len(lb.inbound_nat_pools) > 1: raise CLIError(\"Multiple possible values found for", "client = get_network_client(cmd.cli_ctx).virtual_networks # find VNET in target resource group that matches the", "data_disk_source in namespace.data_disk_sources: source_blob_uri, source_disk, source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, data_disk_source) if source_blob_uri:", "'ssh': raise CLIError('SSH not supported for Windows VMs.') # validate proper arguments supplied", "d = [int(x) for x in address.split('.')] result = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b, c, d)", "name = as_id['name'] rg = as_id.get('resource_group', namespace.resource_group_name) if not check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute',", "raise CLIError(win_err) disallowed_user_names = [ \"administrator\", \"admin\", \"user\", \"user1\", \"test\", \"user2\", \"test1\", \"user3\",", "ag_name = parse_resource_id(namespace.application_gateway)['name'] client.get(rg, ag_name) namespace.app_gateway_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\", "ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx)) def get_network_lb(cli_ctx, resource_group_name, lb_name):", "import list_sku_info if not namespace.location: get_default_location_from_resource_group(cmd, namespace) if zone_info: sku_infos = list_sku_info(cmd.cli_ctx, namespace.location)", "urn_match: namespace.os_publisher = urn_match.group(1) namespace.os_offer = urn_match.group(2) namespace.os_sku = urn_match.group(3) namespace.os_version = urn_match.group(4)", "resource_group, 'networkInterfaces', 'Microsoft.Network') def validate_vm_nic(cmd, namespace): namespace.nic = _get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name) def validate_vm_nics(cmd,", "be skipped\", namespace.image, ex.message) # pylint: disable=inconsistent-return-statements def _get_storage_profile_description(profile): if profile == StorageProfile.SACustomImage:", "and namespace.authentication_type == 'ssh': raise CLIError('SSH not supported for Windows VMs.') # validate", "_get_latest_image_version(cmd.cli_ctx, namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku) else: image_version = namespace.os_version image = compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher,", "namespace) if image_plan: namespace.plan_name = image_plan.name namespace.plan_product = image_plan.product namespace.plan_publisher = image_plan.publisher return", "= parse_resource_id(namespace.image) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) if res['type'].lower() == 'images': image_info = compute_client.images.get(res['resource_group'],", "and subnet '%s'\", namespace.vnet_name, namespace.subnet) return # 3 - create a new vnet/subnet", "namespace.image and not getattr(namespace, 'attach_os_disk', None): image_type = _parse_image_argument(cmd, namespace) if image_type ==", "CLIError(\"usage error: '--single-placement-group' should be turned off for zonal scale-sets or with\" \"", "check_existence(cmd.cli_ctx, namespace.public_ip_address, namespace.resource_group_name, 'Microsoft.Network', 'publicIPAddresses'): namespace.public_ip_address_type = 'existing' logger.debug(\"using existing specified public IP", "None: size = getattr(namespace, 'size', None) or getattr(namespace, 'vm_sku', None) size = size.lower()", "= [] if not nics_value: namespace.nic_type = 'new' logger.debug('new NIC will be created')", "logger.debug('no subnet specified. Attempting to find an existing Vnet and subnet...') # if", "namespace.os_offer, namespace.os_sku, image_version) # pylint: disable=no-member return image.plan except CloudError as ex: logger.warning(\"Querying", "def _check_subnet(s): if s.name.lower() == 'gatewaysubnet': return False subnet_mask = s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask,", "namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku) else: image_version = namespace.os_version image = compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher, namespace.os_offer,", "| \" \"--subnet SUBNET_NAME --vnet-name VNET_NAME\") subnet_exists = \\ check_existence(cmd.cli_ctx, subnet, rg, 'Microsoft.Network',", "CLIError(\"Subnet '{}' does not exist.\".format(subnet)) elif subnet_exists: # 2 - user specified existing", "'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3', 'Standard_D8s_v3'] new_4core_sizes = [x.lower() for x in new_4core_sizes] if", "general requirements, but is specifically disallowed for this image. Please try a different", "namespace.resource_group_name) if not check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute', 'availabilitySets'): raise CLIError(\"Availability set '{}' does", "namespace.nsg: namespace.nsg = _get_resource_id(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'networkSecurityGroups', 'Microsoft.Network') def _validate_vm_vmss_create_public_ip(cmd, namespace): if namespace.public_ip_address:", "logger.debug(\"suitable existing storage account '%s' will be used\", account.name) else: # 4 -", "namespace.os_publisher = matched['publisher'] namespace.os_offer = matched['offer'] namespace.os_sku = matched['sku'] namespace.os_version = matched['version'] return", "type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)), 'properties': { 'primary': nics_value[0] == n } }) namespace.nics = nics", "c, d = [int(x) for x in address.split('.')] result = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b, c,", "common scenario res_id = _get_resource_id(cmd.cli_ctx, namespace.source, namespace.resource_group_name, 'virtualMachines', 'Microsoft.Compute') res = parse_resource_id(res_id) compute_client", "{}'.format(balancer_type)) balancer = client.get(resource_group, balancer_name) values = [x.name for x in balancer.backend_address_pools] if", "namespace.resource_group_name) if check_existence(cmd.cli_ctx, storage_id['name'], rg, 'Microsoft.Storage', 'storageAccounts'): # 1 - existing storage account", "resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)), 'properties': { 'primary': nics_value[0] == n } }) namespace.nics", "logger.debug('new NSG will be created') def _validate_vmss_create_nsg(cmd, namespace): if namespace.nsg: namespace.nsg = _get_resource_id(cmd.cli_ctx,", "not isinstance(nics_value, list): nics_value = [nics_value] for n in nics_value: nics.append({ 'id': n", "_validate_admin_password(password, os_type): import re is_linux = (os_type.lower() == 'linux') max_length = 72 if", "is required for scale-sets with 100+ instances\" else: err = \"'Standard' load balancer", "CLIError(err.format(namespace.image, [x['urnAlias'] for x in images])) def _get_image_plan_info_if_exists(cmd, namespace): from msrestazure.azure_exceptions import CloudError", ">> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: raise CLIError(error_msg) # format back to the", "msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.commands.client_factory import get_subscription_id if is_valid_resource_id(val): return val kwargs", "not exposed yet for VMSS, so use 'getattr' to avoid crash namespace.disk_info =", "namespace.application_gateway == '': namespace.app_gateway_type = None logger.debug('no application gateway will be used') elif", "forbidden, description='network balancer: load balancer') if namespace.load_balancer: rg = parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name) lb_name =", "= \"'Standard' load balancer is required because 'single placement group' is turned off\"", "these out props_to_remove = ['attach_os_disk', 'storage_account'] for prop in props_to_remove: if prop in", "= 'new' logger.debug('new load balancer will be created') if namespace.load_balancer_type == 'new' and", "namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: required = ['os_type', 'attach_os_disk'] forbidden = ['os_disk_name', 'os_caching', 'storage_account', 'storage_container_name',", "file: %s', string_or_file) with open(string_or_file, 'r') as f: content = f.read() elif not", "with .' if re.findall(pattern, username): raise CLIError(linux_err if is_linux else win_err) if is_linux", "a.location == namespace.location), None) if account: # 3 - nothing specified - find", "in non-interactive mode.') # validate password _validate_admin_password(namespace.admin_password, namespace.os_type) elif namespace.authentication_type == 'ssh': if", "password in non-interactive mode.') # validate password _validate_admin_password(namespace.admin_password, namespace.os_type) elif namespace.authentication_type == 'ssh':", "from azure.cli.core.commands.client_factory import get_mgmt_service_client from azure.cli.core.profiles import ResourceType client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions role_id", "', '.join([n.name for n in lb.inbound_nat_pools]))) elif not lb.inbound_nat_pools: # Associated scaleset will", "'{}' meets the general requirements, but is specifically disallowed for this image. Please", "Linux, Debian \"Stretch\" with backports kernel # Oracle Linux 7.4, Windows Server 2016,", "# 4 - nothing specified - create a new storage account namespace.storage_account_type =", "a different value.\".format(username)) return username def _validate_admin_password(password, os_type): import re is_linux = (os_type.lower()", "created') # Public-IP SKU is only exposed for VM. VMSS has no such", "and namespace.vm_domain_name: raise CLIError('Usage error: --vm-domain-name can only be used when --public-ip-per-vm is", "return namespace.admin_username = _validate_admin_username(namespace.admin_username, namespace.os_type) if not namespace.os_type: raise CLIError(\"Unable to resolve OS", "get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts # find storage account in target resource group that matches the", "CLIError('An RSA key file or key value must be supplied to SSH Key", "= next( (a for a in storage_client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value == sku_tier and a.location", "image_version_info = sorted(image_version_infos, key=lambda x: x.publishing_profile.published_date)[-1] else: image_version_info = compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'],", "('coreos', 'coreos', None), ('credativ', 'debian', '-backports'), ('oracle', 'oracle-linux', '^7.4'), ('MicrosoftWindowsServer', 'WindowsServer', '^2016'), ('MicrosoftWindowsServer',", "ValueError('Admin password cannot be used with SSH authentication type') validate_ssh_key(namespace) if not namespace.ssh_dest_key_path:", "has no such needs so far if getattr(namespace, 'public_ip_sku', None): from azure.cli.core.profiles import", "'.private' content = keys.generate_ssh_keys(private_key_filepath, public_key_filepath) logger.warning(\"SSH key files '%s' and '%s' have been", "5 - check if an existing managed disk image resource compute_client = _compute_client_factory(cmd.cli_ctx)", "not namespace.ssh_dest_key_path: namespace.ssh_dest_key_path = \\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def _validate_admin_username(username, os_type): import re if not", "SKU if not provided and using an image based OS if not namespace.storage_sku", "= \"'Standard' load balancer is required for scale-sets with 100+ instances\" else: err", "get_subscription_id if namespace.availability_set: as_id = parse_resource_id(namespace.availability_set) name = as_id['name'] rg = as_id.get('resource_group', namespace.resource_group_name)", "NSG '%s' not found. It will be created.\", namespace.nsg) elif namespace.nsg == '':", "import load_images_from_aliases_doc images = load_images_from_aliases_doc(cmd.cli_ctx) matched = next((x for x in images if", "id role_defs = list(client.list(scope, \"roleName eq '{}'\".format(role))) if not role_defs: raise CLIError(\"Role '{}'", "will be created') def _validate_vmss_create_nsg(cmd, namespace): if namespace.nsg: namespace.nsg = _get_resource_id(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name,", "logger.debug(\"using specified existing load balancer '%s'\", namespace.load_balancer) else: namespace.load_balancer_type = 'new' logger.debug(\"load balancer", "'Secret is missing vaultCertificates array or it is empty at index {0} in", "EXIST_DISK --instance-id ID') def process_disk_or_snapshot_create_namespace(cmd, namespace): from msrestazure.azure_exceptions import CloudError validate_tags(namespace) if namespace.source:", "CLIError('Unrecognized storage profile: {}'.format(namespace.storage_profile)) logger.debug(\"storage profile '%s'\", namespace.storage_profile) if for_scale_set: # VMSS lacks", "'/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def _validate_admin_username(username, os_type): import re if not username: raise CLIError(\"admin user name", "VM. If using machines without \" \"permanent storage, back up your keys to", "id_comps['name'] == vault_name: return id_comps['resource_group'] return None def _get_resource_id(cli_ctx, val, resource_group, resource_type, resource_namespace):", "parse_resource_id(namespace.image) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) if res['type'].lower() == 'images': image_info = compute_client.images.get(res['resource_group'], res['name'])", "from VM, a most common scenario res_id = _get_resource_id(cmd.cli_ctx, namespace.source, namespace.resource_group_name, 'virtualMachines', 'Microsoft.Compute')", "be created') # Public-IP SKU is only exposed for VM. VMSS has no", "'vaults', 'Microsoft.KeyVault') def process_assign_identity_namespace(cmd, namespace): _validate_vm_vmss_msi(cmd, namespace, from_set_command=True) def process_remove_identity_namespace(cmd, namespace): if namespace.identities:", "nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg)) namespace.nics = nic_ids if hasattr(namespace, 'primary_nic') and namespace.primary_nic: namespace.primary_nic =", "nics_value: namespace.nic_type = 'new' logger.debug('new NIC will be created') return if not isinstance(nics_value,", "def _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False): from msrestazure.tools import is_valid_resource_id vnet = namespace.vnet_name subnet =", "'use_unmanaged_disk'] forbidden = ['attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SASpecializedOSDisk: required = ['os_type', 'attach_os_disk',", "'type': resource_type, 'subscription': get_subscription_id(cli_ctx) } missing_kwargs = {k: v for k, v in", "name '{}'. Please pick an id from '{}'\" raise CLIError(err.format(role, ids)) role_id =", "std_lb_is_available: balancer_type = 'loadBalancer' else: # needed for Stack profile 2017_03_09 balancer_type =", "namespace.plan_publisher = image_plan.publisher return 'urn' # 3 - unmanaged vhd based images? if", "try: loaded_secret = [validate_file_or_dict(secret) for secret in secrets] except Exception as err: raise", "= cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer and namespace.application_gateway: raise CLIError('incorrect usage: --load-balancer NAME_OR_ID |", "= namespace.os_version image = compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku, image_version) # pylint: disable=no-member return", "except CloudError: err = 'Invalid image \"{}\". Use a custom image name, id,", "return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2), int(candaidate_str[8:16], 2), int(candaidate_str[16:24], 2), int(candaidate_str[24:32], 2), new_mask) def _validate_vm_create_nsg(cmd, namespace):", "LBSkuName.standard.value logger.debug(\"use Standard sku as single placement group is turned off\") elif namespace.load_balancer_sku", "parse_resource_id from msrestazure.azure_exceptions import CloudError validate_tags(namespace) try: # try capturing from VM, a", "import parse_resource_id # use minimal parameters to resolve the expected storage profile if", "x in balancer.backend_address_pools] if len(values) > 1: raise CLIError(\"Multiple possible values found for", "_get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') def validate_vmss_disk(cmd, namespace): if namespace.disk: namespace.disk = _get_resource_id(cmd.cli_ctx,", "and namespace.application_gateway: raise CLIError('incorrect usage: --load-balancer NAME_OR_ID | ' '--application-gateway NAME_OR_ID') # Resolve", "namespace): namespace.disk_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') if namespace.key_encryption_keyvault: if not namespace.key_encryption_key:", "location_info property if not hasattr(temp, 'location_info'): return if not temp or not [x", "type='availabilitySets', name=name) logger.debug(\"adding to specified availability set '%s'\", namespace.availability_set) def _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False):", "logger.debug(\"adding to specified availability set '%s'\", namespace.availability_set) def _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False): from msrestazure.tools", "'None' if namespace.load_balancer is None and namespace.application_gateway is None: if std_lb_is_available: balancer_type =", "capturing \" \"images from virtual machines\") except CloudError: namespace.os_blob_uri, namespace.os_disk, namespace.os_snapshot = _figure_out_storage_source(cmd.cli_ctx,", "matched['publisher'] namespace.os_offer = matched['offer'] namespace.os_sku = matched['sku'] namespace.os_version = matched['version'] return 'urn' #", "# to refresh the list, run 'az vm create --accelerated-networking --size Standard_DS1_v2' and", "} }) namespace.nics = nics namespace.nic_type = 'existing' namespace.public_ip_address_type = None logger.debug('existing NIC(s)", "raise CLIError(\"incorrect '--subnet' usage: --subnet SUBNET_ID | \" \"--subnet SUBNET_NAME --vnet-name VNET_NAME\") subnet_exists", "--admin-password PASSWORD\") from knack.prompting import prompt_pass, NoTTYException try: if not namespace.admin_password: namespace.admin_password =", "'{}'. Please pick an id from '{}'\" raise CLIError(err.format(role, ids)) role_id = role_defs[0].id", "CloudError: info = compute_client.disks.get(resource_group_name, source) source_disk = info.id return (source_blob_uri, source_disk, source_snapshot) def", "name cannot contain special characters \\/\"[]:|<>+=;,?*@# or ends with .' if re.findall(pattern, username):", "raise CLIError(error_msg) candidate_int = _convert_to_int(subnet_ip_address, subnet_bit_mask_len) + 1 if (candidate_int >> (vnet_bit_mask_len -", "namespace.load_balancer) elif namespace.load_balancer == '': namespace.load_balancer_type = None logger.debug('no load balancer will be", "in client.list(): id_comps = parse_resource_id(vault.id) if id_comps['name'] == vault_name: return id_comps['resource_group'] return None", "def validate_vm_nic(cmd, namespace): namespace.nic = _get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name) def validate_vm_nics(cmd, namespace): rg =", "= 'existing' logger.debug(\"using existing specified public IP '%s'\", namespace.public_ip_address) else: namespace.public_ip_address_type = 'new'", "will be created') return if not isinstance(nics_value, list): nics_value = [nics_value] for n", "'az vm list-skus' can be \" \"used to find such locations\".format(namespace.resource_group_name)) # pylint:", "in images if x['urnAlias'].lower() == namespace.image.lower()), None) if matched: namespace.os_publisher = matched['publisher'] namespace.os_offer", "not supported for Windows VMs.') # validate proper arguments supplied based on the", "for i in range(24, 16, -1): if _subnet_capacity_check(i, namespace.instance_count, not namespace.disable_overprovision): break if", "def _get_storage_profile_description(profile): if profile == StorageProfile.SACustomImage: return 'create unmanaged OS disk created from", "False subnet_mask = s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask, namespace.instance_count, not namespace.disable_overprovision) result = next((s for", "can not be empty\") is_linux = (os_type.lower() == 'linux') # pylint: disable=line-too-long pattern", "is_linux else 123 min_length = 12 if len(password) not in range(min_length, max_length +", "id, or pick one from {}' raise CLIError(err.format(namespace.image, [x['urnAlias'] for x in images]))", "It will be created.\", namespace.application_gateway) elif namespace.application_gateway == '': namespace.app_gateway_type = None logger.debug('no", "CloudError network_client = get_network_client(cli_ctx) try: return network_client.load_balancers.get(resource_group_name, lb_name) except CloudError: return None def", "import _compute_client_factory from ._actions import _get_latest_image_version logger = get_logger(__name__) def validate_asg_names_or_ids(cmd, namespace): from", "= 'existing' logger.debug(\"existing vnet '%s' and subnet '%s' found\", namespace.vnet_name, namespace.subnet) return if", "in target resource group that matches the VM's location sku_tier = 'Premium' if", "_validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd, namespace) if namespace.license_type and namespace.os_type.lower() != 'windows': raise CLIError('usage error: --license-type", "# '2' are the reserved broadcasting addresses # '*1.5' so we have enough", "existing vnet and subnet in the target resource group client = get_network_client(cmd.cli_ctx).virtual_networks #", "namespace.primary_nic, rg) def _validate_secrets(secrets, os_type): \"\"\" Validates a parsed JSON array containing secrets", "in secrets] except Exception as err: raise CLIError('Error decoding secrets: {0}'.format(err)) for idx_arg,", "applicable when assign system identity\") # keep 'identity_role' for output as logical name", "resource_group_name, lb_name): from msrestazure.azure_exceptions import CloudError network_client = get_network_client(cli_ctx) try: return network_client.load_balancers.get(resource_group_name, lb_name)", "logger.debug('existing NIC(s) will be used') def _validate_vm_vmss_create_auth(namespace): if namespace.storage_profile in [StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]: return", "namespace): namespace.keyvault = _get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_vm_secret_format(cmd, namespace): from msrestazure.tools", "name or None :rtype: str \"\"\" from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import", "profile == StorageProfile.ManagedPirImage: return 'create managed OS disk from Azure Marketplace image' elif", "not image_version_infos: raise CLIError('There is no latest image version exists for \"{}\"'.format(namespace.image)) image_version_info", "- existing storage account specified namespace.storage_account_type = 'existing' logger.debug(\"using specified existing storage account", "created.\", namespace.public_ip_address) elif namespace.public_ip_address == '': namespace.public_ip_address_type = None logger.debug('no public IP address", "\"test2\", \"test3\", \"user4\", \"user5\"] if username.lower() in disallowed_user_names: raise CLIError(\"This user name '{}'", "namespace.os_type.lower() != 'windows': raise CLIError('usage error: --license-type is only applicable on Windows VM", "namespace.primary_nic: namespace.primary_nic = _get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg) def _validate_secrets(secrets, os_type): \"\"\" Validates a parsed", "'attach_data_disks', None): if not namespace.use_unmanaged_disk: namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name, 'disks', 'Microsoft.Compute') for", "sizes = compute_client.virtual_machine_sizes.list(namespace.location) size_info = next((s for s in sizes if s.name.lower() ==", "publisher, offer, sku = namespace.os_publisher, namespace.os_offer, namespace.os_sku if not publisher: return publisher, offer,", "= 32 - int(mask) vnet_int = _convert_to_int(vnet_ip_address, vnet_bit_mask_len) subnet_ip_address, mask = subnet_cidr.split('/') subnet_bit_mask_len", "SSH access to the VM. If using machines without \" \"permanent storage, back", "vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine = res_id if namespace.data_disk_sources: raise CLIError(\"'--data-disk-sources' is not allowed when capturing", "= r'admin user name cannot contain special characters \\/\"[]:|<>+=;,?*@# or ends with .'", "created') # AppGateway frontend required = [] if namespace.app_gateway_type == 'new': required.append('app_gateway_sku') required.append('app_gateway_capacity')", "namespace.nsg == '': namespace.nsg_type = None logger.debug('no NSG will be used') elif namespace.nsg", "validate password _validate_admin_password(namespace.admin_password, namespace.os_type) elif namespace.authentication_type == 'ssh': if namespace.admin_password: raise ValueError('Admin password", "= [] if namespace.data_disk_sources: for data_disk_source in namespace.data_disk_sources: source_blob_uri, source_disk, source_snapshot = _figure_out_storage_source(", "= [] try: loaded_secret = [validate_file_or_dict(secret) for secret in secrets] except Exception as", "else 'ssh' if namespace.os_type.lower() == 'windows' and namespace.authentication_type == 'ssh': raise CLIError('SSH not", "if namespace.os_type.lower() == 'windows' and namespace.authentication_type == 'ssh': raise CLIError('SSH not supported for", "if namespace.public_ip_sku == PublicIPAddressSkuName.standard.value: if not namespace.public_ip_address_allocation: namespace.public_ip_address_allocation = IPAllocationMethod.static.value def _validate_vmss_create_public_ip(cmd, namespace):", "next((x for x in images if x['urnAlias'].lower() == namespace.image.lower()), None) if matched: namespace.os_publisher", "namespace.vnet_type = 'new' logger.debug('no suitable subnet found. One will be created.') def _subnet_capacity_check(subnet_mask,", "or application gateway frontend.') namespace.public_ip_address = '' _validate_vm_vmss_create_public_ip(cmd, namespace) def _validate_vm_create_nics(cmd, namespace): from", "'Microsoft.Network', 'subnets', vnet, 'virtualNetworks') if subnet_is_id and not subnet_exists: raise CLIError(\"Subnet '{}' does", "readable setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role, namespace.identity_scope)) elif namespace.identity_scope or getattr(namespace.identity_role, 'is_default', None) is", "retrieve role id role_defs = list(client.list(scope, \"roleName eq '{}'\".format(role))) if not role_defs: raise", "r in role_defs] err = \"More than one role matches the given name", "2 - params for new storage account specified namespace.storage_account_type = 'new' logger.debug(\"specified storage", "namespace.availability_set: as_id = parse_resource_id(namespace.availability_set) name = as_id['name'] rg = as_id.get('resource_group', namespace.resource_group_name) if not", "-------------------------------------------------------------------------------------------- # pylint:disable=too-many-lines import os try: from urllib.parse import urlparse except ImportError: from", "image' elif profile == StorageProfile.ManagedSpecializedOSDisk: return 'attach existing managed OS disk' def _validate_managed_disk_sku(sku):", "err = \"More than one role matches the given name '{}'. Please pick", "ResourceType std_lb_is_available = cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer and namespace.application_gateway: raise CLIError('incorrect usage: --load-balancer", "(if any) being used balancer_type = 'None' if namespace.load_balancer is None and namespace.application_gateway", "in client.list(rg) if v.location == location and v.subnets): # 1 - find a", "'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested', 'Standard_D40_v3', 'Standard_D40s_v3', 'Standard_D15_v2_ABC', 'Standard_M64ms', 'Standard_M64s', 'Standard_M128-64ms', 'Standard_D64_v3', 'Standard_D64s_v3', 'Standard_E64_v3', 'Standard_E64s_v3', 'Standard_E64-16s_v3',", "or namespace.ssh_dest_key_path: raise ValueError( \"incorrect usage for authentication-type 'password': \" \"[--admin-username USERNAME] --admin-password", "namespace.use_unmanaged_disk: namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name, 'disks', 'Microsoft.Compute') for d in namespace.attach_data_disks] if", "# VMSS lacks some parameters, so scrub these out props_to_remove = ['attach_os_disk', 'storage_account']", "v.location == location and v.subnets): # 1 - find a suitable existing vnet/subnet", "= client.get(resource_group, balancer_name) values = [x.name for x in balancer.backend_address_pools] if len(values) >", "profile == StorageProfile.SAPirImage: return 'create unmanaged OS disk from Azure Marketplace image' elif", "'Standard_DS14_v2_Promo', 'Standard_F16', 'Standard_F16s', 'Standard_M64-32ms', 'Standard_M128-32ms', 'Standard_D32_v3', 'Standard_D32s_v3', 'Standard_D64-32s_v3', 'Standard_E32_v3', 'Standard_E32s_v3', 'Standard_E32-8s_v3', 'Standard_E32-16_v3', 'Standard_D5_v2_ABC',", "'urn': if namespace.use_unmanaged_disk: # STORAGE PROFILE #1 namespace.storage_profile = StorageProfile.SAPirImage else: # STORAGE", "disk from Azure Marketplace image' elif profile == StorageProfile.SASpecializedOSDisk: return 'attach to existing", "if 'windows' in namespace.os_offer.lower() else 'linux' from ._vm_utils import normalize_disk_info # attach_data_disks are", "'Standard_F64s_v2', 'Standard_F72s_v2', 'Standard_M128s', 'Standard_M128ms', 'Standard_L8s_v2', 'Standard_L16s_v2', 'Standard_L32s_v2', 'Standard_L64s_v2', 'Standard_L96s_v2', 'SQLGL', 'SQLGLCore', 'Standard_D4_v3', 'Standard_D4s_v3',", "namespace.resource_group_name, lb_name) if lb: namespace.load_balancer_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx,", "namespace.key_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_assign_identity_namespace(cmd, namespace): _validate_vm_vmss_msi(cmd, namespace, from_set_command=True) def process_remove_identity_namespace(cmd, namespace):", "'Standard_DS1_v2' else: namespace.vm_sku = 'Standard_D1_v2' _validate_location(cmd, namespace, namespace.zones, namespace.vm_sku) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace,", "= image_info.os_type.value gallery_image_version = res.get('child_name_2', '') if gallery_image_version.lower() in ['latest', '']: image_version_infos =", "prop in props_to_remove: if prop in required: required.remove(prop) if prop in forbidden: forbidden.remove(prop)", "_get_resource_group_from_vault_name(cli_ctx, vault_name): \"\"\" Fetch resource group from vault name :param str vault_name: name", "raise CLIError('Password must have the 3 of the following: 1 lower case character,", "namespace) _validate_vmss_create_nsg(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd, namespace) if namespace.license_type and namespace.os_type.lower() !=", "sourceVault key at index {0} in arg {1}'.format( idx, idx_arg)) if 'sourceVault' in", "'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC', 'Standard_F16_ABC', 'Standard_F32s_v2', 'Standard_D15_v2', 'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested', 'Standard_DS15_v2', 'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested', 'Standard_D40_v3', 'Standard_D40s_v3', 'Standard_D15_v2_ABC',", "content = keys.generate_ssh_keys(private_key_filepath, public_key_filepath) logger.warning(\"SSH key files '%s' and '%s' have been generated", "'getattr' to avoid crash namespace.disk_info = normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace, 'attach_data_disks', []), storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching,", "images? if urlparse(namespace.image).scheme: return 'uri' # 4 - attempt to match an URN", "(a for a in storage_client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value == sku_tier and a.location == namespace.location),", "if lb: namespace.load_balancer_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, lb_name,", "namespace.size) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace) if namespace.storage_profile in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd, namespace) _validate_vm_create_availability_set(cmd,", "= ['os_type', 'attach_os_disk'] forbidden = ['os_disk_name', 'os_caching', 'storage_account', 'storage_container_name', 'use_unmanaged_disk', 'storage_sku'] + auth_params", "too-many-statements def _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False): from msrestazure.tools import parse_resource_id # use minimal parameters", "\"sys\", \"test2\", \"test3\", \"user4\", \"user5\"] if username.lower() in disallowed_user_names: raise CLIError(\"This user name", "we have enough leeway for over-provision factor = 1.5 if over_provision else 1", "\"supported. Please use '--location' to specify a capable one. 'az vm list-skus' can", "offer, sku = namespace.os_publisher, namespace.os_offer, namespace.os_sku if not publisher: return publisher, offer, sku", "a fully-qualified ID (assumes it is an image ID) if is_valid_resource_id(namespace.image): return 'image_id'", "or not secret['vaultCertificates']: err = 'Secret is missing vaultCertificates array or it is", "if namespace.key_encryption_keyvault: if not namespace.key_encryption_key: raise CLIError(\"Incorrect usage '--key-encryption-keyvault': \" \"'--key-encryption-key' is required\")", "or (not subnet_is_id and not vnet): raise CLIError(\"incorrect '--subnet' usage: --subnet SUBNET_ID |", "between {} and {}'.format(min_length, max_length)) contains_lower = re.findall('[a-z]+', password) contains_upper = re.findall('[A-Z]+', password)", "keys.generate_ssh_keys(private_key_filepath, public_key_filepath) logger.warning(\"SSH key files '%s' and '%s' have been generated under ~/.ssh", "snapshot, image validators def validate_vm_disk(cmd, namespace): namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute')", "validate_keyvault(cmd, namespace) else: if kv and not is_valid_resource_id(kv): raise keyvault_usage def _get_resource_group_from_vault_name(cli_ctx, vault_name):", "> vnet_int: # overflows? candidate_int = candidate_int - 2 # try the other", "property if not hasattr(temp, 'location_info'): return if not temp or not [x for", "i in range(len(namespace.identities)): if namespace.identities[i] != MSI_LOCAL_ID: namespace.identities[i] = _get_resource_id(cmd.cli_ctx, namespace.identities[i], namespace.resource_group_name, 'userAssignedIdentities',", "if account: # 3 - nothing specified - find viable storage account in", "id from '{}'\" raise CLIError(err.format(role, ids)) role_id = role_defs[0].id return role_id def process_vm_create_namespace(cmd,", "balancer_type = 'loadBalancer' elif namespace.application_gateway: balancer_type = 'applicationGateway' if balancer_type == 'applicationGateway': if", "= urn_match.group(2) namespace.os_sku = urn_match.group(3) namespace.os_version = urn_match.group(4) if not any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]):", "== namespace.image.lower()), None) if matched: namespace.os_publisher = matched['publisher'] namespace.os_offer = matched['offer'] namespace.os_sku =", "if namespace.accelerated_networking is None: size = getattr(namespace, 'size', None) or getattr(namespace, 'vm_sku', None)", "def process_assign_identity_namespace(cmd, namespace): _validate_vm_vmss_msi(cmd, namespace, from_set_command=True) def process_remove_identity_namespace(cmd, namespace): if namespace.identities: from ._vm_utils", "\"Stretch\" with backports kernel # Oracle Linux 7.4, Windows Server 2016, Windows Server", "role id role_defs = list(client.list(scope, \"roleName eq '{}'\".format(role))) if not role_defs: raise CLIError(\"Role", "uri? source_blob_uri = source elif '/disks/' in source.lower(): source_disk = source elif '/snapshots/'", "StorageProfile.ManagedSpecializedOSDisk: required = ['os_type', 'attach_os_disk'] forbidden = ['os_disk_name', 'os_caching', 'storage_account', 'storage_container_name', 'use_unmanaged_disk', 'storage_sku']", "if image_plan: namespace.plan_name = image_plan.name namespace.plan_product = image_plan.product namespace.plan_publisher = image_plan.publisher return 'urn'", "dict secrets: Dict fitting the JSON description above :param string os_type: the type", "is missing vaultCertificates array or it is empty at index {0} in '", "'authentication_type', 'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value'] # perform parameter validation for the specific storage profile", "usage: --subnet SUBNET_ID | \" \"--subnet SUBNET_NAME --vnet-name VNET_NAME\") subnet_exists = \\ check_existence(cmd.cli_ctx,", "= \\ check_existence(cmd.cli_ctx, subnet, rg, 'Microsoft.Network', 'subnets', vnet, 'virtualNetworks') if subnet_is_id and not", "user name can not be empty\") is_linux = (os_type.lower() == 'linux') # pylint:", "will be created.\", namespace.load_balancer) elif namespace.load_balancer == '': namespace.load_balancer_type = None logger.debug('no load", "parts = t.split('=', 1) if len(parts) == 1: regions_info.append(TargetRegion(name=parts[0])) else: try: replica_count =", "and (o is None or o.lower() == offer) and (s is None or", "'UltraSSD_LRS'] if sku and sku.lower() not in [x.lower() for x in allowed_skus]: raise", "logger.debug(\"W/o STD LB, defaulting to '%s' under because single placement group is disabled\",", "forbidden: forbidden.remove(prop) # set default storage SKU if not provided and using an", "if namespace.application_gateway: client = get_network_client(cmd.cli_ctx).application_gateways try: rg = parse_resource_id(namespace.application_gateway).get( 'resource_group', namespace.resource_group_name) ag_name =", "subnet in the target resource group client = get_network_client(cmd.cli_ctx).virtual_networks # find VNET in", "attempt to match an URN alias (most likely) from azure.cli.command_modules.vm._actions import load_images_from_aliases_doc images", "'%s' not found and will be created\", storage_id['name']) else: from azure.cli.core.profiles import ResourceType", "subnet_exists = \\ check_existence(cmd.cli_ctx, subnet, rg, 'Microsoft.Network', 'subnets', vnet, 'virtualNetworks') if subnet_is_id and", "have enough leeway for over-provision factor = 1.5 if over_provision else 1 return", "re.findall('[A-Z]+', password) contains_digit = re.findall('[0-9]+', password) contains_special_char = re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password) count =", "_validate_vm_create_nics(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) if namespace.secrets: _validate_secrets(namespace.secrets, namespace.os_type) if namespace.license_type and namespace.os_type.lower()", "public_key_filepath = string_or_file if public_key_filepath[-4:].lower() == '.pub': private_key_filepath = public_key_filepath[:-4] else: private_key_filepath =", "None if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role, re.I): role_id = role else: try: uuid.UUID(role) role_id =", "MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------------------------------", "subnet for vnet_match in (v for v in client.list(rg) if v.location == location", "n in lb.inbound_nat_pools]))) elif not lb.inbound_nat_pools: # Associated scaleset will be missing ssh/rdp,", "network_client.load_balancers.get(resource_group_name, lb_name) except CloudError: return None def process_vmss_create_namespace(cmd, namespace): validate_tags(namespace) if namespace.vm_sku is", "and namespace.zones is None: raise CLIError('usage error: --platform-fault-domain-count COUNT --zones ZONES') if namespace.zones", "\"please specify '--os-type OS_TYPE'\") def _figure_out_storage_source(cli_ctx, resource_group_name, source): from msrestazure.azure_exceptions import CloudError source_blob_uri", "namespace.application_gateway is None: namespace.app_gateway_type = 'new' logger.debug('new application gateway will be created') #", "balancer: application gateway') elif balancer_type == 'loadBalancer': # LoadBalancer frontend required = []", "ssh for Linux) by examining the OS type namespace.authentication_type = 'password' \\ if", "== StorageProfile.SACustomImage: return 'create unmanaged OS disk created from generalized VHD' elif profile", "lb_name) except CloudError: return None def process_vmss_create_namespace(cmd, namespace): validate_tags(namespace) if namespace.vm_sku is None:", "are the reserved broadcasting addresses # '*1.5' so we have enough leeway for", "required for scale-sets with 100+ instances\" else: err = \"'Standard' load balancer is", "API version of 2017-12-01') if namespace.identity_scope: if identities and MSI_LOCAL_ID not in identities:", "if not namespace.authentication_type: # apply default auth type (password for Windows, ssh for", "OS_TYPE'\") def _figure_out_storage_source(cli_ctx, resource_group_name, source): from msrestazure.azure_exceptions import CloudError source_blob_uri = None source_disk", "namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') # TODO move to its own command module https://github.com/Azure/azure-cli/issues/5105 def", "'Standard_F8', 'Standard_F8s', 'Standard_M64-16ms', 'Standard_D16_v3', 'Standard_D16s_v3', 'Standard_D32-16s_v3', 'Standard_D64-16s_v3', 'Standard_E16_v3', 'Standard_E16s_v3', 'Standard_E32-16s_v3', 'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC', 'Standard_F8_ABC',", "= _get_image_plan_info_if_exists(cmd, namespace) if image_plan: namespace.plan_name = image_plan.name namespace.plan_product = image_plan.product namespace.plan_publisher =", "- subnet_bit_mask_len)) > vnet_int: # overflows? candidate_int = candidate_int - 2 # try", "_validate_vm_vmss_accelerated_networking(cli_ctx, namespace): if namespace.accelerated_networking is None: size = getattr(namespace, 'size', None) or getattr(namespace,", "is_linux = (os_type.lower() == 'linux') # pylint: disable=line-too-long pattern = (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if is_linux", "vault_name): \"\"\" Fetch resource group from vault name :param str vault_name: name of", "namespace.load_balancer_type is None and namespace.app_gateway_type is None: if namespace.public_ip_address: raise CLIError('--public-ip-address can only", "subnet_bit_mask_len) + 1 if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: # overflows?", "user name cannot contain special characters \\/\"[]:|<>+=;,?*@# or ends with .' if re.findall(pattern,", "elif namespace.storage_profile == StorageProfile.SASpecializedOSDisk: required = ['os_type', 'attach_os_disk', 'use_unmanaged_disk'] forbidden = ['os_disk_name', 'os_caching',", "vnet) or (not subnet_is_id and not vnet): raise CLIError(\"incorrect '--subnet' usage: --subnet SUBNET_ID", "== location and v.subnets): # 1 - find a suitable existing vnet/subnet result", "'': namespace.load_balancer_type = None logger.debug('no load balancer will be used') elif namespace.load_balancer is", "_validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace) _validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd, namespace) _validate_vmss_create_nsg(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd, namespace)", "namespace.app_gateway_type is None: if namespace.public_ip_address: raise CLIError('--public-ip-address can only be used when creating", "= [] namespace.data_snapshots = [] if namespace.data_disk_sources: for data_disk_source in namespace.data_disk_sources: source_blob_uri, source_disk,", "raise CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix = '{}/{}'.format(cidr, i) if namespace.app_gateway_type and namespace.app_gateway_subnet_address_prefix is None: namespace.app_gateway_subnet_address_prefix", "namespace.public_ip_address: raise CLIError('--public-ip-address can only be used when creating a new load '", "getattr(get_network_client(cli_ctx), balancer_type, None) if not client: raise CLIError('unrecognized balancer type: {}'.format(balancer_type)) balancer =", "from azure.cli.command_modules.vm._template_builder import StorageProfile import azure.cli.core.keys as keys from ._client_factory import _compute_client_factory from", "_parse_image_argument(cmd, namespace) if image_type == 'uri': # STORAGE PROFILE #2 namespace.storage_profile = StorageProfile.SACustomImage", "attach_data_disks are not exposed yet for VMSS, so use 'getattr' to avoid crash", "namespace.resource_group_name, 'virtualMachines', 'Microsoft.Compute') res = parse_resource_id(res_id) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) vm_info = compute_client.virtual_machines.get(res['resource_group'],", "source): from msrestazure.azure_exceptions import CloudError source_blob_uri = None source_disk = None source_snapshot =", "not namespace.admin_password: namespace.admin_password = prompt_pass('Admin Password: ', confirm=True) except NoTTYException: raise CLIError('Please specify", "--vm-domain-name can only be used when --public-ip-per-vm is enabled') if namespace.eviction_policy and not", "d) return int(result[:-bit_mask_len], 2) error_msg = \"usage error: --subnet-address-prefix value should be a", "elif res['type'].lower() == 'galleries': image_info = compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) namespace.os_type = image_info.os_type.value gallery_image_version", "if a fully-qualified ID (assumes it is an image ID) if is_valid_resource_id(namespace.image): return", "storage account namespace.storage_account_type = 'new' logger.debug('no suitable storage account found. One will be", "['Standard_D3_v2', 'Standard_D12_v2', 'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo', 'Standard_DS3_v2', 'Standard_DS12_v2', 'Standard_DS13-4_v2', 'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo', 'Standard_F4',", "(most likely) from azure.cli.command_modules.vm._actions import load_images_from_aliases_doc images = load_images_from_aliases_doc(cmd.cli_ctx) matched = next((x for", "candidate_int - 2 # try the other way around if (candidate_int >> (vnet_bit_mask_len", "VMs need to be a supported image in the marketplace # Ubuntu 16.04,", "'/' in n else resource_id(name=n, resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)), 'properties': { 'primary': nics_value[0]", "(password for Windows, ssh for Linux) by examining the OS type namespace.authentication_type =", "namespace.resource_group_name, 'networkSecurityGroups', 'Microsoft.Network') def _validate_vm_vmss_create_public_ip(cmd, namespace): if namespace.public_ip_address: if check_existence(cmd.cli_ctx, namespace.public_ip_address, namespace.resource_group_name, 'Microsoft.Network',", "'AZAP_Performance_ComputeV17C'] aval_sizes = [x.lower() for x in aval_sizes] if size not in aval_sizes:", "validate_vm_nic(cmd, namespace): namespace.nic = _get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name) def validate_vm_nics(cmd, namespace): rg = namespace.resource_group_name", "== '.pub': private_key_filepath = public_key_filepath[:-4] else: private_key_filepath = public_key_filepath + '.private' content =", "NoTTYException: raise CLIError('Please specify password in non-interactive mode.') # validate password _validate_admin_password(namespace.admin_password, namespace.os_type)", "namespace.generate_ssh_keys: # figure out appropriate file names: # 'base_name'(with private keys), and 'base_name.pub'(with", "key file or key value must be supplied to SSH Key Value. '", "if not missing_kwargs else None def _get_nic_id(cli_ctx, val, resource_group): return _get_resource_id(cli_ctx, val, resource_group,", "_get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name) def validate_vm_nics(cmd, namespace): rg = namespace.resource_group_name nic_ids = [] for", "if 'sourceVault' not in secret: errors.append( 'Secret is missing sourceVault key at index", "x in image_version_infos if not x.publishing_profile.exclude_from_latest] if not image_version_infos: raise CLIError('There is no", "get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions role_id = None if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role, re.I): role_id = role else:", "None) if size_info is None or size_info.number_of_cores < 8: return # VMs need", "'Standard_M128-64ms', 'Standard_D64_v3', 'Standard_D64s_v3', 'Standard_E64_v3', 'Standard_E64s_v3', 'Standard_E64-16s_v3', 'Standard_E64-32s_v3', 'Standard_F64s_v2', 'Standard_F72s_v2', 'Standard_M128s', 'Standard_M128ms', 'Standard_L8s_v2', 'Standard_L16s_v2',", "--instance-id ID') def process_disk_or_snapshot_create_namespace(cmd, namespace): from msrestazure.azure_exceptions import CloudError validate_tags(namespace) if namespace.source: usage_error", "VM Creation Secrets JSON structure [{ \"sourceVault\": { \"id\": \"value\" }, \"vaultCertificates\": [{", "= namespace.subnet rg = namespace.resource_group_name location = namespace.location nics = getattr(namespace, 'nics', None)", "info.id return (source_blob_uri, source_disk, source_snapshot) def process_disk_encryption_namespace(cmd, namespace): namespace.disk_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault, namespace.resource_group_name,", "size_info = next((s for s in sizes if s.name.lower() == size), None) if", "when capturing \" \"images from virtual machines\") except CloudError: namespace.os_blob_uri, namespace.os_disk, namespace.os_snapshot =", "extract vnet information needed to verify the defaults we are coming out vnet_ip_address,", "1 - check if a fully-qualified ID (assumes it is an image ID)", "namespace.storage_sku = 'Standard_LRS' if for_scale_set else 'Premium_LRS' if namespace.storage_sku == 'UltraSSD_LRS' and namespace.ultra_ssd_enabled", "elif namespace.load_balancer_sku == LBSkuName.basic.value: if namespace.zones: err = \"'Standard' load balancer is required", "= getattr(namespace, 'size', None) or getattr(namespace, 'vm_sku', None) size = size.lower() # to", "address will be used') elif namespace.public_ip_address is None: namespace.public_ip_address_type = 'new' logger.debug('new public", "forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: required = ['os_type', 'attach_os_disk'] forbidden = ['os_disk_name',", "cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if getattr(namespace, 'attach_data_disks', None): if not namespace.use_unmanaged_disk: namespace.attach_data_disks", "namespace.disable_overprovision): break if i < 16: err = \"instance count '{}' is out", "be created.\", namespace.nsg) elif namespace.nsg == '': namespace.nsg_type = None logger.debug('no NSG will", "GB') elif bool(namespace.disk) != bool(namespace.instance_id): raise CLIError('usage error: --disk EXIST_DISK --instance-id ID') def", "from knack.util import CLIError from azure.cli.core.commands.validators import ( get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set, validate_tags) from", "_validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) if namespace.secrets: _validate_secrets(namespace.secrets, namespace.os_type) if namespace.license_type and namespace.os_type.lower() != 'windows':", "namespace.data_disk_sources: source_blob_uri, source_disk, source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, data_disk_source) if source_blob_uri: namespace.data_blob_uris.append(source_blob_uri) if", "namespace.os_type.lower() == 'windows' and namespace.authentication_type == 'ssh': raise CLIError('SSH not supported for Windows", "secret or not secret['vaultCertificates']: err = 'Secret is missing vaultCertificates array or it", "\"user\", \"user1\", \"test\", \"user2\", \"test1\", \"user3\", \"admin1\", \"1\", \"123\", \"a\", \"actuser\", \"adm\", \"admin2\",", "# Associated scaleset will be missing ssh/rdp, so warn here. logger.warning(\"No inbound nat", "subnet_cidr.split('/') subnet_bit_mask_len = 32 - int(mask) if vnet_bit_mask_len <= subnet_bit_mask_len: raise CLIError(error_msg) candidate_int", "namespace.load_balancer is None and namespace.application_gateway is None: if std_lb_is_available: balancer_type = 'loadBalancer' else:", "is only applicable when assign system identity\") # keep 'identity_role' for output as", "namespace.application_gateway: balancer_type = 'applicationGateway' if balancer_type == 'applicationGateway': if namespace.application_gateway: client = get_network_client(cmd.cli_ctx).application_gateways", "if is_linux and re.findall(r'^[$-]+', username): raise CLIError(linux_err) if not is_linux and username.endswith('.'): raise", "import azure.cli.core.keys as keys from ._client_factory import _compute_client_factory from ._actions import _get_latest_image_version logger", "CLIError(usage_error) def process_image_create_namespace(cmd, namespace): from msrestazure.tools import parse_resource_id from msrestazure.azure_exceptions import CloudError validate_tags(namespace)", "information needed to verify the defaults we are coming out vnet_ip_address, mask =", "= None if not for_scale_set: result = next((s for s in vnet_match.subnets if", "off\") elif namespace.load_balancer_sku == LBSkuName.basic.value: if namespace.zones: err = \"'Standard' load balancer is", "\"--subnet SUBNET_NAME --vnet-name VNET_NAME\") subnet_exists = \\ check_existence(cmd.cli_ctx, subnet, rg, 'Microsoft.Network', 'subnets', vnet,", "not keys.is_valid_ssh_rsa_public_key(content): if namespace.generate_ssh_keys: # figure out appropriate file names: # 'base_name'(with private", "machines\") except CloudError: namespace.os_blob_uri, namespace.os_disk, namespace.os_snapshot = _figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name, namespace.source) # pylint: disable=line-too-long", "_validate_vm_create_nsg(cmd, namespace) _validate_vm_vmss_create_public_ip(cmd, namespace) _validate_vm_create_nics(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) if namespace.secrets: _validate_secrets(namespace.secrets, namespace.os_type)", "_get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr, new_mask): def _convert_to_int(address, bit_mask_len): a, b, c, d = [int(x) for", "'%s' found\", namespace.vnet_name, namespace.subnet) return if subnet: subnet_is_id = is_valid_resource_id(subnet) if (subnet_is_id and", "raise CLIError('There is no latest image version exists for \"{}\"'.format(namespace.image)) image_version_info = sorted(image_version_infos,", "namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id nics_value = namespace.nics nics", "in secret['sourceVault']: errors.append( 'Secret is missing sourceVault.id key at index {0} in arg", "return 'create unmanaged OS disk created from generalized VHD' elif profile == StorageProfile.SAPirImage:", "at index {0} in ' \\ 'arg {1} ' errors.append(err.format(idx, idx_arg)) else: for", "_validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: required = ['os_type', 'attach_os_disk'] forbidden = ['os_disk_name', 'os_caching',", "else: # STORAGE PROFILE #4 namespace.storage_profile = StorageProfile.ManagedPirImage else: raise CLIError('Unrecognized image type:", "= (os_type.lower() == 'linux') # pylint: disable=line-too-long pattern = (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if is_linux else", "role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id, role) except ValueError: pass if not role_id: # retrieve", "so scrub these out props_to_remove = ['attach_os_disk', 'storage_account'] for prop in props_to_remove: if", "> vnet_int: raise CLIError(error_msg) # format back to the cidr candaidate_str = '{0:32b}'.format(candidate_int", "disallowed for this image. Please try a different value.\".format(username)) return username def _validate_admin_password(password,", "= [] if names_or_ids == [\"\"] or not names_or_ids: return for val in", "# try the other way around if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) >", "ssh/rdp, so warn here. logger.warning(\"No inbound nat pool was configured on '%s'\", namespace.load_balancer)", "namespace.storage_profile == StorageProfile.ManagedPirImage: required = ['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk']", "if username.lower() in disallowed_user_names: raise CLIError(\"This user name '{}' meets the general requirements,", "idx, idx_arg)) if 'sourceVault' in secret and 'id' not in secret['sourceVault']: errors.append( 'Secret", "CLIError('There is no latest image version exists for \"{}\"'.format(namespace.image)) image_version_info = sorted(image_version_infos, key=lambda", "image ID) if is_valid_resource_id(namespace.image): return 'image_id' # 2 - attempt to match an", "CLIError('Unrecognized image type: {}'.format(image_type)) else: # did not specify image XOR attach-os-disk raise", "= [] for n in namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg)) namespace.nics = nic_ids if", "be used to create the VM/VMSS because availablity zone is not yet \"", "'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo', 'Standard_DS3_v2', 'Standard_DS12_v2', 'Standard_DS13-4_v2', 'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo', 'Standard_F4', 'Standard_F4s', 'Standard_D8_v3',", "msrestazure.tools import parse_resource_id from msrestazure.azure_exceptions import CloudError validate_tags(namespace) try: # try capturing from", "user specified existing vnet/subnet namespace.vnet_type = 'existing' logger.debug(\"using specified vnet '%s' and subnet", "the cidr candaidate_str = '{0:32b}'.format(candidate_int << subnet_bit_mask_len) return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2), int(candaidate_str[8:16], 2), int(candaidate_str[16:24],", "Server 2012R2 publisher, offer, sku = namespace.os_publisher, namespace.os_offer, namespace.os_sku if not publisher: return", "in enumerate(secret['vaultCertificates']): message = 'Secret is missing {0} within vaultCertificates array at secret", "re if not username: raise CLIError(\"admin user name can not be empty\") is_linux", "for '{0}': {1}\\nSpecify '{0}' \" \"explicitly.\".format(option_name, ', '.join(values))) elif not values: raise CLIError(\"No", "type (password for Windows, ssh for Linux) by examining the OS type namespace.authentication_type", "can only be used when --public-ip-per-vm is enabled') if namespace.eviction_policy and not namespace.priority:", "namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if bool(namespace.disk) == bool(namespace.size_gb): raise CLIError('usage", "custom image name, id, or pick one from {}' raise CLIError(err.format(namespace.image, [x['urnAlias'] for", "StorageProfile import azure.cli.core.keys as keys from ._client_factory import _compute_client_factory from ._actions import _get_latest_image_version", "idx, jdx, idx_arg)) if is_windows and 'certificateStore' not in cert: errors.append(message.format('certificateStore', idx, jdx,", "find VNET in target resource group that matches the VM's location with a", "namespace.disk_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') if namespace.key_encryption_keyvault: if not namespace.key_encryption_key: raise", "if source_blob_uri: namespace.data_blob_uris.append(source_blob_uri) if source_disk: namespace.data_disks.append(source_disk) if source_snapshot: namespace.data_snapshots.append(source_snapshot) if not namespace.os_type: raise", "import _get_latest_image_version logger = get_logger(__name__) def validate_asg_names_or_ids(cmd, namespace): from msrestazure.tools import resource_id, is_valid_resource_id", "[] for t in namespace.target_regions: parts = t.split('=', 1) if len(parts) == 1:", "elif profile == StorageProfile.ManagedPirImage: return 'create managed OS disk from Azure Marketplace image'", "account = next( (a for a in storage_client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value == sku_tier and", "a most common scenario res_id = _get_resource_id(cmd.cli_ctx, namespace.source, namespace.resource_group_name, 'virtualMachines', 'Microsoft.Compute') res =", "contain upper case character A-Z, special characters \\/\"[]:|<>+=;,?*@#()! or start with $ or", "not kv or is_valid_resource_id(kv): raise keyvault_usage validate_keyvault(cmd, namespace) else: if kv and not", "- int(mask) if vnet_bit_mask_len <= subnet_bit_mask_len: raise CLIError(error_msg) candidate_int = _convert_to_int(subnet_ip_address, subnet_bit_mask_len) +", "for i, _ in enumerate(identities): if identities[i] != MSI_LOCAL_ID: identities[i] = _get_resource_id(cmd.cli_ctx, identities[i],", "return 'urn' # 3 - unmanaged vhd based images? if urlparse(namespace.image).scheme: return 'uri'", "not username: raise CLIError(\"admin user name can not be empty\") is_linux = (os_type.lower()", "resource_id from azure.cli.core.commands.client_factory import get_subscription_id nics_value = namespace.nics nics = [] if not", "specified existing application gateway '%s'\", namespace.application_gateway) except CloudError: namespace.app_gateway_type = 'new' logger.debug(\"application gateway", "= sorted(image_version_infos, key=lambda x: x.publishing_profile.published_date)[-1] else: image_version_info = compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2'])", "'^7.4'), ('openlogic', 'centos', '^7.4'), ('coreos', 'coreos', None), ('credativ', 'debian', '-backports'), ('oracle', 'oracle-linux', '^7.4'),", "StorageProfile.ManagedPirImage: required = ['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if for_scale_set:", "if s.name.lower() != 'gatewaysubnet'), None) else: def _check_subnet(s): if s.name.lower() == 'gatewaysubnet': return", "not nics_value: namespace.nic_type = 'new' logger.debug('new NIC will be created') return if not", "x.zones]: raise CLIError(\"{}'s location can't be used to create the VM/VMSS because availablity", "\"{}\"'.format(namespace.image)) # pylint: disable=no-member elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: # accept disk name or", "' \\ 'arg {1} ' errors.append(err.format(idx, idx_arg)) else: for jdx, cert in enumerate(secret['vaultCertificates']):", "# attach_data_disks are not exposed yet for VMSS, so use 'getattr' to avoid", "matches the VM's location sku_tier = 'Premium' if 'Premium' in namespace.storage_sku else 'Standard'", "else: namespace.vm_sku = 'Standard_D1_v2' _validate_location(cmd, namespace, namespace.zones, namespace.vm_sku) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=True)", "logger.debug(\"existing vnet '%s' and subnet '%s' found\", namespace.vnet_name, namespace.subnet) return if subnet: subnet_is_id", "return int(result[:-bit_mask_len], 2) error_msg = \"usage error: --subnet-address-prefix value should be a subrange", "client.list(): id_comps = parse_resource_id(vault.id) if id_comps['name'] == vault_name: return id_comps['resource_group'] return None def", "'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC', 'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4', 'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3',", "azure.cli.core.commands.client_factory import get_subscription_id vm_id = resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name = namespace.network_security_group_name", "prop in required: required.remove(prop) if prop in forbidden: forbidden.remove(prop) # set default storage", "factor) def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace): if namespace.accelerated_networking is None: size = getattr(namespace, 'size', None)", "2016, Windows Server 2012R2 publisher, offer, sku = namespace.os_publisher, namespace.os_offer, namespace.os_sku if not", "_validate_vm_vmss_create_public_ip(cmd, namespace) def _validate_vm_create_nics(cmd, namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id", "namespace.instance_count > 100: err = \"'Standard' load balancer is required for scale-sets with", "except NoTTYException: raise CLIError('Please specify password in non-interactive mode.') # validate password _validate_admin_password(namespace.admin_password,", "# 1 - check if a fully-qualified ID (assumes it is an image", "not in cert: errors.append(message.format('certificateStore', idx, jdx, idx_arg)) if errors: raise CLIError('\\n'.join(errors)) # region", "CLIError(\"incorrect '--subnet' usage: --subnet SUBNET_ID | \" \"--subnet SUBNET_NAME --vnet-name VNET_NAME\") subnet_exists =", "logger.debug(\"application gateway '%s' not found. It will be created.\", namespace.application_gateway) elif namespace.application_gateway ==", "get_logger(__name__) def validate_asg_names_or_ids(cmd, namespace): from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.profiles import ResourceType", "resource_type, 'subscription': get_subscription_id(cli_ctx) } missing_kwargs = {k: v for k, v in kwargs.items()", "def _validate_vm_vmss_create_auth(namespace): if namespace.storage_profile in [StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]: return namespace.admin_username = _validate_admin_username(namespace.admin_username, namespace.os_type) if", "vnet '%s' and subnet '%s' found\", namespace.vnet_name, namespace.subnet) return if subnet: subnet_is_id =", "the type of balancer (if any) being used balancer_type = 'None' if namespace.load_balancer", "Validators def _get_default_address_pool(cli_ctx, resource_group, balancer_name, balancer_type): option_name = '--backend-pool-name' client = getattr(get_network_client(cli_ctx), balancer_type,", "try: return network_client.load_balancers.get(resource_group_name, lb_name) except CloudError: return None def process_vmss_create_namespace(cmd, namespace): validate_tags(namespace) if", "resolve the expected storage profile if getattr(namespace, 'attach_os_disk', None) and not namespace.image: if", "required.append('app_gateway_subnet_address_prefix') elif namespace.app_gateway_type == 'existing': required.append('backend_pool_name') forbidden = ['nat_pool_name', 'load_balancer', 'health_probe'] validate_parameter_set(namespace, required,", "resource compute_client = _compute_client_factory(cmd.cli_ctx) try: compute_client.images.get(namespace.resource_group_name, namespace.image) namespace.image = _get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name, 'images',", "namespace.application_gateway is None: if std_lb_is_available: balancer_type = 'loadBalancer' else: # needed for Stack", "a, b, c, d = [int(x) for x in address.split('.')] result = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a,", "= 'new' logger.debug('new application gateway will be created') # AppGateway frontend required =", "msrestazure.azure_exceptions import CloudError network_client = get_network_client(cli_ctx) try: return network_client.load_balancers.get(resource_group_name, lb_name) except CloudError: return", "publisher: return publisher, offer, sku = publisher.lower(), offer.lower(), sku.lower() distros = [('canonical', 'UbuntuServer',", "application gateway') elif balancer_type == 'loadBalancer': # LoadBalancer frontend required = [] forbidden", "24) def _get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr, new_mask): def _convert_to_int(address, bit_mask_len): a, b, c, d =", "image_info = compute_client.images.get(res['resource_group'], res['name']) namespace.os_type = image_info.storage_profile.os_disk.os_type.value image_data_disks_num = len(image_info.storage_profile.data_disks or []) elif", "only be used when creating a new load ' 'balancer or application gateway", "be created') # AppGateway frontend required = [] if namespace.app_gateway_type == 'new': required.append('app_gateway_sku')", "will be used') elif namespace.load_balancer is None: namespace.load_balancer_type = 'new' logger.debug('new load balancer", "resource_id from azure.cli.core.commands.client_factory import get_subscription_id if namespace.availability_set: as_id = parse_resource_id(namespace.availability_set) name = as_id['name']", "bool(namespace.instance_id): raise CLIError('usage error: --disk EXIST_DISK --instance-id ID') def process_disk_or_snapshot_create_namespace(cmd, namespace): from msrestazure.azure_exceptions", "gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2']) image_data_disks_num = len(image_version_info.storage_profile.data_disk_images or []) else: raise CLIError('usage error: unrecognized image", "knack.prompting import prompt_pass, NoTTYException try: if not namespace.admin_password: namespace.admin_password = prompt_pass('Admin Password: ',", "case character, 1 upper case character, 1 number and 1 special character') def", "in source.lower(): source_disk = source elif '/snapshots/' in source.lower(): source_snapshot = source else:", "the marketplace # Ubuntu 16.04, SLES 12 SP3, RHEL 7.4, CentOS 7.4, CoreOS", "names: # 'base_name'(with private keys), and 'base_name.pub'(with public keys) public_key_filepath = string_or_file if", "name is more readable setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role, namespace.identity_scope)) elif namespace.identity_scope or getattr(namespace.identity_role,", "== size), None) if size_info is None or size_info.number_of_cores < 8: return #", "type: {}'.format(image_type)) else: # did not specify image XOR attach-os-disk raise CLIError('incorrect usage:", "load_images_from_aliases_doc images = load_images_from_aliases_doc(cmd.cli_ctx) matched = next((x for x in images if x['urnAlias'].lower()", "not be empty\") is_linux = (os_type.lower() == 'linux') # pylint: disable=line-too-long pattern =", "None: namespace.load_balancer_type = 'new' logger.debug('new load balancer will be created') if namespace.load_balancer_type ==", "VHD_BLOB_URI [--source-storage-account-id ID]' try: namespace.source_blob_uri, namespace.source_disk, namespace.source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, namespace.source) if", "Server 2016, Windows Server 2012R2 publisher, offer, sku = namespace.os_publisher, namespace.os_offer, namespace.os_sku if", "list): nics_value = [nics_value] for n in nics_value: nics.append({ 'id': n if '/'", "namespace.resource_group_name location = namespace.location nics = getattr(namespace, 'nics', None) if not vnet and", "marketplace # Ubuntu 16.04, SLES 12 SP3, RHEL 7.4, CentOS 7.4, CoreOS Linux,", "<= subnet_bit_mask_len: raise CLIError(error_msg) candidate_int = _convert_to_int(subnet_ip_address, subnet_bit_mask_len) + 1 if (candidate_int >>", "cert: errors.append(message.format('certificateUrl', idx, jdx, idx_arg)) if is_windows and 'certificateStore' not in cert: errors.append(message.format('certificateStore',", "re.findall('[0-9]+', password) contains_special_char = re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password) count = len([x for x in", "process_disk_encryption_namespace(cmd, namespace): namespace.disk_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') if namespace.key_encryption_keyvault: if not", "to refresh the list, run 'az vm create --accelerated-networking --size Standard_DS1_v2' and #", "zonal scale-sets\" elif namespace.instance_count > 100: err = \"'Standard' load balancer is required", "\\/\"[]:|<>+=;,?*@# or ends with .' if re.findall(pattern, username): raise CLIError(linux_err if is_linux else", "getattr(namespace, 'attach_os_disk', None): image_type = _parse_image_argument(cmd, namespace) if image_type == 'uri': # STORAGE", "def _parse_image_argument(cmd, namespace): \"\"\" Systematically determines what type is supplied for the --image", "namespace.identity_scope and getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError(\"usage error: '--role {}' is", "at index {0} in arg {1}'.format( idx, idx_arg)) if 'vaultCertificates' not in secret", "None: raise CLIError(\"usage error: '--role {}' is not applicable as the '--scope' is", "namespace.app_gateway_subnet_address_prefix = _get_next_subnet_addr_suffix( namespace.vnet_address_prefix, namespace.subnet_address_prefix, 24) def _get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr, new_mask): def _convert_to_int(address, bit_mask_len):", "'networkInterfaces', 'Microsoft.Network') def validate_vm_nic(cmd, namespace): namespace.nic = _get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name) def validate_vm_nics(cmd, namespace):", "x.publishing_profile.published_date)[-1] else: image_version_info = compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2']) image_data_disks_num = len(image_version_info.storage_profile.data_disk_images or", "namespace.single_placement_group: raise CLIError(\"usage error: '--single-placement-group' should be turned off for zonal scale-sets or", "raise CLIError('Usage error: --priority PRIORITY [--eviction-policy POLICY]') # endregion # region disk, snapshot,", "namespace.source_storage_account_id: raise CLIError(usage_error) except CloudError: raise CLIError(usage_error) def process_image_create_namespace(cmd, namespace): from msrestazure.tools import", "'identity_role' for output as logical name is more readable setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role,", "namespace.image: if namespace.use_unmanaged_disk: # STORAGE PROFILE #3 namespace.storage_profile = StorageProfile.SASpecializedOSDisk else: # STORAGE", "compute_client.images.get(res['resource_group'], res['name']) namespace.os_type = image_info.storage_profile.os_disk.os_type.value image_data_disks_num = len(image_info.storage_profile.data_disks or []) elif res['type'].lower() ==", "or None :rtype: str \"\"\" from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client", "find viable storage account in target resource group namespace.storage_account = account.name namespace.storage_account_type =", "re.findall(pattern, username): raise CLIError(linux_err if is_linux else win_err) if is_linux and re.findall(r'^[$-]+', username):", "reserved. # Licensed under the MIT License. See License.txt in the project root", "from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_subscription_id ApplicationSecurityGroup = cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK) resource_group", "'existing' namespace.public_ip_address_type = None logger.debug('existing NIC(s) will be used') def _validate_vm_vmss_create_auth(namespace): if namespace.storage_profile", "namespace.resource_group_name, namespace.source) if not namespace.source_blob_uri and namespace.source_storage_account_id: raise CLIError(usage_error) except CloudError: raise CLIError(usage_error)", "storage account '%s' will be used\", account.name) else: # 4 - nothing specified", "'%s'\", namespace.load_balancer) else: namespace.load_balancer_type = 'new' logger.debug(\"load balancer '%s' not found. It will", "1)[0] i = 0 for i in range(24, 16, -1): if _subnet_capacity_check(i, namespace.instance_count,", "an image based OS if not namespace.storage_sku and namespace.storage_profile in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]: #", "namespace.public_ip_address: if check_existence(cmd.cli_ctx, namespace.public_ip_address, namespace.resource_group_name, 'Microsoft.Network', 'publicIPAddresses'): namespace.public_ip_address_type = 'existing' logger.debug(\"using existing specified", "resource_id from azure.cli.core.commands.client_factory import get_subscription_id vm_id = resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name", "resource_id(name=n, resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)), 'properties': { 'primary': nics_value[0] == n } })", "type. Specify '--os-type' argument.\") if not namespace.authentication_type: # apply default auth type (password", "if len(values) > 1: raise CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify '{0}'", "disable=line-too-long namespace.storage_sku = 'Standard_LRS' if for_scale_set else 'Premium_LRS' if namespace.storage_sku == 'UltraSSD_LRS' and", "and username.endswith('.'): raise CLIError(win_err) disallowed_user_names = [ \"administrator\", \"admin\", \"user\", \"user1\", \"test\", \"user2\",", "if len(parts) == 1: regions_info.append(TargetRegion(name=parts[0])) else: try: replica_count = int(parts[1]) except ValueError: raise", "_get_next_subnet_addr_suffix( namespace.vnet_address_prefix, namespace.subnet_address_prefix, 24) def _get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr, new_mask): def _convert_to_int(address, bit_mask_len): a, b,", "= lb.inbound_nat_pools[0].name logger.debug(\"using specified existing load balancer '%s'\", namespace.load_balancer) else: namespace.load_balancer_type = 'new'", "'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedCustomImage: required = ['image']", "possible values found for '{0}': {1}\\nSpecify '{0}' \" \"explicitly.\".format(option_name, ', '.join(values))) elif not", "os_type): import re if not username: raise CLIError(\"admin user name can not be", "namespace.vnet_address_prefix.split('/', 1)[0] i = 0 for i in range(24, 16, -1): if _subnet_capacity_check(i,", "azure.cli.command_modules.vm._actions import load_images_from_aliases_doc images = load_images_from_aliases_doc(cmd.cli_ctx) matched = next((x for x in images", "None def _get_resource_id(cli_ctx, val, resource_group, resource_type, resource_namespace): from msrestazure.tools import resource_id, is_valid_resource_id from", "return val kwargs = { 'name': val, 'resource_group': resource_group, 'namespace': resource_namespace, 'type': resource_type,", "[{ \"certificateUrl\": \"value\", \"certificateStore\": \"cert store name (only on windows)\" }] }] :param", "JSON description above :param string os_type: the type of OS (linux or windows)", "namespace): from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import", "StorageProfile.ManagedCustomImage: return 'create managed OS disk from custom image' elif profile == StorageProfile.ManagedPirImage:", "_resolve_role_id(cmd.cli_ctx, namespace.identity_role, namespace.identity_scope)) elif namespace.identity_scope or getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError('usage", "a in storage_client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value == sku_tier and a.location == namespace.location), None) if", "your keys to a safe location.\", private_key_filepath, public_key_filepath) else: raise CLIError('An RSA key", "parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name) lb_name = parse_resource_id(namespace.load_balancer)['name'] lb = get_network_lb(cmd.cli_ctx, namespace.resource_group_name, lb_name) if lb: namespace.load_balancer_type", "own command module https://github.com/Azure/azure-cli/issues/5105 def process_msi_namespace(cmd, namespace): get_default_location_from_resource_group(cmd, namespace) validate_tags(namespace) def process_gallery_image_version_namespace(cmd, namespace):", "and not subnet and not nics: logger.debug('no subnet specified. Attempting to find an", "7.4, CentOS 7.4, CoreOS Linux, Debian \"Stretch\" with backports kernel # Oracle Linux", "is None: namespace.app_gateway_subnet_address_prefix = _get_next_subnet_addr_suffix( namespace.vnet_address_prefix, namespace.subnet_address_prefix, 24) def _get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr, new_mask): def", "'Standard_D3_v2_ABC', 'Standard_DS3_v2', 'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC', 'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4', 'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3',", "the JSON description above :param string os_type: the type of OS (linux or", "subnet '%s' found\", namespace.vnet_name, namespace.subnet) return if subnet: subnet_is_id = is_valid_resource_id(subnet) if (subnet_is_id", "and re.findall(r'^[$-]+', username): raise CLIError(linux_err) if not is_linux and username.endswith('.'): raise CLIError(win_err) disallowed_user_names", "'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: required =", "\"test3\", \"user4\", \"user5\"] if username.lower() in disallowed_user_names: raise CLIError(\"This user name '{}' meets", "specified namespace.storage_account_type = 'existing' logger.debug(\"using specified existing storage account '%s'\", storage_id['name']) else: #", "be \" \"used to find such locations\".format(namespace.resource_group_name)) # pylint: disable=too-many-branches, too-many-statements def _validate_vm_create_storage_profile(cmd,", "CLIError('The password length must be between {} and {}'.format(min_length, max_length)) contains_lower = re.findall('[a-z]+',", "_subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision): mask = int(subnet_mask) # '2' are the reserved broadcasting addresses", "exist.\".format(role)) elif len(role_defs) > 1: ids = [r.id for r in role_defs] err", "'resource_group', namespace.resource_group_name) ag_name = parse_resource_id(namespace.application_gateway)['name'] client.get(rg, ag_name) namespace.app_gateway_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name", "_validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=True) _validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace) _validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd, namespace) _validate_vmss_create_nsg(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace)", "subnet '%s'\", namespace.vnet_name, namespace.subnet) return # 3 - create a new vnet/subnet namespace.vnet_type", "None) is None: raise CLIError('usage error: --assign-identity [--scope SCOPE] [--role ROLE]') def _resolve_role_id(cli_ctx,", "namespace.source: usage_error = 'usage error: --source {SNAPSHOT | DISK} | --source VHD_BLOB_URI [--source-storage-account-id", "lb_name, 'load_balancers') if not namespace.nat_pool_name: if len(lb.inbound_nat_pools) > 1: raise CLIError(\"Multiple possible values", "doesn't implement location_info property if not hasattr(temp, 'location_info'): return if not temp or", "'Standard_M128ms', 'Standard_L8s_v2', 'Standard_L16s_v2', 'Standard_L32s_v2', 'Standard_L64s_v2', 'Standard_L96s_v2', 'SQLGL', 'SQLGLCore', 'Standard_D4_v3', 'Standard_D4s_v3', 'Standard_D2_v2', 'Standard_DS2_v2', 'Standard_E4_v3',", "found for '{0}': {1}\\nSpecify '{0}' \" \"explicitly.\".format(option_name, ', '.join(values))) elif not values: raise", "'public_ip_sku', None): from azure.cli.core.profiles import ResourceType PublicIPAddressSkuName, IPAllocationMethod = cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK) if", "namespace.identity_role, namespace.identity_scope)) elif namespace.identity_scope or getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError('usage error:", "_get_resource_id(cli_ctx, val, resource_group, 'networkInterfaces', 'Microsoft.Network') def validate_vm_nic(cmd, namespace): namespace.nic = _get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name)", "= _get_next_subnet_addr_suffix( namespace.vnet_address_prefix, namespace.subnet_address_prefix, 24) def _get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr, new_mask): def _convert_to_int(address, bit_mask_len): a,", "'sourceVault' in secret and 'id' not in secret['sourceVault']: errors.append( 'Secret is missing sourceVault.id", "access to the VM. If using machines without \" \"permanent storage, back up", "namespace.resource_group_name, 'disks', 'Microsoft.Compute') def validate_vmss_disk(cmd, namespace): if namespace.disk: namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name,", "some parameters, so scrub these out props_to_remove = ['attach_os_disk', 'storage_account'] for prop in", "t.split('=', 1) if len(parts) == 1: regions_info.append(TargetRegion(name=parts[0])) else: try: replica_count = int(parts[1]) except", "\"roleName eq '{}'\".format(role))) if not role_defs: raise CLIError(\"Role '{}' doesn't exist.\".format(role)) elif len(role_defs)", "get_network_lb(cmd.cli_ctx, namespace.resource_group_name, lb_name) if lb: namespace.load_balancer_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\", "None) else: def _check_subnet(s): if s.name.lower() == 'gatewaysubnet': return False subnet_mask = s.address_prefix.split('/')[-1]", "is_windows = os_type == 'windows' errors = [] try: loaded_secret = [validate_file_or_dict(secret) for", "in vnet_match.subnets if _check_subnet(s)), None) if not result: continue namespace.subnet = result.name namespace.vnet_name", "'Standard_D8_v3', 'Standard_D8s_v3'] new_4core_sizes = [x.lower() for x in new_4core_sizes] if size not in", "Now verify that the status of required and forbidden parameters validate_parameter_set( namespace, required,", "subnet_bit_mask_len)) > vnet_int: # overflows? candidate_int = candidate_int - 2 # try the", "a new load ' 'balancer or application gateway frontend.') namespace.public_ip_address = '' _validate_vm_vmss_create_public_ip(cmd,", "from msrestazure.tools import is_valid_resource_id vnet = namespace.vnet_name subnet = namespace.subnet rg = namespace.resource_group_name", "PROFILE #3 namespace.storage_profile = StorageProfile.SASpecializedOSDisk else: # STORAGE PROFILE #6 namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk", "the defaults we are coming out vnet_ip_address, mask = vnet_cidr.split('/') vnet_bit_mask_len = 32", "'applicationGateway': if namespace.application_gateway: client = get_network_client(cmd.cli_ctx).application_gateways try: rg = parse_resource_id(namespace.application_gateway).get( 'resource_group', namespace.resource_group_name) ag_name", "--disk EXIST_DISK --instance-id ID | --size-gb GB') elif bool(namespace.disk) != bool(namespace.instance_id): raise CLIError('usage", "= _get_resource_id(cmd.cli_ctx, namespace.source, namespace.resource_group_name, 'virtualMachines', 'Microsoft.Compute') res = parse_resource_id(res_id) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription'])", "source_disk, source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, data_disk_source) if source_blob_uri: namespace.data_blob_uris.append(source_blob_uri) if source_disk: namespace.data_disks.append(source_disk)", "source_blob_uri: namespace.data_blob_uris.append(source_blob_uri) if source_disk: namespace.data_disks.append(source_disk) if source_snapshot: namespace.data_snapshots.append(source_snapshot) if not namespace.os_type: raise CLIError(\"usage", "= (os_type.lower() == 'linux') max_length = 72 if is_linux else 123 min_length =", "from custom image' elif profile == StorageProfile.ManagedPirImage: return 'create managed OS disk from", "on Windows VM') _validate_vm_vmss_msi(cmd, namespace) if namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage = get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage) # endregion", "= t.split('=', 1) if len(parts) == 1: regions_info.append(TargetRegion(name=parts[0])) else: try: replica_count = int(parts[1])", "'uri': # STORAGE PROFILE #2 namespace.storage_profile = StorageProfile.SACustomImage elif image_type == 'image_id': #", "in namespace.target_regions: parts = t.split('=', 1) if len(parts) == 1: regions_info.append(TargetRegion(name=parts[0])) else: try:", "(compute - 2017-03-30), Resource_sku doesn't implement location_info property if not hasattr(temp, 'location_info'): return", "logger.debug(\"using existing specified public IP '%s'\", namespace.public_ip_address) else: namespace.public_ip_address_type = 'new' logger.debug(\"specified public", "validate_vm_nics(cmd, namespace): rg = namespace.resource_group_name nic_ids = [] for n in namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx,", "public key file: %s', string_or_file) with open(string_or_file, 'r') as f: content = f.read()", "{2} in arg {3}' if 'certificateUrl' not in cert: errors.append(message.format('certificateUrl', idx, jdx, idx_arg))", "'properties': { 'primary': nics_value[0] == n } }) namespace.nics = nics namespace.nic_type =", "False elif namespace.single_placement_group: raise CLIError(\"usage error: '--single-placement-group' should be turned off for zonal", "namespace) if namespace.license_type and namespace.os_type.lower() != 'windows': raise CLIError('usage error: --license-type is only", "resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg, namespace='Microsoft.Compute', type='availabilitySets', name=name) logger.debug(\"adding to specified availability set '%s'\", namespace.availability_set)", "the required/forbidden parameters for VM if namespace.storage_profile == StorageProfile.ManagedPirImage: required = ['image'] forbidden", "from msrestazure.tools import parse_resource_id # use minimal parameters to resolve the expected storage", "use minimal parameters to resolve the expected storage profile if getattr(namespace, 'attach_os_disk', None)", "= ['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2', 'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC', 'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4',", "images if x['urnAlias'].lower() == namespace.image.lower()), None) if matched: namespace.os_publisher = matched['publisher'] namespace.os_offer =", "username: raise CLIError(\"admin user name can not be empty\") is_linux = (os_type.lower() ==", "values: raise CLIError(\"No existing values found for '{0}'. Create one first and try", "\"'--key-encryption-key' is required\") namespace.key_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_assign_identity_namespace(cmd, namespace):", "validate_parameter_set(namespace, required, forbidden, description='network balancer: load balancer') if namespace.load_balancer: rg = parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name)", "d in namespace.attach_data_disks] if not namespace.os_type: namespace.os_type = 'windows' if 'windows' in namespace.os_offer.lower()", "= namespace.vnet_address_prefix.split('/', 1)[0] i = 0 for i in range(24, 16, -1): if", "x.name.lower() == size_info.lower()), None) # For Stack (compute - 2017-03-30), Resource_sku doesn't implement", "azure.cli.core.profiles import ResourceType std_lb_is_available = cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer and namespace.application_gateway: raise CLIError('incorrect", "'images': image_info = compute_client.images.get(res['resource_group'], res['name']) namespace.os_type = image_info.storage_profile.os_disk.os_type.value image_data_disks_num = len(image_info.storage_profile.data_disks or [])", "decoding secrets: {0}'.format(err)) for idx_arg, narg_secret in enumerate(loaded_secret): for idx, secret in enumerate(narg_secret):", "when creating a new load ' 'balancer or application gateway frontend.') namespace.public_ip_address =", "if not namespace.public_ip_per_vm and namespace.vm_domain_name: raise CLIError('Usage error: --vm-domain-name can only be used", "Oracle Linux 7.4, Windows Server 2016, Windows Server 2012R2 publisher, offer, sku =", "= namespace.nics nics = [] if not nics_value: namespace.nic_type = 'new' logger.debug('new NIC", "and namespace.primary_nic: namespace.primary_nic = _get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg) def _validate_secrets(secrets, os_type): \"\"\" Validates a", "for '{0}': {1}\\nSpecify '{0}' explicitly.\".format( # pylint: disable=line-too-long '--nat-pool-name', ', '.join([n.name for n", "import ResourceType PublicIPAddressSkuName, IPAllocationMethod = cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK) if namespace.public_ip_sku == PublicIPAddressSkuName.standard.value: if", "\"sql\", \"support\", \"support_388945a0\", \"sys\", \"test2\", \"test3\", \"user4\", \"user5\"] if username.lower() in disallowed_user_names: raise", "you') namespace.ssh_key_value = content def _validate_vm_vmss_msi(cmd, namespace, from_set_command=False): if from_set_command or namespace.assign_identity is", "gateway will be used') elif namespace.application_gateway is None: namespace.app_gateway_type = 'new' logger.debug('new application", "'Standard_DS3_v2', 'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC', 'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4', 'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3',", "license information. # -------------------------------------------------------------------------------------------- # pylint:disable=too-many-lines import os try: from urllib.parse import urlparse", "from Azure Marketplace image' elif profile == StorageProfile.SASpecializedOSDisk: return 'attach to existing unmanaged", "'storage_container_name', 'use_unmanaged_disk', 'storage_sku'] + auth_params _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.SAPirImage: required = ['image',", "in address.split('.')] result = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b, c, d) return int(result[:-bit_mask_len], 2) error_msg =", "os.path.exists(string_or_file): logger.info('Use existing SSH public key file: %s', string_or_file) with open(string_or_file, 'r') as", "# 2 - params for new storage account specified namespace.storage_account_type = 'new' logger.debug(\"specified", "character') def validate_ssh_key(namespace): string_or_file = (namespace.ssh_key_value or os.path.join(os.path.expanduser('~'), '.ssh', 'id_rsa.pub')) content = string_or_file", "if len(password) not in range(min_length, max_length + 1): raise CLIError('The password length must", "get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage) # endregion # region VMSS Create Validators def _get_default_address_pool(cli_ctx, resource_group, balancer_name,", "elif namespace.instance_count > 100: err = \"'Standard' load balancer is required for scale-sets", "is not allowed when capturing \" \"images from virtual machines\") except CloudError: namespace.os_blob_uri,", "or not names_or_ids: return for val in names_or_ids: if not is_valid_resource_id(val): val =", "\"\"\" Systematically determines what type is supplied for the --image parameter. Updates the", "in new_4core_sizes: compute_client = _compute_client_factory(cli_ctx) sizes = compute_client.virtual_machine_sizes.list(namespace.location) size_info = next((s for s", "the 3 of the following: 1 lower case character, 1 upper case character,", "try: uuid.UUID(role) role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id, role) except ValueError: pass if not role_id:", "ids)) role_id = role_defs[0].id return role_id def process_vm_create_namespace(cmd, namespace): validate_tags(namespace) _validate_location(cmd, namespace, namespace.zone,", "as the '--scope' is not provided\".format( namespace.identity_role)) user_assigned_identities = [x for x in", "if namespace.load_balancer_type == 'new' and namespace.single_placement_group is False and std_lb_is_available: LBSkuName = cmd.get_models('LoadBalancerSkuName',", "'Standard_L64s_v2', 'Standard_L96s_v2', 'SQLGL', 'SQLGLCore', 'Standard_D4_v3', 'Standard_D4s_v3', 'Standard_D2_v2', 'Standard_DS2_v2', 'Standard_E4_v3', 'Standard_E4s_v3', 'Standard_F2', 'Standard_F2s', 'Standard_F4s_v2',", "Password: ', confirm=True) except NoTTYException: raise CLIError('Please specify password in non-interactive mode.') #", "and subnet in the target resource group client = get_network_client(cmd.cli_ctx).virtual_networks # find VNET", "'.ssh', 'id_rsa.pub')) content = string_or_file if os.path.exists(string_or_file): logger.info('Use existing SSH public key file:", "is required\") namespace.key_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_assign_identity_namespace(cmd, namespace): _validate_vm_vmss_msi(cmd,", "\" \"supported. Please use '--location' to specify a capable one. 'az vm list-skus'", "'%s'\", namespace.vnet_name, namespace.subnet) return # 3 - create a new vnet/subnet namespace.vnet_type =", "_get_resource_id(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'networkSecurityGroups', 'Microsoft.Network') def _validate_vm_vmss_create_public_ip(cmd, namespace): if namespace.public_ip_address: if check_existence(cmd.cli_ctx, namespace.public_ip_address,", "'new' logger.debug('no suitable subnet found. One will be created.') def _subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision):", "gallery_name=res['name'], gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2']) image_data_disks_num = len(image_version_info.storage_profile.data_disk_images or []) else: raise CLIError('usage error: unrecognized", "_figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name, namespace.source) # pylint: disable=line-too-long namespace.data_blob_uris = [] namespace.data_disks = [] namespace.data_snapshots", "NSG will be created') def _validate_vmss_create_nsg(cmd, namespace): if namespace.nsg: namespace.nsg = _get_resource_id(cmd.cli_ctx, namespace.nsg,", "cannot contain special characters \\/\"[]:|<>+=;,?*@# or ends with .' if re.findall(pattern, username): raise", "['nat_pool_name', 'load_balancer', 'health_probe'] validate_parameter_set(namespace, required, forbidden, description='network balancer: application gateway') elif balancer_type ==", "_validate_vmss_create_subnet(namespace): if namespace.vnet_type == 'new': if namespace.subnet_address_prefix is None: cidr = namespace.vnet_address_prefix.split('/', 1)[0]", "for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: required = ['os_type', 'attach_os_disk'] forbidden =", "the VM's location with a matching subnet for vnet_match in (v for v", "latest image version exists for \"{}\"'.format(namespace.image)) image_version_info = sorted(image_version_infos, key=lambda x: x.publishing_profile.published_date)[-1] else:", "an URN alias (most likely) from azure.cli.command_modules.vm._actions import load_images_from_aliases_doc images = load_images_from_aliases_doc(cmd.cli_ctx) matched", "= cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK) resource_group = namespace.resource_group_name subscription_id = get_subscription_id(cmd.cli_ctx) names_or_ids = getattr(namespace, 'application_security_groups')", "secret and 'id' not in secret['sourceVault']: errors.append( 'Secret is missing sourceVault.id key at", "'attach existing managed OS disk' def _validate_managed_disk_sku(sku): allowed_skus = ['Premium_LRS', 'Standard_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS']", "\"\"\" from msrestazure.tools import is_valid_resource_id from msrestazure.azure_exceptions import CloudError import re # 1", "= namespace.resource_group_name location = namespace.location nics = getattr(namespace, 'nics', None) if not vnet", "('oracle', 'oracle-linux', '^7.4'), ('MicrosoftWindowsServer', 'WindowsServer', '^2016'), ('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')] import re for p,", "'SQLGL', 'SQLGLCore', 'Standard_D4_v3', 'Standard_D4s_v3', 'Standard_D2_v2', 'Standard_DS2_v2', 'Standard_E4_v3', 'Standard_E4s_v3', 'Standard_F2', 'Standard_F2s', 'Standard_F4s_v2', 'Standard_D11_v2', 'Standard_DS11_v2',", "--subnet-address-prefix value should be a subrange of --vnet-address-prefix's\" # extract vnet information needed", "windows)\" }] }] :param dict secrets: Dict fitting the JSON description above :param", "msrestazure.tools import parse_resource_id, resource_id from azure.cli.core.commands.client_factory import get_subscription_id if namespace.availability_set: as_id = parse_resource_id(namespace.availability_set)", "have been generated under ~/.ssh to \" \"allow SSH access to the VM.", "1: raise CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify '{0}' \" \"explicitly.\".format(option_name, ',", "description='network balancer: load balancer') if namespace.load_balancer: rg = parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name) lb_name = parse_resource_id(namespace.load_balancer)['name']", "+ 1 if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: # overflows? candidate_int", "_validate_admin_password(namespace.admin_password, namespace.os_type) elif namespace.authentication_type == 'ssh': if namespace.admin_password: raise ValueError('Admin password cannot be", "'ssh_dest_key_path', 'ssh_key_value'] # perform parameter validation for the specific storage profile # start", "try \" \"again.\".format(option_name)) return values[0] def _validate_vmss_single_placement_group(namespace): if namespace.platform_fault_domain_count is not None and", "namespace.load_balancer) else: namespace.nat_pool_name = lb.inbound_nat_pools[0].name logger.debug(\"using specified existing load balancer '%s'\", namespace.load_balancer) else:", "for subsequent processing. \"\"\" from msrestazure.tools import is_valid_resource_id from msrestazure.azure_exceptions import CloudError import", "from msrestazure.azure_exceptions import CloudError validate_tags(namespace) if namespace.source: usage_error = 'usage error: --source {SNAPSHOT", "image name, id, or pick one from {}' raise CLIError(err.format(namespace.image, [x['urnAlias'] for x", "= None logger.debug('existing NIC(s) will be used') def _validate_vm_vmss_create_auth(namespace): if namespace.storage_profile in [StorageProfile.ManagedSpecializedOSDisk,", "over-provision factor = 1.5 if over_provision else 1 return ((1 << (32 -", "in target resource group namespace.storage_account = account.name namespace.storage_account_type = 'existing' logger.debug(\"suitable existing storage", "'--subnet' usage: --subnet SUBNET_ID | \" \"--subnet SUBNET_NAME --vnet-name VNET_NAME\") subnet_exists = \\", "parse_resource_id(vault.id) if id_comps['name'] == vault_name: return id_comps['resource_group'] return None def _get_resource_id(cli_ctx, val, resource_group,", "'urn' # 3 - unmanaged vhd based images? if urlparse(namespace.image).scheme: return 'uri' #", "namespace) def _validate_vm_create_nics(cmd, namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id nics_value", "namespace.data_disk_sources: for data_disk_source in namespace.data_disk_sources: source_blob_uri, source_disk, source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, data_disk_source)", "['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk:", "--source VHD_BLOB_URI [--source-storage-account-id ID]' try: namespace.source_blob_uri, namespace.source_disk, namespace.source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, namespace.source)", "client: raise CLIError('unrecognized balancer type: {}'.format(balancer_type)) balancer = client.get(resource_group, balancer_name) values = [x.name", "'new': if namespace.subnet_address_prefix is None: cidr = namespace.vnet_address_prefix.split('/', 1)[0] i = 0 for", "return 'attach to existing unmanaged OS disk' elif profile == StorageProfile.ManagedCustomImage: return 'create", "is None: raise CLIError('usage error: --assign-identity [--scope SCOPE] [--role ROLE]') def _resolve_role_id(cli_ctx, role,", "def _validate_secrets(secrets, os_type): \"\"\" Validates a parsed JSON array containing secrets for use", "errors: raise CLIError('\\n'.join(errors)) # region VM Create Validators def _parse_image_argument(cmd, namespace): \"\"\" Systematically", "not namespace.identity_scope and getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError(\"usage error: '--role {}'", "['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif", "= 'new' logger.debug(\"application gateway '%s' not found. It will be created.\", namespace.application_gateway) elif", "parse_resource_id(namespace.application_gateway)['name'] client.get(rg, ag_name) namespace.app_gateway_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg,", "else: compute_client = _compute_client_factory(cli_ctx) # pylint: disable=no-member try: info = compute_client.snapshots.get(resource_group_name, source) source_snapshot", "namespace.data_blob_uris = [] namespace.data_disks = [] namespace.data_snapshots = [] if namespace.data_disk_sources: for data_disk_source", "CloudError try: compute_client = _compute_client_factory(cmd.cli_ctx) if namespace.os_version.lower() == 'latest': image_version = _get_latest_image_version(cmd.cli_ctx, namespace.location,", "set '{}' does not exist.\".format(name)) namespace.availability_set = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg, namespace='Microsoft.Compute', type='availabilitySets', name=name)", "NIC will be created') return if not isinstance(nics_value, list): nics_value = [nics_value] for", "prompt_pass, NoTTYException try: if not namespace.admin_password: namespace.admin_password = prompt_pass('Admin Password: ', confirm=True) except", "= [] for t in namespace.target_regions: parts = t.split('=', 1) if len(parts) ==", "from msrestazure.tools import parse_resource_id if namespace.storage_account: storage_id = parse_resource_id(namespace.storage_account) rg = storage_id.get('resource_group', namespace.resource_group_name)", "created\", storage_id['name']) else: from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client storage_client =", "= subnet_cidr.split('/') subnet_bit_mask_len = 32 - int(mask) if vnet_bit_mask_len <= subnet_bit_mask_len: raise CLIError(error_msg)", "= '' _validate_vm_vmss_create_public_ip(cmd, namespace) def _validate_vm_create_nics(cmd, namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory", "namespace.nics = nics namespace.nic_type = 'existing' namespace.public_ip_address_type = None logger.debug('existing NIC(s) will be", "with $ or -' win_err = r'admin user name cannot contain special characters", "vnet_ip_address, mask = vnet_cidr.split('/') vnet_bit_mask_len = 32 - int(mask) vnet_int = _convert_to_int(vnet_ip_address, vnet_bit_mask_len)", "CLIError('Password must have the 3 of the following: 1 lower case character, 1", "in range(24, 16, -1): if _subnet_capacity_check(i, namespace.instance_count, not namespace.disable_overprovision): break if i <", "MSI_LOCAL_ID not in identities: raise CLIError(\"usage error: '--scope'/'--role' is only applicable when assign", "namespace): namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') def validate_vmss_disk(cmd, namespace): if namespace.disk:", "arguments supplied based on the authentication type if namespace.authentication_type == 'password': if namespace.ssh_key_value", "that matches the VM's location sku_tier = 'Premium' if 'Premium' in namespace.storage_sku else", "CLIError('usage error: user assigned identity is only available under profile ' 'with minimum", "res_id if namespace.data_disk_sources: raise CLIError(\"'--data-disk-sources' is not allowed when capturing \" \"images from", "CLIError('usage error: unrecognized image informations \"{}\"'.format(namespace.image)) # pylint: disable=no-member elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk:", "\"1\", \"123\", \"a\", \"actuser\", \"adm\", \"admin2\", \"aspnet\", \"backup\", \"console\", \"guest\", \"owner\", \"root\", \"server\",", "\"vaultCertificates\": [{ \"certificateUrl\": \"value\", \"certificateStore\": \"cert store name (only on windows)\" }] }]", "- find a suitable existing vnet/subnet result = None if not for_scale_set: result", "_compute_client_factory(cmd.cli_ctx) try: compute_client.images.get(namespace.resource_group_name, namespace.image) namespace.image = _get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name, 'images', 'Microsoft.Compute') return 'image_id'", "target resource group namespace.storage_account = account.name namespace.storage_account_type = 'existing' logger.debug(\"suitable existing storage account", "# validate proper arguments supplied based on the authentication type if namespace.authentication_type ==", "or pick one from {}' raise CLIError(err.format(namespace.image, [x['urnAlias'] for x in images])) def", "namespace.load_balancer and namespace.application_gateway: raise CLIError('incorrect usage: --load-balancer NAME_OR_ID | ' '--application-gateway NAME_OR_ID') #", "used') elif namespace.application_gateway is None: namespace.app_gateway_type = 'new' logger.debug('new application gateway will be", "32 - int(mask) vnet_int = _convert_to_int(vnet_ip_address, vnet_bit_mask_len) subnet_ip_address, mask = subnet_cidr.split('/') subnet_bit_mask_len =", "parameter. Updates the namespace and returns the type for subsequent processing. \"\"\" from", "res['type'].lower() == 'galleries': image_info = compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) namespace.os_type = image_info.os_type.value gallery_image_version =", "JSON array containing secrets for use in VM Creation Secrets JSON structure [{", "from msrestazure.tools import parse_resource_id from msrestazure.azure_exceptions import CloudError validate_tags(namespace) try: # try capturing", "not in identities: raise CLIError(\"usage error: '--scope'/'--role' is only applicable when assign system", "namespace.data_snapshots.append(source_snapshot) if not namespace.os_type: raise CLIError(\"usage error: os type is required to create", "parse_resource_id(namespace.availability_set) name = as_id['name'] rg = as_id.get('resource_group', namespace.resource_group_name) if not check_existence(cmd.cli_ctx, name, rg,", "'.join(values))) elif not values: raise CLIError(\"No existing values found for '{0}'. Create one", "validate_tags) from azure.cli.core.util import hash_string from azure.cli.command_modules.vm._vm_utils import check_existence, get_target_network_api, get_storage_blob_uri from azure.cli.command_modules.vm._template_builder", "'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK) if namespace.public_ip_sku == PublicIPAddressSkuName.standard.value: if not namespace.public_ip_address_allocation: namespace.public_ip_address_allocation = IPAllocationMethod.static.value def", "#2 namespace.storage_profile = StorageProfile.SACustomImage elif image_type == 'image_id': # STORAGE PROFILE #5 namespace.storage_profile", "= ['Premium_LRS', 'Standard_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS'] if sku and sku.lower() not in [x.lower() for", "namespace): rg = namespace.resource_group_name nic_ids = [] for n in namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx, n,", "on the authentication type if namespace.authentication_type == 'password': if namespace.ssh_key_value or namespace.ssh_dest_key_path: raise", "namespace.plan_product = image_plan.product namespace.plan_publisher = image_plan.publisher return 'urn' # 3 - unmanaged vhd", "STORAGE PROFILE #4 namespace.storage_profile = StorageProfile.ManagedPirImage else: raise CLIError('Unrecognized image type: {}'.format(image_type)) else:", "client.get(rg, ag_name) namespace.app_gateway_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, ag_name,", "'%s' not found. It will be created.\", namespace.load_balancer) elif namespace.load_balancer == '': namespace.load_balancer_type", "+ 1): raise CLIError('The password length must be between {} and {}'.format(min_length, max_length))", "namespace.instance_count, not namespace.disable_overprovision) result = next((s for s in vnet_match.subnets if _check_subnet(s)), None)", "placement group is turned off\") elif namespace.load_balancer_sku == LBSkuName.basic.value: if namespace.zones: err =", "of 2017-12-01') if namespace.identity_scope: if identities and MSI_LOCAL_ID not in identities: raise CLIError(\"usage", "authentication type') validate_ssh_key(namespace) if not namespace.ssh_dest_key_path: namespace.ssh_dest_key_path = \\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def _validate_admin_username(username, os_type):", "os_type == 'windows' errors = [] try: loaded_secret = [validate_file_or_dict(secret) for secret in", "'id_rsa.pub')) content = string_or_file if os.path.exists(string_or_file): logger.info('Use existing SSH public key file: %s',", "forbidden = ['app_gateway_subnet_address_prefix', 'application_gateway', 'app_gateway_sku', 'app_gateway_capacity'] validate_parameter_set(namespace, required, forbidden, description='network balancer: load balancer')", "or -' win_err = r'admin user name cannot contain special characters \\/\"[]:|<>+=;,?*@# or", "import ResourceType from azure.cli.core.commands.client_factory import get_subscription_id ApplicationSecurityGroup = cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK) resource_group = namespace.resource_group_name", "return _subnet_capacity_check(subnet_mask, namespace.instance_count, not namespace.disable_overprovision) result = next((s for s in vnet_match.subnets if", "not namespace.disable_overprovision): break if i < 16: err = \"instance count '{}' is", "profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num = 0 if namespace.storage_profile == StorageProfile.ManagedCustomImage: # extract additional information", "isinstance(nics_value, list): nics_value = [nics_value] for n in nics_value: nics.append({ 'id': n if", "= None logger.debug('no public IP address will be used') elif namespace.public_ip_address is None:", "\" \"allow SSH access to the VM. If using machines without \" \"permanent", "and namespace.os_type.lower() != 'windows': raise CLIError('usage error: --license-type is only applicable on Windows", "raise CLIError(error_msg) # format back to the cidr candaidate_str = '{0:32b}'.format(candidate_int << subnet_bit_mask_len)", "> 1: ids = [r.id for r in role_defs] err = \"More than", "if namespace.single_placement_group is None: namespace.single_placement_group = False elif namespace.single_placement_group: raise CLIError(\"usage error: '--single-placement-group'", "[]) else: raise CLIError('usage error: unrecognized image informations \"{}\"'.format(namespace.image)) # pylint: disable=no-member elif", "namespace.ssh_dest_key_path = \\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def _validate_admin_username(username, os_type): import re if not username: raise", "== StorageProfile.ManagedPirImage: return 'create managed OS disk from Azure Marketplace image' elif profile", "type namespace.authentication_type = 'password' \\ if (namespace.os_type.lower() == 'windows' or namespace.admin_password) else 'ssh'", "vault name :param str vault_name: name of the key vault :return: resource group", "within vaultCertificates array at secret ' \\ 'index {1} and vaultCertificate index {2}", "namespace.application_gateway) except CloudError: namespace.app_gateway_type = 'new' logger.debug(\"application gateway '%s' not found. It will", "'app_gateway_sku', 'app_gateway_capacity'] validate_parameter_set(namespace, required, forbidden, description='network balancer: load balancer') if namespace.load_balancer: rg =", "namespace.load_balancer_type == 'new' and namespace.single_placement_group is False and std_lb_is_available: LBSkuName = cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK)", "new_4core_sizes = [x.lower() for x in new_4core_sizes] if size not in new_4core_sizes: compute_client", "provided and using an image based OS if not namespace.storage_sku and namespace.storage_profile in", "= 'new' logger.debug('new NSG will be created') def _validate_vmss_create_nsg(cmd, namespace): if namespace.nsg: namespace.nsg", "storage, back up your keys to a safe location.\", private_key_filepath, public_key_filepath) else: raise", "'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4', 'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3', 'Standard_D8s_v3'] new_4core_sizes = [x.lower() for", "re.match(s, sku, re.I)): namespace.accelerated_networking = True def _validate_vmss_create_subnet(namespace): if namespace.vnet_type == 'new': if", "else: for jdx, cert in enumerate(secret['vaultCertificates']): message = 'Secret is missing {0} within", "namespace and returns the type for subsequent processing. \"\"\" from msrestazure.tools import is_valid_resource_id", "to \" \"allow SSH access to the VM. If using machines without \"", "_validate_secrets(secrets, os_type): \"\"\" Validates a parsed JSON array containing secrets for use in", "'Microsoft.Compute') if bool(namespace.disk) == bool(namespace.size_gb): raise CLIError('usage error: --disk EXIST_DISK --instance-id ID |", "72 if is_linux else 123 min_length = 12 if len(password) not in range(min_length,", "= source else: compute_client = _compute_client_factory(cli_ctx) # pylint: disable=no-member try: info = compute_client.snapshots.get(resource_group_name,", "from msrestazure.tools import is_valid_resource_id keyvault_usage = CLIError('usage error: [--keyvault NAME --resource-group NAME |", "VNET_NAME\") subnet_exists = \\ check_existence(cmd.cli_ctx, subnet, rg, 'Microsoft.Network', 'subnets', vnet, 'virtualNetworks') if subnet_is_id", "vnet and not subnet and not nics: logger.debug('no subnet specified. Attempting to find", "import re if not username: raise CLIError(\"admin user name can not be empty\")", "different value.\".format(username)) return username def _validate_admin_password(password, os_type): import re is_linux = (os_type.lower() ==", "MSI_LOCAL_ID: identities[i] = _get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') if not namespace.identity_scope and getattr(namespace.identity_role,", "if namespace.storage_profile in [StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]: return namespace.admin_username = _validate_admin_username(namespace.admin_username, namespace.os_type) if not namespace.os_type:", "if namespace.data_disk_sources: raise CLIError(\"'--data-disk-sources' is not allowed when capturing \" \"images from virtual", "= 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, lb_name, 'load_balancers') if not", "'urn' # 5 - check if an existing managed disk image resource compute_client", "is_valid_resource_id(kv): raise keyvault_usage validate_keyvault(cmd, namespace) else: if kv and not is_valid_resource_id(kv): raise keyvault_usage", "{}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num = 0 if namespace.storage_profile == StorageProfile.ManagedCustomImage: # extract additional information from", "number and 1 special character') def validate_ssh_key(namespace): string_or_file = (namespace.ssh_key_value or os.path.join(os.path.expanduser('~'), '.ssh',", "resource_id(**kwargs) if not missing_kwargs else None def _get_nic_id(cli_ctx, val, resource_group): return _get_resource_id(cli_ctx, val,", "\\ check_existence(cmd.cli_ctx, subnet, rg, 'Microsoft.Network', 'subnets', vnet, 'virtualNetworks') if subnet_is_id and not subnet_exists:", "2017-12-01') if namespace.identity_scope: if identities and MSI_LOCAL_ID not in identities: raise CLIError(\"usage error:", "2) error_msg = \"usage error: --subnet-address-prefix value should be a subrange of --vnet-address-prefix's\"", "os_type): \"\"\" Validates a parsed JSON array containing secrets for use in VM", "elif namespace.authentication_type == 'ssh': if namespace.admin_password: raise ValueError('Admin password cannot be used with", "namespace.load_balancer_sku == LBSkuName.basic.value: if namespace.zones: err = \"'Standard' load balancer is required for", "SKU '{}': allowed values: '{}'\".format(sku, allowed_skus)) def _validate_location(cmd, namespace, zone_info, size_info): from ._vm_utils", "keys), and 'base_name.pub'(with public keys) public_key_filepath = string_or_file if public_key_filepath[-4:].lower() == '.pub': private_key_filepath", "== 'galleries': image_info = compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) namespace.os_type = image_info.os_type.value gallery_image_version = res.get('child_name_2',", "_validate_vm_vmss_msi(cmd, namespace, from_set_command=False): if from_set_command or namespace.assign_identity is not None: identities = namespace.assign_identity", "process_vm_create_namespace(cmd, namespace): validate_tags(namespace) _validate_location(cmd, namespace, namespace.zone, namespace.size) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace) if namespace.storage_profile", "\"again.\".format(option_name)) return values[0] def _validate_vmss_single_placement_group(namespace): if namespace.platform_fault_domain_count is not None and namespace.zones is", "if urlparse(source).scheme: # a uri? source_blob_uri = source elif '/disks/' in source.lower(): source_disk", "errors.append( 'Secret is missing sourceVault.id key at index {0} in arg {1}'.format( idx,", "= res_id if namespace.data_disk_sources: raise CLIError(\"'--data-disk-sources' is not allowed when capturing \" \"images", "namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') def validate_vmss_disk(cmd, namespace): if namespace.disk: namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk,", "# find VNET in target resource group that matches the VM's location with", "with the required/forbidden parameters for VM if namespace.storage_profile == StorageProfile.ManagedPirImage: required = ['image']", "namespace): validate_tags(namespace) if namespace.vm_sku is None: from azure.cli.core.cloud import AZURE_US_GOV_CLOUD if cmd.cli_ctx.cloud.name !=", "for x in identities if x != MSI_LOCAL_ID] if user_assigned_identities and not cmd.supported_api_version(min_api='2017-12-01'):", "be used') elif namespace.nsg is None: namespace.nsg_type = 'new' logger.debug('new NSG will be", "rg = as_id.get('resource_group', namespace.resource_group_name) if not check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute', 'availabilitySets'): raise CLIError(\"Availability", "namespace): from msrestazure.tools import parse_resource_id if namespace.storage_account: storage_id = parse_resource_id(namespace.storage_account) rg = storage_id.get('resource_group',", "existing vnet/subnet result = None if not for_scale_set: result = next((s for s", "image_version) # pylint: disable=no-member return image.plan except CloudError as ex: logger.warning(\"Querying the image", "cert in enumerate(secret['vaultCertificates']): message = 'Secret is missing {0} within vaultCertificates array at", "cmd.supported_api_version(min_api='2017-12-01'): raise CLIError('usage error: user assigned identity is only available under profile '", "namespace.load_balancer) else: namespace.load_balancer_type = 'new' logger.debug(\"load balancer '%s' not found. It will be", "disable=import-error from knack.log import get_logger from knack.util import CLIError from azure.cli.core.commands.validators import (", "= { 'name': val, 'resource_group': resource_group, 'namespace': resource_namespace, 'type': resource_type, 'subscription': get_subscription_id(cli_ctx) }", "os type is required to create the image, \" \"please specify '--os-type OS_TYPE'\")", "'Microsoft.Storage', 'storageAccounts'): # 1 - existing storage account specified namespace.storage_account_type = 'existing' logger.debug(\"using", "'os_type', 'use_unmanaged_disk'] forbidden = ['attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SASpecializedOSDisk: required = ['os_type',", "'create managed OS disk from custom image' elif profile == StorageProfile.ManagedPirImage: return 'create", "namespace.os_type: raise CLIError(\"Unable to resolve OS type. Specify '--os-type' argument.\") if not namespace.authentication_type:", "azure.cli.core.commands.client_factory import get_subscription_id if namespace.availability_set: as_id = parse_resource_id(namespace.availability_set) name = as_id['name'] rg =", "custom image res = parse_resource_id(namespace.image) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) if res['type'].lower() == 'images':", "or os.path.join(os.path.expanduser('~'), '.ssh', 'id_rsa.pub')) content = string_or_file if os.path.exists(string_or_file): logger.info('Use existing SSH public", "cmd.cli_ctx, namespace.resource_group_name, data_disk_source) if source_blob_uri: namespace.data_blob_uris.append(source_blob_uri) if source_disk: namespace.data_disks.append(source_disk) if source_snapshot: namespace.data_snapshots.append(source_snapshot) if", "not namespace.authentication_type: # apply default auth type (password for Windows, ssh for Linux)", "namespace.keyvault = _get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_vm_secret_format(cmd, namespace): from msrestazure.tools import", "ag_name, 'application_gateways') logger.debug(\"using specified existing application gateway '%s'\", namespace.application_gateway) except CloudError: namespace.app_gateway_type =", "image' elif profile == StorageProfile.ManagedPirImage: return 'create managed OS disk from Azure Marketplace", "namespace.os_sku = matched['sku'] namespace.os_version = matched['version'] return 'urn' # 5 - check if", "unmanaged OS disk from Azure Marketplace image' elif profile == StorageProfile.SASpecializedOSDisk: return 'attach", "StorageProfile.SACustomImage]: # pylint: disable=line-too-long namespace.storage_sku = 'Standard_LRS' if for_scale_set else 'Premium_LRS' if namespace.storage_sku", "import MSI_LOCAL_ID for i in range(len(namespace.identities)): if namespace.identities[i] != MSI_LOCAL_ID: namespace.identities[i] = _get_resource_id(cmd.cli_ctx,", "1 upper case character, 1 number and 1 special character') def validate_ssh_key(namespace): string_or_file", "if x['urnAlias'].lower() == namespace.image.lower()), None) if matched: namespace.os_publisher = matched['publisher'] namespace.os_offer = matched['offer']", "bool(namespace.disk) != bool(namespace.instance_id): raise CLIError('usage error: --disk EXIST_DISK --instance-id ID') def process_disk_or_snapshot_create_namespace(cmd, namespace):", "needed for Stack profile 2017_03_09 balancer_type = 'loadBalancer' if namespace.single_placement_group is not False", "= getattr(namespace, 'application_security_groups') ids = [] if names_or_ids == [\"\"] or not names_or_ids:", "def _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace): from msrestazure.azure_exceptions import CloudError from msrestazure.tools import parse_resource_id from azure.cli.core.profiles", "identities = namespace.assign_identity or [] from ._vm_utils import MSI_LOCAL_ID for i, _ in", "source_snapshot: namespace.data_snapshots.append(source_snapshot) if not namespace.os_type: raise CLIError(\"usage error: os type is required to", "VM Create Validators def _parse_image_argument(cmd, namespace): \"\"\" Systematically determines what type is supplied", "= 0 for i in range(24, 16, -1): if _subnet_capacity_check(i, namespace.instance_count, not namespace.disable_overprovision):", "description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num = 0 if namespace.storage_profile == StorageProfile.ManagedCustomImage: # extract additional", "the type for subsequent processing. \"\"\" from msrestazure.tools import is_valid_resource_id from msrestazure.azure_exceptions import", "warn here. logger.warning(\"No inbound nat pool was configured on '%s'\", namespace.load_balancer) else: namespace.nat_pool_name", "needs so far if getattr(namespace, 'public_ip_sku', None): from azure.cli.core.profiles import ResourceType PublicIPAddressSkuName, IPAllocationMethod", "range(min_length, max_length + 1): raise CLIError('The password length must be between {} and", "balancer_type = 'None' if namespace.load_balancer is None and namespace.application_gateway is None: if std_lb_is_available:", "else: namespace.load_balancer_type = 'new' logger.debug(\"load balancer '%s' not found. It will be created.\",", "CLIError(\"usage error: '--role {}' is not applicable as the '--scope' is not provided\".format(", "pick one from {}' raise CLIError(err.format(namespace.image, [x['urnAlias'] for x in images])) def _get_image_plan_info_if_exists(cmd,", "source_disk = source elif '/snapshots/' in source.lower(): source_snapshot = source else: compute_client =", "required because 'single placement group' is turned off\" raise CLIError('usage error:{}'.format(err)) def get_network_client(cli_ctx):", "elif bool(namespace.disk) != bool(namespace.instance_id): raise CLIError('usage error: --disk EXIST_DISK --instance-id ID') def process_disk_or_snapshot_create_namespace(cmd,", "[] namespace.data_snapshots = [] if namespace.data_disk_sources: for data_disk_source in namespace.data_disk_sources: source_blob_uri, source_disk, source_snapshot", "(r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if is_linux else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err = r'admin user name cannot contain upper", "else: # 2 - params for new storage account specified namespace.storage_account_type = 'new'", "= _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if bool(namespace.disk) == bool(namespace.size_gb): raise CLIError('usage error:", "2), new_mask) def _validate_vm_create_nsg(cmd, namespace): if namespace.nsg: if check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'):", "account specified namespace.storage_account_type = 'new' logger.debug(\"specified storage account '%s' not found and will", "'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo', 'Standard_F4', 'Standard_F4s', 'Standard_D8_v3', 'Standard_D8s_v3', 'Standard_D32-8s_v3', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC', 'Standard_F4_ABC', 'Standard_F8s_v2',", "import ResourceType std_lb_is_available = cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer and namespace.application_gateway: raise CLIError('incorrect usage:", "== bool(namespace.size_gb): raise CLIError('usage error: --disk EXIST_DISK --instance-id ID | --size-gb GB') elif", "'SQLGLCore', 'Standard_D4_v3', 'Standard_D4s_v3', 'Standard_D2_v2', 'Standard_DS2_v2', 'Standard_E4_v3', 'Standard_E4s_v3', 'Standard_F2', 'Standard_F2s', 'Standard_F4s_v2', 'Standard_D11_v2', 'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C']", "NoTTYException try: if not namespace.admin_password: namespace.admin_password = prompt_pass('Admin Password: ', confirm=True) except NoTTYException:", "= namespace.os_publisher, namespace.os_offer, namespace.os_sku if not publisher: return publisher, offer, sku = publisher.lower(),", "def validate_keyvault(cmd, namespace): namespace.keyvault = _get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_vm_secret_format(cmd, namespace):", "name cannot contain upper case character A-Z, special characters \\/\"[]:|<>+=;,?*@#()! or start with", "= os_type == 'windows' errors = [] try: loaded_secret = [validate_file_or_dict(secret) for secret", "raise CLIError('usage error:{}'.format(err)) def get_network_client(cli_ctx): from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client", "ResourceType.MGMT_AUTHORIZATION).role_definitions role_id = None if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role, re.I): role_id = role else: try:", "at index {0} in arg {1}'.format( idx, idx_arg)) if 'sourceVault' in secret and", "for_scale_set=True) _validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace) _validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd, namespace) _validate_vmss_create_nsg(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd,", "profile: {}'.format(namespace.storage_profile)) logger.debug(\"storage profile '%s'\", namespace.storage_profile) if for_scale_set: # VMSS lacks some parameters,", "i < 16: err = \"instance count '{}' is out of range of", "lb_name) if lb: namespace.load_balancer_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg,", "= string_or_file if public_key_filepath[-4:].lower() == '.pub': private_key_filepath = public_key_filepath[:-4] else: private_key_filepath = public_key_filepath", "CLIError(\"usage error: '--scope'/'--role' is only applicable when assign system identity\") # keep 'identity_role'", "namespace.boot_diagnostics_storage) # endregion # region VMSS Create Validators def _get_default_address_pool(cli_ctx, resource_group, balancer_name, balancer_type):", "back to the cidr candaidate_str = '{0:32b}'.format(candidate_int << subnet_bit_mask_len) return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2), int(candaidate_str[8:16],", "for jdx, cert in enumerate(secret['vaultCertificates']): message = 'Secret is missing {0} within vaultCertificates", "\"user2\", \"test1\", \"user3\", \"admin1\", \"1\", \"123\", \"a\", \"actuser\", \"adm\", \"admin2\", \"aspnet\", \"backup\", \"console\",", "logger.info('Use existing SSH public key file: %s', string_or_file) with open(string_or_file, 'r') as f:", "_validate_vm_vmss_msi(cmd, namespace) if namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage = get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage) # endregion # region VMSS", "= getattr(get_network_client(cli_ctx), balancer_type, None) if not client: raise CLIError('unrecognized balancer type: {}'.format(balancer_type)) balancer", "else: raise CLIError('Unrecognized image type: {}'.format(image_type)) else: # did not specify image XOR", "candidate_int = _convert_to_int(subnet_ip_address, subnet_bit_mask_len) + 1 if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) >", "err = 'Secret is missing vaultCertificates array or it is empty at index", "validate_file_or_dict, validate_parameter_set, validate_tags) from azure.cli.core.util import hash_string from azure.cli.command_modules.vm._vm_utils import check_existence, get_target_network_api, get_storage_blob_uri", "from azure.cli.core.commands.client_factory import get_subscription_id ApplicationSecurityGroup = cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK) resource_group = namespace.resource_group_name subscription_id =", "if namespace.load_balancer_type is None and namespace.app_gateway_type is None: if namespace.public_ip_address: raise CLIError('--public-ip-address can", "= _compute_client_factory(cli_ctx) sizes = compute_client.virtual_machine_sizes.list(namespace.location) size_info = next((s for s in sizes if", "enumerate(secret['vaultCertificates']): message = 'Secret is missing {0} within vaultCertificates array at secret '", "raise CLIError(\"Availability set '{}' does not exist.\".format(name)) namespace.availability_set = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg, namespace='Microsoft.Compute',", "additional information from a managed custom image res = parse_resource_id(namespace.image) compute_client = _compute_client_factory(cmd.cli_ctx,", "'Standard_E16_v3', 'Standard_E16s_v3', 'Standard_E32-16s_v3', 'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC', 'Standard_F8_ABC', 'Standard_F16s_v2', 'Standard_D5_v2', 'Standard_D14_v2', 'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo', 'Standard_DS5_v2', 'Standard_DS14_v2',", "gateway '%s'\", namespace.application_gateway) except CloudError: namespace.app_gateway_type = 'new' logger.debug(\"application gateway '%s' not found.", "= ['os_disk_name', 'os_caching', 'image', 'storage_account', 'storage_container_name', 'data_disk_sizes_gb', 'storage_sku'] + auth_params else: raise CLIError('Unrecognized", "'image', 'storage_account', 'storage_container_name', 'data_disk_sizes_gb', 'storage_sku'] + auth_params else: raise CLIError('Unrecognized storage profile: {}'.format(namespace.storage_profile))", "account in target resource group that matches the VM's location sku_tier = 'Premium'", "f: content = f.read() elif not keys.is_valid_ssh_rsa_public_key(content): if namespace.generate_ssh_keys: # figure out appropriate", "or namespace.instance_count > 100: if namespace.single_placement_group is None: namespace.single_placement_group = False elif namespace.single_placement_group:", "not namespace.nat_pool_name: if len(lb.inbound_nat_pools) > 1: raise CLIError(\"Multiple possible values found for '{0}':", "CloudError validate_tags(namespace) if namespace.source: usage_error = 'usage error: --source {SNAPSHOT | DISK} |", "validate_asg_names_or_ids(cmd, namespace): from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory", "('suse', 'sles', '^12-sp3'), ('redhat', 'rhel', '^7.4'), ('openlogic', 'centos', '^7.4'), ('coreos', 'coreos', None), ('credativ',", "image_data_disks_num = len(image_version_info.storage_profile.data_disk_images or []) else: raise CLIError('usage error: unrecognized image informations \"{}\"'.format(namespace.image))", "if i < 16: err = \"instance count '{}' is out of range", "will be used') elif namespace.public_ip_address is None: namespace.public_ip_address_type = 'new' logger.debug('new public IP", "availability set '%s'\", namespace.availability_set) def _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False): from msrestazure.tools import is_valid_resource_id vnet", "image based OS if not namespace.storage_sku and namespace.storage_profile in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]: # pylint:", "if namespace.load_balancer is None and namespace.application_gateway is None: if std_lb_is_available: balancer_type = 'loadBalancer'", "namespace.single_placement_group is False and std_lb_is_available: LBSkuName = cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer_sku is None:", "error_msg = \"usage error: --subnet-address-prefix value should be a subrange of --vnet-address-prefix's\" #", "the image, \" \"please specify '--os-type OS_TYPE'\") def _figure_out_storage_source(cli_ctx, resource_group_name, source): from msrestazure.azure_exceptions", "CLIError('SSH not supported for Windows VMs.') # validate proper arguments supplied based on", "== 'image_id': # STORAGE PROFILE #5 namespace.storage_profile = StorageProfile.ManagedCustomImage elif image_type == 'urn':", "and 'base_name.pub'(with public keys) public_key_filepath = string_or_file if public_key_filepath[-4:].lower() == '.pub': private_key_filepath =", "_get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_vm_secret_format(cmd, namespace): from msrestazure.tools import is_valid_resource_id keyvault_usage", "= compute_client.disks.get(resource_group_name, source) source_disk = info.id return (source_blob_uri, source_disk, source_snapshot) def process_disk_encryption_namespace(cmd, namespace):", "forbidden = ['os_disk_name', 'os_caching', 'image', 'storage_account', 'storage_container_name', 'data_disk_sizes_gb', 'storage_sku'] + auth_params else: raise", "ResourceType.MGMT_KEYVAULT).vaults for vault in client.list(): id_comps = parse_resource_id(vault.id) if id_comps['name'] == vault_name: return", "namespace.resource_group_name, 'disks', 'Microsoft.Compute') for d in namespace.attach_data_disks] if not namespace.os_type: namespace.os_type = 'windows'", "logger.debug('no suitable subnet found. One will be created.') def _subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision): mask", "None) or getattr(namespace, 'vm_sku', None) size = size.lower() # to refresh the list,", "image_type == 'image_id': # STORAGE PROFILE #5 namespace.storage_profile = StorageProfile.ManagedCustomImage elif image_type ==", "containing secrets for use in VM Creation Secrets JSON structure [{ \"sourceVault\": {", "STORAGE PROFILE #2 namespace.storage_profile = StorageProfile.SACustomImage elif image_type == 'image_id': # STORAGE PROFILE", "def _get_resource_group_from_vault_name(cli_ctx, vault_name): \"\"\" Fetch resource group from vault name :param str vault_name:", "CLIError(\"invalid storage SKU '{}': allowed values: '{}'\".format(sku, allowed_skus)) def _validate_location(cmd, namespace, zone_info, size_info):", "vnet/subnet namespace.vnet_type = 'existing' logger.debug(\"using specified vnet '%s' and subnet '%s'\", namespace.vnet_name, namespace.subnet)", "sku.lower() distros = [('canonical', 'UbuntuServer', '^16.04'), ('suse', 'sles', '^12-sp3'), ('redhat', 'rhel', '^7.4'), ('openlogic',", "True def _validate_vmss_create_subnet(namespace): if namespace.vnet_type == 'new': if namespace.subnet_address_prefix is None: cidr =", "be a subrange of --vnet-address-prefix's\" # extract vnet information needed to verify the", "cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK) resource_group = namespace.resource_group_name subscription_id = get_subscription_id(cmd.cli_ctx) names_or_ids = getattr(namespace, 'application_security_groups') ids", "else: image_version_info = compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2']) image_data_disks_num = len(image_version_info.storage_profile.data_disk_images or [])", "import CloudError validate_tags(namespace) try: # try capturing from VM, a most common scenario", "[] if namespace.data_disk_sources: for data_disk_source in namespace.data_disk_sources: source_blob_uri, source_disk, source_snapshot = _figure_out_storage_source( cmd.cli_ctx,", "is not False else 'applicationGateway' logger.debug(\"W/o STD LB, defaulting to '%s' under because", "# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under", "in source.lower(): source_snapshot = source else: compute_client = _compute_client_factory(cli_ctx) # pylint: disable=no-member try:", "open(string_or_file, 'r') as f: content = f.read() elif not keys.is_valid_ssh_rsa_public_key(content): if namespace.generate_ssh_keys: #", "logger.warning(\"SSH key files '%s' and '%s' have been generated under ~/.ssh to \"", "client.list(rg) if v.location == location and v.subnets): # 1 - find a suitable", "raise CLIError(\"usage error: '--single-placement-group' should be turned off for zonal scale-sets or with\"", "_compute_client_factory(cli_ctx) sizes = compute_client.virtual_machine_sizes.list(namespace.location) size_info = next((s for s in sizes if s.name.lower()", "azure.cli.core.commands.client_factory import get_subscription_id nics_value = namespace.nics nics = [] if not nics_value: namespace.nic_type", "f.read() elif not keys.is_valid_ssh_rsa_public_key(content): if namespace.generate_ssh_keys: # figure out appropriate file names: #", "namespace.secrets: _validate_secrets(namespace.secrets, namespace.os_type) if namespace.license_type and namespace.os_type.lower() != 'windows': raise CLIError('usage error: --license-type", "if re.findall(pattern, username): raise CLIError(linux_err if is_linux else win_err) if is_linux and re.findall(r'^[$-]+',", "values: '{}'\".format(sku, allowed_skus)) def _validate_location(cmd, namespace, zone_info, size_info): from ._vm_utils import list_sku_info if", "linux_err = r'admin user name cannot contain upper case character A-Z, special characters", "'load_balancers') if not namespace.nat_pool_name: if len(lb.inbound_nat_pools) > 1: raise CLIError(\"Multiple possible values found", "in cert: errors.append(message.format('certificateStore', idx, jdx, idx_arg)) if errors: raise CLIError('\\n'.join(errors)) # region VM", "compute_client = _compute_client_factory(cli_ctx) sizes = compute_client.virtual_machine_sizes.list(namespace.location) size_info = next((s for s in sizes", "to find an existing vnet and subnet in the target resource group client", "with\" \" 100+ instances\") def _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace): from msrestazure.azure_exceptions import CloudError from msrestazure.tools", "--priority PRIORITY [--eviction-policy POLICY]') # endregion # region disk, snapshot, image validators def", "lower case character, 1 upper case character, 1 number and 1 special character')", "contains_digit = re.findall('[0-9]+', password) contains_special_char = re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password) count = len([x for", "get it from the error aval_sizes = ['Standard_D3_v2', 'Standard_D12_v2', 'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo', 'Standard_DS3_v2', 'Standard_DS12_v2',", "hasattr(temp, 'location_info'): return if not temp or not [x for x in (temp.location_info", "namespace.key_encryption_keyvault: if not namespace.key_encryption_key: raise CLIError(\"Incorrect usage '--key-encryption-keyvault': \" \"'--key-encryption-key' is required\") namespace.key_encryption_keyvault", "vault_name: return id_comps['resource_group'] return None def _get_resource_id(cli_ctx, val, resource_group, resource_type, resource_namespace): from msrestazure.tools", "None logger.debug('no application gateway will be used') elif namespace.application_gateway is None: namespace.app_gateway_type =", "= 'windows' if 'windows' in namespace.os_offer.lower() else 'linux' from ._vm_utils import normalize_disk_info #", "CLIError(\"admin user name can not be empty\") is_linux = (os_type.lower() == 'linux') #", "_validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedCustomImage: required = ['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account',", "rg, 'Microsoft.Storage', 'storageAccounts'): # 1 - existing storage account specified namespace.storage_account_type = 'existing'", "if size_info is None or size_info.number_of_cores < 8: return # VMs need to", "from azure.cli.core.commands.client_factory import get_mgmt_service_client storage_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts # find storage account in", "in lb.inbound_nat_pools]))) elif not lb.inbound_nat_pools: # Associated scaleset will be missing ssh/rdp, so", "list_sku_info if not namespace.location: get_default_location_from_resource_group(cmd, namespace) if zone_info: sku_infos = list_sku_info(cmd.cli_ctx, namespace.location) temp", "return 'urn' # 5 - check if an existing managed disk image resource", "namespace.storage_profile) if for_scale_set: # VMSS lacks some parameters, so scrub these out props_to_remove", "ex.message) # pylint: disable=inconsistent-return-statements def _get_storage_profile_description(profile): if profile == StorageProfile.SACustomImage: return 'create unmanaged", "namespace): validate_tags(namespace) _validate_location(cmd, namespace, namespace.zone, namespace.size) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace) if namespace.storage_profile in", "creating a new load ' 'balancer or application gateway frontend.') namespace.public_ip_address = ''", "CloudError: return None def process_vmss_create_namespace(cmd, namespace): validate_tags(namespace) if namespace.vm_sku is None: from azure.cli.core.cloud", "not namespace.public_ip_per_vm and namespace.vm_domain_name: raise CLIError('Usage error: --vm-domain-name can only be used when", "not in new_4core_sizes: compute_client = _compute_client_factory(cli_ctx) sizes = compute_client.virtual_machine_sizes.list(namespace.location) size_info = next((s for", "[_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name, 'disks', 'Microsoft.Compute') for d in namespace.attach_data_disks] if not namespace.os_type: namespace.os_type", "# 3 - nothing specified - find viable storage account in target resource", "namespace.admin_password: raise ValueError('Admin password cannot be used with SSH authentication type') validate_ssh_key(namespace) if", "next( (a for a in storage_client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value == sku_tier and a.location ==", "'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC', 'Standard_F8_ABC', 'Standard_F16s_v2', 'Standard_D5_v2', 'Standard_D14_v2', 'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo', 'Standard_DS5_v2', 'Standard_DS14_v2', 'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo', 'Standard_F16',", "namespace, namespace.zone, namespace.size) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace) if namespace.storage_profile in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd,", "ends with .' if re.findall(pattern, username): raise CLIError(linux_err if is_linux else win_err) if", "None) if not client: raise CLIError('unrecognized balancer type: {}'.format(balancer_type)) balancer = client.get(resource_group, balancer_name)", "if not role_id: # retrieve role id role_defs = list(client.list(scope, \"roleName eq '{}'\".format(role)))", "when --public-ip-per-vm is enabled') if namespace.eviction_policy and not namespace.priority: raise CLIError('Usage error: --priority", "Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License.", "not namespace.source_blob_uri and namespace.source_storage_account_id: raise CLIError(usage_error) except CloudError: raise CLIError(usage_error) def process_image_create_namespace(cmd, namespace):", "image. Please try a different value.\".format(username)) return username def _validate_admin_password(password, os_type): import re", "missing ssh/rdp, so warn here. logger.warning(\"No inbound nat pool was configured on '%s'\",", "count < 3: raise CLIError('Password must have the 3 of the following: 1", "vnet, 'virtualNetworks') if subnet_is_id and not subnet_exists: raise CLIError(\"Subnet '{}' does not exist.\".format(subnet))", "'userAssignedIdentities', 'Microsoft.ManagedIdentity') if not namespace.identity_scope and getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError(\"usage", "_validate_vm_vmss_create_public_ip(cmd, namespace): if namespace.public_ip_address: if check_existence(cmd.cli_ctx, namespace.public_ip_address, namespace.resource_group_name, 'Microsoft.Network', 'publicIPAddresses'): namespace.public_ip_address_type = 'existing'", "but is specifically disallowed for this image. Please try a different value.\".format(username)) return", "== 1: regions_info.append(TargetRegion(name=parts[0])) else: try: replica_count = int(parts[1]) except ValueError: raise CLIError(\"usage error:", "= ['nat_pool_name', 'load_balancer', 'health_probe'] validate_parameter_set(namespace, required, forbidden, description='network balancer: application gateway') elif balancer_type", "'disks', 'Microsoft.Compute') for d in namespace.attach_data_disks] if not namespace.os_type: namespace.os_type = 'windows' if", "index {2} in arg {3}' if 'certificateUrl' not in cert: errors.append(message.format('certificateUrl', idx, jdx,", "not subnet_exists: raise CLIError(\"Subnet '{}' does not exist.\".format(subnet)) elif subnet_exists: # 2 -", "'Standard' account = next( (a for a in storage_client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value == sku_tier", "authentication-type 'password': \" \"[--admin-username USERNAME] --admin-password PASSWORD\") from knack.prompting import prompt_pass, NoTTYException try:", "doesn't exist.\".format(role)) elif len(role_defs) > 1: ids = [r.id for r in role_defs]", "namespace.load_balancer: balancer_type = 'loadBalancer' elif namespace.application_gateway: balancer_type = 'applicationGateway' if balancer_type == 'applicationGateway':", "namespace.app_gateway_type == 'new': required.append('app_gateway_sku') required.append('app_gateway_capacity') if namespace.vnet_type != 'new': required.append('app_gateway_subnet_address_prefix') elif namespace.app_gateway_type ==", "VMSS Create Validators def _get_default_address_pool(cli_ctx, resource_group, balancer_name, balancer_type): option_name = '--backend-pool-name' client =", "resource_group): return _get_resource_id(cli_ctx, val, resource_group, 'networkInterfaces', 'Microsoft.Network') def validate_vm_nic(cmd, namespace): namespace.nic = _get_nic_id(cmd.cli_ctx,", "OS disk from custom image' elif profile == StorageProfile.ManagedPirImage: return 'create managed OS", "only exposed for VM. VMSS has no such needs so far if getattr(namespace,", "res.get('child_name_2', '') if gallery_image_version.lower() in ['latest', '']: image_version_infos = compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'])", "= [] namespace.data_disks = [] namespace.data_snapshots = [] if namespace.data_disk_sources: for data_disk_source in", "\"{}\". Use a custom image name, id, or pick one from {}' raise", "'Standard_DS4_v2', 'Standard_DS13_v2', 'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo', 'Standard_F8', 'Standard_F8s', 'Standard_M64-16ms', 'Standard_D16_v3', 'Standard_D16s_v3', 'Standard_D32-16s_v3', 'Standard_D64-16s_v3',", "off\" raise CLIError('usage error:{}'.format(err)) def get_network_client(cli_ctx): from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import", "not names_or_ids: return for val in names_or_ids: if not is_valid_resource_id(val): val = resource_id(", "namespace.identities: from ._vm_utils import MSI_LOCAL_ID for i in range(len(namespace.identities)): if namespace.identities[i] != MSI_LOCAL_ID:", "if from_set_command or namespace.assign_identity is not None: identities = namespace.assign_identity or [] from", "'Standard_D12_v2', 'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo', 'Standard_DS3_v2', 'Standard_DS12_v2', 'Standard_DS13-4_v2', 'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo', 'Standard_F4', 'Standard_F4s',", "OS disk created from generalized VHD' elif profile == StorageProfile.SAPirImage: return 'create unmanaged", "namespace): if namespace.accelerated_networking is None: size = getattr(namespace, 'size', None) or getattr(namespace, 'vm_sku',", "back up your keys to a safe location.\", private_key_filepath, public_key_filepath) else: raise CLIError('An", "(linux or windows) :return: errors if any were found :rtype: list \"\"\" is_windows", "must be between {} and {}'.format(min_length, max_length)) contains_lower = re.findall('[a-z]+', password) contains_upper =", "in secret or not secret['vaultCertificates']: err = 'Secret is missing vaultCertificates array or", "v.subnets): # 1 - find a suitable existing vnet/subnet result = None if", "get_network_client(cmd.cli_ctx).virtual_networks # find VNET in target resource group that matches the VM's location", "StorageProfile.ManagedSpecializedOSDisk: # accept disk name or ID namespace.attach_os_disk = _get_resource_id( cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name,", "import parse_resource_id if namespace.storage_account: storage_id = parse_resource_id(namespace.storage_account) rg = storage_id.get('resource_group', namespace.resource_group_name) if check_existence(cmd.cli_ctx,", "' 'with minimum Compute API version of 2017-12-01') if namespace.identity_scope: if identities and", "subscription=subscription_id, resource_group=resource_group, namespace='Microsoft.Network', type='applicationSecurityGroups', name=val ) ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace, 'application_security_groups', ids) def validate_nsg_name(cmd, namespace):", "namespace.eviction_policy and not namespace.priority: raise CLIError('Usage error: --priority PRIORITY [--eviction-policy POLICY]') # endregion", "resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) image_version_infos = [x for x in image_version_infos if not x.publishing_profile.exclude_from_latest]", "is_valid_resource_id vnet = namespace.vnet_name subnet = namespace.subnet rg = namespace.resource_group_name location = namespace.location", "'']: image_version_infos = compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) image_version_infos = [x for x in", "parse_resource_id(namespace.application_gateway).get( 'resource_group', namespace.resource_group_name) ag_name = parse_resource_id(namespace.application_gateway)['name'] client.get(rg, ag_name) namespace.app_gateway_type = 'existing' namespace.backend_pool_name =", "= None logger.debug('no application gateway will be used') elif namespace.application_gateway is None: namespace.app_gateway_type", "'image_id' except CloudError: err = 'Invalid image \"{}\". Use a custom image name,", "2), int(candaidate_str[24:32], 2), new_mask) def _validate_vm_create_nsg(cmd, namespace): if namespace.nsg: if check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name,", "urn_match.group(2) namespace.os_sku = urn_match.group(3) namespace.os_version = urn_match.group(4) if not any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]): image_plan", "return 'image_id' except CloudError: err = 'Invalid image \"{}\". Use a custom image", "else 'applicationGateway' logger.debug(\"W/o STD LB, defaulting to '%s' under because single placement group", "--public-ip-per-vm is enabled') if namespace.eviction_policy and not namespace.priority: raise CLIError('Usage error: --priority PRIORITY", "pylint: disable=no-member elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: # accept disk name or ID namespace.attach_os_disk", "s.name.lower() == 'gatewaysubnet': return False subnet_mask = s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask, namespace.instance_count, not namespace.disable_overprovision)", "appropriate file names: # 'base_name'(with private keys), and 'base_name.pub'(with public keys) public_key_filepath =", "--license-type is only applicable on Windows VM scaleset') if not namespace.public_ip_per_vm and namespace.vm_domain_name:", "return 'attach existing managed OS disk' def _validate_managed_disk_sku(sku): allowed_skus = ['Premium_LRS', 'Standard_LRS', 'StandardSSD_LRS',", "secrets] except Exception as err: raise CLIError('Error decoding secrets: {0}'.format(err)) for idx_arg, narg_secret", "[x.lower() for x in aval_sizes] if size not in aval_sizes: return new_4core_sizes =", "to the cidr candaidate_str = '{0:32b}'.format(candidate_int << subnet_bit_mask_len) return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2), int(candaidate_str[8:16], 2),", "namespace.storage_profile in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd, namespace) _validate_vm_create_availability_set(cmd, namespace) _validate_vm_vmss_create_vnet(cmd, namespace) _validate_vm_create_nsg(cmd, namespace) _validate_vm_vmss_create_public_ip(cmd,", "capturing from VM, a most common scenario res_id = _get_resource_id(cmd.cli_ctx, namespace.source, namespace.resource_group_name, 'virtualMachines',", "project root for license information. # -------------------------------------------------------------------------------------------- # pylint:disable=too-many-lines import os try: from", "or getattr(namespace, 'vm_sku', None) size = size.lower() # to refresh the list, run", "if namespace.public_ip_address: if check_existence(cmd.cli_ctx, namespace.public_ip_address, namespace.resource_group_name, 'Microsoft.Network', 'publicIPAddresses'): namespace.public_ip_address_type = 'existing' logger.debug(\"using existing", "settings \" \"will be skipped\", namespace.image, ex.message) # pylint: disable=inconsistent-return-statements def _get_storage_profile_description(profile): if", "namespace.image) if urn_match: namespace.os_publisher = urn_match.group(1) namespace.os_offer = urn_match.group(2) namespace.os_sku = urn_match.group(3) namespace.os_version", "not yet \" \"supported. Please use '--location' to specify a capable one. 'az", "'') if gallery_image_version.lower() in ['latest', '']: image_version_infos = compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) image_version_infos", "'%s' and subnet '%s' found\", namespace.vnet_name, namespace.subnet) return if subnet: subnet_is_id = is_valid_resource_id(subnet)", "else resource_id(name=n, resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)), 'properties': { 'primary': nics_value[0] == n }", "namespace) _validate_vm_vmss_create_auth(namespace) if namespace.secrets: _validate_secrets(namespace.secrets, namespace.os_type) if namespace.license_type and namespace.os_type.lower() != 'windows': raise", "if not hasattr(temp, 'location_info'): return if not temp or not [x for x", "in cert: errors.append(message.format('certificateUrl', idx, jdx, idx_arg)) if is_windows and 'certificateStore' not in cert:", "namespace) if namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage = get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage) # endregion # region VMSS Create", "Standard_DS1_v2' and # get it from the error aval_sizes = ['Standard_D3_v2', 'Standard_D12_v2', 'Standard_D3_v2_Promo',", "2017_03_09 balancer_type = 'loadBalancer' if namespace.single_placement_group is not False else 'applicationGateway' logger.debug(\"W/o STD", "'latest': image_version = _get_latest_image_version(cmd.cli_ctx, namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku) else: image_version = namespace.os_version image", "size_info is None or size_info.number_of_cores < 8: return # VMs need to be", "failed for an error '%s'. Configuring plan settings \" \"will be skipped\", namespace.image,", "namespace.os_version image = compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku, image_version) # pylint: disable=no-member return image.plan", "\\ 'arg {1} ' errors.append(err.format(idx, idx_arg)) else: for jdx, cert in enumerate(secret['vaultCertificates']): message", "out props_to_remove = ['attach_os_disk', 'storage_account'] for prop in props_to_remove: if prop in required:", "in enumerate(identities): if identities[i] != MSI_LOCAL_ID: identities[i] = _get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity')", "== '': namespace.app_gateway_type = None logger.debug('no application gateway will be used') elif namespace.application_gateway", "urlparse(source).scheme: # a uri? source_blob_uri = source elif '/disks/' in source.lower(): source_disk =", "namespace.image, namespace.resource_group_name, 'images', 'Microsoft.Compute') return 'image_id' except CloudError: err = 'Invalid image \"{}\".", "found and will be created\", storage_id['name']) else: from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory", "specified existing storage account '%s'\", storage_id['name']) else: # 2 - params for new", "size), None) if size_info is None or size_info.number_of_cores < 8: return # VMs", "max_length = 72 if is_linux else 123 min_length = 12 if len(password) not", "is_valid_resource_id from azure.cli.core.commands.client_factory import get_subscription_id if is_valid_resource_id(val): return val kwargs = { 'name':", "used when --public-ip-per-vm is enabled') if namespace.eviction_policy and not namespace.priority: raise CLIError('Usage error:", "{SNAPSHOT | DISK} | --source VHD_BLOB_URI [--source-storage-account-id ID]' try: namespace.source_blob_uri, namespace.source_disk, namespace.source_snapshot =", "1 special character') def validate_ssh_key(namespace): string_or_file = (namespace.ssh_key_value or os.path.join(os.path.expanduser('~'), '.ssh', 'id_rsa.pub')) content", "== '': namespace.load_balancer_type = None logger.debug('no load balancer will be used') elif namespace.load_balancer", "name '{}' meets the general requirements, but is specifically disallowed for this image.", "public_key_filepath) logger.warning(\"SSH key files '%s' and '%s' have been generated under ~/.ssh to", "'^7.4'), ('coreos', 'coreos', None), ('credativ', 'debian', '-backports'), ('oracle', 'oracle-linux', '^7.4'), ('MicrosoftWindowsServer', 'WindowsServer', '^2016'),", "and subnet '%s' found\", namespace.vnet_name, namespace.subnet) return if subnet: subnet_is_id = is_valid_resource_id(subnet) if", "' \\ 'index {1} and vaultCertificate index {2} in arg {3}' if 'certificateUrl'", "compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2']) image_data_disks_num = len(image_version_info.storage_profile.data_disk_images or []) else: raise CLIError('usage", "def _resolve_role_id(cli_ctx, role, scope): import re import uuid from azure.cli.core.commands.client_factory import get_mgmt_service_client from", "or \\ _get_default_address_pool(cmd.cli_ctx, rg, ag_name, 'application_gateways') logger.debug(\"using specified existing application gateway '%s'\", namespace.application_gateway)", "get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx)) def get_network_lb(cli_ctx, resource_group_name, lb_name): from msrestazure.azure_exceptions import CloudError network_client =", "matches the given name '{}'. Please pick an id from '{}'\" raise CLIError(err.format(role,", "XOR attach-os-disk raise CLIError('incorrect usage: --image IMAGE | --attach-os-disk DISK') auth_params = ['<PASSWORD>_password',", "str vault_name: name of the key vault :return: resource group name or None", "ResourceType.MGMT_STORAGE).storage_accounts # find storage account in target resource group that matches the VM's", "namespace.public_ip_address = '' _validate_vm_vmss_create_public_ip(cmd, namespace) def _validate_vm_create_nics(cmd, namespace): from msrestazure.tools import resource_id from", "try: rg = parse_resource_id(namespace.application_gateway).get( 'resource_group', namespace.resource_group_name) ag_name = parse_resource_id(namespace.application_gateway)['name'] client.get(rg, ag_name) namespace.app_gateway_type =", "will be used') elif namespace.nsg is None: namespace.nsg_type = 'new' logger.debug('new NSG will", "_get_resource_id(cli_ctx, val, resource_group, resource_type, resource_namespace): from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.commands.client_factory import", "= [x.name for x in balancer.backend_address_pools] if len(values) > 1: raise CLIError(\"Multiple possible", "'application_security_groups') ids = [] if names_or_ids == [\"\"] or not names_or_ids: return for", "explicitly.\".format( # pylint: disable=line-too-long '--nat-pool-name', ', '.join([n.name for n in lb.inbound_nat_pools]))) elif not", "mode.') # validate password _validate_admin_password(namespace.admin_password, namespace.os_type) elif namespace.authentication_type == 'ssh': if namespace.admin_password: raise", "unmanaged OS disk created from generalized VHD' elif profile == StorageProfile.SAPirImage: return 'create", "or ends with .' if re.findall(pattern, username): raise CLIError(linux_err if is_linux else win_err)", "system identity\") # keep 'identity_role' for output as logical name is more readable", "validate_parameter_set( namespace, required, forbidden, description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num = 0 if namespace.storage_profile ==", "from ._vm_utils import MSI_LOCAL_ID for i, _ in enumerate(identities): if identities[i] != MSI_LOCAL_ID:", "_get_image_plan_info_if_exists(cmd, namespace): from msrestazure.azure_exceptions import CloudError try: compute_client = _compute_client_factory(cmd.cli_ctx) if namespace.os_version.lower() ==", "== 'UltraSSD_LRS' and namespace.ultra_ssd_enabled is None: namespace.ultra_ssd_enabled = True # Now verify that", "if not x.publishing_profile.exclude_from_latest] if not image_version_infos: raise CLIError('There is no latest image version", "--load-balancer NAME_OR_ID | ' '--application-gateway NAME_OR_ID') # Resolve the type of balancer (if", "CLIError('Usage error: --priority PRIORITY [--eviction-policy POLICY]') # endregion # region disk, snapshot, image", "aval_sizes = ['Standard_D3_v2', 'Standard_D12_v2', 'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo', 'Standard_DS3_v2', 'Standard_DS12_v2', 'Standard_DS13-4_v2', 'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo',", "source.lower(): source_disk = source elif '/snapshots/' in source.lower(): source_snapshot = source else: compute_client", "CLIError('usage error: [--keyvault NAME --resource-group NAME | --keyvault ID]') kv = namespace.keyvault rg", "StorageProfile.SAPirImage else: # STORAGE PROFILE #4 namespace.storage_profile = StorageProfile.ManagedPirImage else: raise CLIError('Unrecognized image", "_validate_location(cmd, namespace, namespace.zone, namespace.size) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace) if namespace.storage_profile in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]:", "not provided and using an image based OS if not namespace.storage_sku and namespace.storage_profile", "'Standard_D13_v2_ABC', 'Standard_F8_ABC', 'Standard_F16s_v2', 'Standard_D5_v2', 'Standard_D14_v2', 'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo', 'Standard_DS5_v2', 'Standard_DS14_v2', 'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo', 'Standard_F16', 'Standard_F16s',", "specify password in non-interactive mode.') # validate password _validate_admin_password(namespace.admin_password, namespace.os_type) elif namespace.authentication_type ==", "raise CLIError(\"usage error: '--scope'/'--role' is only applicable when assign system identity\") # keep", "if namespace.eviction_policy and not namespace.priority: raise CLIError('Usage error: --priority PRIORITY [--eviction-policy POLICY]') #", "azure.cli.core.profiles import ResourceType client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions role_id = None if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role,", "CloudError: raise CLIError(usage_error) def process_image_create_namespace(cmd, namespace): from msrestazure.tools import parse_resource_id from msrestazure.azure_exceptions import", "validate_tags(namespace) def process_gallery_image_version_namespace(cmd, namespace): TargetRegion = cmd.get_models('TargetRegion') if namespace.target_regions: regions_info = [] for", "if count < 3: raise CLIError('Password must have the 3 of the following:", "for n in lb.inbound_nat_pools]))) elif not lb.inbound_nat_pools: # Associated scaleset will be missing", "logger.warning(\"No inbound nat pool was configured on '%s'\", namespace.load_balancer) else: namespace.nat_pool_name = lb.inbound_nat_pools[0].name", "def process_remove_identity_namespace(cmd, namespace): if namespace.identities: from ._vm_utils import MSI_LOCAL_ID for i in range(len(namespace.identities)):", "namespace.storage_profile = StorageProfile.ManagedPirImage else: raise CLIError('Unrecognized image type: {}'.format(image_type)) else: # did not", "if is_linux else 123 min_length = 12 if len(password) not in range(min_length, max_length", "process_assign_identity_namespace(cmd, namespace): _validate_vm_vmss_msi(cmd, namespace, from_set_command=True) def process_remove_identity_namespace(cmd, namespace): if namespace.identities: from ._vm_utils import", "== size_info.lower()), None) # For Stack (compute - 2017-03-30), Resource_sku doesn't implement location_info", "auth_params = ['<PASSWORD>_password', 'admin_username', 'authentication_type', 'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value'] # perform parameter validation for", "sku = namespace.os_publisher, namespace.os_offer, namespace.os_sku if not publisher: return publisher, offer, sku =", "# 2 - user specified existing vnet/subnet namespace.vnet_type = 'existing' logger.debug(\"using specified vnet", "parameters to resolve the expected storage profile if getattr(namespace, 'attach_os_disk', None) and not", "yet for VMSS, so use 'getattr' to avoid crash namespace.disk_info = normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb,", "namespace.resource_group_name) def validate_vm_nics(cmd, namespace): rg = namespace.resource_group_name nic_ids = [] for n in", "- subnet_bit_mask_len)) > vnet_int: raise CLIError(error_msg) # format back to the cidr candaidate_str", "def _get_resource_id(cli_ctx, val, resource_group, resource_type, resource_namespace): from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.commands.client_factory", "namespace.identity_scope or getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError('usage error: --assign-identity [--scope SCOPE]", "if namespace.vnet_type != 'new': required.append('app_gateway_subnet_address_prefix') elif namespace.app_gateway_type == 'existing': required.append('backend_pool_name') forbidden = ['nat_pool_name',", "not role_defs: raise CLIError(\"Role '{}' doesn't exist.\".format(role)) elif len(role_defs) > 1: ids =", "raise CLIError(\"Role '{}' doesn't exist.\".format(role)) elif len(role_defs) > 1: ids = [r.id for", "instances\") def _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace): from msrestazure.azure_exceptions import CloudError from msrestazure.tools import parse_resource_id from", "with 100+ instances\" else: err = \"'Standard' load balancer is required because 'single", "See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # pylint:disable=too-many-lines", "not allowed when capturing \" \"images from virtual machines\") except CloudError: namespace.os_blob_uri, namespace.os_disk,", "namespace.nsg_type = None logger.debug('no NSG will be used') elif namespace.nsg is None: namespace.nsg_type", "CLIError(usage_error) except CloudError: raise CLIError(usage_error) def process_image_create_namespace(cmd, namespace): from msrestazure.tools import parse_resource_id from", "namespace.source) # pylint: disable=line-too-long namespace.data_blob_uris = [] namespace.data_disks = [] namespace.data_snapshots = []", "'Microsoft.ManagedIdentity') if not namespace.identity_scope and getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError(\"usage error:", "Compute API version of 2017-12-01') if namespace.identity_scope: if identities and MSI_LOCAL_ID not in", "not vnet and not subnet and not nics: logger.debug('no subnet specified. Attempting to", "\" \"please specify '--os-type OS_TYPE'\") def _figure_out_storage_source(cli_ctx, resource_group_name, source): from msrestazure.azure_exceptions import CloudError", "namespace.application_gateway: client = get_network_client(cmd.cli_ctx).application_gateways try: rg = parse_resource_id(namespace.application_gateway).get( 'resource_group', namespace.resource_group_name) ag_name = parse_resource_id(namespace.application_gateway)['name']", "'existing' logger.debug(\"using specified NSG '%s'\", namespace.nsg) else: namespace.nsg_type = 'new' logger.debug(\"specified NSG '%s'", "namespace.key_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_assign_identity_namespace(cmd, namespace): _validate_vm_vmss_msi(cmd, namespace, from_set_command=True)", "profile == StorageProfile.ManagedCustomImage: return 'create managed OS disk from custom image' elif profile", "if not namespace.location: get_default_location_from_resource_group(cmd, namespace) if zone_info: sku_infos = list_sku_info(cmd.cli_ctx, namespace.location) temp =", "A-Z, special characters \\/\"[]:|<>+=;,?*@#()! or start with $ or -' win_err = r'admin", "re import uuid from azure.cli.core.commands.client_factory import get_mgmt_service_client from azure.cli.core.profiles import ResourceType client =", "def _get_default_address_pool(cli_ctx, resource_group, balancer_name, balancer_type): option_name = '--backend-pool-name' client = getattr(get_network_client(cli_ctx), balancer_type, None)", "raise CLIError('incorrect usage: --load-balancer NAME_OR_ID | ' '--application-gateway NAME_OR_ID') # Resolve the type", "Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in", "for Stack profile 2017_03_09 balancer_type = 'loadBalancer' if namespace.single_placement_group is not False else", "namespace.single_placement_group = False elif namespace.single_placement_group: raise CLIError(\"usage error: '--single-placement-group' should be turned off", "and not namespace.image: if namespace.use_unmanaged_disk: # STORAGE PROFILE #3 namespace.storage_profile = StorageProfile.SASpecializedOSDisk else:", "or with\" \" 100+ instances\") def _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace): from msrestazure.azure_exceptions import CloudError from", "namespace): get_default_location_from_resource_group(cmd, namespace) validate_tags(namespace) def process_gallery_image_version_namespace(cmd, namespace): TargetRegion = cmd.get_models('TargetRegion') if namespace.target_regions: regions_info", "| --size-gb GB') elif bool(namespace.disk) != bool(namespace.instance_id): raise CLIError('usage error: --disk EXIST_DISK --instance-id", "\"used to find such locations\".format(namespace.resource_group_name)) # pylint: disable=too-many-branches, too-many-statements def _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False):", "except Exception as err: raise CLIError('Error decoding secrets: {0}'.format(err)) for idx_arg, narg_secret in", "specified, try to find an existing vnet and subnet in the target resource", "with SSH authentication type') validate_ssh_key(namespace) if not namespace.ssh_dest_key_path: namespace.ssh_dest_key_path = \\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def", "https://github.com/Azure/azure-cli/issues/5105 def process_msi_namespace(cmd, namespace): get_default_location_from_resource_group(cmd, namespace) validate_tags(namespace) def process_gallery_image_version_namespace(cmd, namespace): TargetRegion = cmd.get_models('TargetRegion')", "namespace.source) if not namespace.source_blob_uri and namespace.source_storage_account_id: raise CLIError(usage_error) except CloudError: raise CLIError(usage_error) def", "SSH public key file: %s', string_or_file) with open(string_or_file, 'r') as f: content =", "name=name) logger.debug(\"adding to specified availability set '%s'\", namespace.availability_set) def _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False): from", "namespace.vnet_type == 'new': if namespace.subnet_address_prefix is None: cidr = namespace.vnet_address_prefix.split('/', 1)[0] i =", "a subrange of --vnet-address-prefix's\" # extract vnet information needed to verify the defaults", "= 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, ag_name, 'application_gateways') logger.debug(\"using specified", "'%s' not found. It will be created.\", namespace.public_ip_address) elif namespace.public_ip_address == '': namespace.public_ip_address_type", "= IPAllocationMethod.static.value def _validate_vmss_create_public_ip(cmd, namespace): if namespace.load_balancer_type is None and namespace.app_gateway_type is None:", "likely) from azure.cli.command_modules.vm._actions import load_images_from_aliases_doc images = load_images_from_aliases_doc(cmd.cli_ctx) matched = next((x for x", "'Standard_D14_v2', 'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo', 'Standard_DS5_v2', 'Standard_DS14_v2', 'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo', 'Standard_F16', 'Standard_F16s', 'Standard_M64-32ms', 'Standard_M128-32ms', 'Standard_D32_v3', 'Standard_D32s_v3',", "namespace.resource_group_name, 'disks', 'Microsoft.Compute') if bool(namespace.disk) == bool(namespace.size_gb): raise CLIError('usage error: --disk EXIST_DISK --instance-id", "try to find an existing vnet and subnet in the target resource group", "turned off\") elif namespace.load_balancer_sku == LBSkuName.basic.value: if namespace.zones: err = \"'Standard' load balancer", "'Standard_F4s_v2', 'Standard_D11_v2', 'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C'] aval_sizes = [x.lower() for x in aval_sizes] if size", "elif namespace.image and not getattr(namespace, 'attach_os_disk', None): image_type = _parse_image_argument(cmd, namespace) if image_type", "for scale-sets with 100+ instances\" else: err = \"'Standard' load balancer is required", "namespace.resource_group_name subscription_id = get_subscription_id(cmd.cli_ctx) names_or_ids = getattr(namespace, 'application_security_groups') ids = [] if names_or_ids", "if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedCustomImage: required = ['image'] forbidden =", "<< (32 - mask)) - 2) > int(vmss_instance_count * factor) def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace):", "int(mask) vnet_int = _convert_to_int(vnet_ip_address, vnet_bit_mask_len) subnet_ip_address, mask = subnet_cidr.split('/') subnet_bit_mask_len = 32 -", "= 'None' if namespace.load_balancer is None and namespace.application_gateway is None: if std_lb_is_available: balancer_type", "import get_subscription_id ApplicationSecurityGroup = cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK) resource_group = namespace.resource_group_name subscription_id = get_subscription_id(cmd.cli_ctx) names_or_ids", "raise CLIError('usage error: --disk EXIST_DISK --instance-id ID') def process_disk_or_snapshot_create_namespace(cmd, namespace): from msrestazure.azure_exceptions import", "namespace.source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, namespace.source) if not namespace.source_blob_uri and namespace.source_storage_account_id: raise CLIError(usage_error)", "size not in aval_sizes: return new_4core_sizes = ['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2', 'Standard_DS3_v2_Promo', 'Standard_D12_v2',", "nothing specified - find viable storage account in target resource group namespace.storage_account =", "used\", account.name) else: # 4 - nothing specified - create a new storage", "not subnet and not nics: logger.debug('no subnet specified. Attempting to find an existing", "in aval_sizes] if size not in aval_sizes: return new_4core_sizes = ['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC',", "if public_key_filepath[-4:].lower() == '.pub': private_key_filepath = public_key_filepath[:-4] else: private_key_filepath = public_key_filepath + '.private'", "import CloudError source_blob_uri = None source_disk = None source_snapshot = None if urlparse(source).scheme:", "idx_arg)) if 'sourceVault' in secret and 'id' not in secret['sourceVault']: errors.append( 'Secret is", "source_blob_uri = source elif '/disks/' in source.lower(): source_disk = source elif '/snapshots/' in", "namespace.vnet_address_prefix, namespace.subnet_address_prefix, 24) def _get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr, new_mask): def _convert_to_int(address, bit_mask_len): a, b, c,", "range(len(namespace.identities)): if namespace.identities[i] != MSI_LOCAL_ID: namespace.identities[i] = _get_resource_id(cmd.cli_ctx, namespace.identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') #", "forbidden, description='network balancer: application gateway') elif balancer_type == 'loadBalancer': # LoadBalancer frontend required", "'existing' logger.debug(\"existing vnet '%s' and subnet '%s' found\", namespace.vnet_name, namespace.subnet) return if subnet:", "= is_valid_resource_id(subnet) if (subnet_is_id and vnet) or (not subnet_is_id and not vnet): raise", "by examining the OS type namespace.authentication_type = 'password' \\ if (namespace.os_type.lower() == 'windows'", "is required because 'single placement group' is turned off\" raise CLIError('usage error:{}'.format(err)) def", "namespace.resource_group_name, namespace.source) # pylint: disable=line-too-long namespace.data_blob_uris = [] namespace.data_disks = [] namespace.data_snapshots =", "source_disk = info.id return (source_blob_uri, source_disk, source_snapshot) def process_disk_encryption_namespace(cmd, namespace): namespace.disk_encryption_keyvault = _get_resource_id(cmd.cli_ctx,", "identities and MSI_LOCAL_ID not in identities: raise CLIError(\"usage error: '--scope'/'--role' is only applicable", "'Standard_D11_v2', 'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C'] aval_sizes = [x.lower() for x in aval_sizes] if size not", "resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name = namespace.network_security_group_name \\ or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8))", "if 'sourceVault' in secret and 'id' not in secret['sourceVault']: errors.append( 'Secret is missing", "import parse_resource_id client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults for vault in client.list(): id_comps = parse_resource_id(vault.id)", "enumerate(narg_secret): if 'sourceVault' not in secret: errors.append( 'Secret is missing sourceVault key at", ">> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: # overflows? candidate_int = candidate_int - 2", "== PublicIPAddressSkuName.standard.value: if not namespace.public_ip_address_allocation: namespace.public_ip_address_allocation = IPAllocationMethod.static.value def _validate_vmss_create_public_ip(cmd, namespace): if namespace.load_balancer_type", "CLIError('usage error:{}'.format(err)) def get_network_client(cli_ctx): from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client return", "= len(image_info.storage_profile.data_disks or []) elif res['type'].lower() == 'galleries': image_info = compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'])", "'--location' to specify a capable one. 'az vm list-skus' can be \" \"used", "License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # pylint:disable=too-many-lines import", "should be turned off for zonal scale-sets or with\" \" 100+ instances\") def", "if over_provision else 1 return ((1 << (32 - mask)) - 2) >", "StorageProfile.SAPirImage: return 'create unmanaged OS disk from Azure Marketplace image' elif profile ==", "v in client.list(rg) if v.location == location and v.subnets): # 1 - find", "in the project root for license information. # -------------------------------------------------------------------------------------------- # pylint:disable=too-many-lines import os", "load_images_from_aliases_doc(cmd.cli_ctx) matched = next((x for x in images if x['urnAlias'].lower() == namespace.image.lower()), None)", "_validate_location(cmd, namespace, namespace.zones, namespace.vm_sku) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=True) _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=True) _validate_vmss_single_placement_group(namespace)", "raise CLIError(linux_err if is_linux else win_err) if is_linux and re.findall(r'^[$-]+', username): raise CLIError(linux_err)", "(not subnet_is_id and not vnet): raise CLIError(\"incorrect '--subnet' usage: --subnet SUBNET_ID | \"", "because single placement group is disabled\", balancer_type) elif namespace.load_balancer: balancer_type = 'loadBalancer' elif", "{1}'.format( idx, idx_arg)) if 'vaultCertificates' not in secret or not secret['vaultCertificates']: err =", "PROFILE #5 namespace.storage_profile = StorageProfile.ManagedCustomImage elif image_type == 'urn': if namespace.use_unmanaged_disk: # STORAGE", "contain special characters \\/\"[]:|<>+=;,?*@# or ends with .' if re.findall(pattern, username): raise CLIError(linux_err", "(temp.location_info or []) if x.zones]: raise CLIError(\"{}'s location can't be used to create", "if namespace.public_ip_address: raise CLIError('--public-ip-address can only be used when creating a new load", "to let CLI generate one for you') namespace.ssh_key_value = content def _validate_vm_vmss_msi(cmd, namespace,", "as err: raise CLIError('Error decoding secrets: {0}'.format(err)) for idx_arg, narg_secret in enumerate(loaded_secret): for", "namespace.load_balancer_type = 'new' logger.debug(\"load balancer '%s' not found. It will be created.\", namespace.load_balancer)", "used') elif namespace.load_balancer is None: namespace.load_balancer_type = 'new' logger.debug('new load balancer will be", "azure.cli.core.cloud import AZURE_US_GOV_CLOUD if cmd.cli_ctx.cloud.name != AZURE_US_GOV_CLOUD.name: namespace.vm_sku = 'Standard_DS1_v2' else: namespace.vm_sku =", "return (source_blob_uri, source_disk, source_snapshot) def process_disk_encryption_namespace(cmd, namespace): namespace.disk_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault, namespace.resource_group_name, 'vaults',", "from azure.cli.core.profiles import ResourceType std_lb_is_available = cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer and namespace.application_gateway: raise", "and returns the type for subsequent processing. \"\"\" from msrestazure.tools import is_valid_resource_id from", "we are coming out vnet_ip_address, mask = vnet_cidr.split('/') vnet_bit_mask_len = 32 - int(mask)", "raise CLIError(\"usage error: '--role {}' is not applicable as the '--scope' is not", "(candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: # overflows? candidate_int = candidate_int -", "special characters \\/\"[]:|<>+=;,?*@# or ends with .' if re.findall(pattern, username): raise CLIError(linux_err if", "'userAssignedIdentities', 'Microsoft.ManagedIdentity') # TODO move to its own command module https://github.com/Azure/azure-cli/issues/5105 def process_msi_namespace(cmd,", "not in aval_sizes: return new_4core_sizes = ['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2', 'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo',", "required/forbidden parameters for VM if namespace.storage_profile == StorageProfile.ManagedPirImage: required = ['image'] forbidden =", "keys) public_key_filepath = string_or_file if public_key_filepath[-4:].lower() == '.pub': private_key_filepath = public_key_filepath[:-4] else: private_key_filepath", "description='network balancer: application gateway') elif balancer_type == 'loadBalancer': # LoadBalancer frontend required =", "vnet_match.subnets if _check_subnet(s)), None) if not result: continue namespace.subnet = result.name namespace.vnet_name =", "#5 namespace.storage_profile = StorageProfile.ManagedCustomImage elif image_type == 'urn': if namespace.use_unmanaged_disk: # STORAGE PROFILE", "nics namespace.nic_type = 'existing' namespace.public_ip_address_type = None logger.debug('existing NIC(s) will be used') def", "is required to create the image, \" \"please specify '--os-type OS_TYPE'\") def _figure_out_storage_source(cli_ctx,", "for s in vnet_match.subnets if _check_subnet(s)), None) if not result: continue namespace.subnet =", "parameter validation for the specific storage profile # start with the required/forbidden parameters", "# region VMSS Create Validators def _get_default_address_pool(cli_ctx, resource_group, balancer_name, balancer_type): option_name = '--backend-pool-name'", "def _validate_managed_disk_sku(sku): allowed_skus = ['Premium_LRS', 'Standard_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS'] if sku and sku.lower() not", "AppGateway frontend required = [] if namespace.app_gateway_type == 'new': required.append('app_gateway_sku') required.append('app_gateway_capacity') if namespace.vnet_type", "'--os-type OS_TYPE'\") def _figure_out_storage_source(cli_ctx, resource_group_name, source): from msrestazure.azure_exceptions import CloudError source_blob_uri = None", "to verify the defaults we are coming out vnet_ip_address, mask = vnet_cidr.split('/') vnet_bit_mask_len", "= namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, lb_name, 'load_balancers') if not namespace.nat_pool_name: if len(lb.inbound_nat_pools)", "compute_client = _compute_client_factory(cli_ctx) # pylint: disable=no-member try: info = compute_client.snapshots.get(resource_group_name, source) source_snapshot =", "1: raise CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify '{0}' explicitly.\".format( # pylint:", "for t in namespace.target_regions: parts = t.split('=', 1) if len(parts) == 1: regions_info.append(TargetRegion(name=parts[0]))", "pool was configured on '%s'\", namespace.load_balancer) else: namespace.nat_pool_name = lb.inbound_nat_pools[0].name logger.debug(\"using specified existing", "no such needs so far if getattr(namespace, 'public_ip_sku', None): from azure.cli.core.profiles import ResourceType", "def _get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr, new_mask): def _convert_to_int(address, bit_mask_len): a, b, c, d = [int(x)", "because availablity zone is not yet \" \"supported. Please use '--location' to specify", "namespace): from msrestazure.tools import parse_resource_id, resource_id from azure.cli.core.commands.client_factory import get_subscription_id if namespace.availability_set: as_id", "be missing ssh/rdp, so warn here. logger.warning(\"No inbound nat pool was configured on", "if a.sku.tier.value == sku_tier and a.location == namespace.location), None) if account: # 3", "azure.cli.core.commands.client_factory import get_mgmt_service_client return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx)) def get_network_lb(cli_ctx, resource_group_name, lb_name): from msrestazure.azure_exceptions", "pattern urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image) if urn_match: namespace.os_publisher = urn_match.group(1) namespace.os_offer = urn_match.group(2)", "'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, lb_name, 'load_balancers') if not namespace.nat_pool_name:", "get_network_client(cli_ctx) try: return network_client.load_balancers.get(resource_group_name, lb_name) except CloudError: return None def process_vmss_create_namespace(cmd, namespace): validate_tags(namespace)", "if not namespace.storage_sku and namespace.storage_profile in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]: # pylint: disable=line-too-long namespace.storage_sku =", "raise CLIError(\"{}'s location can't be used to create the VM/VMSS because availablity zone", "configured on '%s'\", namespace.load_balancer) else: namespace.nat_pool_name = lb.inbound_nat_pools[0].name logger.debug(\"using specified existing load balancer", "azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx)) def get_network_lb(cli_ctx,", "['Premium_LRS', 'Standard_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS'] if sku and sku.lower() not in [x.lower() for x", "v} return resource_id(**kwargs) if not missing_kwargs else None def _get_nic_id(cli_ctx, val, resource_group): return", "required: required.remove(prop) if prop in forbidden: forbidden.remove(prop) # set default storage SKU if", "= source elif '/snapshots/' in source.lower(): source_snapshot = source else: compute_client = _compute_client_factory(cli_ctx)", "if gallery_image_version.lower() in ['latest', '']: image_version_infos = compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) image_version_infos =", "\"sourceVault\": { \"id\": \"value\" }, \"vaultCertificates\": [{ \"certificateUrl\": \"value\", \"certificateStore\": \"cert store name", "namespace.image) namespace.image = _get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name, 'images', 'Microsoft.Compute') return 'image_id' except CloudError: err", "namespace.use_unmanaged_disk: # STORAGE PROFILE #3 namespace.storage_profile = StorageProfile.SASpecializedOSDisk else: # STORAGE PROFILE #6", "vnet_int: raise CLIError(error_msg) # format back to the cidr candaidate_str = '{0:32b}'.format(candidate_int <<", "'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, ag_name, 'application_gateways') logger.debug(\"using specified existing", "len(lb.inbound_nat_pools) > 1: raise CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify '{0}' explicitly.\".format(", "replica count must be an integer\".format(parts[0])) regions_info.append(TargetRegion(name=parts[0], regional_replica_count=replica_count)) namespace.target_regions = regions_info # endregion", "def validate_vm_nics(cmd, namespace): rg = namespace.resource_group_name nic_ids = [] for n in namespace.nics:", "in (temp.location_info or []) if x.zones]: raise CLIError(\"{}'s location can't be used to", "azure.cli.core.commands.client_factory import get_subscription_id if is_valid_resource_id(val): return val kwargs = { 'name': val, 'resource_group':", "StorageProfile.SASpecializedOSDisk]: return namespace.admin_username = _validate_admin_username(namespace.admin_username, namespace.os_type) if not namespace.os_type: raise CLIError(\"Unable to resolve", "or \\ _get_default_address_pool(cmd.cli_ctx, rg, lb_name, 'load_balancers') if not namespace.nat_pool_name: if len(lb.inbound_nat_pools) > 1:", "forbidden = ['attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SASpecializedOSDisk: required = ['os_type', 'attach_os_disk', 'use_unmanaged_disk']", "namespace.admin_password: namespace.admin_password = prompt_pass('Admin Password: ', confirm=True) except NoTTYException: raise CLIError('Please specify password", "target resource group client = get_network_client(cmd.cli_ctx).virtual_networks # find VNET in target resource group", "'Standard_L16s_v2', 'Standard_L32s_v2', 'Standard_L64s_v2', 'Standard_L96s_v2', 'SQLGL', 'SQLGLCore', 'Standard_D4_v3', 'Standard_D4s_v3', 'Standard_D2_v2', 'Standard_DS2_v2', 'Standard_E4_v3', 'Standard_E4s_v3', 'Standard_F2',", "subscription_id=res['subscription']) vm_info = compute_client.virtual_machines.get(res['resource_group'], res['name']) # pylint: disable=no-member namespace.os_type = vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine =", "else: namespace.nat_pool_name = lb.inbound_nat_pools[0].name logger.debug(\"using specified existing load balancer '%s'\", namespace.load_balancer) else: namespace.load_balancer_type", "'Standard_M64s', 'Standard_M128-64ms', 'Standard_D64_v3', 'Standard_D64s_v3', 'Standard_E64_v3', 'Standard_E64s_v3', 'Standard_E64-16s_v3', 'Standard_E64-32s_v3', 'Standard_F64s_v2', 'Standard_F72s_v2', 'Standard_M128s', 'Standard_M128ms', 'Standard_L8s_v2',", "namespace, from_set_command=True) def process_remove_identity_namespace(cmd, namespace): if namespace.identities: from ._vm_utils import MSI_LOCAL_ID for i", "= load_images_from_aliases_doc(cmd.cli_ctx) matched = next((x for x in images if x['urnAlias'].lower() == namespace.image.lower()),", "supported image in the marketplace # Ubuntu 16.04, SLES 12 SP3, RHEL 7.4,", "rg, 'Microsoft.Network', 'subnets', vnet, 'virtualNetworks') if subnet_is_id and not subnet_exists: raise CLIError(\"Subnet '{}'", "authentication type if namespace.authentication_type == 'password': if namespace.ssh_key_value or namespace.ssh_dest_key_path: raise ValueError( \"incorrect", "can only be used when creating a new load ' 'balancer or application", "is None: from azure.cli.core.cloud import AZURE_US_GOV_CLOUD if cmd.cli_ctx.cloud.name != AZURE_US_GOV_CLOUD.name: namespace.vm_sku = 'Standard_DS1_v2'", "required, forbidden, description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num = 0 if namespace.storage_profile == StorageProfile.ManagedCustomImage: #", ":param dict secrets: Dict fitting the JSON description above :param string os_type: the", "cmd.cli_ctx, namespace.resource_group_name, namespace.source) if not namespace.source_blob_uri and namespace.source_storage_account_id: raise CLIError(usage_error) except CloudError: raise", "val, 'resource_group': resource_group, 'namespace': resource_namespace, 'type': resource_type, 'subscription': get_subscription_id(cli_ctx) } missing_kwargs = {k:", "# apply default auth type (password for Windows, ssh for Linux) by examining", "raise CLIError('Error decoding secrets: {0}'.format(err)) for idx_arg, narg_secret in enumerate(loaded_secret): for idx, secret", "if size not in aval_sizes: return new_4core_sizes = ['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2', 'Standard_DS3_v2_Promo',", "from_set_command=False): if from_set_command or namespace.assign_identity is not None: identities = namespace.assign_identity or []", "if x != MSI_LOCAL_ID] if user_assigned_identities and not cmd.supported_api_version(min_api='2017-12-01'): raise CLIError('usage error: user", "'centos', '^7.4'), ('coreos', 'coreos', None), ('credativ', 'debian', '-backports'), ('oracle', 'oracle-linux', '^7.4'), ('MicrosoftWindowsServer', 'WindowsServer',", "[] if not nics_value: namespace.nic_type = 'new' logger.debug('new NIC will be created') return", "* factor) def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace): if namespace.accelerated_networking is None: size = getattr(namespace, 'size',", "disable=line-too-long pattern = (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if is_linux else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err = r'admin user name", "source_disk, source_snapshot) def process_disk_encryption_namespace(cmd, namespace): namespace.disk_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') if", "image = compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku, image_version) # pylint: disable=no-member return image.plan except", "# accept disk name or ID namespace.attach_os_disk = _get_resource_id( cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name, 'disks',", "os_type: the type of OS (linux or windows) :return: errors if any were", "None): from azure.cli.core.profiles import ResourceType PublicIPAddressSkuName, IPAllocationMethod = cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK) if namespace.public_ip_sku", "'--application-gateway NAME_OR_ID') # Resolve the type of balancer (if any) being used balancer_type", "cmd.get_models('TargetRegion') if namespace.target_regions: regions_info = [] for t in namespace.target_regions: parts = t.split('=',", "= LBSkuName.standard.value logger.debug(\"use Standard sku as single placement group is turned off\") elif", "balancer (if any) being used balancer_type = 'None' if namespace.load_balancer is None and", "Exception as err: raise CLIError('Error decoding secrets: {0}'.format(err)) for idx_arg, narg_secret in enumerate(loaded_secret):", "value.\".format(username)) return username def _validate_admin_password(password, os_type): import re is_linux = (os_type.lower() == 'linux')", "source_snapshot = info.id except CloudError: info = compute_client.disks.get(resource_group_name, source) source_disk = info.id return", "cannot be used with SSH authentication type') validate_ssh_key(namespace) if not namespace.ssh_dest_key_path: namespace.ssh_dest_key_path =", "None if urlparse(source).scheme: # a uri? source_blob_uri = source elif '/disks/' in source.lower():", "existing managed disk image resource compute_client = _compute_client_factory(cmd.cli_ctx) try: compute_client.images.get(namespace.resource_group_name, namespace.image) namespace.image =", "d, namespace.resource_group_name, 'disks', 'Microsoft.Compute') for d in namespace.attach_data_disks] if not namespace.os_type: namespace.os_type =", "in namespace.os_offer.lower() else 'linux' from ._vm_utils import normalize_disk_info # attach_data_disks are not exposed", "'new' logger.debug('new public IP address will be created') # Public-IP SKU is only", "= _get_resource_id(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'networkSecurityGroups', 'Microsoft.Network') def _validate_vm_vmss_create_public_ip(cmd, namespace): if namespace.public_ip_address: if check_existence(cmd.cli_ctx,", "when assign system identity\") # keep 'identity_role' for output as logical name is", "[x.lower() for x in new_4core_sizes] if size not in new_4core_sizes: compute_client = _compute_client_factory(cli_ctx)", "required.append('backend_pool_name') forbidden = ['nat_pool_name', 'load_balancer', 'health_probe'] validate_parameter_set(namespace, required, forbidden, description='network balancer: application gateway')", "namespace, required, forbidden, description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num = 0 if namespace.storage_profile == StorageProfile.ManagedCustomImage:", "[] if names_or_ids == [\"\"] or not names_or_ids: return for val in names_or_ids:", "only applicable on Windows VM') _validate_vm_vmss_msi(cmd, namespace) if namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage = get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage)", "Secrets JSON structure [{ \"sourceVault\": { \"id\": \"value\" }, \"vaultCertificates\": [{ \"certificateUrl\": \"value\",", "_compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) if res['type'].lower() == 'images': image_info = compute_client.images.get(res['resource_group'], res['name']) namespace.os_type = image_info.storage_profile.os_disk.os_type.value", "{0} in ' \\ 'arg {1} ' errors.append(err.format(idx, idx_arg)) else: for jdx, cert", "new_4core_sizes] if size not in new_4core_sizes: compute_client = _compute_client_factory(cli_ctx) sizes = compute_client.virtual_machine_sizes.list(namespace.location) size_info", "offer.lower(), sku.lower() distros = [('canonical', 'UbuntuServer', '^16.04'), ('suse', 'sles', '^12-sp3'), ('redhat', 'rhel', '^7.4'),", "res_id = _get_resource_id(cmd.cli_ctx, namespace.source, namespace.resource_group_name, 'virtualMachines', 'Microsoft.Compute') res = parse_resource_id(res_id) compute_client = _compute_client_factory(cmd.cli_ctx,", "for n in namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg)) namespace.nics = nic_ids if hasattr(namespace, 'primary_nic')", "subnet and not nics: logger.debug('no subnet specified. Attempting to find an existing Vnet", "username.endswith('.'): raise CLIError(win_err) disallowed_user_names = [ \"administrator\", \"admin\", \"user\", \"user1\", \"test\", \"user2\", \"test1\",", "balancer_type = 'applicationGateway' if balancer_type == 'applicationGateway': if namespace.application_gateway: client = get_network_client(cmd.cli_ctx).application_gateways try:", "\"a\", \"actuser\", \"adm\", \"admin2\", \"aspnet\", \"backup\", \"console\", \"guest\", \"owner\", \"root\", \"server\", \"sql\", \"support\",", "VM's location with a matching subnet for vnet_match in (v for v in", "not x.publishing_profile.exclude_from_latest] if not image_version_infos: raise CLIError('There is no latest image version exists", "- check if a fully-qualified ID (assumes it is an image ID) if", "if is_valid_resource_id(val): return val kwargs = { 'name': val, 'resource_group': resource_group, 'namespace': resource_namespace,", "return None def _get_resource_id(cli_ctx, val, resource_group, resource_type, resource_namespace): from msrestazure.tools import resource_id, is_valid_resource_id", "'images', 'Microsoft.Compute') return 'image_id' except CloudError: err = 'Invalid image \"{}\". Use a", "managed custom image res = parse_resource_id(namespace.image) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) if res['type'].lower() ==", "for VM if namespace.storage_profile == StorageProfile.ManagedPirImage: required = ['image'] forbidden = ['os_type', 'attach_os_disk',", "for p, o, s in distros: if p.lower() == publisher and (o is", "if not namespace.public_ip_address_allocation: namespace.public_ip_address_allocation = IPAllocationMethod.static.value def _validate_vmss_create_public_ip(cmd, namespace): if namespace.load_balancer_type is None", "usage for authentication-type 'password': \" \"[--admin-username USERNAME] --admin-password PASSWORD\") from knack.prompting import prompt_pass,", "is not applicable as the '--scope' is not provided\".format( namespace.identity_role)) user_assigned_identities = [x", "sourceVault.id key at index {0} in arg {1}'.format( idx, idx_arg)) if 'vaultCertificates' not", "_validate_vmss_create_nsg(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd, namespace) if namespace.license_type and namespace.os_type.lower() != 'windows':", "min_length = 12 if len(password) not in range(min_length, max_length + 1): raise CLIError('The", "not None and namespace.zones is None: raise CLIError('usage error: --platform-fault-domain-count COUNT --zones ZONES')", "None: namespace.load_balancer_sku = LBSkuName.standard.value logger.debug(\"use Standard sku as single placement group is turned", "'.join([n.name for n in lb.inbound_nat_pools]))) elif not lb.inbound_nat_pools: # Associated scaleset will be", "be created') return if not isinstance(nics_value, list): nics_value = [nics_value] for n in", "= get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults for vault in client.list(): id_comps = parse_resource_id(vault.id) if id_comps['name'] ==", "and not nics: logger.debug('no subnet specified. Attempting to find an existing Vnet and", "next((s for s in vnet_match.subnets if _check_subnet(s)), None) if not result: continue namespace.subnet", "aval_sizes: return new_4core_sizes = ['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2', 'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC', 'Standard_DS12_v2',", "'Standard_F72s_v2', 'Standard_M128s', 'Standard_M128ms', 'Standard_L8s_v2', 'Standard_L16s_v2', 'Standard_L32s_v2', 'Standard_L64s_v2', 'Standard_L96s_v2', 'SQLGL', 'SQLGLCore', 'Standard_D4_v3', 'Standard_D4s_v3', 'Standard_D2_v2',", "[x for x in image_version_infos if not x.publishing_profile.exclude_from_latest] if not image_version_infos: raise CLIError('There", "should be a subrange of --vnet-address-prefix's\" # extract vnet information needed to verify", "an existing managed disk image resource compute_client = _compute_client_factory(cmd.cli_ctx) try: compute_client.images.get(namespace.resource_group_name, namespace.image) namespace.image", "from azure.cli.core.commands.client_factory import get_subscription_id if namespace.availability_set: as_id = parse_resource_id(namespace.availability_set) name = as_id['name'] rg", "hasattr(namespace, 'primary_nic') and namespace.primary_nic: namespace.primary_nic = _get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg) def _validate_secrets(secrets, os_type): \"\"\"", "'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo', 'Standard_DS4_v2', 'Standard_DS13_v2', 'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo', 'Standard_F8', 'Standard_F8s', 'Standard_M64-16ms', 'Standard_D16_v3', 'Standard_D16s_v3',", "will be created.') def _validate_vm_create_availability_set(cmd, namespace): from msrestazure.tools import parse_resource_id, resource_id from azure.cli.core.commands.client_factory", "'Standard_L8s_v2', 'Standard_L16s_v2', 'Standard_L32s_v2', 'Standard_L64s_v2', 'Standard_L96s_v2', 'SQLGL', 'SQLGLCore', 'Standard_D4_v3', 'Standard_D4s_v3', 'Standard_D2_v2', 'Standard_DS2_v2', 'Standard_E4_v3', 'Standard_E4s_v3',", "elif image_type == 'urn': if namespace.use_unmanaged_disk: # STORAGE PROFILE #1 namespace.storage_profile = StorageProfile.SAPirImage", "will be created.\", namespace.nsg) elif namespace.nsg == '': namespace.nsg_type = None logger.debug('no NSG", "'index {1} and vaultCertificate index {2} in arg {3}' if 'certificateUrl' not in", "namespace): from msrestazure.tools import parse_resource_id from msrestazure.azure_exceptions import CloudError validate_tags(namespace) try: # try", "\"'Standard' load balancer is required because 'single placement group' is turned off\" raise", "namespace.accelerated_networking is None: size = getattr(namespace, 'size', None) or getattr(namespace, 'vm_sku', None) size", "def process_disk_encryption_namespace(cmd, namespace): namespace.disk_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') if namespace.key_encryption_keyvault: if", "[] if namespace.app_gateway_type == 'new': required.append('app_gateway_sku') required.append('app_gateway_capacity') if namespace.vnet_type != 'new': required.append('app_gateway_subnet_address_prefix') elif", "_validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False): from msrestazure.tools import parse_resource_id # use minimal parameters to resolve", "# STORAGE PROFILE #2 namespace.storage_profile = StorageProfile.SACustomImage elif image_type == 'image_id': # STORAGE", "# pylint: disable=no-member elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: # accept disk name or ID", "vnet_int: # overflows? candidate_int = candidate_int - 2 # try the other way", "else: # needed for Stack profile 2017_03_09 balancer_type = 'loadBalancer' if namespace.single_placement_group is", "import is_valid_resource_id keyvault_usage = CLIError('usage error: [--keyvault NAME --resource-group NAME | --keyvault ID]')", "location can't be used to create the VM/VMSS because availablity zone is not", "logger.debug(\"storage profile '%s'\", namespace.storage_profile) if for_scale_set: # VMSS lacks some parameters, so scrub", "== n } }) namespace.nics = nics namespace.nic_type = 'existing' namespace.public_ip_address_type = None", "check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_type = 'existing' logger.debug(\"using specified NSG '%s'\", namespace.nsg)", "defaulting to '%s' under because single placement group is disabled\", balancer_type) elif namespace.load_balancer:", "= res.get('child_name_2', '') if gallery_image_version.lower() in ['latest', '']: image_version_infos = compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'], gallery_name=res['name'],", "int(mask) if vnet_bit_mask_len <= subnet_bit_mask_len: raise CLIError(error_msg) candidate_int = _convert_to_int(subnet_ip_address, subnet_bit_mask_len) + 1", "for_scale_set: # VMSS lacks some parameters, so scrub these out props_to_remove = ['attach_os_disk',", "resource_group = namespace.resource_group_name subscription_id = get_subscription_id(cmd.cli_ctx) names_or_ids = getattr(namespace, 'application_security_groups') ids = []", "subnet found. One will be created.') def _subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision): mask = int(subnet_mask)", "enough leeway for over-provision factor = 1.5 if over_provision else 1 return ((1", "pattern = (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if is_linux else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err = r'admin user name cannot", "namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage = get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage) # endregion # region VMSS Create Validators def", "will be used') def _validate_vm_vmss_create_auth(namespace): if namespace.storage_profile in [StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]: return namespace.admin_username =", "-------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the", "Validates a parsed JSON array containing secrets for use in VM Creation Secrets", "CLIError('incorrect usage: --image IMAGE | --attach-os-disk DISK') auth_params = ['<PASSWORD>_password', 'admin_username', 'authentication_type', 'generate_ssh_keys',", "'Microsoft.KeyVault') if namespace.key_encryption_keyvault: if not namespace.key_encryption_key: raise CLIError(\"Incorrect usage '--key-encryption-keyvault': \" \"'--key-encryption-key' is", "resource_group, resource_type, resource_namespace): from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.commands.client_factory import get_subscription_id if", "for zonal scale-sets\" elif namespace.instance_count > 100: err = \"'Standard' load balancer is", "pick an id from '{}'\" raise CLIError(err.format(role, ids)) role_id = role_defs[0].id return role_id", "broadcasting addresses # '*1.5' so we have enough leeway for over-provision factor =", "'Standard_E32-16s_v3', 'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC', 'Standard_F8_ABC', 'Standard_F16s_v2', 'Standard_D5_v2', 'Standard_D14_v2', 'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo', 'Standard_DS5_v2', 'Standard_DS14_v2', 'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo',", "msrestazure.tools import is_valid_resource_id keyvault_usage = CLIError('usage error: [--keyvault NAME --resource-group NAME | --keyvault", "else: if kv and not is_valid_resource_id(kv): raise keyvault_usage def _get_resource_group_from_vault_name(cli_ctx, vault_name): \"\"\" Fetch", "image res = parse_resource_id(namespace.image) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) if res['type'].lower() == 'images': image_info", "<< subnet_bit_mask_len) return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2), int(candaidate_str[8:16], 2), int(candaidate_str[16:24], 2), int(candaidate_str[24:32], 2), new_mask) def", "None: identities = namespace.assign_identity or [] from ._vm_utils import MSI_LOCAL_ID for i, _", "storage account specified namespace.storage_account_type = 'new' logger.debug(\"specified storage account '%s' not found and", "azure.cli.core.commands.client_factory import get_subscription_id ApplicationSecurityGroup = cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK) resource_group = namespace.resource_group_name subscription_id = get_subscription_id(cmd.cli_ctx)", "image XOR attach-os-disk raise CLIError('incorrect usage: --image IMAGE | --attach-os-disk DISK') auth_params =", "USERNAME] --admin-password PASSWORD\") from knack.prompting import prompt_pass, NoTTYException try: if not namespace.admin_password: namespace.admin_password", "cannot contain upper case character A-Z, special characters \\/\"[]:|<>+=;,?*@#()! or start with $", "keyvault_usage def _get_resource_group_from_vault_name(cli_ctx, vault_name): \"\"\" Fetch resource group from vault name :param str", "'Standard_D5_v2', 'Standard_D14_v2', 'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo', 'Standard_DS5_v2', 'Standard_DS14_v2', 'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo', 'Standard_F16', 'Standard_F16s', 'Standard_M64-32ms', 'Standard_M128-32ms', 'Standard_D32_v3',", "cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK) if namespace.public_ip_sku == PublicIPAddressSkuName.standard.value: if not namespace.public_ip_address_allocation: namespace.public_ip_address_allocation = IPAllocationMethod.static.value", "namespace) if namespace.storage_profile in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd, namespace) _validate_vm_create_availability_set(cmd, namespace) _validate_vm_vmss_create_vnet(cmd, namespace) _validate_vm_create_nsg(cmd,", "resolve OS type. Specify '--os-type' argument.\") if not namespace.authentication_type: # apply default auth", "'UltraSSD_LRS' and namespace.ultra_ssd_enabled is None: namespace.ultra_ssd_enabled = True # Now verify that the", "be used') def _validate_vm_vmss_create_auth(namespace): if namespace.storage_profile in [StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]: return namespace.admin_username = _validate_admin_username(namespace.admin_username,", "compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku, image_version) # pylint: disable=no-member return image.plan except CloudError as", "= StorageProfile.ManagedSpecializedOSDisk elif namespace.image and not getattr(namespace, 'attach_os_disk', None): image_type = _parse_image_argument(cmd, namespace)", "the expected storage profile if getattr(namespace, 'attach_os_disk', None) and not namespace.image: if namespace.use_unmanaged_disk:", "found\", namespace.vnet_name, namespace.subnet) return if subnet: subnet_is_id = is_valid_resource_id(subnet) if (subnet_is_id and vnet)", "nics = getattr(namespace, 'nics', None) if not vnet and not subnet and not", "namespace.nsg, namespace.resource_group_name, 'networkSecurityGroups', 'Microsoft.Network') def _validate_vm_vmss_create_public_ip(cmd, namespace): if namespace.public_ip_address: if check_existence(cmd.cli_ctx, namespace.public_ip_address, namespace.resource_group_name,", "in arg {1}'.format( idx, idx_arg)) if 'sourceVault' in secret and 'id' not in", "idx_arg, narg_secret in enumerate(loaded_secret): for idx, secret in enumerate(narg_secret): if 'sourceVault' not in", "not found. It will be created.\", namespace.public_ip_address) elif namespace.public_ip_address == '': namespace.public_ip_address_type =", "for Windows, ssh for Linux) by examining the OS type namespace.authentication_type = 'password'", "role_id: # retrieve role id role_defs = list(client.list(scope, \"roleName eq '{}'\".format(role))) if not", "= ['app_gateway_subnet_address_prefix', 'application_gateway', 'app_gateway_sku', 'app_gateway_capacity'] validate_parameter_set(namespace, required, forbidden, description='network balancer: load balancer') if", "namespace.primary_nic = _get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg) def _validate_secrets(secrets, os_type): \"\"\" Validates a parsed JSON", "'%s'\", storage_id['name']) else: # 2 - params for new storage account specified namespace.storage_account_type", "'Standard_D4_v3', 'Standard_D4s_v3', 'Standard_D2_v2', 'Standard_DS2_v2', 'Standard_E4_v3', 'Standard_E4s_v3', 'Standard_F2', 'Standard_F2s', 'Standard_F4s_v2', 'Standard_D11_v2', 'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C'] aval_sizes", "sizes if s.name.lower() == size), None) if size_info is None or size_info.number_of_cores <", "import re # 1 - check if a fully-qualified ID (assumes it is", "storage account specified namespace.storage_account_type = 'existing' logger.debug(\"using specified existing storage account '%s'\", storage_id['name'])", "namespace) _validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd, namespace) _validate_vmss_create_nsg(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd, namespace) if namespace.license_type", "= 72 if is_linux else 123 min_length = 12 if len(password) not in", "will be created') # AppGateway frontend required = [] if namespace.app_gateway_type == 'new':", "public_key_filepath + '.private' content = keys.generate_ssh_keys(private_key_filepath, public_key_filepath) logger.warning(\"SSH key files '%s' and '%s'", "'storage_container_name', 'data_disk_sizes_gb', 'storage_sku'] + auth_params else: raise CLIError('Unrecognized storage profile: {}'.format(namespace.storage_profile)) logger.debug(\"storage profile", "'storage_account'] for prop in props_to_remove: if prop in required: required.remove(prop) if prop in", "name, id, or pick one from {}' raise CLIError(err.format(namespace.image, [x['urnAlias'] for x in", "for idx, secret in enumerate(narg_secret): if 'sourceVault' not in secret: errors.append( 'Secret is", "\"test\", \"user2\", \"test1\", \"user3\", \"admin1\", \"1\", \"123\", \"a\", \"actuser\", \"adm\", \"admin2\", \"aspnet\", \"backup\",", "allowed_skus)) def _validate_location(cmd, namespace, zone_info, size_info): from ._vm_utils import list_sku_info if not namespace.location:", "CLIError(error_msg) candidate_int = _convert_to_int(subnet_ip_address, subnet_bit_mask_len) + 1 if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len))", "if source_snapshot: namespace.data_snapshots.append(source_snapshot) if not namespace.os_type: raise CLIError(\"usage error: os type is required", "= get_subscription_id(cmd.cli_ctx) names_or_ids = getattr(namespace, 'application_security_groups') ids = [] if names_or_ids == [\"\"]", "if s.name.lower() == 'gatewaysubnet': return False subnet_mask = s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask, namespace.instance_count, not", "namespace.data_disks = [] namespace.data_snapshots = [] if namespace.data_disk_sources: for data_disk_source in namespace.data_disk_sources: source_blob_uri,", "None) and not namespace.image: if namespace.use_unmanaged_disk: # STORAGE PROFILE #3 namespace.storage_profile = StorageProfile.SASpecializedOSDisk", "logger.debug(\"use Standard sku as single placement group is turned off\") elif namespace.load_balancer_sku ==", "else: # 4 - nothing specified - create a new storage account namespace.storage_account_type", "Attempting to find an existing Vnet and subnet...') # if nothing specified, try", "determines what type is supplied for the --image parameter. Updates the namespace and", "'Standard_DS12_v2', 'Standard_DS13-4_v2', 'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo', 'Standard_F4', 'Standard_F4s', 'Standard_D8_v3', 'Standard_D8s_v3', 'Standard_D32-8s_v3', 'Standard_E8_v3',", "== StorageProfile.SAPirImage: required = ['image', 'use_unmanaged_disk'] forbidden = ['os_type', 'attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile", "namespace.storage_account: storage_id = parse_resource_id(namespace.storage_account) rg = storage_id.get('resource_group', namespace.resource_group_name) if check_existence(cmd.cli_ctx, storage_id['name'], rg, 'Microsoft.Storage',", "None or o.lower() == offer) and (s is None or re.match(s, sku, re.I)):", "pylint: disable=import-error from knack.log import get_logger from knack.util import CLIError from azure.cli.core.commands.validators import", "allowed when capturing \" \"images from virtual machines\") except CloudError: namespace.os_blob_uri, namespace.os_disk, namespace.os_snapshot", "namespace.accelerated_networking = True def _validate_vmss_create_subnet(namespace): if namespace.vnet_type == 'new': if namespace.subnet_address_prefix is None:", "gallery_image_name=res['child_name_1']) image_version_infos = [x for x in image_version_infos if not x.publishing_profile.exclude_from_latest] if not", "CLIError('\\n'.join(errors)) # region VM Create Validators def _parse_image_argument(cmd, namespace): \"\"\" Systematically determines what", "source elif '/snapshots/' in source.lower(): source_snapshot = source else: compute_client = _compute_client_factory(cli_ctx) #", "100+ instances\" else: err = \"'Standard' load balancer is required because 'single placement", "suitable subnet found. One will be created.') def _subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision): mask =", "'availabilitySets'): raise CLIError(\"Availability set '{}' does not exist.\".format(name)) namespace.availability_set = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg,", "list_sku_info(cmd.cli_ctx, namespace.location) temp = next((x for x in sku_infos if x.name.lower() == size_info.lower()),", "StorageProfile.SASpecializedOSDisk: return 'attach to existing unmanaged OS disk' elif profile == StorageProfile.ManagedCustomImage: return", "= vnet_cidr.split('/') vnet_bit_mask_len = 32 - int(mask) vnet_int = _convert_to_int(vnet_ip_address, vnet_bit_mask_len) subnet_ip_address, mask", "such needs so far if getattr(namespace, 'public_ip_sku', None): from azure.cli.core.profiles import ResourceType PublicIPAddressSkuName,", "namespace.plan_name = image_plan.name namespace.plan_product = image_plan.product namespace.plan_publisher = image_plan.publisher return 'urn' # 3", "and not getattr(namespace, 'attach_os_disk', None): image_type = _parse_image_argument(cmd, namespace) if image_type == 'uri':", "re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image) if urn_match: namespace.os_publisher = urn_match.group(1) namespace.os_offer = urn_match.group(2) namespace.os_sku = urn_match.group(3)", "username def _validate_admin_password(password, os_type): import re is_linux = (os_type.lower() == 'linux') max_length =", "SLES 12 SP3, RHEL 7.4, CentOS 7.4, CoreOS Linux, Debian \"Stretch\" with backports", "can be \" \"used to find such locations\".format(namespace.resource_group_name)) # pylint: disable=too-many-branches, too-many-statements def", "in [StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]: return namespace.admin_username = _validate_admin_username(namespace.admin_username, namespace.os_type) if not namespace.os_type: raise CLIError(\"Unable", "n else resource_id(name=n, resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)), 'properties': { 'primary': nics_value[0] == n", "{1}\\nSpecify '{0}' \" \"explicitly.\".format(option_name, ', '.join(values))) elif not values: raise CLIError(\"No existing values", "scaleset') if not namespace.public_ip_per_vm and namespace.vm_domain_name: raise CLIError('Usage error: --vm-domain-name can only be", "(o is None or o.lower() == offer) and (s is None or re.match(s,", "nothing specified - create a new storage account namespace.storage_account_type = 'new' logger.debug('no suitable", "kwargs = { 'name': val, 'resource_group': resource_group, 'namespace': resource_namespace, 'type': resource_type, 'subscription': get_subscription_id(cli_ctx)", "gallery_image_version_name=res['child_name_2']) image_data_disks_num = len(image_version_info.storage_profile.data_disk_images or []) else: raise CLIError('usage error: unrecognized image informations", "info = compute_client.disks.get(resource_group_name, source) source_disk = info.id return (source_blob_uri, source_disk, source_snapshot) def process_disk_encryption_namespace(cmd,", "logger.debug('no suitable storage account found. One will be created.') def _validate_vm_create_availability_set(cmd, namespace): from", "resource_namespace): from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.commands.client_factory import get_subscription_id if is_valid_resource_id(val): return", "namespace.os_offer.lower() else 'linux' from ._vm_utils import normalize_disk_info # attach_data_disks are not exposed yet", "'Microsoft.Network', 'publicIPAddresses'): namespace.public_ip_address_type = 'existing' logger.debug(\"using existing specified public IP '%s'\", namespace.public_ip_address) else:", "balancer.backend_address_pools] if len(values) > 1: raise CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify", "!= 'new': required.append('app_gateway_subnet_address_prefix') elif namespace.app_gateway_type == 'existing': required.append('backend_pool_name') forbidden = ['nat_pool_name', 'load_balancer', 'health_probe']", "content = f.read() elif not keys.is_valid_ssh_rsa_public_key(content): if namespace.generate_ssh_keys: # figure out appropriate file", "let CLI generate one for you') namespace.ssh_key_value = content def _validate_vm_vmss_msi(cmd, namespace, from_set_command=False):", "type of OS (linux or windows) :return: errors if any were found :rtype:", "\"value\", \"certificateStore\": \"cert store name (only on windows)\" }] }] :param dict secrets:", "= [x for x in image_version_infos if not x.publishing_profile.exclude_from_latest] if not image_version_infos: raise", "normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace, 'attach_data_disks', []), storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching) def _validate_vm_create_storage_account(cmd, namespace): from msrestazure.tools", "and subnet...') # if nothing specified, try to find an existing vnet and", "('redhat', 'rhel', '^7.4'), ('openlogic', 'centos', '^7.4'), ('coreos', 'coreos', None), ('credativ', 'debian', '-backports'), ('oracle',", "from ._vm_utils import MSI_LOCAL_ID for i in range(len(namespace.identities)): if namespace.identities[i] != MSI_LOCAL_ID: namespace.identities[i]", "raise CLIError(\"usage error: {}'s replica count must be an integer\".format(parts[0])) regions_info.append(TargetRegion(name=parts[0], regional_replica_count=replica_count)) namespace.target_regions", "in secret: errors.append( 'Secret is missing sourceVault key at index {0} in arg", "provided\".format( namespace.identity_role)) user_assigned_identities = [x for x in identities if x != MSI_LOCAL_ID]", "namespace.source, namespace.resource_group_name, 'virtualMachines', 'Microsoft.Compute') res = parse_resource_id(res_id) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) vm_info =", "pylint: disable=line-too-long namespace.storage_sku = 'Standard_LRS' if for_scale_set else 'Premium_LRS' if namespace.storage_sku == 'UltraSSD_LRS'", "['<PASSWORD>_password', 'admin_username', 'authentication_type', 'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value'] # perform parameter validation for the specific", "one from {}' raise CLIError(err.format(namespace.image, [x['urnAlias'] for x in images])) def _get_image_plan_info_if_exists(cmd, namespace):", "# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT", "image_version_infos = [x for x in image_version_infos if not x.publishing_profile.exclude_from_latest] if not image_version_infos:", "arg {1}'.format( idx, idx_arg)) if 'sourceVault' in secret and 'id' not in secret['sourceVault']:", "import prompt_pass, NoTTYException try: if not namespace.admin_password: namespace.admin_password = prompt_pass('Admin Password: ', confirm=True)", "False else 'applicationGateway' logger.debug(\"W/o STD LB, defaulting to '%s' under because single placement", "string_or_file if os.path.exists(string_or_file): logger.info('Use existing SSH public key file: %s', string_or_file) with open(string_or_file,", "namespace): \"\"\" Systematically determines what type is supplied for the --image parameter. Updates", "or windows) :return: errors if any were found :rtype: list \"\"\" is_windows =", "specify image XOR attach-os-disk raise CLIError('incorrect usage: --image IMAGE | --attach-os-disk DISK') auth_params", "matched: namespace.os_publisher = matched['publisher'] namespace.os_offer = matched['offer'] namespace.os_sku = matched['sku'] namespace.os_version = matched['version']", "usage: --image IMAGE | --attach-os-disk DISK') auth_params = ['<PASSWORD>_password', 'admin_username', 'authentication_type', 'generate_ssh_keys', 'ssh_dest_key_path',", "ID | --size-gb GB') elif bool(namespace.disk) != bool(namespace.instance_id): raise CLIError('usage error: --disk EXIST_DISK", "= re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password) count = len([x for x in [contains_lower, contains_upper, contains_digit,", "private_key_filepath = public_key_filepath[:-4] else: private_key_filepath = public_key_filepath + '.private' content = keys.generate_ssh_keys(private_key_filepath, public_key_filepath)", "to its own command module https://github.com/Azure/azure-cli/issues/5105 def process_msi_namespace(cmd, namespace): get_default_location_from_resource_group(cmd, namespace) validate_tags(namespace) def", "'{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2), int(candaidate_str[8:16], 2), int(candaidate_str[16:24], 2), int(candaidate_str[24:32], 2), new_mask) def _validate_vm_create_nsg(cmd, namespace): if", "or not [x for x in (temp.location_info or []) if x.zones]: raise CLIError(\"{}'s", "'attach_os_disk', 'use_unmanaged_disk'] forbidden = ['os_disk_name', 'os_caching', 'image', 'storage_account', 'storage_container_name', 'data_disk_sizes_gb', 'storage_sku'] + auth_params", "= get_network_client(cmd.cli_ctx).application_gateways try: rg = parse_resource_id(namespace.application_gateway).get( 'resource_group', namespace.resource_group_name) ag_name = parse_resource_id(namespace.application_gateway)['name'] client.get(rg, ag_name)", "\" \"used to find such locations\".format(namespace.resource_group_name)) # pylint: disable=too-many-branches, too-many-statements def _validate_vm_create_storage_profile(cmd, namespace,", "nics = [] if not nics_value: namespace.nic_type = 'new' logger.debug('new NIC will be", "be used with SSH authentication type') validate_ssh_key(namespace) if not namespace.ssh_dest_key_path: namespace.ssh_dest_key_path = \\", "specified public IP '%s'\", namespace.public_ip_address) else: namespace.public_ip_address_type = 'new' logger.debug(\"specified public IP '%s'", "pylint: disable=inconsistent-return-statements def _get_storage_profile_description(profile): if profile == StorageProfile.SACustomImage: return 'create unmanaged OS disk", "VM') _validate_vm_vmss_msi(cmd, namespace) if namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage = get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage) # endregion # region", "compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) vm_info = compute_client.virtual_machines.get(res['resource_group'], res['name']) # pylint: disable=no-member namespace.os_type =", "and vaultCertificate index {2} in arg {3}' if 'certificateUrl' not in cert: errors.append(message.format('certificateUrl',", "is None: namespace.load_balancer_type = 'new' logger.debug('new load balancer will be created') if namespace.load_balancer_type", "'{}' does not exist.\".format(name)) namespace.availability_set = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg, namespace='Microsoft.Compute', type='availabilitySets', name=name) logger.debug(\"adding", "= _get_resource_id(cmd.cli_ctx, namespace.identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') # TODO move to its own command", "balancer = client.get(resource_group, balancer_name) values = [x.name for x in balancer.backend_address_pools] if len(values)", "publisher and (o is None or o.lower() == offer) and (s is None", "namespace.load_balancer is None: namespace.load_balancer_type = 'new' logger.debug('new load balancer will be created') if", "== StorageProfile.ManagedSpecializedOSDisk: # accept disk name or ID namespace.attach_os_disk = _get_resource_id( cmd.cli_ctx, namespace.attach_os_disk,", "os.path.join(os.path.expanduser('~'), '.ssh', 'id_rsa.pub')) content = string_or_file if os.path.exists(string_or_file): logger.info('Use existing SSH public key", "_subnet_capacity_check(subnet_mask, namespace.instance_count, not namespace.disable_overprovision) result = next((s for s in vnet_match.subnets if _check_subnet(s)),", "if std_lb_is_available: balancer_type = 'loadBalancer' else: # needed for Stack profile 2017_03_09 balancer_type", "= nic_ids if hasattr(namespace, 'primary_nic') and namespace.primary_nic: namespace.primary_nic = _get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg) def", "allowed_skus = ['Premium_LRS', 'Standard_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS'] if sku and sku.lower() not in [x.lower()", "import parse_resource_id, resource_id from azure.cli.core.commands.client_factory import get_subscription_id if namespace.availability_set: as_id = parse_resource_id(namespace.availability_set) name", "or start with $ or -' win_err = r'admin user name cannot contain", "key value must be supplied to SSH Key Value. ' 'You can use", "_validate_vm_create_availability_set(cmd, namespace) _validate_vm_vmss_create_vnet(cmd, namespace) _validate_vm_create_nsg(cmd, namespace) _validate_vm_vmss_create_public_ip(cmd, namespace) _validate_vm_create_nics(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace)", "of the key vault :return: resource group name or None :rtype: str \"\"\"", "-1): if _subnet_capacity_check(i, namespace.instance_count, not namespace.disable_overprovision): break if i < 16: err =", "'{}'\".format(role))) if not role_defs: raise CLIError(\"Role '{}' doesn't exist.\".format(role)) elif len(role_defs) > 1:", "validate_keyvault(cmd, namespace): namespace.keyvault = _get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_vm_secret_format(cmd, namespace): from", "vhd based images? if urlparse(namespace.image).scheme: return 'uri' # 4 - attempt to match", "_validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace) _validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd, namespace) _validate_vmss_create_nsg(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd, namespace) if", "| --source VHD_BLOB_URI [--source-storage-account-id ID]' try: namespace.source_blob_uri, namespace.source_disk, namespace.source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name,", "namespace.os_sku) else: image_version = namespace.os_version image = compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku, image_version) #", "image_version_infos if not x.publishing_profile.exclude_from_latest] if not image_version_infos: raise CLIError('There is no latest image", "pylint: disable=no-member return image.plan except CloudError as ex: logger.warning(\"Querying the image of '%s'", "is not None: identities = namespace.assign_identity or [] from ._vm_utils import MSI_LOCAL_ID for", "addresses # '*1.5' so we have enough leeway for over-provision factor = 1.5", "'{0}'. Create one first and try \" \"again.\".format(option_name)) return values[0] def _validate_vmss_single_placement_group(namespace): if", "source_snapshot = source else: compute_client = _compute_client_factory(cli_ctx) # pylint: disable=no-member try: info =", "be created') def _validate_vmss_create_nsg(cmd, namespace): if namespace.nsg: namespace.nsg = _get_resource_id(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'networkSecurityGroups',", "VM, a most common scenario res_id = _get_resource_id(cmd.cli_ctx, namespace.source, namespace.resource_group_name, 'virtualMachines', 'Microsoft.Compute') res", "VMSS lacks some parameters, so scrub these out props_to_remove = ['attach_os_disk', 'storage_account'] for", "in [x.lower() for x in allowed_skus]: raise CLIError(\"invalid storage SKU '{}': allowed values:", "be used') elif namespace.application_gateway is None: namespace.app_gateway_type = 'new' logger.debug('new application gateway will", "namespace='Microsoft.Network', type='applicationSecurityGroups', name=val ) ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace, 'application_security_groups', ids) def validate_nsg_name(cmd, namespace): from msrestazure.tools", "module https://github.com/Azure/azure-cli/issues/5105 def process_msi_namespace(cmd, namespace): get_default_location_from_resource_group(cmd, namespace) validate_tags(namespace) def process_gallery_image_version_namespace(cmd, namespace): TargetRegion =", "PROFILE #4 namespace.storage_profile = StorageProfile.ManagedPirImage else: raise CLIError('Unrecognized image type: {}'.format(image_type)) else: #", "'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role, namespace.identity_scope)) elif namespace.identity_scope or getattr(namespace.identity_role, 'is_default', None) is None: raise", "._client_factory import _compute_client_factory from ._actions import _get_latest_image_version logger = get_logger(__name__) def validate_asg_names_or_ids(cmd, namespace):", "accept disk name or ID namespace.attach_os_disk = _get_resource_id( cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute')", "namespace.resource_group_name if rg: if not kv or is_valid_resource_id(kv): raise keyvault_usage validate_keyvault(cmd, namespace) else:", "'gatewaysubnet'), None) else: def _check_subnet(s): if s.name.lower() == 'gatewaysubnet': return False subnet_mask =", "--subnet SUBNET_ID | \" \"--subnet SUBNET_NAME --vnet-name VNET_NAME\") subnet_exists = \\ check_existence(cmd.cli_ctx, subnet,", "= parse_resource_id(namespace.storage_account) rg = storage_id.get('resource_group', namespace.resource_group_name) if check_existence(cmd.cli_ctx, storage_id['name'], rg, 'Microsoft.Storage', 'storageAccounts'): #", "\\ _get_default_address_pool(cmd.cli_ctx, rg, lb_name, 'load_balancers') if not namespace.nat_pool_name: if len(lb.inbound_nat_pools) > 1: raise", "['os_disk_name', 'os_caching', 'storage_account', 'storage_container_name', 'use_unmanaged_disk', 'storage_sku'] + auth_params _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.SAPirImage:", "enumerate(loaded_secret): for idx, secret in enumerate(narg_secret): if 'sourceVault' not in secret: errors.append( 'Secret", "'{0}': {1}\\nSpecify '{0}' explicitly.\".format( # pylint: disable=line-too-long '--nat-pool-name', ', '.join([n.name for n in", "bool(namespace.size_gb): raise CLIError('usage error: --disk EXIST_DISK --instance-id ID | --size-gb GB') elif bool(namespace.disk)", "in required: required.remove(prop) if prop in forbidden: forbidden.remove(prop) # set default storage SKU", "only available under profile ' 'with minimum Compute API version of 2017-12-01') if", "((1 << (32 - mask)) - 2) > int(vmss_instance_count * factor) def _validate_vm_vmss_accelerated_networking(cli_ctx,", "move to its own command module https://github.com/Azure/azure-cli/issues/5105 def process_msi_namespace(cmd, namespace): get_default_location_from_resource_group(cmd, namespace) validate_tags(namespace)", "the MIT License. See License.txt in the project root for license information. #", "{3}' if 'certificateUrl' not in cert: errors.append(message.format('certificateUrl', idx, jdx, idx_arg)) if is_windows and", "None) if account: # 3 - nothing specified - find viable storage account", "existing Vnet and subnet...') # if nothing specified, try to find an existing", "'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedCustomImage: required", "in vnet_match.subnets if s.name.lower() != 'gatewaysubnet'), None) else: def _check_subnet(s): if s.name.lower() ==", "kv = namespace.keyvault rg = namespace.resource_group_name if rg: if not kv or is_valid_resource_id(kv):", "CloudError as ex: logger.warning(\"Querying the image of '%s' failed for an error '%s'.", "msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id vm_id = resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines',", "created.\", namespace.load_balancer) elif namespace.load_balancer == '': namespace.load_balancer_type = None logger.debug('no load balancer will", "is missing {0} within vaultCertificates array at secret ' \\ 'index {1} and", "namespace.os_type = vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine = res_id if namespace.data_disk_sources: raise CLIError(\"'--data-disk-sources' is not allowed", "and namespace.storage_profile in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]: # pylint: disable=line-too-long namespace.storage_sku = 'Standard_LRS' if for_scale_set", "as_id = parse_resource_id(namespace.availability_set) name = as_id['name'] rg = as_id.get('resource_group', namespace.resource_group_name) if not check_existence(cmd.cli_ctx,", "'.pub': private_key_filepath = public_key_filepath[:-4] else: private_key_filepath = public_key_filepath + '.private' content = keys.generate_ssh_keys(private_key_filepath,", "except ValueError: raise CLIError(\"usage error: {}'s replica count must be an integer\".format(parts[0])) regions_info.append(TargetRegion(name=parts[0],", "_validate_vm_create_availability_set(cmd, namespace): from msrestazure.tools import parse_resource_id, resource_id from azure.cli.core.commands.client_factory import get_subscription_id if namespace.availability_set:", "urlparse except ImportError: from urlparse import urlparse # pylint: disable=import-error from knack.log import", "MSI_LOCAL_ID: namespace.identities[i] = _get_resource_id(cmd.cli_ctx, namespace.identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') # TODO move to its", "\\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def _validate_admin_username(username, os_type): import re if not username: raise CLIError(\"admin user", "type if namespace.authentication_type == 'password': if namespace.ssh_key_value or namespace.ssh_dest_key_path: raise ValueError( \"incorrect usage", "= image_plan.product namespace.plan_publisher = image_plan.publisher return 'urn' # 3 - unmanaged vhd based", "0 for i in range(24, 16, -1): if _subnet_capacity_check(i, namespace.instance_count, not namespace.disable_overprovision): break", "'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: required = ['os_type',", "specified NSG '%s'\", namespace.nsg) else: namespace.nsg_type = 'new' logger.debug(\"specified NSG '%s' not found.", "nics_value = namespace.nics nics = [] if not nics_value: namespace.nic_type = 'new' logger.debug('new", "# find storage account in target resource group that matches the VM's location", "one. 'az vm list-skus' can be \" \"used to find such locations\".format(namespace.resource_group_name)) #", "= StorageProfile.SAPirImage else: # STORAGE PROFILE #4 namespace.storage_profile = StorageProfile.ManagedPirImage else: raise CLIError('Unrecognized", "# pylint: disable=no-member return image.plan except CloudError as ex: logger.warning(\"Querying the image of", "get_subscription_id(cmd.cli_ctx) names_or_ids = getattr(namespace, 'application_security_groups') ids = [] if names_or_ids == [\"\"] or", "namespace.os_offer = matched['offer'] namespace.os_sku = matched['sku'] namespace.os_version = matched['version'] return 'urn' # 5", "disk image resource compute_client = _compute_client_factory(cmd.cli_ctx) try: compute_client.images.get(namespace.resource_group_name, namespace.image) namespace.image = _get_resource_id(cmd.cli_ctx, namespace.image,", "for over-provision factor = 1.5 if over_provision else 1 return ((1 << (32", "namespace.os_publisher, namespace.os_offer, namespace.os_sku) else: image_version = namespace.os_version image = compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku,", "turned off for zonal scale-sets or with\" \" 100+ instances\") def _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace):", "process_msi_namespace(cmd, namespace): get_default_location_from_resource_group(cmd, namespace) validate_tags(namespace) def process_gallery_image_version_namespace(cmd, namespace): TargetRegion = cmd.get_models('TargetRegion') if namespace.target_regions:", "o.lower() == offer) and (s is None or re.match(s, sku, re.I)): namespace.accelerated_networking =", "not result: continue namespace.subnet = result.name namespace.vnet_name = vnet_match.name namespace.vnet_type = 'existing' logger.debug(\"existing", "'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested', 'Standard_DS15_v2', 'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested', 'Standard_D40_v3', 'Standard_D40s_v3', 'Standard_D15_v2_ABC', 'Standard_M64ms', 'Standard_M64s', 'Standard_M128-64ms', 'Standard_D64_v3', 'Standard_D64s_v3',", "\\ if (namespace.os_type.lower() == 'windows' or namespace.admin_password) else 'ssh' if namespace.os_type.lower() == 'windows'", "= _get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg) def _validate_secrets(secrets, os_type): \"\"\" Validates a parsed JSON array", "= public_key_filepath + '.private' content = keys.generate_ssh_keys(private_key_filepath, public_key_filepath) logger.warning(\"SSH key files '%s' and", "list-skus' can be \" \"used to find such locations\".format(namespace.resource_group_name)) # pylint: disable=too-many-branches, too-many-statements", "--assign-identity [--scope SCOPE] [--role ROLE]') def _resolve_role_id(cli_ctx, role, scope): import re import uuid", "and std_lb_is_available: LBSkuName = cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer_sku is None: namespace.load_balancer_sku = LBSkuName.standard.value", "if rg: if not kv or is_valid_resource_id(kv): raise keyvault_usage validate_keyvault(cmd, namespace) else: if", "resource group namespace.storage_account = account.name namespace.storage_account_type = 'existing' logger.debug(\"suitable existing storage account '%s'", "Public-IP SKU is only exposed for VM. VMSS has no such needs so", "source_disk = None source_snapshot = None if urlparse(source).scheme: # a uri? source_blob_uri =", ":return: errors if any were found :rtype: list \"\"\" is_windows = os_type ==", "get_mgmt_service_client from azure.cli.core.profiles import ResourceType client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions role_id = None if", "elif subnet_exists: # 2 - user specified existing vnet/subnet namespace.vnet_type = 'existing' logger.debug(\"using", "nics: logger.debug('no subnet specified. Attempting to find an existing Vnet and subnet...') #", "is disabled\", balancer_type) elif namespace.load_balancer: balancer_type = 'loadBalancer' elif namespace.application_gateway: balancer_type = 'applicationGateway'", "parse_resource_id, resource_id from azure.cli.core.commands.client_factory import get_subscription_id if namespace.availability_set: as_id = parse_resource_id(namespace.availability_set) name =", "1 if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: # overflows? candidate_int =", "resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name = namespace.network_security_group_name \\ or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8)) def", "minimum Compute API version of 2017-12-01') if namespace.identity_scope: if identities and MSI_LOCAL_ID not", "role else: try: uuid.UUID(role) role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id, role) except ValueError: pass if", "'uri' # 4 - attempt to match an URN alias (most likely) from", "'is_default', None) is None: raise CLIError(\"usage error: '--role {}' is not applicable as", "validate_ssh_key(namespace) if not namespace.ssh_dest_key_path: namespace.ssh_dest_key_path = \\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def _validate_admin_username(username, os_type): import re", "= _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) if res['type'].lower() == 'images': image_info = compute_client.images.get(res['resource_group'], res['name']) namespace.os_type =", "raise CLIError(\"No existing values found for '{0}'. Create one first and try \"", "get_subscription_id vm_id = resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name = namespace.network_security_group_name \\ or", "secret in secrets] except Exception as err: raise CLIError('Error decoding secrets: {0}'.format(err)) for", "1.5 if over_provision else 1 return ((1 << (32 - mask)) - 2)", "usage: --load-balancer NAME_OR_ID | ' '--application-gateway NAME_OR_ID') # Resolve the type of balancer", "will be created.\", namespace.public_ip_address) elif namespace.public_ip_address == '': namespace.public_ip_address_type = None logger.debug('no public", "and getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError(\"usage error: '--role {}' is not", "# LoadBalancer frontend required = [] forbidden = ['app_gateway_subnet_address_prefix', 'application_gateway', 'app_gateway_sku', 'app_gateway_capacity'] validate_parameter_set(namespace,", "--image parameter. Updates the namespace and returns the type for subsequent processing. \"\"\"", "target resource group that matches the VM's location with a matching subnet for", "n in nics_value: nics.append({ 'id': n if '/' in n else resource_id(name=n, resource_group=namespace.resource_group_name,", "managed OS disk from Azure Marketplace image' elif profile == StorageProfile.ManagedSpecializedOSDisk: return 'attach", "def _validate_vm_vmss_msi(cmd, namespace, from_set_command=False): if from_set_command or namespace.assign_identity is not None: identities =", "namespace.subnet) return # 3 - create a new vnet/subnet namespace.vnet_type = 'new' logger.debug('no", "'Standard_F4s', 'Standard_D8_v3', 'Standard_D8s_v3', 'Standard_D32-8s_v3', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC', 'Standard_F4_ABC', 'Standard_F8s_v2', 'Standard_D4_v2', 'Standard_D13_v2', 'Standard_D4_v2_Promo',", "image.plan except CloudError as ex: logger.warning(\"Querying the image of '%s' failed for an", "--vnet-name VNET_NAME\") subnet_exists = \\ check_existence(cmd.cli_ctx, subnet, rg, 'Microsoft.Network', 'subnets', vnet, 'virtualNetworks') if", "info.id except CloudError: info = compute_client.disks.get(resource_group_name, source) source_disk = info.id return (source_blob_uri, source_disk,", "_validate_managed_disk_sku(sku): allowed_skus = ['Premium_LRS', 'Standard_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS'] if sku and sku.lower() not in", "raise CLIError('usage error: unrecognized image informations \"{}\"'.format(namespace.image)) # pylint: disable=no-member elif namespace.storage_profile ==", "namespace.os_type = image_info.os_type.value gallery_image_version = res.get('child_name_2', '') if gallery_image_version.lower() in ['latest', '']: image_version_infos", "return username def _validate_admin_password(password, os_type): import re is_linux = (os_type.lower() == 'linux') max_length", "is missing sourceVault.id key at index {0} in arg {1}'.format( idx, idx_arg)) if", "from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id vm_id = resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name, namespace='Microsoft.Compute',", "namespace.storage_profile == StorageProfile.SASpecializedOSDisk: required = ['os_type', 'attach_os_disk', 'use_unmanaged_disk'] forbidden = ['os_disk_name', 'os_caching', 'image',", "namespace.image.lower()), None) if matched: namespace.os_publisher = matched['publisher'] namespace.os_offer = matched['offer'] namespace.os_sku = matched['sku']", "CLIError('incorrect usage: --load-balancer NAME_OR_ID | ' '--application-gateway NAME_OR_ID') # Resolve the type of", "'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo', 'Standard_DS5_v2', 'Standard_DS14_v2', 'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo', 'Standard_F16', 'Standard_F16s', 'Standard_M64-32ms', 'Standard_M128-32ms', 'Standard_D32_v3', 'Standard_D32s_v3', 'Standard_D64-32s_v3',", "for x in images if x['urnAlias'].lower() == namespace.image.lower()), None) if matched: namespace.os_publisher =", "{1}'.format( idx, idx_arg)) if 'sourceVault' in secret and 'id' not in secret['sourceVault']: errors.append(", "required = ['os_type', 'attach_os_disk'] forbidden = ['os_disk_name', 'os_caching', 'storage_account', 'storage_container_name', 'use_unmanaged_disk', 'storage_sku'] +", "scrub these out props_to_remove = ['attach_os_disk', 'storage_account'] for prop in props_to_remove: if prop", "\"test1\", \"user3\", \"admin1\", \"1\", \"123\", \"a\", \"actuser\", \"adm\", \"admin2\", \"aspnet\", \"backup\", \"console\", \"guest\",", "must have the 3 of the following: 1 lower case character, 1 upper", "storage account '%s' not found and will be created\", storage_id['name']) else: from azure.cli.core.profiles", "check_existence(cmd.cli_ctx, subnet, rg, 'Microsoft.Network', 'subnets', vnet, 'virtualNetworks') if subnet_is_id and not subnet_exists: raise", "return if not temp or not [x for x in (temp.location_info or [])", "if subnet: subnet_is_id = is_valid_resource_id(subnet) if (subnet_is_id and vnet) or (not subnet_is_id and", "return # 3 - create a new vnet/subnet namespace.vnet_type = 'new' logger.debug('no suitable", "raise CLIError('--public-ip-address can only be used when creating a new load ' 'balancer", "error: unrecognized image informations \"{}\"'.format(namespace.image)) # pylint: disable=no-member elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: #", "= ['image', 'os_type', 'use_unmanaged_disk'] forbidden = ['attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SASpecializedOSDisk: required", "= cmd.get_models('TargetRegion') if namespace.target_regions: regions_info = [] for t in namespace.target_regions: parts =", "(subnet_is_id and vnet) or (not subnet_is_id and not vnet): raise CLIError(\"incorrect '--subnet' usage:", "account found. One will be created.') def _validate_vm_create_availability_set(cmd, namespace): from msrestazure.tools import parse_resource_id,", "if not client: raise CLIError('unrecognized balancer type: {}'.format(balancer_type)) balancer = client.get(resource_group, balancer_name) values", "def _validate_vm_create_nsg(cmd, namespace): if namespace.nsg: if check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_type =", "specify '--os-type OS_TYPE'\") def _figure_out_storage_source(cli_ctx, resource_group_name, source): from msrestazure.azure_exceptions import CloudError source_blob_uri =", "if hasattr(namespace, 'primary_nic') and namespace.primary_nic: namespace.primary_nic = _get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg) def _validate_secrets(secrets, os_type):", "resource group client = get_network_client(cmd.cli_ctx).virtual_networks # find VNET in target resource group that", "= info.id except CloudError: info = compute_client.disks.get(resource_group_name, source) source_disk = info.id return (source_blob_uri,", "'os_caching', 'image', 'storage_account', 'storage_container_name', 'data_disk_sizes_gb', 'storage_sku'] + auth_params else: raise CLIError('Unrecognized storage profile:", "specified namespace.storage_account_type = 'new' logger.debug(\"specified storage account '%s' not found and will be", "namespace.subnet_address_prefix is None: cidr = namespace.vnet_address_prefix.split('/', 1)[0] i = 0 for i in", "namespace.os_version = urn_match.group(4) if not any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]): image_plan = _get_image_plan_info_if_exists(cmd, namespace) if", "continue namespace.subnet = result.name namespace.vnet_name = vnet_match.name namespace.vnet_type = 'existing' logger.debug(\"existing vnet '%s'", "Key Value. ' 'You can use --generate-ssh-keys to let CLI generate one for", "(v for v in client.list(rg) if v.location == location and v.subnets): # 1", "namespace.os_type.lower() != 'windows': raise CLIError('usage error: --license-type is only applicable on Windows VM')", "any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]): image_plan = _get_image_plan_info_if_exists(cmd, namespace) if image_plan: namespace.plan_name = image_plan.name namespace.plan_product", "logger.debug(\"using specified existing application gateway '%s'\", namespace.application_gateway) except CloudError: namespace.app_gateway_type = 'new' logger.debug(\"application", "_compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) vm_info = compute_client.virtual_machines.get(res['resource_group'], res['name']) # pylint: disable=no-member namespace.os_type = vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine", "new_4core_sizes: compute_client = _compute_client_factory(cli_ctx) sizes = compute_client.virtual_machine_sizes.list(namespace.location) size_info = next((s for s in", "get_mgmt_service_client from msrestazure.tools import parse_resource_id client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults for vault in client.list():", "'StandardSSD_LRS', 'UltraSSD_LRS'] if sku and sku.lower() not in [x.lower() for x in allowed_skus]:", "existing managed OS disk' def _validate_managed_disk_sku(sku): allowed_skus = ['Premium_LRS', 'Standard_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS'] if", "VM/VMSS because availablity zone is not yet \" \"supported. Please use '--location' to", "'Standard_D12_v2_Promo', 'Standard_DS3_v2', 'Standard_DS12_v2', 'Standard_DS13-4_v2', 'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo', 'Standard_F4', 'Standard_F4s', 'Standard_D8_v3', 'Standard_D8s_v3',", "get_subscription_id ApplicationSecurityGroup = cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK) resource_group = namespace.resource_group_name subscription_id = get_subscription_id(cmd.cli_ctx) names_or_ids =", "case character, 1 number and 1 special character') def validate_ssh_key(namespace): string_or_file = (namespace.ssh_key_value", "role, re.I): role_id = role else: try: uuid.UUID(role) role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id, role)", "re.I)): namespace.accelerated_networking = True def _validate_vmss_create_subnet(namespace): if namespace.vnet_type == 'new': if namespace.subnet_address_prefix is", "disk name or ID namespace.attach_os_disk = _get_resource_id( cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if", "namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name, 'disks', 'Microsoft.Compute') for d in namespace.attach_data_disks] if not", "namespace.nsg = _get_resource_id(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'networkSecurityGroups', 'Microsoft.Network') def _validate_vm_vmss_create_public_ip(cmd, namespace): if namespace.public_ip_address: if", "is_valid_resource_id(val): return val kwargs = { 'name': val, 'resource_group': resource_group, 'namespace': resource_namespace, 'type':", "NAME_OR_ID') # Resolve the type of balancer (if any) being used balancer_type =", "if id_comps['name'] == vault_name: return id_comps['resource_group'] return None def _get_resource_id(cli_ctx, val, resource_group, resource_type,", "None: from azure.cli.core.cloud import AZURE_US_GOV_CLOUD if cmd.cli_ctx.cloud.name != AZURE_US_GOV_CLOUD.name: namespace.vm_sku = 'Standard_DS1_v2' else:", "for x in new_4core_sizes] if size not in new_4core_sizes: compute_client = _compute_client_factory(cli_ctx) sizes", "\" \"again.\".format(option_name)) return values[0] def _validate_vmss_single_placement_group(namespace): if namespace.platform_fault_domain_count is not None and namespace.zones", "namespace.single_placement_group is not False else 'applicationGateway' logger.debug(\"W/o STD LB, defaulting to '%s' under", "to a safe location.\", private_key_filepath, public_key_filepath) else: raise CLIError('An RSA key file or", "to match an URN alias (most likely) from azure.cli.command_modules.vm._actions import load_images_from_aliases_doc images =", "os try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse #", "default storage SKU if not provided and using an image based OS if", "= image_info.storage_profile.os_disk.os_type.value image_data_disks_num = len(image_info.storage_profile.data_disks or []) elif res['type'].lower() == 'galleries': image_info =", "does not exist.\".format(name)) namespace.availability_set = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg, namespace='Microsoft.Compute', type='availabilitySets', name=name) logger.debug(\"adding to", "user name cannot contain upper case character A-Z, special characters \\/\"[]:|<>+=;,?*@#()! or start", "disk, snapshot, image validators def validate_vm_disk(cmd, namespace): namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks',", "image of '%s' failed for an error '%s'. Configuring plan settings \" \"will", "- nothing specified - find viable storage account in target resource group namespace.storage_account", "error: user assigned identity is only available under profile ' 'with minimum Compute", "user assigned identity is only available under profile ' 'with minimum Compute API", "not in [x.lower() for x in allowed_skus]: raise CLIError(\"invalid storage SKU '{}': allowed", "\"will be skipped\", namespace.image, ex.message) # pylint: disable=inconsistent-return-statements def _get_storage_profile_description(profile): if profile ==", "sku_infos = list_sku_info(cmd.cli_ctx, namespace.location) temp = next((x for x in sku_infos if x.name.lower()", "or getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError('usage error: --assign-identity [--scope SCOPE] [--role", "elif namespace.single_placement_group: raise CLIError(\"usage error: '--single-placement-group' should be turned off for zonal scale-sets", "off for zonal scale-sets or with\" \" 100+ instances\") def _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace): from", "profile 2017_03_09 balancer_type = 'loadBalancer' if namespace.single_placement_group is not False else 'applicationGateway' logger.debug(\"W/o", "namespace): TargetRegion = cmd.get_models('TargetRegion') if namespace.target_regions: regions_info = [] for t in namespace.target_regions:", "for \"{}\"'.format(namespace.image)) image_version_info = sorted(image_version_infos, key=lambda x: x.publishing_profile.published_date)[-1] else: image_version_info = compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'],", "balancer') if namespace.load_balancer: rg = parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name) lb_name = parse_resource_id(namespace.load_balancer)['name'] lb = get_network_lb(cmd.cli_ctx,", "def get_network_lb(cli_ctx, resource_group_name, lb_name): from msrestazure.azure_exceptions import CloudError network_client = get_network_client(cli_ctx) try: return", "'nics', None) if not vnet and not subnet and not nics: logger.debug('no subnet", "resource_namespace, 'type': resource_type, 'subscription': get_subscription_id(cli_ctx) } missing_kwargs = {k: v for k, v", "raise CLIError('usage error: --assign-identity [--scope SCOPE] [--role ROLE]') def _resolve_role_id(cli_ctx, role, scope): import", "(namespace.ssh_key_value or os.path.join(os.path.expanduser('~'), '.ssh', 'id_rsa.pub')) content = string_or_file if os.path.exists(string_or_file): logger.info('Use existing SSH", "import is_valid_resource_id from msrestazure.azure_exceptions import CloudError import re # 1 - check if", "elif profile == StorageProfile.ManagedCustomImage: return 'create managed OS disk from custom image' elif", "is only applicable on Windows VM scaleset') if not namespace.public_ip_per_vm and namespace.vm_domain_name: raise", "Marketplace image' elif profile == StorageProfile.SASpecializedOSDisk: return 'attach to existing unmanaged OS disk'", "(os_type.lower() == 'linux') # pylint: disable=line-too-long pattern = (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if is_linux else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+')", "profile # start with the required/forbidden parameters for VM if namespace.storage_profile == StorageProfile.ManagedPirImage:", "sku_infos if x.name.lower() == size_info.lower()), None) # For Stack (compute - 2017-03-30), Resource_sku", "# pylint: disable=no-member try: info = compute_client.snapshots.get(resource_group_name, source) source_snapshot = info.id except CloudError:", "elif namespace.storage_profile == StorageProfile.SACustomImage: required = ['image', 'os_type', 'use_unmanaged_disk'] forbidden = ['attach_os_disk', 'data_disk_sizes_gb']", "resource_group=resource_group, namespace='Microsoft.Network', type='applicationSecurityGroups', name=val ) ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace, 'application_security_groups', ids) def validate_nsg_name(cmd, namespace): from", "gateway') elif balancer_type == 'loadBalancer': # LoadBalancer frontend required = [] forbidden =", "disk from custom image' elif profile == StorageProfile.ManagedPirImage: return 'create managed OS disk", "subnet_is_id and not subnet_exists: raise CLIError(\"Subnet '{}' does not exist.\".format(subnet)) elif subnet_exists: #", "= 'loadBalancer' elif namespace.application_gateway: balancer_type = 'applicationGateway' if balancer_type == 'applicationGateway': if namespace.application_gateway:", "namespace): from msrestazure.azure_exceptions import CloudError validate_tags(namespace) if namespace.source: usage_error = 'usage error: --source", "try: namespace.source_blob_uri, namespace.source_disk, namespace.source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, namespace.source) if not namespace.source_blob_uri and", "import resource_id, is_valid_resource_id from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_subscription_id ApplicationSecurityGroup =", "namespace.ultra_ssd_enabled is None: namespace.ultra_ssd_enabled = True # Now verify that the status of", "p.lower() == publisher and (o is None or o.lower() == offer) and (s", "if for_scale_set else 'Premium_LRS' if namespace.storage_sku == 'UltraSSD_LRS' and namespace.ultra_ssd_enabled is None: namespace.ultra_ssd_enabled", "fully-qualified ID (assumes it is an image ID) if is_valid_resource_id(namespace.image): return 'image_id' #", "import CLIError from azure.cli.core.commands.validators import ( get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set, validate_tags) from azure.cli.core.util import", "for_scale_set else 'Premium_LRS' if namespace.storage_sku == 'UltraSSD_LRS' and namespace.ultra_ssd_enabled is None: namespace.ultra_ssd_enabled =", "version of 2017-12-01') if namespace.identity_scope: if identities and MSI_LOCAL_ID not in identities: raise", "'new': required.append('app_gateway_subnet_address_prefix') elif namespace.app_gateway_type == 'existing': required.append('backend_pool_name') forbidden = ['nat_pool_name', 'load_balancer', 'health_probe'] validate_parameter_set(namespace,", "match an URN alias (most likely) from azure.cli.command_modules.vm._actions import load_images_from_aliases_doc images = load_images_from_aliases_doc(cmd.cli_ctx)", "}] :param dict secrets: Dict fitting the JSON description above :param string os_type:", "if bool(namespace.disk) == bool(namespace.size_gb): raise CLIError('usage error: --disk EXIST_DISK --instance-id ID | --size-gb", "All rights reserved. # Licensed under the MIT License. See License.txt in the", "namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_vm_secret_format(cmd, namespace): from msrestazure.tools import is_valid_resource_id keyvault_usage = CLIError('usage", "else: try: replica_count = int(parts[1]) except ValueError: raise CLIError(\"usage error: {}'s replica count", "id_comps = parse_resource_id(vault.id) if id_comps['name'] == vault_name: return id_comps['resource_group'] return None def _get_resource_id(cli_ctx,", "2 - attempt to match an URN pattern urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image) if", "PublicIPAddressSkuName.standard.value: if not namespace.public_ip_address_allocation: namespace.public_ip_address_allocation = IPAllocationMethod.static.value def _validate_vmss_create_public_ip(cmd, namespace): if namespace.load_balancer_type is", "4 - nothing specified - create a new storage account namespace.storage_account_type = 'new'", "is only applicable on Windows VM') _validate_vm_vmss_msi(cmd, namespace) if namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage = get_storage_blob_uri(cmd.cli_ctx,", "zonal scale-sets or with\" \" 100+ instances\") def _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace): from msrestazure.azure_exceptions import", "over_provision): mask = int(subnet_mask) # '2' are the reserved broadcasting addresses # '*1.5'", "'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3', 'Standard_D8s_v3'] new_4core_sizes = [x.lower() for x in new_4core_sizes]", "public_key_filepath[-4:].lower() == '.pub': private_key_filepath = public_key_filepath[:-4] else: private_key_filepath = public_key_filepath + '.private' content", "for idx_arg, narg_secret in enumerate(loaded_secret): for idx, secret in enumerate(narg_secret): if 'sourceVault' not", "namespace.load_balancer: rg = parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name) lb_name = parse_resource_id(namespace.load_balancer)['name'] lb = get_network_lb(cmd.cli_ctx, namespace.resource_group_name, lb_name)", "'image_id' # 2 - attempt to match an URN pattern urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)',", "in distros: if p.lower() == publisher and (o is None or o.lower() ==", "= _compute_client_factory(cmd.cli_ctx) try: compute_client.images.get(namespace.resource_group_name, namespace.image) namespace.image = _get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name, 'images', 'Microsoft.Compute') return", "if any were found :rtype: list \"\"\" is_windows = os_type == 'windows' errors", "elif namespace.storage_profile == StorageProfile.SAPirImage: required = ['image', 'use_unmanaged_disk'] forbidden = ['os_type', 'attach_os_disk', 'data_disk_sizes_gb']", "namespace.ssh_dest_key_path: raise ValueError( \"incorrect usage for authentication-type 'password': \" \"[--admin-username USERNAME] --admin-password PASSWORD\")", "!= MSI_LOCAL_ID: identities[i] = _get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') if not namespace.identity_scope and", "SUBNET_ID | \" \"--subnet SUBNET_NAME --vnet-name VNET_NAME\") subnet_exists = \\ check_existence(cmd.cli_ctx, subnet, rg,", "CloudError from msrestazure.tools import parse_resource_id from azure.cli.core.profiles import ResourceType std_lb_is_available = cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK)", "CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix = '{}/{}'.format(cidr, i) if namespace.app_gateway_type and namespace.app_gateway_subnet_address_prefix is None: namespace.app_gateway_subnet_address_prefix =", "account '%s'\", storage_id['name']) else: # 2 - params for new storage account specified", "if namespace.single_placement_group is not False else 'applicationGateway' logger.debug(\"W/o STD LB, defaulting to '%s'", "in range(len(namespace.identities)): if namespace.identities[i] != MSI_LOCAL_ID: namespace.identities[i] = _get_resource_id(cmd.cli_ctx, namespace.identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity')", "namespace.ssh_key_value = content def _validate_vm_vmss_msi(cmd, namespace, from_set_command=False): if from_set_command or namespace.assign_identity is not", "no latest image version exists for \"{}\"'.format(namespace.image)) image_version_info = sorted(image_version_infos, key=lambda x: x.publishing_profile.published_date)[-1]", "else 'Premium_LRS' if namespace.storage_sku == 'UltraSSD_LRS' and namespace.ultra_ssd_enabled is None: namespace.ultra_ssd_enabled = True", "import os try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse", "'use_unmanaged_disk'] forbidden = ['os_disk_name', 'os_caching', 'image', 'storage_account', 'storage_container_name', 'data_disk_sizes_gb', 'storage_sku'] + auth_params else:", "in the target resource group client = get_network_client(cmd.cli_ctx).virtual_networks # find VNET in target", "- 2) > int(vmss_instance_count * factor) def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace): if namespace.accelerated_networking is None:", "new_4core_sizes = ['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2', 'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC', 'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2',", "'%s' and subnet '%s'\", namespace.vnet_name, namespace.subnet) return # 3 - create a new", "else: namespace.nsg_type = 'new' logger.debug(\"specified NSG '%s' not found. It will be created.\",", "'ssh' if namespace.os_type.lower() == 'windows' and namespace.authentication_type == 'ssh': raise CLIError('SSH not supported", "'primary': nics_value[0] == n } }) namespace.nics = nics namespace.nic_type = 'existing' namespace.public_ip_address_type", "if namespace.load_balancer: rg = parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name) lb_name = parse_resource_id(namespace.load_balancer)['name'] lb = get_network_lb(cmd.cli_ctx, namespace.resource_group_name,", "if namespace.load_balancer_sku is None: namespace.load_balancer_sku = LBSkuName.standard.value logger.debug(\"use Standard sku as single placement", "= source elif '/disks/' in source.lower(): source_disk = source elif '/snapshots/' in source.lower():", "character A-Z, special characters \\/\"[]:|<>+=;,?*@#()! or start with $ or -' win_err =", "None: if namespace.public_ip_address: raise CLIError('--public-ip-address can only be used when creating a new", "123 min_length = 12 if len(password) not in range(min_length, max_length + 1): raise", "from the error aval_sizes = ['Standard_D3_v2', 'Standard_D12_v2', 'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo', 'Standard_DS3_v2', 'Standard_DS12_v2', 'Standard_DS13-4_v2', 'Standard_DS14-4_v2',", "resource group that matches the VM's location sku_tier = 'Premium' if 'Premium' in", "logger.debug(\"load balancer '%s' not found. It will be created.\", namespace.load_balancer) elif namespace.load_balancer ==", "# pylint: disable=import-error from knack.log import get_logger from knack.util import CLIError from azure.cli.core.commands.validators", "t in namespace.target_regions: parts = t.split('=', 1) if len(parts) == 1: regions_info.append(TargetRegion(name=parts[0])) else:", "# pylint: disable=too-many-branches, too-many-statements def _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False): from msrestazure.tools import parse_resource_id #", "namespace.application_gateway) elif namespace.application_gateway == '': namespace.app_gateway_type = None logger.debug('no application gateway will be", "import urlparse except ImportError: from urlparse import urlparse # pylint: disable=import-error from knack.log", "resource_group, balancer_name, balancer_type): option_name = '--backend-pool-name' client = getattr(get_network_client(cli_ctx), balancer_type, None) if not", "not client: raise CLIError('unrecognized balancer type: {}'.format(balancer_type)) balancer = client.get(resource_group, balancer_name) values =", "namespace.data_blob_uris.append(source_blob_uri) if source_disk: namespace.data_disks.append(source_disk) if source_snapshot: namespace.data_snapshots.append(source_snapshot) if not namespace.os_type: raise CLIError(\"usage error:", "missing vaultCertificates array or it is empty at index {0} in ' \\", "vnet '%s' and subnet '%s'\", namespace.vnet_name, namespace.subnet) return # 3 - create a", "[StorageProfile.SACustomImage, StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd, namespace) _validate_vm_create_availability_set(cmd, namespace) _validate_vm_vmss_create_vnet(cmd, namespace) _validate_vm_create_nsg(cmd, namespace) _validate_vm_vmss_create_public_ip(cmd, namespace) _validate_vm_create_nics(cmd,", "None: namespace.nsg_type = 'new' logger.debug('new NSG will be created') def _validate_vmss_create_nsg(cmd, namespace): if", "LB, defaulting to '%s' under because single placement group is disabled\", balancer_type) elif", "int(result[:-bit_mask_len], 2) error_msg = \"usage error: --subnet-address-prefix value should be a subrange of", "[]) if x.zones]: raise CLIError(\"{}'s location can't be used to create the VM/VMSS", "not namespace.priority: raise CLIError('Usage error: --priority PRIORITY [--eviction-policy POLICY]') # endregion # region", "'password': if namespace.ssh_key_value or namespace.ssh_dest_key_path: raise ValueError( \"incorrect usage for authentication-type 'password': \"", "namespace.os_publisher = urn_match.group(1) namespace.os_offer = urn_match.group(2) namespace.os_sku = urn_match.group(3) namespace.os_version = urn_match.group(4) if", "'new': required.append('app_gateway_sku') required.append('app_gateway_capacity') if namespace.vnet_type != 'new': required.append('app_gateway_subnet_address_prefix') elif namespace.app_gateway_type == 'existing': required.append('backend_pool_name')", "group' is turned off\" raise CLIError('usage error:{}'.format(err)) def get_network_client(cli_ctx): from azure.cli.core.profiles import ResourceType", "balancer will be used') elif namespace.load_balancer is None: namespace.load_balancer_type = 'new' logger.debug('new load", "result: continue namespace.subnet = result.name namespace.vnet_name = vnet_match.name namespace.vnet_type = 'existing' logger.debug(\"existing vnet", "setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role, namespace.identity_scope)) elif namespace.identity_scope or getattr(namespace.identity_role, 'is_default', None) is None:", "else: # did not specify image XOR attach-os-disk raise CLIError('incorrect usage: --image IMAGE", "and namespace.app_gateway_subnet_address_prefix is None: namespace.app_gateway_subnet_address_prefix = _get_next_subnet_addr_suffix( namespace.vnet_address_prefix, namespace.subnet_address_prefix, 24) def _get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr,", "the project root for license information. # -------------------------------------------------------------------------------------------- # pylint:disable=too-many-lines import os try:", "a new vnet/subnet namespace.vnet_type = 'new' logger.debug('no suitable subnet found. One will be", "frontend.') namespace.public_ip_address = '' _validate_vm_vmss_create_public_ip(cmd, namespace) def _validate_vm_create_nics(cmd, namespace): from msrestazure.tools import resource_id", "if subnet_is_id and not subnet_exists: raise CLIError(\"Subnet '{}' does not exist.\".format(subnet)) elif subnet_exists:", "one role matches the given name '{}'. Please pick an id from '{}'\"", "#4 namespace.storage_profile = StorageProfile.ManagedPirImage else: raise CLIError('Unrecognized image type: {}'.format(image_type)) else: # did", "it is empty at index {0} in ' \\ 'arg {1} ' errors.append(err.format(idx,", "s.name.lower() != 'gatewaysubnet'), None) else: def _check_subnet(s): if s.name.lower() == 'gatewaysubnet': return False", "s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask, namespace.instance_count, not namespace.disable_overprovision) result = next((s for s in vnet_match.subnets", "namespace.vnet_type = 'existing' logger.debug(\"existing vnet '%s' and subnet '%s' found\", namespace.vnet_name, namespace.subnet) return", "is None: raise CLIError('usage error: --platform-fault-domain-count COUNT --zones ZONES') if namespace.zones or namespace.instance_count", "for zonal scale-sets or with\" \" 100+ instances\") def _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace): from msrestazure.azure_exceptions", "CLIError(\"Incorrect usage '--key-encryption-keyvault': \" \"'--key-encryption-key' is required\") namespace.key_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault, namespace.resource_group_name, 'vaults',", "x['urnAlias'].lower() == namespace.image.lower()), None) if matched: namespace.os_publisher = matched['publisher'] namespace.os_offer = matched['offer'] namespace.os_sku", "Windows, ssh for Linux) by examining the OS type namespace.authentication_type = 'password' \\", "3: raise CLIError('Password must have the 3 of the following: 1 lower case", "disable=inconsistent-return-statements def _get_storage_profile_description(profile): if profile == StorageProfile.SACustomImage: return 'create unmanaged OS disk created", "= role else: try: uuid.UUID(role) role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id, role) except ValueError: pass", "= ['attach_os_disk', 'storage_account'] for prop in props_to_remove: if prop in required: required.remove(prop) if", "if cmd.cli_ctx.cloud.name != AZURE_US_GOV_CLOUD.name: namespace.vm_sku = 'Standard_DS1_v2' else: namespace.vm_sku = 'Standard_D1_v2' _validate_location(cmd, namespace,", "= 'Standard_LRS' if for_scale_set else 'Premium_LRS' if namespace.storage_sku == 'UltraSSD_LRS' and namespace.ultra_ssd_enabled is", "if namespace.target_regions: regions_info = [] for t in namespace.target_regions: parts = t.split('=', 1)", "if getattr(namespace, 'attach_os_disk', None) and not namespace.image: if namespace.use_unmanaged_disk: # STORAGE PROFILE #3", "image_plan.publisher return 'urn' # 3 - unmanaged vhd based images? if urlparse(namespace.image).scheme: return", "namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, lb_name, 'load_balancers') if not namespace.nat_pool_name: if", "except ValueError: pass if not role_id: # retrieve role id role_defs = list(client.list(scope,", "is None or size_info.number_of_cores < 8: return # VMs need to be a", "> 1: raise CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify '{0}' explicitly.\".format( #", "vnet/subnet result = None if not for_scale_set: result = next((s for s in", "overflows? candidate_int = candidate_int - 2 # try the other way around if", "azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_subscription_id ApplicationSecurityGroup = cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK) resource_group =", "== [\"\"] or not names_or_ids: return for val in names_or_ids: if not is_valid_resource_id(val):", "subnet specified. Attempting to find an existing Vnet and subnet...') # if nothing", "from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.commands.client_factory import get_subscription_id if is_valid_resource_id(val): return val", "namespace.os_sku = urn_match.group(3) namespace.os_version = urn_match.group(4) if not any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]): image_plan =", "managed OS disk' def _validate_managed_disk_sku(sku): allowed_skus = ['Premium_LRS', 'Standard_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS'] if sku", "# format back to the cidr candaidate_str = '{0:32b}'.format(candidate_int << subnet_bit_mask_len) return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8],", "coming out vnet_ip_address, mask = vnet_cidr.split('/') vnet_bit_mask_len = 32 - int(mask) vnet_int =", ":rtype: list \"\"\" is_windows = os_type == 'windows' errors = [] try: loaded_secret", "- check if an existing managed disk image resource compute_client = _compute_client_factory(cmd.cli_ctx) try:", "std_lb_is_available = cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer and namespace.application_gateway: raise CLIError('incorrect usage: --load-balancer NAME_OR_ID", "'subscription': get_subscription_id(cli_ctx) } missing_kwargs = {k: v for k, v in kwargs.items() if", "and {}'.format(min_length, max_length)) contains_lower = re.findall('[a-z]+', password) contains_upper = re.findall('[A-Z]+', password) contains_digit =", "source elif '/disks/' in source.lower(): source_disk = source elif '/snapshots/' in source.lower(): source_snapshot", "_get_default_address_pool(cmd.cli_ctx, rg, ag_name, 'application_gateways') logger.debug(\"using specified existing application gateway '%s'\", namespace.application_gateway) except CloudError:", "_convert_to_int(subnet_ip_address, subnet_bit_mask_len) + 1 if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: #", "subrange of --vnet-address-prefix's\" # extract vnet information needed to verify the defaults we", "a managed custom image res = parse_resource_id(namespace.image) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) if res['type'].lower()", "subnet size'\" raise CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix = '{}/{}'.format(cidr, i) if namespace.app_gateway_type and namespace.app_gateway_subnet_address_prefix is", "['image', 'use_unmanaged_disk'] forbidden = ['os_type', 'attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SACustomImage: required =", "'ssh': if namespace.admin_password: raise ValueError('Admin password cannot be used with SSH authentication type')", "a uri? source_blob_uri = source elif '/disks/' in source.lower(): source_disk = source elif", "pass if not role_id: # retrieve role id role_defs = list(client.list(scope, \"roleName eq", "above :param string os_type: the type of OS (linux or windows) :return: errors", "balancer '%s' not found. It will be created.\", namespace.load_balancer) elif namespace.load_balancer == '':", "'storage_sku'] + auth_params else: raise CLIError('Unrecognized storage profile: {}'.format(namespace.storage_profile)) logger.debug(\"storage profile '%s'\", namespace.storage_profile)", "except CloudError: raise CLIError(usage_error) def process_image_create_namespace(cmd, namespace): from msrestazure.tools import parse_resource_id from msrestazure.azure_exceptions", "the following: 1 lower case character, 1 upper case character, 1 number and", "namespace.identity_role)) user_assigned_identities = [x for x in identities if x != MSI_LOCAL_ID] if", "_get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if bool(namespace.disk) == bool(namespace.size_gb): raise CLIError('usage error: --disk", "(only on windows)\" }] }] :param dict secrets: Dict fitting the JSON description", "namespace.storage_sku else 'Standard' account = next( (a for a in storage_client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value", "with a matching subnet for vnet_match in (v for v in client.list(rg) if", "'is_default', None) is None: raise CLIError('usage error: --assign-identity [--scope SCOPE] [--role ROLE]') def", "create the image, \" \"please specify '--os-type OS_TYPE'\") def _figure_out_storage_source(cli_ctx, resource_group_name, source): from", "exists for \"{}\"'.format(namespace.image)) image_version_info = sorted(image_version_infos, key=lambda x: x.publishing_profile.published_date)[-1] else: image_version_info = compute_client.gallery_image_versions.get(", "validate_vm_disk(cmd, namespace): namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') def validate_vmss_disk(cmd, namespace): if", "elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: required = ['os_type', 'attach_os_disk'] forbidden = ['os_disk_name', 'os_caching', 'storage_account',", "namespace.instance_count, not namespace.disable_overprovision): break if i < 16: err = \"instance count '{}'", "identities if x != MSI_LOCAL_ID] if user_assigned_identities and not cmd.supported_api_version(min_api='2017-12-01'): raise CLIError('usage error:", "elif namespace.nsg == '': namespace.nsg_type = None logger.debug('no NSG will be used') elif", "{1} ' errors.append(err.format(idx, idx_arg)) else: for jdx, cert in enumerate(secret['vaultCertificates']): message = 'Secret", "balancer will be created') if namespace.load_balancer_type == 'new' and namespace.single_placement_group is False and", "role matches the given name '{}'. Please pick an id from '{}'\" raise", "'Standard_E64-32s_v3', 'Standard_F64s_v2', 'Standard_F72s_v2', 'Standard_M128s', 'Standard_M128ms', 'Standard_L8s_v2', 'Standard_L16s_v2', 'Standard_L32s_v2', 'Standard_L64s_v2', 'Standard_L96s_v2', 'SQLGL', 'SQLGLCore', 'Standard_D4_v3',", "supported for Windows VMs.') # validate proper arguments supplied based on the authentication", "import resource_id, is_valid_resource_id from azure.cli.core.commands.client_factory import get_subscription_id if is_valid_resource_id(val): return val kwargs =", "StorageProfile.SACustomImage: return 'create unmanaged OS disk created from generalized VHD' elif profile ==", "'--os-type' argument.\") if not namespace.authentication_type: # apply default auth type (password for Windows,", "VMs.') # validate proper arguments supplied based on the authentication type if namespace.authentication_type", "import re for p, o, s in distros: if p.lower() == publisher and", "is False and std_lb_is_available: LBSkuName = cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer_sku is None: namespace.load_balancer_sku", "type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name = namespace.network_security_group_name \\ or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8)) def validate_keyvault(cmd, namespace):", "= 'Invalid image \"{}\". Use a custom image name, id, or pick one", "namespace.load_balancer == '': namespace.load_balancer_type = None logger.debug('no load balancer will be used') elif", "'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SACustomImage: required = ['image', 'os_type', 'use_unmanaged_disk'] forbidden = ['attach_os_disk',", "namespace.location), None) if account: # 3 - nothing specified - find viable storage", "Azure Marketplace image' elif profile == StorageProfile.SASpecializedOSDisk: return 'attach to existing unmanaged OS", "namespace.vnet_name, namespace.subnet) return # 3 - create a new vnet/subnet namespace.vnet_type = 'new'", "SSH Key Value. ' 'You can use --generate-ssh-keys to let CLI generate one", "'Standard_F8_ABC', 'Standard_F16s_v2', 'Standard_D5_v2', 'Standard_D14_v2', 'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo', 'Standard_DS5_v2', 'Standard_DS14_v2', 'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo', 'Standard_F16', 'Standard_F16s', 'Standard_M64-32ms',", "== StorageProfile.ManagedCustomImage: required = ['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if", "def _validate_vmss_single_placement_group(namespace): if namespace.platform_fault_domain_count is not None and namespace.zones is None: raise CLIError('usage", "CLIError from azure.cli.core.commands.validators import ( get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set, validate_tags) from azure.cli.core.util import hash_string", "\"user4\", \"user5\"] if username.lower() in disallowed_user_names: raise CLIError(\"This user name '{}' meets the", "_validate_secrets(namespace.secrets, namespace.os_type) if namespace.license_type and namespace.os_type.lower() != 'windows': raise CLIError('usage error: --license-type is", "Specify '--os-type' argument.\") if not namespace.authentication_type: # apply default auth type (password for", "= None source_snapshot = None if urlparse(source).scheme: # a uri? source_blob_uri = source", "be created.') def _subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision): mask = int(subnet_mask) # '2' are the", "only applicable on Windows VM scaleset') if not namespace.public_ip_per_vm and namespace.vm_domain_name: raise CLIError('Usage", "None :rtype: str \"\"\" from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client from", "== StorageProfile.SASpecializedOSDisk: return 'attach to existing unmanaged OS disk' elif profile == StorageProfile.ManagedCustomImage:", "attach-os-disk raise CLIError('incorrect usage: --image IMAGE | --attach-os-disk DISK') auth_params = ['<PASSWORD>_password', 'admin_username',", "profile ' 'with minimum Compute API version of 2017-12-01') if namespace.identity_scope: if identities", "arg {1}'.format( idx, idx_arg)) if 'vaultCertificates' not in secret or not secret['vaultCertificates']: err", "kernel # Oracle Linux 7.4, Windows Server 2016, Windows Server 2012R2 publisher, offer,", "= _convert_to_int(vnet_ip_address, vnet_bit_mask_len) subnet_ip_address, mask = subnet_cidr.split('/') subnet_bit_mask_len = 32 - int(mask) if", "namespace.vnet_name = vnet_match.name namespace.vnet_type = 'existing' logger.debug(\"existing vnet '%s' and subnet '%s' found\",", "except CloudError: return None def process_vmss_create_namespace(cmd, namespace): validate_tags(namespace) if namespace.vm_sku is None: from", "and using an image based OS if not namespace.storage_sku and namespace.storage_profile in [StorageProfile.SAPirImage,", "subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg, namespace='Microsoft.Compute', type='availabilitySets', name=name) logger.debug(\"adding to specified availability set '%s'\", namespace.availability_set) def", "setattr(namespace, 'application_security_groups', ids) def validate_nsg_name(cmd, namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import", "backports kernel # Oracle Linux 7.4, Windows Server 2016, Windows Server 2012R2 publisher,", "import normalize_disk_info # attach_data_disks are not exposed yet for VMSS, so use 'getattr'", "balancer is required because 'single placement group' is turned off\" raise CLIError('usage error:{}'.format(err))", "msrestazure.tools import parse_resource_id # use minimal parameters to resolve the expected storage profile", "ids = [] if names_or_ids == [\"\"] or not names_or_ids: return for val", "'networkSecurityGroups', 'Microsoft.Network') def _validate_vm_vmss_create_public_ip(cmd, namespace): if namespace.public_ip_address: if check_existence(cmd.cli_ctx, namespace.public_ip_address, namespace.resource_group_name, 'Microsoft.Network', 'publicIPAddresses'):", "image resource compute_client = _compute_client_factory(cmd.cli_ctx) try: compute_client.images.get(namespace.resource_group_name, namespace.image) namespace.image = _get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name,", "will be created.') def _subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision): mask = int(subnet_mask) # '2' are", "= CLIError('usage error: [--keyvault NAME --resource-group NAME | --keyvault ID]') kv = namespace.keyvault", "errors.append(message.format('certificateUrl', idx, jdx, idx_arg)) if is_windows and 'certificateStore' not in cert: errors.append(message.format('certificateStore', idx,", "[x.name for x in balancer.backend_address_pools] if len(values) > 1: raise CLIError(\"Multiple possible values", "value should be a subrange of --vnet-address-prefix's\" # extract vnet information needed to", "idx_arg)) if 'vaultCertificates' not in secret or not secret['vaultCertificates']: err = 'Secret is", "License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- #", "\"allow SSH access to the VM. If using machines without \" \"permanent storage,", "role, scope): import re import uuid from azure.cli.core.commands.client_factory import get_mgmt_service_client from azure.cli.core.profiles import", "\"administrator\", \"admin\", \"user\", \"user1\", \"test\", \"user2\", \"test1\", \"user3\", \"admin1\", \"1\", \"123\", \"a\", \"actuser\",", "is None: namespace.app_gateway_type = 'new' logger.debug('new application gateway will be created') # AppGateway", "'Standard_M64-16ms', 'Standard_D16_v3', 'Standard_D16s_v3', 'Standard_D32-16s_v3', 'Standard_D64-16s_v3', 'Standard_E16_v3', 'Standard_E16s_v3', 'Standard_E32-16s_v3', 'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC', 'Standard_F8_ABC', 'Standard_F16s_v2', 'Standard_D5_v2',", "compute_client.virtual_machine_sizes.list(namespace.location) size_info = next((s for s in sizes if s.name.lower() == size), None)", "subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name = namespace.network_security_group_name \\ or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8)) def validate_keyvault(cmd, namespace): namespace.keyvault", "if namespace.vnet_type == 'new': if namespace.subnet_address_prefix is None: cidr = namespace.vnet_address_prefix.split('/', 1)[0] i", "CLIError('Please specify password in non-interactive mode.') # validate password _validate_admin_password(namespace.admin_password, namespace.os_type) elif namespace.authentication_type", "import check_existence, get_target_network_api, get_storage_blob_uri from azure.cli.command_modules.vm._template_builder import StorageProfile import azure.cli.core.keys as keys from", "1 return ((1 << (32 - mask)) - 2) > int(vmss_instance_count * factor)", "= (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if is_linux else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err = r'admin user name cannot contain", "elif balancer_type == 'loadBalancer': # LoadBalancer frontend required = [] forbidden = ['app_gateway_subnet_address_prefix',", "in secret and 'id' not in secret['sourceVault']: errors.append( 'Secret is missing sourceVault.id key", "'Standard_D32-16s_v3', 'Standard_D64-16s_v3', 'Standard_E16_v3', 'Standard_E16s_v3', 'Standard_E32-16s_v3', 'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC', 'Standard_F8_ABC', 'Standard_F16s_v2', 'Standard_D5_v2', 'Standard_D14_v2', 'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo',", "from msrestazure.tools import parse_resource_id from azure.cli.core.profiles import ResourceType std_lb_is_available = cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK) if", "# -------------------------------------------------------------------------------------------- # pylint:disable=too-many-lines import os try: from urllib.parse import urlparse except ImportError:", "is None and namespace.app_gateway_type is None: if namespace.public_ip_address: raise CLIError('--public-ip-address can only be", "if an existing managed disk image resource compute_client = _compute_client_factory(cmd.cli_ctx) try: compute_client.images.get(namespace.resource_group_name, namespace.image)", "= '{0:32b}'.format(candidate_int << subnet_bit_mask_len) return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2), int(candaidate_str[8:16], 2), int(candaidate_str[16:24], 2), int(candaidate_str[24:32], 2),", "keys.is_valid_ssh_rsa_public_key(content): if namespace.generate_ssh_keys: # figure out appropriate file names: # 'base_name'(with private keys),", "suitable existing vnet/subnet result = None if not for_scale_set: result = next((s for", "distros = [('canonical', 'UbuntuServer', '^16.04'), ('suse', 'sles', '^12-sp3'), ('redhat', 'rhel', '^7.4'), ('openlogic', 'centos',", "meets the general requirements, but is specifically disallowed for this image. Please try", "Stack profile 2017_03_09 balancer_type = 'loadBalancer' if namespace.single_placement_group is not False else 'applicationGateway'", "= 'existing' logger.debug(\"suitable existing storage account '%s' will be used\", account.name) else: #", "'Standard_DS3_v2', 'Standard_DS12_v2', 'Standard_DS13-4_v2', 'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo', 'Standard_F4', 'Standard_F4s', 'Standard_D8_v3', 'Standard_D8s_v3', 'Standard_D32-8s_v3',", "= s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask, namespace.instance_count, not namespace.disable_overprovision) result = next((s for s in", "gateway '%s' not found. It will be created.\", namespace.application_gateway) elif namespace.application_gateway == '':", "--generate-ssh-keys to let CLI generate one for you') namespace.ssh_key_value = content def _validate_vm_vmss_msi(cmd,", "Configuring plan settings \" \"will be skipped\", namespace.image, ex.message) # pylint: disable=inconsistent-return-statements def", "res = parse_resource_id(res_id) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) vm_info = compute_client.virtual_machines.get(res['resource_group'], res['name']) # pylint:", "namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) if namespace.secrets: _validate_secrets(namespace.secrets, namespace.os_type) if namespace.license_type and namespace.os_type.lower() !=", "k, v in kwargs.items() if not v} return resource_id(**kwargs) if not missing_kwargs else", "content = string_or_file if os.path.exists(string_or_file): logger.info('Use existing SSH public key file: %s', string_or_file)", "(source_blob_uri, source_disk, source_snapshot) def process_disk_encryption_namespace(cmd, namespace): namespace.disk_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault')", "image_type = _parse_image_argument(cmd, namespace) if image_type == 'uri': # STORAGE PROFILE #2 namespace.storage_profile", "\\ 'index {1} and vaultCertificate index {2} in arg {3}' if 'certificateUrl' not", "= get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage) # endregion # region VMSS Create Validators def _get_default_address_pool(cli_ctx, resource_group,", "namespace.storage_account_type = 'new' logger.debug('no suitable storage account found. One will be created.') def", "('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')] import re for p, o, s in distros: if p.lower()", "= matched['sku'] namespace.os_version = matched['version'] return 'urn' # 5 - check if an", "= \"'Standard' load balancer is required for zonal scale-sets\" elif namespace.instance_count > 100:", "usage '--key-encryption-keyvault': \" \"'--key-encryption-key' is required\") namespace.key_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault')", "resource_group, 'namespace': resource_namespace, 'type': resource_type, 'subscription': get_subscription_id(cli_ctx) } missing_kwargs = {k: v for", "= \"usage error: --subnet-address-prefix value should be a subrange of --vnet-address-prefix's\" # extract", "CLIError('usage error: --license-type is only applicable on Windows VM') _validate_vm_vmss_msi(cmd, namespace) if namespace.boot_diagnostics_storage:", "endregion # region disk, snapshot, image validators def validate_vm_disk(cmd, namespace): namespace.disk = _get_resource_id(cmd.cli_ctx,", "namespace.vnet_type = 'existing' logger.debug(\"using specified vnet '%s' and subnet '%s'\", namespace.vnet_name, namespace.subnet) return", "process_remove_identity_namespace(cmd, namespace): if namespace.identities: from ._vm_utils import MSI_LOCAL_ID for i in range(len(namespace.identities)): if", "def _convert_to_int(address, bit_mask_len): a, b, c, d = [int(x) for x in address.split('.')]", "from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client from msrestazure.tools import parse_resource_id client", "{ \"id\": \"value\" }, \"vaultCertificates\": [{ \"certificateUrl\": \"value\", \"certificateStore\": \"cert store name (only", "Updates the namespace and returns the type for subsequent processing. \"\"\" from msrestazure.tools", "application gateway will be created') # AppGateway frontend required = [] if namespace.app_gateway_type", "namespace): _validate_vm_vmss_msi(cmd, namespace, from_set_command=True) def process_remove_identity_namespace(cmd, namespace): if namespace.identities: from ._vm_utils import MSI_LOCAL_ID", "= '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id, role) except ValueError: pass if not role_id: # retrieve role", "on windows)\" }] }] :param dict secrets: Dict fitting the JSON description above", "use '--location' to specify a capable one. 'az vm list-skus' can be \"", "role_defs = list(client.list(scope, \"roleName eq '{}'\".format(role))) if not role_defs: raise CLIError(\"Role '{}' doesn't", "[--role ROLE]') def _resolve_role_id(cli_ctx, role, scope): import re import uuid from azure.cli.core.commands.client_factory import", "== 'new': if namespace.subnet_address_prefix is None: cidr = namespace.vnet_address_prefix.split('/', 1)[0] i = 0", "process_vmss_create_namespace(cmd, namespace): validate_tags(namespace) if namespace.vm_sku is None: from azure.cli.core.cloud import AZURE_US_GOV_CLOUD if cmd.cli_ctx.cloud.name", "res['type'].lower() == 'images': image_info = compute_client.images.get(res['resource_group'], res['name']) namespace.os_type = image_info.storage_profile.os_disk.os_type.value image_data_disks_num = len(image_info.storage_profile.data_disks", "= [_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name, 'disks', 'Microsoft.Compute') for d in namespace.attach_data_disks] if not namespace.os_type:", "find an existing Vnet and subnet...') # if nothing specified, try to find", "--size Standard_DS1_v2' and # get it from the error aval_sizes = ['Standard_D3_v2', 'Standard_D12_v2',", "= _parse_image_argument(cmd, namespace) if image_type == 'uri': # STORAGE PROFILE #2 namespace.storage_profile =", "int(candaidate_str[16:24], 2), int(candaidate_str[24:32], 2), new_mask) def _validate_vm_create_nsg(cmd, namespace): if namespace.nsg: if check_existence(cmd.cli_ctx, namespace.nsg,", "is more readable setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role, namespace.identity_scope)) elif namespace.identity_scope or getattr(namespace.identity_role, 'is_default',", "= int(subnet_mask) # '2' are the reserved broadcasting addresses # '*1.5' so we", "logger.debug('no public IP address will be used') elif namespace.public_ip_address is None: namespace.public_ip_address_type =", "from azure.cli.core.profiles import ResourceType PublicIPAddressSkuName, IPAllocationMethod = cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK) if namespace.public_ip_sku ==", "'new' logger.debug('new NSG will be created') def _validate_vmss_create_nsg(cmd, namespace): if namespace.nsg: namespace.nsg =", "to match an URN pattern urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image) if urn_match: namespace.os_publisher =", "{ 'primary': nics_value[0] == n } }) namespace.nics = nics namespace.nic_type = 'existing'", "if is_linux else win_err) if is_linux and re.findall(r'^[$-]+', username): raise CLIError(linux_err) if not", "will be used\", account.name) else: # 4 - nothing specified - create a", "== 'gatewaysubnet': return False subnet_mask = s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask, namespace.instance_count, not namespace.disable_overprovision) result", "namespace.subnet_address_prefix = '{}/{}'.format(cidr, i) if namespace.app_gateway_type and namespace.app_gateway_subnet_address_prefix is None: namespace.app_gateway_subnet_address_prefix = _get_next_subnet_addr_suffix(", "2), int(candaidate_str[8:16], 2), int(candaidate_str[16:24], 2), int(candaidate_str[24:32], 2), new_mask) def _validate_vm_create_nsg(cmd, namespace): if namespace.nsg:", "One will be created.') def _validate_vm_create_availability_set(cmd, namespace): from msrestazure.tools import parse_resource_id, resource_id from", "else: namespace.public_ip_address_type = 'new' logger.debug(\"specified public IP '%s' not found. It will be", "\"{}\"'.format(namespace.image)) image_version_info = sorted(image_version_infos, key=lambda x: x.publishing_profile.published_date)[-1] else: image_version_info = compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'], gallery_name=res['name'],", "'storage_account', 'storage_container_name', 'data_disk_sizes_gb', 'storage_sku'] + auth_params else: raise CLIError('Unrecognized storage profile: {}'.format(namespace.storage_profile)) logger.debug(\"storage", "raise CLIError('usage error: --license-type is only applicable on Windows VM') _validate_vm_vmss_msi(cmd, namespace) if", "possible values found for '{0}': {1}\\nSpecify '{0}' explicitly.\".format( # pylint: disable=line-too-long '--nat-pool-name', ',", "disable=line-too-long namespace.data_blob_uris = [] namespace.data_disks = [] namespace.data_snapshots = [] if namespace.data_disk_sources: for", "as keys from ._client_factory import _compute_client_factory from ._actions import _get_latest_image_version logger = get_logger(__name__)", "ResourceType PublicIPAddressSkuName, IPAllocationMethod = cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK) if namespace.public_ip_sku == PublicIPAddressSkuName.standard.value: if not", "in nics_value: nics.append({ 'id': n if '/' in n else resource_id(name=n, resource_group=namespace.resource_group_name, namespace='Microsoft.Network',", "because 'single placement group' is turned off\" raise CLIError('usage error:{}'.format(err)) def get_network_client(cli_ctx): from", "import ( get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set, validate_tags) from azure.cli.core.util import hash_string from azure.cli.command_modules.vm._vm_utils import", "names_or_ids: return for val in names_or_ids: if not is_valid_resource_id(val): val = resource_id( subscription=subscription_id,", "'linux' from ._vm_utils import normalize_disk_info # attach_data_disks are not exposed yet for VMSS,", "not namespace.os_type: raise CLIError(\"Unable to resolve OS type. Specify '--os-type' argument.\") if not", "namespace.load_balancer_sku is None: namespace.load_balancer_sku = LBSkuName.standard.value logger.debug(\"use Standard sku as single placement group", "= (namespace.ssh_key_value or os.path.join(os.path.expanduser('~'), '.ssh', 'id_rsa.pub')) content = string_or_file if os.path.exists(string_or_file): logger.info('Use existing", "= _figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name, namespace.source) # pylint: disable=line-too-long namespace.data_blob_uris = [] namespace.data_disks = []", "Associated scaleset will be missing ssh/rdp, so warn here. logger.warning(\"No inbound nat pool", "ID (assumes it is an image ID) if is_valid_resource_id(namespace.image): return 'image_id' # 2", "subnet_bit_mask_len = 32 - int(mask) if vnet_bit_mask_len <= subnet_bit_mask_len: raise CLIError(error_msg) candidate_int =", "if is_linux else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err = r'admin user name cannot contain upper case", "message = 'Secret is missing {0} within vaultCertificates array at secret ' \\", "ResourceType client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions role_id = None if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role, re.I): role_id", "namespace.resource_group_name, 'Microsoft.Network', 'publicIPAddresses'): namespace.public_ip_address_type = 'existing' logger.debug(\"using existing specified public IP '%s'\", namespace.public_ip_address)", "not is_linux and username.endswith('.'): raise CLIError(win_err) disallowed_user_names = [ \"administrator\", \"admin\", \"user\", \"user1\",", "found :rtype: list \"\"\" is_windows = os_type == 'windows' errors = [] try:", "= None if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role, re.I): role_id = role else: try: uuid.UUID(role) role_id", "def _validate_vm_create_storage_account(cmd, namespace): from msrestazure.tools import parse_resource_id if namespace.storage_account: storage_id = parse_resource_id(namespace.storage_account) rg", "namespace.single_placement_group is None: namespace.single_placement_group = False elif namespace.single_placement_group: raise CLIError(\"usage error: '--single-placement-group' should", "{}'.format(min_length, max_length)) contains_lower = re.findall('[a-z]+', password) contains_upper = re.findall('[A-Z]+', password) contains_digit = re.findall('[0-9]+',", "ag_name) namespace.app_gateway_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, ag_name, 'application_gateways')", "error: --vm-domain-name can only be used when --public-ip-per-vm is enabled') if namespace.eviction_policy and", "required = ['image', 'os_type', 'use_unmanaged_disk'] forbidden = ['attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SASpecializedOSDisk:", "logger.warning(\"Querying the image of '%s' failed for an error '%s'. Configuring plan settings", "and not subnet_exists: raise CLIError(\"Subnet '{}' does not exist.\".format(subnet)) elif subnet_exists: # 2", "== 'ssh': raise CLIError('SSH not supported for Windows VMs.') # validate proper arguments", "nat pool was configured on '%s'\", namespace.load_balancer) else: namespace.nat_pool_name = lb.inbound_nat_pools[0].name logger.debug(\"using specified", "= list_sku_info(cmd.cli_ctx, namespace.location) temp = next((x for x in sku_infos if x.name.lower() ==", "compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) namespace.os_type = image_info.os_type.value gallery_image_version = res.get('child_name_2', '') if gallery_image_version.lower() in", "msrestazure.tools import is_valid_resource_id from msrestazure.azure_exceptions import CloudError import re # 1 - check", "ZONES') if namespace.zones or namespace.instance_count > 100: if namespace.single_placement_group is None: namespace.single_placement_group =", "re.findall(r'^[$-]+', username): raise CLIError(linux_err) if not is_linux and username.endswith('.'): raise CLIError(win_err) disallowed_user_names =", "array containing secrets for use in VM Creation Secrets JSON structure [{ \"sourceVault\":", "r'admin user name cannot contain upper case character A-Z, special characters \\/\"[]:|<>+=;,?*@#()! or", "'%s'\", namespace.public_ip_address) else: namespace.public_ip_address_type = 'new' logger.debug(\"specified public IP '%s' not found. It", "err = \"instance count '{}' is out of range of 2^16 subnet size'\"", "STORAGE PROFILE #1 namespace.storage_profile = StorageProfile.SAPirImage else: # STORAGE PROFILE #4 namespace.storage_profile =", "forbidden parameters validate_parameter_set( namespace, required, forbidden, description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num = 0 if", "namespace.plan_publisher]): image_plan = _get_image_plan_info_if_exists(cmd, namespace) if image_plan: namespace.plan_name = image_plan.name namespace.plan_product = image_plan.product", "used with SSH authentication type') validate_ssh_key(namespace) if not namespace.ssh_dest_key_path: namespace.ssh_dest_key_path = \\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username)", "if namespace.subnet_address_prefix is None: cidr = namespace.vnet_address_prefix.split('/', 1)[0] i = 0 for i", "_get_latest_image_version logger = get_logger(__name__) def validate_asg_names_or_ids(cmd, namespace): from msrestazure.tools import resource_id, is_valid_resource_id from", "namespace.os_offer = urn_match.group(2) namespace.os_sku = urn_match.group(3) namespace.os_version = urn_match.group(4) if not any([namespace.plan_name, namespace.plan_product,", "= as_id.get('resource_group', namespace.resource_group_name) if not check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute', 'availabilitySets'): raise CLIError(\"Availability set", "mask = int(subnet_mask) # '2' are the reserved broadcasting addresses # '*1.5' so", "return publisher, offer, sku = publisher.lower(), offer.lower(), sku.lower() distros = [('canonical', 'UbuntuServer', '^16.04'),", "\"user1\", \"test\", \"user2\", \"test1\", \"user3\", \"admin1\", \"1\", \"123\", \"a\", \"actuser\", \"adm\", \"admin2\", \"aspnet\",", "return image.plan except CloudError as ex: logger.warning(\"Querying the image of '%s' failed for", "getattr(namespace, 'public_ip_sku', None): from azure.cli.core.profiles import ResourceType PublicIPAddressSkuName, IPAllocationMethod = cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK)", "as f: content = f.read() elif not keys.is_valid_ssh_rsa_public_key(content): if namespace.generate_ssh_keys: # figure out", "check if an existing managed disk image resource compute_client = _compute_client_factory(cmd.cli_ctx) try: compute_client.images.get(namespace.resource_group_name,", "if not role_defs: raise CLIError(\"Role '{}' doesn't exist.\".format(role)) elif len(role_defs) > 1: ids", "ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client from msrestazure.tools import parse_resource_id client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults", "'Standard_E32-8s_v3', 'Standard_E32-16_v3', 'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC', 'Standard_F16_ABC', 'Standard_F32s_v2', 'Standard_D15_v2', 'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested', 'Standard_DS15_v2', 'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested', 'Standard_D40_v3',", "description above :param string os_type: the type of OS (linux or windows) :return:", "namespace.data_snapshots = [] if namespace.data_disk_sources: for data_disk_source in namespace.data_disk_sources: source_blob_uri, source_disk, source_snapshot =", "['os_type', 'attach_os_disk', 'use_unmanaged_disk'] forbidden = ['os_disk_name', 'os_caching', 'image', 'storage_account', 'storage_container_name', 'data_disk_sizes_gb', 'storage_sku'] +", "account.name namespace.storage_account_type = 'existing' logger.debug(\"suitable existing storage account '%s' will be used\", account.name)", "be created.\", namespace.load_balancer) elif namespace.load_balancer == '': namespace.load_balancer_type = None logger.debug('no load balancer", "namespace.location nics = getattr(namespace, 'nics', None) if not vnet and not subnet and", "_convert_to_int(vnet_ip_address, vnet_bit_mask_len) subnet_ip_address, mask = subnet_cidr.split('/') subnet_bit_mask_len = 32 - int(mask) if vnet_bit_mask_len", "raise CLIError(linux_err) if not is_linux and username.endswith('.'): raise CLIError(win_err) disallowed_user_names = [ \"administrator\",", "'Secret is missing sourceVault key at index {0} in arg {1}'.format( idx, idx_arg))", "namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_assign_identity_namespace(cmd, namespace): _validate_vm_vmss_msi(cmd, namespace, from_set_command=True) def process_remove_identity_namespace(cmd, namespace): if", "res['name']) namespace.os_type = image_info.storage_profile.os_disk.os_type.value image_data_disks_num = len(image_info.storage_profile.data_disks or []) elif res['type'].lower() == 'galleries':", "= namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, ag_name, 'application_gateways') logger.debug(\"using specified existing application gateway", "# STORAGE PROFILE #5 namespace.storage_profile = StorageProfile.ManagedCustomImage elif image_type == 'urn': if namespace.use_unmanaged_disk:", "group namespace.storage_account = account.name namespace.storage_account_type = 'existing' logger.debug(\"suitable existing storage account '%s' will", "return for val in names_or_ids: if not is_valid_resource_id(val): val = resource_id( subscription=subscription_id, resource_group=resource_group,", "['app_gateway_subnet_address_prefix', 'application_gateway', 'app_gateway_sku', 'app_gateway_capacity'] validate_parameter_set(namespace, required, forbidden, description='network balancer: load balancer') if namespace.load_balancer:", "namespace.app_gateway_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, ag_name, 'application_gateways') logger.debug(\"using", "specified. Attempting to find an existing Vnet and subnet...') # if nothing specified,", "namespace.public_ip_address_type = 'new' logger.debug('new public IP address will be created') # Public-IP SKU", "forbidden = ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile", "# 3 - create a new vnet/subnet namespace.vnet_type = 'new' logger.debug('no suitable subnet", "namespace.app_gateway_type and namespace.app_gateway_subnet_address_prefix is None: namespace.app_gateway_subnet_address_prefix = _get_next_subnet_addr_suffix( namespace.vnet_address_prefix, namespace.subnet_address_prefix, 24) def _get_next_subnet_addr_suffix(vnet_cidr,", "< 3: raise CLIError('Password must have the 3 of the following: 1 lower", "}, \"vaultCertificates\": [{ \"certificateUrl\": \"value\", \"certificateStore\": \"cert store name (only on windows)\" }]", "allowed_skus]: raise CLIError(\"invalid storage SKU '{}': allowed values: '{}'\".format(sku, allowed_skus)) def _validate_location(cmd, namespace,", "Windows VM scaleset') if not namespace.public_ip_per_vm and namespace.vm_domain_name: raise CLIError('Usage error: --vm-domain-name can", "figure out appropriate file names: # 'base_name'(with private keys), and 'base_name.pub'(with public keys)", "import get_subscription_id vm_id = resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name = namespace.network_security_group_name \\", "get_subscription_id(cli_ctx) } missing_kwargs = {k: v for k, v in kwargs.items() if not", "range(24, 16, -1): if _subnet_capacity_check(i, namespace.instance_count, not namespace.disable_overprovision): break if i < 16:", "[ \"administrator\", \"admin\", \"user\", \"user1\", \"test\", \"user2\", \"test1\", \"user3\", \"admin1\", \"1\", \"123\", \"a\",", "namespace): from msrestazure.azure_exceptions import CloudError from msrestazure.tools import parse_resource_id from azure.cli.core.profiles import ResourceType", "if not username: raise CLIError(\"admin user name can not be empty\") is_linux =", "return new_4core_sizes = ['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2', 'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC', 'Standard_DS12_v2', 'Standard_DS12_v2_Promo',", "import get_mgmt_service_client from msrestazure.tools import parse_resource_id client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults for vault in", "except CloudError: namespace.os_blob_uri, namespace.os_disk, namespace.os_snapshot = _figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name, namespace.source) # pylint: disable=line-too-long namespace.data_blob_uris", "elif profile == StorageProfile.SASpecializedOSDisk: return 'attach to existing unmanaged OS disk' elif profile", "len(parts) == 1: regions_info.append(TargetRegion(name=parts[0])) else: try: replica_count = int(parts[1]) except ValueError: raise CLIError(\"usage", "urlparse(namespace.image).scheme: return 'uri' # 4 - attempt to match an URN alias (most", "'windows' if 'windows' in namespace.os_offer.lower() else 'linux' from ._vm_utils import normalize_disk_info # attach_data_disks", "import get_mgmt_service_client return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx)) def get_network_lb(cli_ctx, resource_group_name, lb_name): from msrestazure.azure_exceptions import", "sku_tier = 'Premium' if 'Premium' in namespace.storage_sku else 'Standard' account = next( (a", "= matched['version'] return 'urn' # 5 - check if an existing managed disk", "# endregion # region VMSS Create Validators def _get_default_address_pool(cli_ctx, resource_group, balancer_name, balancer_type): option_name", "'Standard_D32-8s_v3', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC', 'Standard_F4_ABC', 'Standard_F8s_v2', 'Standard_D4_v2', 'Standard_D13_v2', 'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo', 'Standard_DS4_v2', 'Standard_DS13_v2',", "'Standard_DS14-8_v2_Promo', 'Standard_F8', 'Standard_F8s', 'Standard_M64-16ms', 'Standard_D16_v3', 'Standard_D16s_v3', 'Standard_D32-16s_v3', 'Standard_D64-16s_v3', 'Standard_E16_v3', 'Standard_E16s_v3', 'Standard_E32-16s_v3', 'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC',", "size_info): from ._vm_utils import list_sku_info if not namespace.location: get_default_location_from_resource_group(cmd, namespace) if zone_info: sku_infos", "= 12 if len(password) not in range(min_length, max_length + 1): raise CLIError('The password", "if size not in new_4core_sizes: compute_client = _compute_client_factory(cli_ctx) sizes = compute_client.virtual_machine_sizes.list(namespace.location) size_info =", "load balancer is required for zonal scale-sets\" elif namespace.instance_count > 100: err =", "namespace='Microsoft.Network', type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)), 'properties': { 'primary': nics_value[0] == n } }) namespace.nics =", "return id_comps['resource_group'] return None def _get_resource_id(cli_ctx, val, resource_group, resource_type, resource_namespace): from msrestazure.tools import", "+ auth_params _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.SAPirImage: required = ['image', 'use_unmanaged_disk'] forbidden =", "status of required and forbidden parameters validate_parameter_set( namespace, required, forbidden, description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile)))", "if '/' in n else resource_id(name=n, resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)), 'properties': { 'primary':", "keys to a safe location.\", private_key_filepath, public_key_filepath) else: raise CLIError('An RSA key file", "given name '{}'. Please pick an id from '{}'\" raise CLIError(err.format(role, ids)) role_id", "== 'windows' or namespace.admin_password) else 'ssh' if namespace.os_type.lower() == 'windows' and namespace.authentication_type ==", "here. logger.warning(\"No inbound nat pool was configured on '%s'\", namespace.load_balancer) else: namespace.nat_pool_name =", "namespace.use_unmanaged_disk: # STORAGE PROFILE #1 namespace.storage_profile = StorageProfile.SAPirImage else: # STORAGE PROFILE #4", "= getattr(namespace, 'nics', None) if not vnet and not subnet and not nics:", "# figure out appropriate file names: # 'base_name'(with private keys), and 'base_name.pub'(with public", "from virtual machines\") except CloudError: namespace.os_blob_uri, namespace.os_disk, namespace.os_snapshot = _figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name, namespace.source) #", "if namespace.use_unmanaged_disk: # STORAGE PROFILE #3 namespace.storage_profile = StorageProfile.SASpecializedOSDisk else: # STORAGE PROFILE", "IMAGE | --attach-os-disk DISK') auth_params = ['<PASSWORD>_password', 'admin_username', 'authentication_type', 'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value'] #", "== StorageProfile.SASpecializedOSDisk: required = ['os_type', 'attach_os_disk', 'use_unmanaged_disk'] forbidden = ['os_disk_name', 'os_caching', 'image', 'storage_account',", "raise keyvault_usage def _get_resource_group_from_vault_name(cli_ctx, vault_name): \"\"\" Fetch resource group from vault name :param", "get_subscription_id nics_value = namespace.nics nics = [] if not nics_value: namespace.nic_type = 'new'", "pylint:disable=too-many-lines import os try: from urllib.parse import urlparse except ImportError: from urlparse import", "normalize_disk_info # attach_data_disks are not exposed yet for VMSS, so use 'getattr' to", "image type: {}'.format(image_type)) else: # did not specify image XOR attach-os-disk raise CLIError('incorrect", "= string_or_file if os.path.exists(string_or_file): logger.info('Use existing SSH public key file: %s', string_or_file) with", "not cmd.supported_api_version(min_api='2017-12-01'): raise CLIError('usage error: user assigned identity is only available under profile", "values found for '{0}'. Create one first and try \" \"again.\".format(option_name)) return values[0]", "is no latest image version exists for \"{}\"'.format(namespace.image)) image_version_info = sorted(image_version_infos, key=lambda x:", "characters \\/\"[]:|<>+=;,?*@#()! or start with $ or -' win_err = r'admin user name", "['attach_os_disk', 'storage_account'] for prop in props_to_remove: if prop in required: required.remove(prop) if prop", "= namespace.assign_identity or [] from ._vm_utils import MSI_LOCAL_ID for i, _ in enumerate(identities):", "None: namespace.single_placement_group = False elif namespace.single_placement_group: raise CLIError(\"usage error: '--single-placement-group' should be turned", "bool(namespace.disk) == bool(namespace.size_gb): raise CLIError('usage error: --disk EXIST_DISK --instance-id ID | --size-gb GB')", "getattr(namespace, 'attach_os_disk', None) and not namespace.image: if namespace.use_unmanaged_disk: # STORAGE PROFILE #3 namespace.storage_profile", "required\") namespace.key_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_assign_identity_namespace(cmd, namespace): _validate_vm_vmss_msi(cmd, namespace,", "namespace.zones or namespace.instance_count > 100: if namespace.single_placement_group is None: namespace.single_placement_group = False elif", "subnet_is_id = is_valid_resource_id(subnet) if (subnet_is_id and vnet) or (not subnet_is_id and not vnet):", "Vnet and subnet...') # if nothing specified, try to find an existing vnet", "name (only on windows)\" }] }] :param dict secrets: Dict fitting the JSON", "('openlogic', 'centos', '^7.4'), ('coreos', 'coreos', None), ('credativ', 'debian', '-backports'), ('oracle', 'oracle-linux', '^7.4'), ('MicrosoftWindowsServer',", "('MicrosoftWindowsServer', 'WindowsServer', '^2016'), ('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')] import re for p, o, s in", "\"\"\" from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client from msrestazure.tools import parse_resource_id", "# use minimal parameters to resolve the expected storage profile if getattr(namespace, 'attach_os_disk',", "of 2^16 subnet size'\" raise CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix = '{}/{}'.format(cidr, i) if namespace.app_gateway_type and", "a custom image name, id, or pick one from {}' raise CLIError(err.format(namespace.image, [x['urnAlias']", "re.I): role_id = role else: try: uuid.UUID(role) role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id, role) except", "len(values) > 1: raise CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify '{0}' \"", "prop in forbidden: forbidden.remove(prop) # set default storage SKU if not provided and", "namespace) validate_tags(namespace) def process_gallery_image_version_namespace(cmd, namespace): TargetRegion = cmd.get_models('TargetRegion') if namespace.target_regions: regions_info = []", "for x in balancer.backend_address_pools] if len(values) > 1: raise CLIError(\"Multiple possible values found", "!= 'windows': raise CLIError('usage error: --license-type is only applicable on Windows VM scaleset')", "keyvault_usage validate_keyvault(cmd, namespace) else: if kv and not is_valid_resource_id(kv): raise keyvault_usage def _get_resource_group_from_vault_name(cli_ctx,", "= namespace.resource_group_name nic_ids = [] for n in namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg)) namespace.nics", "urn_match.group(1) namespace.os_offer = urn_match.group(2) namespace.os_sku = urn_match.group(3) namespace.os_version = urn_match.group(4) if not any([namespace.plan_name,", "case character A-Z, special characters \\/\"[]:|<>+=;,?*@#()! or start with $ or -' win_err", "\" \"'--key-encryption-key' is required\") namespace.key_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_assign_identity_namespace(cmd,", "applicable on Windows VM scaleset') if not namespace.public_ip_per_vm and namespace.vm_domain_name: raise CLIError('Usage error:", "# region disk, snapshot, image validators def validate_vm_disk(cmd, namespace): namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk,", "= next((s for s in sizes if s.name.lower() == size), None) if size_info", "names_or_ids == [\"\"] or not names_or_ids: return for val in names_or_ids: if not", "not temp or not [x for x in (temp.location_info or []) if x.zones]:", "\"permanent storage, back up your keys to a safe location.\", private_key_filepath, public_key_filepath) else:", "the specific storage profile # start with the required/forbidden parameters for VM if", "identities: raise CLIError(\"usage error: '--scope'/'--role' is only applicable when assign system identity\") #", "None if not for_scale_set: result = next((s for s in vnet_match.subnets if s.name.lower()", "logger.debug('new NIC will be created') return if not isinstance(nics_value, list): nics_value = [nics_value]", "create a new vnet/subnet namespace.vnet_type = 'new' logger.debug('no suitable subnet found. One will", "rg) def _validate_secrets(secrets, os_type): \"\"\" Validates a parsed JSON array containing secrets for", "1 lower case character, 1 upper case character, 1 number and 1 special", "for VMSS, so use 'getattr' to avoid crash namespace.disk_info = normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace,", "namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg)) namespace.nics = nic_ids if hasattr(namespace, 'primary_nic') and namespace.primary_nic: namespace.primary_nic", "{}'.format(namespace.storage_profile)) logger.debug(\"storage profile '%s'\", namespace.storage_profile) if for_scale_set: # VMSS lacks some parameters, so", "if namespace.ssh_key_value or namespace.ssh_dest_key_path: raise ValueError( \"incorrect usage for authentication-type 'password': \" \"[--admin-username", "group client = get_network_client(cmd.cli_ctx).virtual_networks # find VNET in target resource group that matches", "--resource-group NAME | --keyvault ID]') kv = namespace.keyvault rg = namespace.resource_group_name if rg:", "OS disk from Azure Marketplace image' elif profile == StorageProfile.ManagedSpecializedOSDisk: return 'attach existing", "'loadBalancer' else: # needed for Stack profile 2017_03_09 balancer_type = 'loadBalancer' if namespace.single_placement_group", "if user_assigned_identities and not cmd.supported_api_version(min_api='2017-12-01'): raise CLIError('usage error: user assigned identity is only", "int(candaidate_str[24:32], 2), new_mask) def _validate_vm_create_nsg(cmd, namespace): if namespace.nsg: if check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'Microsoft.Network',", "image_type == 'urn': if namespace.use_unmanaged_disk: # STORAGE PROFILE #1 namespace.storage_profile = StorageProfile.SAPirImage else:", "role_defs: raise CLIError(\"Role '{}' doesn't exist.\".format(role)) elif len(role_defs) > 1: ids = [r.id", "\"explicitly.\".format(option_name, ', '.join(values))) elif not values: raise CLIError(\"No existing values found for '{0}'.", "= r'admin user name cannot contain upper case character A-Z, special characters \\/\"[]:|<>+=;,?*@#()!", "- mask)) - 2) > int(vmss_instance_count * factor) def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace): if namespace.accelerated_networking", "else: err = \"'Standard' load balancer is required because 'single placement group' is", "msrestazure.azure_exceptions import CloudError source_blob_uri = None source_disk = None source_snapshot = None if", "for i in range(len(namespace.identities)): if namespace.identities[i] != MSI_LOCAL_ID: namespace.identities[i] = _get_resource_id(cmd.cli_ctx, namespace.identities[i], namespace.resource_group_name,", "pylint: disable=no-member namespace.os_type = vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine = res_id if namespace.data_disk_sources: raise CLIError(\"'--data-disk-sources' is", "if identities and MSI_LOCAL_ID not in identities: raise CLIError(\"usage error: '--scope'/'--role' is only", "to specified availability set '%s'\", namespace.availability_set) def _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False): from msrestazure.tools import", "RSA key file or key value must be supplied to SSH Key Value.", "namespace.os_offer, namespace.os_sku if not publisher: return publisher, offer, sku = publisher.lower(), offer.lower(), sku.lower()", "found. It will be created.\", namespace.load_balancer) elif namespace.load_balancer == '': namespace.load_balancer_type = None", ":rtype: str \"\"\" from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client from msrestazure.tools", "private_key_filepath = public_key_filepath + '.private' content = keys.generate_ssh_keys(private_key_filepath, public_key_filepath) logger.warning(\"SSH key files '%s'", "if not namespace.source_blob_uri and namespace.source_storage_account_id: raise CLIError(usage_error) except CloudError: raise CLIError(usage_error) def process_image_create_namespace(cmd,", "not in cert: errors.append(message.format('certificateUrl', idx, jdx, idx_arg)) if is_windows and 'certificateStore' not in", "namespace): if namespace.nsg: if check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_type = 'existing' logger.debug(\"using", "to create the image, \" \"please specify '--os-type OS_TYPE'\") def _figure_out_storage_source(cli_ctx, resource_group_name, source):", "name of the key vault :return: resource group name or None :rtype: str", "= [nics_value] for n in nics_value: nics.append({ 'id': n if '/' in n", "is_valid_resource_id from msrestazure.azure_exceptions import CloudError import re # 1 - check if a", "'%s' not found. It will be created.\", namespace.application_gateway) elif namespace.application_gateway == '': namespace.app_gateway_type", "'Standard_F16s', 'Standard_M64-32ms', 'Standard_M128-32ms', 'Standard_D32_v3', 'Standard_D32s_v3', 'Standard_D64-32s_v3', 'Standard_E32_v3', 'Standard_E32s_v3', 'Standard_E32-8s_v3', 'Standard_E32-16_v3', 'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC', 'Standard_F16_ABC',", "- attempt to match an URN alias (most likely) from azure.cli.command_modules.vm._actions import load_images_from_aliases_doc", "_validate_vm_vmss_msi(cmd, namespace, from_set_command=True) def process_remove_identity_namespace(cmd, namespace): if namespace.identities: from ._vm_utils import MSI_LOCAL_ID for", "val, resource_group): return _get_resource_id(cli_ctx, val, resource_group, 'networkInterfaces', 'Microsoft.Network') def validate_vm_nic(cmd, namespace): namespace.nic =", "is None or re.match(s, sku, re.I)): namespace.accelerated_networking = True def _validate_vmss_create_subnet(namespace): if namespace.vnet_type", "'--backend-pool-name' client = getattr(get_network_client(cli_ctx), balancer_type, None) if not client: raise CLIError('unrecognized balancer type:", "disk' def _validate_managed_disk_sku(sku): allowed_skus = ['Premium_LRS', 'Standard_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS'] if sku and sku.lower()", "subnet_bit_mask_len)) > vnet_int: raise CLIError(error_msg) # format back to the cidr candaidate_str =", "nics.append({ 'id': n if '/' in n else resource_id(name=n, resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)),", "raise CLIError('Usage error: --vm-domain-name can only be used when --public-ip-per-vm is enabled') if", "CLIError(err.format(role, ids)) role_id = role_defs[0].id return role_id def process_vm_create_namespace(cmd, namespace): validate_tags(namespace) _validate_location(cmd, namespace,", "secrets for use in VM Creation Secrets JSON structure [{ \"sourceVault\": { \"id\":", "raise CLIError('usage error: --platform-fault-domain-count COUNT --zones ZONES') if namespace.zones or namespace.instance_count > 100:", "vaultCertificates array or it is empty at index {0} in ' \\ 'arg", "StorageProfile.ManagedCustomImage elif image_type == 'urn': if namespace.use_unmanaged_disk: # STORAGE PROFILE #1 namespace.storage_profile =", "load balancer') if namespace.load_balancer: rg = parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name) lb_name = parse_resource_id(namespace.load_balancer)['name'] lb =", "not False else 'applicationGateway' logger.debug(\"W/o STD LB, defaulting to '%s' under because single", "source else: compute_client = _compute_client_factory(cli_ctx) # pylint: disable=no-member try: info = compute_client.snapshots.get(resource_group_name, source)", "temp or not [x for x in (temp.location_info or []) if x.zones]: raise", "list(client.list(scope, \"roleName eq '{}'\".format(role))) if not role_defs: raise CLIError(\"Role '{}' doesn't exist.\".format(role)) elif", "namespace.vnet_name, namespace.subnet) return if subnet: subnet_is_id = is_valid_resource_id(subnet) if (subnet_is_id and vnet) or", "specified - find viable storage account in target resource group namespace.storage_account = account.name", "Licensed under the MIT License. See License.txt in the project root for license", "None) if matched: namespace.os_publisher = matched['publisher'] namespace.os_offer = matched['offer'] namespace.os_sku = matched['sku'] namespace.os_version", "int(candaidate_str[8:16], 2), int(candaidate_str[16:24], 2), int(candaidate_str[24:32], 2), new_mask) def _validate_vm_create_nsg(cmd, namespace): if namespace.nsg: if", "os_type): import re is_linux = (os_type.lower() == 'linux') max_length = 72 if is_linux", "not getattr(namespace, 'attach_os_disk', None): image_type = _parse_image_argument(cmd, namespace) if image_type == 'uri': #", "[--keyvault NAME --resource-group NAME | --keyvault ID]') kv = namespace.keyvault rg = namespace.resource_group_name", "storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching) def _validate_vm_create_storage_account(cmd, namespace): from msrestazure.tools import parse_resource_id if namespace.storage_account: storage_id", "found for '{0}': {1}\\nSpecify '{0}' explicitly.\".format( # pylint: disable=line-too-long '--nat-pool-name', ', '.join([n.name for", "if namespace.nsg: namespace.nsg = _get_resource_id(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'networkSecurityGroups', 'Microsoft.Network') def _validate_vm_vmss_create_public_ip(cmd, namespace): if", "if namespace.zones: err = \"'Standard' load balancer is required for zonal scale-sets\" elif", "find an existing vnet and subnet in the target resource group client =", "locations\".format(namespace.resource_group_name)) # pylint: disable=too-many-branches, too-many-statements def _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False): from msrestazure.tools import parse_resource_id", "= account.name namespace.storage_account_type = 'existing' logger.debug(\"suitable existing storage account '%s' will be used\",", "and namespace.app_gateway_type is None: if namespace.public_ip_address: raise CLIError('--public-ip-address can only be used when", "for Linux) by examining the OS type namespace.authentication_type = 'password' \\ if (namespace.os_type.lower()", "'{}'\".format(sku, allowed_skus)) def _validate_location(cmd, namespace, zone_info, size_info): from ._vm_utils import list_sku_info if not", "data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace, 'attach_data_disks', []), storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching) def _validate_vm_create_storage_account(cmd, namespace): from msrestazure.tools import", "parameters validate_parameter_set( namespace, required, forbidden, description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num = 0 if namespace.storage_profile", "is None or o.lower() == offer) and (s is None or re.match(s, sku,", "except CloudError: namespace.app_gateway_type = 'new' logger.debug(\"application gateway '%s' not found. It will be", "subscription_id = get_subscription_id(cmd.cli_ctx) names_or_ids = getattr(namespace, 'application_security_groups') ids = [] if names_or_ids ==", "is_windows and 'certificateStore' not in cert: errors.append(message.format('certificateStore', idx, jdx, idx_arg)) if errors: raise", "the target resource group client = get_network_client(cmd.cli_ctx).virtual_networks # find VNET in target resource", "managed OS disk from custom image' elif profile == StorageProfile.ManagedPirImage: return 'create managed", "namespace.public_ip_address_type = None logger.debug('no public IP address will be used') elif namespace.public_ip_address is", "values found for '{0}': {1}\\nSpecify '{0}' explicitly.\".format( # pylint: disable=line-too-long '--nat-pool-name', ', '.join([n.name", "yet \" \"supported. Please use '--location' to specify a capable one. 'az vm", "not None: identities = namespace.assign_identity or [] from ._vm_utils import MSI_LOCAL_ID for i,", "== 'loadBalancer': # LoadBalancer frontend required = [] forbidden = ['app_gateway_subnet_address_prefix', 'application_gateway', 'app_gateway_sku',", "TODO move to its own command module https://github.com/Azure/azure-cli/issues/5105 def process_msi_namespace(cmd, namespace): get_default_location_from_resource_group(cmd, namespace)", "'%s' under because single placement group is disabled\", balancer_type) elif namespace.load_balancer: balancer_type =", "store name (only on windows)\" }] }] :param dict secrets: Dict fitting the", "# pylint: disable=line-too-long namespace.data_blob_uris = [] namespace.data_disks = [] namespace.data_snapshots = [] if", "over_provision else 1 return ((1 << (32 - mask)) - 2) > int(vmss_instance_count", "namespace) if zone_info: sku_infos = list_sku_info(cmd.cli_ctx, namespace.location) temp = next((x for x in", "'Premium' in namespace.storage_sku else 'Standard' account = next( (a for a in storage_client.list_by_resource_group(namespace.resource_group_name)", "'existing' logger.debug(\"suitable existing storage account '%s' will be used\", account.name) else: # 4", "- user specified existing vnet/subnet namespace.vnet_type = 'existing' logger.debug(\"using specified vnet '%s' and", "range of 2^16 subnet size'\" raise CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix = '{}/{}'.format(cidr, i) if namespace.app_gateway_type", "OS type namespace.authentication_type = 'password' \\ if (namespace.os_type.lower() == 'windows' or namespace.admin_password) else", "= [] if namespace.app_gateway_type == 'new': required.append('app_gateway_sku') required.append('app_gateway_capacity') if namespace.vnet_type != 'new': required.append('app_gateway_subnet_address_prefix')", "= re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image) if urn_match: namespace.os_publisher = urn_match.group(1) namespace.os_offer = urn_match.group(2) namespace.os_sku =", "apply default auth type (password for Windows, ssh for Linux) by examining the", "nics_value[0] == n } }) namespace.nics = nics namespace.nic_type = 'existing' namespace.public_ip_address_type =", "vnet_match.name namespace.vnet_type = 'existing' logger.debug(\"existing vnet '%s' and subnet '%s' found\", namespace.vnet_name, namespace.subnet)", "disable=line-too-long if count < 3: raise CLIError('Password must have the 3 of the", "!= MSI_LOCAL_ID] if user_assigned_identities and not cmd.supported_api_version(min_api='2017-12-01'): raise CLIError('usage error: user assigned identity", ":param str vault_name: name of the key vault :return: resource group name or", "['os_type', 'attach_os_disk'] forbidden = ['os_disk_name', 'os_caching', 'storage_account', 'storage_container_name', 'use_unmanaged_disk', 'storage_sku'] + auth_params _validate_managed_disk_sku(namespace.storage_sku)", "contains_upper, contains_digit, contains_special_char] if x]) # pylint: disable=line-too-long if count < 3: raise", "in namespace.storage_sku else 'Standard' account = next( (a for a in storage_client.list_by_resource_group(namespace.resource_group_name) if", "offer) and (s is None or re.match(s, sku, re.I)): namespace.accelerated_networking = True def", "= [('canonical', 'UbuntuServer', '^16.04'), ('suse', 'sles', '^12-sp3'), ('redhat', 'rhel', '^7.4'), ('openlogic', 'centos', '^7.4'),", "r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err = r'admin user name cannot contain upper case character A-Z, special", "from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id nics_value = namespace.nics nics =", "is_linux else win_err) if is_linux and re.findall(r'^[$-]+', username): raise CLIError(linux_err) if not is_linux", "_get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') if not namespace.identity_scope and getattr(namespace.identity_role, 'is_default', None) is", "_validate_vmss_single_placement_group(namespace): if namespace.platform_fault_domain_count is not None and namespace.zones is None: raise CLIError('usage error:", "Dict fitting the JSON description above :param string os_type: the type of OS", "namespace.storage_profile == StorageProfile.ManagedCustomImage: # extract additional information from a managed custom image res", "ID namespace.attach_os_disk = _get_resource_id( cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if getattr(namespace, 'attach_data_disks', None):", "CLIError('usage error: --assign-identity [--scope SCOPE] [--role ROLE]') def _resolve_role_id(cli_ctx, role, scope): import re", "namespace) _validate_vm_create_availability_set(cmd, namespace) _validate_vm_vmss_create_vnet(cmd, namespace) _validate_vm_create_nsg(cmd, namespace) _validate_vm_vmss_create_public_ip(cmd, namespace) _validate_vm_create_nics(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace)", "def process_image_create_namespace(cmd, namespace): from msrestazure.tools import parse_resource_id from msrestazure.azure_exceptions import CloudError validate_tags(namespace) try:", "'certificateUrl' not in cert: errors.append(message.format('certificateUrl', idx, jdx, idx_arg)) if is_windows and 'certificateStore' not", "if not isinstance(nics_value, list): nics_value = [nics_value] for n in nics_value: nics.append({ 'id':", "'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo', 'Standard_F4', 'Standard_F4s', 'Standard_D8_v3', 'Standard_D8s_v3', 'Standard_D32-8s_v3', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D3_v2_ABC',", "!= 'windows': raise CLIError('usage error: --license-type is only applicable on Windows VM') _validate_vm_vmss_msi(cmd,", "in namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg)) namespace.nics = nic_ids if hasattr(namespace, 'primary_nic') and namespace.primary_nic:", "_get_default_address_pool(cli_ctx, resource_group, balancer_name, balancer_type): option_name = '--backend-pool-name' client = getattr(get_network_client(cli_ctx), balancer_type, None) if", "namespace.os_sku if not publisher: return publisher, offer, sku = publisher.lower(), offer.lower(), sku.lower() distros", "storage_id['name']) else: # 2 - params for new storage account specified namespace.storage_account_type =", "re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password) count = len([x for x in [contains_lower, contains_upper, contains_digit, contains_special_char]", "urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image) if urn_match: namespace.os_publisher = urn_match.group(1) namespace.os_offer = urn_match.group(2) namespace.os_sku", "# STORAGE PROFILE #4 namespace.storage_profile = StorageProfile.ManagedPirImage else: raise CLIError('Unrecognized image type: {}'.format(image_type))", "are not exposed yet for VMSS, so use 'getattr' to avoid crash namespace.disk_info", "OS (linux or windows) :return: errors if any were found :rtype: list \"\"\"", "StorageProfile.ManagedPirImage else: raise CLIError('Unrecognized image type: {}'.format(image_type)) else: # did not specify image", "logger.debug(\"using specified vnet '%s' and subnet '%s'\", namespace.vnet_name, namespace.subnet) return # 3 -", "zone_info: sku_infos = list_sku_info(cmd.cli_ctx, namespace.location) temp = next((x for x in sku_infos if", "profile == StorageProfile.SASpecializedOSDisk: return 'attach to existing unmanaged OS disk' elif profile ==", "'az vm create --accelerated-networking --size Standard_DS1_v2' and # get it from the error", "if not v} return resource_id(**kwargs) if not missing_kwargs else None def _get_nic_id(cli_ctx, val,", "idx, idx_arg)) if 'vaultCertificates' not in secret or not secret['vaultCertificates']: err = 'Secret", "StorageProfile.ManagedCustomImage: # extract additional information from a managed custom image res = parse_resource_id(namespace.image)", "= compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) image_version_infos = [x for x in image_version_infos if", "'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo', 'Standard_F4', 'Standard_F4s', 'Standard_D8_v3', 'Standard_D8s_v3', 'Standard_D32-8s_v3', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC',", "= _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, namespace.source) if not namespace.source_blob_uri and namespace.source_storage_account_id: raise CLIError(usage_error) except", "'Standard_E16s_v3', 'Standard_E32-16s_v3', 'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC', 'Standard_F8_ABC', 'Standard_F16s_v2', 'Standard_D5_v2', 'Standard_D14_v2', 'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo', 'Standard_DS5_v2', 'Standard_DS14_v2', 'Standard_DS5_v2_Promo',", "for data_disk_source in namespace.data_disk_sources: source_blob_uri, source_disk, source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, data_disk_source) if", "values = [x.name for x in balancer.backend_address_pools] if len(values) > 1: raise CLIError(\"Multiple", "It will be created.\", namespace.load_balancer) elif namespace.load_balancer == '': namespace.load_balancer_type = None logger.debug('no", "error: --disk EXIST_DISK --instance-id ID | --size-gb GB') elif bool(namespace.disk) != bool(namespace.instance_id): raise", "Creation Secrets JSON structure [{ \"sourceVault\": { \"id\": \"value\" }, \"vaultCertificates\": [{ \"certificateUrl\":", "forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedCustomImage: required = ['image'] forbidden = ['os_type', 'attach_os_disk',", "(namespace.os_type.lower() == 'windows' or namespace.admin_password) else 'ssh' if namespace.os_type.lower() == 'windows' and namespace.authentication_type", "'Standard_L32s_v2', 'Standard_L64s_v2', 'Standard_L96s_v2', 'SQLGL', 'SQLGLCore', 'Standard_D4_v3', 'Standard_D4s_v3', 'Standard_D2_v2', 'Standard_DS2_v2', 'Standard_E4_v3', 'Standard_E4s_v3', 'Standard_F2', 'Standard_F2s',", "existing load balancer '%s'\", namespace.load_balancer) else: namespace.load_balancer_type = 'new' logger.debug(\"load balancer '%s' not", "from azure.cli.core.cloud import AZURE_US_GOV_CLOUD if cmd.cli_ctx.cloud.name != AZURE_US_GOV_CLOUD.name: namespace.vm_sku = 'Standard_DS1_v2' else: namespace.vm_sku", "result = None if not for_scale_set: result = next((s for s in vnet_match.subnets", "process_image_create_namespace(cmd, namespace): from msrestazure.tools import parse_resource_id from msrestazure.azure_exceptions import CloudError validate_tags(namespace) try: #", "of '%s' failed for an error '%s'. Configuring plan settings \" \"will be", "import is_valid_resource_id vnet = namespace.vnet_name subnet = namespace.subnet rg = namespace.resource_group_name location =", "i in range(24, 16, -1): if _subnet_capacity_check(i, namespace.instance_count, not namespace.disable_overprovision): break if i", "\\/\"[]:|<>+=;,?*@#()! or start with $ or -' win_err = r'admin user name cannot", "as single placement group is turned off\") elif namespace.load_balancer_sku == LBSkuName.basic.value: if namespace.zones:", "= image_plan.name namespace.plan_product = image_plan.product namespace.plan_publisher = image_plan.publisher return 'urn' # 3 -", "namespace.vnet_type != 'new': required.append('app_gateway_subnet_address_prefix') elif namespace.app_gateway_type == 'existing': required.append('backend_pool_name') forbidden = ['nat_pool_name', 'load_balancer',", "_validate_vmss_create_public_ip(cmd, namespace): if namespace.load_balancer_type is None and namespace.app_gateway_type is None: if namespace.public_ip_address: raise", "namespace.disk_info = normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace, 'attach_data_disks', []), storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching) def _validate_vm_create_storage_account(cmd, namespace):", "validate_ssh_key(namespace): string_or_file = (namespace.ssh_key_value or os.path.join(os.path.expanduser('~'), '.ssh', 'id_rsa.pub')) content = string_or_file if os.path.exists(string_or_file):", "== 'applicationGateway': if namespace.application_gateway: client = get_network_client(cmd.cli_ctx).application_gateways try: rg = parse_resource_id(namespace.application_gateway).get( 'resource_group', namespace.resource_group_name)", "not in secret or not secret['vaultCertificates']: err = 'Secret is missing vaultCertificates array", "= list(client.list(scope, \"roleName eq '{}'\".format(role))) if not role_defs: raise CLIError(\"Role '{}' doesn't exist.\".format(role))", "attempt to match an URN pattern urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image) if urn_match: namespace.os_publisher", "== 'windows' errors = [] try: loaded_secret = [validate_file_or_dict(secret) for secret in secrets]", "1 - find a suitable existing vnet/subnet result = None if not for_scale_set:", "result = next((s for s in vnet_match.subnets if _check_subnet(s)), None) if not result:", "with backports kernel # Oracle Linux 7.4, Windows Server 2016, Windows Server 2012R2", "azure.cli.command_modules.vm._template_builder import StorageProfile import azure.cli.core.keys as keys from ._client_factory import _compute_client_factory from ._actions", "vnet_cidr.split('/') vnet_bit_mask_len = 32 - int(mask) vnet_int = _convert_to_int(vnet_ip_address, vnet_bit_mask_len) subnet_ip_address, mask =", "1 number and 1 special character') def validate_ssh_key(namespace): string_or_file = (namespace.ssh_key_value or os.path.join(os.path.expanduser('~'),", "# a uri? source_blob_uri = source elif '/disks/' in source.lower(): source_disk = source", "'%s'\", namespace.availability_set) def _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False): from msrestazure.tools import is_valid_resource_id vnet = namespace.vnet_name", "[--source-storage-account-id ID]' try: namespace.source_blob_uri, namespace.source_disk, namespace.source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, namespace.source) if not", "if namespace.source: usage_error = 'usage error: --source {SNAPSHOT | DISK} | --source VHD_BLOB_URI", "CLIError(\"Role '{}' doesn't exist.\".format(role)) elif len(role_defs) > 1: ids = [r.id for r", "storage profile: {}'.format(namespace.storage_profile)) logger.debug(\"storage profile '%s'\", namespace.storage_profile) if for_scale_set: # VMSS lacks some", "namespace.ultra_ssd_enabled = True # Now verify that the status of required and forbidden", "vnet = namespace.vnet_name subnet = namespace.subnet rg = namespace.resource_group_name location = namespace.location nics", "'^2012-R2')] import re for p, o, s in distros: if p.lower() == publisher", "'Standard_DS14_v2', 'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo', 'Standard_F16', 'Standard_F16s', 'Standard_M64-32ms', 'Standard_M128-32ms', 'Standard_D32_v3', 'Standard_D32s_v3', 'Standard_D64-32s_v3', 'Standard_E32_v3', 'Standard_E32s_v3', 'Standard_E32-8s_v3',", "cidr = namespace.vnet_address_prefix.split('/', 1)[0] i = 0 for i in range(24, 16, -1):", "raise CLIError('Unrecognized image type: {}'.format(image_type)) else: # did not specify image XOR attach-os-disk", "existing application gateway '%s'\", namespace.application_gateway) except CloudError: namespace.app_gateway_type = 'new' logger.debug(\"application gateway '%s'", "--accelerated-networking --size Standard_DS1_v2' and # get it from the error aval_sizes = ['Standard_D3_v2',", "def validate_ssh_key(namespace): string_or_file = (namespace.ssh_key_value or os.path.join(os.path.expanduser('~'), '.ssh', 'id_rsa.pub')) content = string_or_file if", "else: from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client storage_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts", "source) source_snapshot = info.id except CloudError: info = compute_client.disks.get(resource_group_name, source) source_disk = info.id", "eq '{}'\".format(role))) if not role_defs: raise CLIError(\"Role '{}' doesn't exist.\".format(role)) elif len(role_defs) >", "validate_vmss_disk(cmd, namespace): if namespace.disk: namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if bool(namespace.disk)", "'create managed OS disk from Azure Marketplace image' elif profile == StorageProfile.ManagedSpecializedOSDisk: return", "inbound nat pool was configured on '%s'\", namespace.load_balancer) else: namespace.nat_pool_name = lb.inbound_nat_pools[0].name logger.debug(\"using", "for the specific storage profile # start with the required/forbidden parameters for VM", "machines without \" \"permanent storage, back up your keys to a safe location.\",", "if not kv or is_valid_resource_id(kv): raise keyvault_usage validate_keyvault(cmd, namespace) else: if kv and", "\"support\", \"support_388945a0\", \"sys\", \"test2\", \"test3\", \"user4\", \"user5\"] if username.lower() in disallowed_user_names: raise CLIError(\"This", "\"123\", \"a\", \"actuser\", \"adm\", \"admin2\", \"aspnet\", \"backup\", \"console\", \"guest\", \"owner\", \"root\", \"server\", \"sql\",", "its own command module https://github.com/Azure/azure-cli/issues/5105 def process_msi_namespace(cmd, namespace): get_default_location_from_resource_group(cmd, namespace) validate_tags(namespace) def process_gallery_image_version_namespace(cmd,", "'Standard_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS'] if sku and sku.lower() not in [x.lower() for x in", "far if getattr(namespace, 'public_ip_sku', None): from azure.cli.core.profiles import ResourceType PublicIPAddressSkuName, IPAllocationMethod = cmd.get_models('PublicIPAddressSkuName',", "s.name.lower() == size), None) if size_info is None or size_info.number_of_cores < 8: return", "pylint: disable=line-too-long if count < 3: raise CLIError('Password must have the 3 of", "run 'az vm create --accelerated-networking --size Standard_DS1_v2' and # get it from the", "namespace.storage_profile == StorageProfile.SAPirImage: required = ['image', 'use_unmanaged_disk'] forbidden = ['os_type', 'attach_os_disk', 'data_disk_sizes_gb'] elif", "to create the VM/VMSS because availablity zone is not yet \" \"supported. Please", "not namespace.storage_sku and namespace.storage_profile in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]: # pylint: disable=line-too-long namespace.storage_sku = 'Standard_LRS'", "'loadBalancer' elif namespace.application_gateway: balancer_type = 'applicationGateway' if balancer_type == 'applicationGateway': if namespace.application_gateway: client", "most common scenario res_id = _get_resource_id(cmd.cli_ctx, namespace.source, namespace.resource_group_name, 'virtualMachines', 'Microsoft.Compute') res = parse_resource_id(res_id)", "resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer_sku is None: namespace.load_balancer_sku = LBSkuName.standard.value logger.debug(\"use Standard sku as single", "if not namespace.identity_scope and getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError(\"usage error: '--role", "azure.cli.core.commands.validators import ( get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set, validate_tags) from azure.cli.core.util import hash_string from azure.cli.command_modules.vm._vm_utils", "None or size_info.number_of_cores < 8: return # VMs need to be a supported", "VM scaleset') if not namespace.public_ip_per_vm and namespace.vm_domain_name: raise CLIError('Usage error: --vm-domain-name can only" ]
[ "# print(0 + i - 3) return answer[0 : 0 + i -", "+ len(questions[i]) end = bodyText.index(questions[i + 1], start, -1) print(\"Start : \", start", "print(bodyText) questionCount = len(questions) answerList = [] for i in range(0, questionCount): print('Q:", "\"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" # questions, answerList = getFaqOfLink(link) if __name__== \"__main__\": with open(FAQ_LINKS, 'r') as", "removeDuplicates(questionList) def getLastAnswer(question, bodyText): start = bodyText.index(question) + len(question) text = bodyText[start :", "re import httplib2 from bs4 import BeautifulSoup from scraping.faqscrapperutil import stripExtra, removeDuplicates, removeBlackListedQuestions,", "False: return blackListedQuestions = getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions) print(questions) def getFaqOfLink(link): # print(\"LINK :", "http = httplib2.Http() status, html = http.request(link) soup = BeautifulSoup(html, 'html.parser') body =", "soup = BeautifulSoup(html, 'html.parser') body = soup.body questions = cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) # print(questions) processWithCustomQuestions(questions)", "if text[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount >= 3: # print(0", "answerTag = getAnswerTag(body, bodyText, questions) # print(bodyText) questionCount = len(questions) answerList = []", "if whitespaceCount >= 3: # print(0 + i - 3) # print(text[0 :", "httplib2 from bs4 import BeautifulSoup from scraping.faqscrapperutil import stripExtra, removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList,", "html = http.request(link) soup = BeautifulSoup(html, 'html.parser') body = soup.body questions = cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)')))", "import stripExtra, removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList, saveToMongo from scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME", "def cleanQuestions(questions): questionList = [] for question in questions: questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList) def", "answer[i].isspace()) if text[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount >= 3: #", "answerList.append(answer) print('A: ', answer) return answerList def processWithCustomQuestions(questions): # isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) #", "print(0 + i - 3) return answer[0 : 0 + i - 2].lstrip()", "2]) return text[0 : 0 + i - 2] else : if whitespaceCount", "return answerList def processWithCustomQuestions(questions): # isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print(\"isCustomQuestionsEnabled : \", isCustomQuestionsEnabled)", "getAnswerTag(body, bodyText, questions) # print(bodyText) questionCount = len(questions) answerList = [] for i", "questions = cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) # print(questions) processWithCustomQuestions(questions) answerList = getAnswers(body, questions) return questions, answerList", ": \", isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER == False: return blackListedQuestions = getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions)", "- 3) return answer[0 : 0 + i - 2].lstrip() else : if", "answerList = getAnswers(body, questions) return questions, answerList # link = \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" # questions,", "len(question) text = bodyText[start : -1].lstrip() # print(text.lstrip()) whitespaceCount = 0 # print(answerLength)", ": start = bodyText.index(questions[i]) + len(questions[i]) end = bodyText.index(questions[i + 1], start, -1)", "1: #Last element answer = getLastAnswer(questions[i], bodyText) else : start = bodyText.index(questions[i]) +", "if __name__== \"__main__\": with open(FAQ_LINKS, 'r') as myfile: FAQ_LINKS = myfile.read().split('\\n') faqJsonList =", "whitespaceCount = whitespaceCount + 1 if whitespaceCount >= 3: # print(0 + i", "i - 2].lstrip() else : if whitespaceCount != 0: whitespaceCount = 0 return", "= bodyText[start : -1].lstrip() # print(text.lstrip()) whitespaceCount = 0 # print(answerLength) for i", "answer[i].isspace()) if answer[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount >= 3: #", "cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) # print(questions) processWithCustomQuestions(questions) answerList = getAnswers(body, questions) return questions, answerList # link", "whitespaceCount != 0: whitespaceCount = 0 return answer.rstrip() def getAnswers(body, questions): bodyText =", ": -1].lstrip() # print(text.lstrip()) whitespaceCount = 0 # print(answerLength) for i in range(0,", "checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print(\"isCustomQuestionsEnabled : \", isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER == False: return blackListedQuestions =", "whitespaceCount = 0 # print(answerLength) for i in range(0, len(text)): # print(answer[i], '", "whitespaceCount != 0: whitespaceCount = 0 def cleanAnswer(answer): answerLength = len(answer) whitespaceCount =", "in range(0, questionCount): print('Q: ', questions[i]) if i == questionCount - 1: #Last", ": 0 + i - 2].lstrip() else : if whitespaceCount != 0: whitespaceCount", "if whitespaceCount != 0: whitespaceCount = 0 return answer.rstrip() def getAnswers(body, questions): bodyText", "answer = cleanAnswer(answer) answerList.append(answer) print('A: ', answer) return answerList def processWithCustomQuestions(questions): # isCustomQuestionsEnabled", "'html.parser') # print(soup1) answer = soup1.getText().lstrip() answer = cleanAnswer(answer) answerList.append(answer) print('A: ', answer)", "bodyText.index(questions[i + 1], start, -1) print(\"Start : \", start , \" End :", "getAnswers(body, questions): bodyText = body.getText() # answerTag = getAnswerTag(body, bodyText, questions) # print(bodyText)", "removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList, saveToMongo from scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME def cleanQuestions(questions):", "answer.rstrip() def getAnswers(body, questions): bodyText = body.getText() # answerTag = getAnswerTag(body, bodyText, questions)", "print(\"Start : \", start , \" End : \", end) soup1 = BeautifulSoup(bodyText[start", "in range(0, len(FAQ_LINKS)): link = FAQ_LINKS[i] questions, answerList = getFaqOfLink(link) jsonList = convertToJsonList(link,", "' isSpace : ', answer[i].isspace()) if text[i].isspace(): whitespaceCount = whitespaceCount + 1 if", "end], 'html.parser') # print(soup1) answer = soup1.getText().lstrip() answer = cleanAnswer(answer) answerList.append(answer) print('A: ',", "return blackListedQuestions = getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions) print(questions) def getFaqOfLink(link): # print(\"LINK : \",", "whitespaceCount = 0 return answer.rstrip() def getAnswers(body, questions): bodyText = body.getText() # answerTag", "def getLastAnswer(question, bodyText): start = bodyText.index(question) + len(question) text = bodyText[start : -1].lstrip()", "-1].lstrip() # print(text.lstrip()) whitespaceCount = 0 # print(answerLength) for i in range(0, len(text)):", "+ i - 2].lstrip() else : if whitespaceCount != 0: whitespaceCount = 0", "questions) return questions, answerList # link = \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" # questions, answerList = getFaqOfLink(link)", "import BeautifulSoup from scraping.faqscrapperutil import stripExtra, removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList, saveToMongo from scraping.Constants", "# print(bodyText) questionCount = len(questions) answerList = [] for i in range(0, questionCount):", "print(questions) processWithCustomQuestions(questions) answerList = getAnswers(body, questions) return questions, answerList # link = \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\"", "= getAnswers(body, questions) return questions, answerList # link = \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" # questions, answerList", "return questions, answerList # link = \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" # questions, answerList = getFaqOfLink(link) if", "questions[i]) if i == questionCount - 1: #Last element answer = getLastAnswer(questions[i], bodyText)", "+ i - 2]) return text[0 : 0 + i - 2] else", "start = bodyText.index(questions[i]) + len(questions[i]) end = bodyText.index(questions[i + 1], start, -1) print(\"Start", "answer[0 : 0 + i - 2].lstrip() else : if whitespaceCount != 0:", "= [] for i in range(0, questionCount): print('Q: ', questions[i]) if i ==", "= myfile.read().split('\\n') faqJsonList = [] for i in range(0, len(FAQ_LINKS)): link = FAQ_LINKS[i]", "= checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print(\"isCustomQuestionsEnabled : \", isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER == False: return blackListedQuestions", "return answer[0 : 0 + i - 2].lstrip() else : if whitespaceCount !=", "convertToJsonList, saveToMongo from scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME def cleanQuestions(questions): questionList = []", "cleanAnswer(answer): answerLength = len(answer) whitespaceCount = 0 # print(answerLength) for i in range(0,", "# print(\"LINK : \", link) http = httplib2.Http() status, html = http.request(link) soup", "== False: return blackListedQuestions = getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions) print(questions) def getFaqOfLink(link): # print(\"LINK", "# print(answer[i], ' isSpace : ', answer[i].isspace()) if answer[i].isspace(): whitespaceCount = whitespaceCount +", ": \", start , \" End : \", end) soup1 = BeautifulSoup(bodyText[start :", "= BeautifulSoup(html, 'html.parser') body = soup.body questions = cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) # print(questions) processWithCustomQuestions(questions) answerList", "def processWithCustomQuestions(questions): # isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print(\"isCustomQuestionsEnabled : \", isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER", "\" End : \", end) soup1 = BeautifulSoup(bodyText[start : end], 'html.parser') # print(soup1)", "', answer) return answerList def processWithCustomQuestions(questions): # isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print(\"isCustomQuestionsEnabled :", "def cleanAnswer(answer): answerLength = len(answer) whitespaceCount = 0 # print(answerLength) for i in", "answerLength): # print(answer[i], ' isSpace : ', answer[i].isspace()) if answer[i].isspace(): whitespaceCount = whitespaceCount", "bs4 import BeautifulSoup from scraping.faqscrapperutil import stripExtra, removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList, saveToMongo from", "questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList) def getLastAnswer(question, bodyText): start = bodyText.index(question) + len(question) text =", "0 def cleanAnswer(answer): answerLength = len(answer) whitespaceCount = 0 # print(answerLength) for i", "answer) return answerList def processWithCustomQuestions(questions): # isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print(\"isCustomQuestionsEnabled : \",", "= BeautifulSoup(bodyText[start : end], 'html.parser') # print(soup1) answer = soup1.getText().lstrip() answer = cleanAnswer(answer)", "link = \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" # questions, answerList = getFaqOfLink(link) if __name__== \"__main__\": with open(FAQ_LINKS,", "# print(text.lstrip()) whitespaceCount = 0 # print(answerLength) for i in range(0, len(text)): #", "for i in range(0, len(FAQ_LINKS)): link = FAQ_LINKS[i] questions, answerList = getFaqOfLink(link) jsonList", "= body.getText() # answerTag = getAnswerTag(body, bodyText, questions) # print(bodyText) questionCount = len(questions)", "myfile.read().split('\\n') faqJsonList = [] for i in range(0, len(FAQ_LINKS)): link = FAQ_LINKS[i] questions,", "scraping.faqscrapperutil import stripExtra, removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList, saveToMongo from scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS,", "i in range(0, len(FAQ_LINKS)): link = FAQ_LINKS[i] questions, answerList = getFaqOfLink(link) jsonList =", "questions): bodyText = body.getText() # answerTag = getAnswerTag(body, bodyText, questions) # print(bodyText) questionCount", "__name__== \"__main__\": with open(FAQ_LINKS, 'r') as myfile: FAQ_LINKS = myfile.read().split('\\n') faqJsonList = []", "start, -1) print(\"Start : \", start , \" End : \", end) soup1", "i - 2]) return text[0 : 0 + i - 2] else :", "= 0 # print(answerLength) for i in range(0, len(text)): # print(answer[i], ' isSpace", "soup1 = BeautifulSoup(bodyText[start : end], 'html.parser') # print(soup1) answer = soup1.getText().lstrip() answer =", "= [] for i in range(0, len(FAQ_LINKS)): link = FAQ_LINKS[i] questions, answerList =", "# print(soup1) answer = soup1.getText().lstrip() answer = cleanAnswer(answer) answerList.append(answer) print('A: ', answer) return", "with open(FAQ_LINKS, 'r') as myfile: FAQ_LINKS = myfile.read().split('\\n') faqJsonList = [] for i", "bodyText): start = bodyText.index(question) + len(question) text = bodyText[start : -1].lstrip() # print(text.lstrip())", "0 # print(answerLength) for i in range(0, answerLength): # print(answer[i], ' isSpace :", "return answer.rstrip() def getAnswers(body, questions): bodyText = body.getText() # answerTag = getAnswerTag(body, bodyText,", "= httplib2.Http() status, html = http.request(link) soup = BeautifulSoup(html, 'html.parser') body = soup.body", "else : start = bodyText.index(questions[i]) + len(questions[i]) end = bodyText.index(questions[i + 1], start,", "in questions: questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList) def getLastAnswer(question, bodyText): start = bodyText.index(question) + len(question)", ": if whitespaceCount != 0: whitespaceCount = 0 return answer.rstrip() def getAnswers(body, questions):", "answerList = getFaqOfLink(link) if __name__== \"__main__\": with open(FAQ_LINKS, 'r') as myfile: FAQ_LINKS =", "= cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) # print(questions) processWithCustomQuestions(questions) answerList = getAnswers(body, questions) return questions, answerList #", "cleanQuestions(questions): questionList = [] for question in questions: questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList) def getLastAnswer(question,", "- 2] else : if whitespaceCount != 0: whitespaceCount = 0 def cleanAnswer(answer):", "[] for i in range(0, len(FAQ_LINKS)): link = FAQ_LINKS[i] questions, answerList = getFaqOfLink(link)", "# link = \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" # questions, answerList = getFaqOfLink(link) if __name__== \"__main__\": with", "-1) print(\"Start : \", start , \" End : \", end) soup1 =", "getLastAnswer(questions[i], bodyText) else : start = bodyText.index(questions[i]) + len(questions[i]) end = bodyText.index(questions[i +", "= 0 return answer.rstrip() def getAnswers(body, questions): bodyText = body.getText() # answerTag =", "bodyText.index(questions[i]) + len(questions[i]) end = bodyText.index(questions[i + 1], start, -1) print(\"Start : \",", "[] for question in questions: questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList) def getLastAnswer(question, bodyText): start =", "- 1: #Last element answer = getLastAnswer(questions[i], bodyText) else : start = bodyText.index(questions[i])", "def getAnswers(body, questions): bodyText = body.getText() # answerTag = getAnswerTag(body, bodyText, questions) #", "httplib2.Http() status, html = http.request(link) soup = BeautifulSoup(html, 'html.parser') body = soup.body questions", "for question in questions: questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList) def getLastAnswer(question, bodyText): start = bodyText.index(question)", "1 if whitespaceCount >= 3: # print(0 + i - 3) return answer[0", "# questions, answerList = getFaqOfLink(link) if __name__== \"__main__\": with open(FAQ_LINKS, 'r') as myfile:", "in range(0, answerLength): # print(answer[i], ' isSpace : ', answer[i].isspace()) if answer[i].isspace(): whitespaceCount", "<reponame>ednihs-yahska/unibrowser import re import httplib2 from bs4 import BeautifulSoup from scraping.faqscrapperutil import stripExtra,", "from bs4 import BeautifulSoup from scraping.faqscrapperutil import stripExtra, removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList, saveToMongo", "def getFaqOfLink(link): # print(\"LINK : \", link) http = httplib2.Http() status, html =", "0 + i - 2] else : if whitespaceCount != 0: whitespaceCount =", "status, html = http.request(link) soup = BeautifulSoup(html, 'html.parser') body = soup.body questions =", "getAnswers(body, questions) return questions, answerList # link = \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" # questions, answerList =", "i in range(0, len(text)): # print(answer[i], ' isSpace : ', answer[i].isspace()) if text[i].isspace():", "= bodyText.index(questions[i + 1], start, -1) print(\"Start : \", start , \" End", "scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME def cleanQuestions(questions): questionList = [] for question in", "questions, answerList # link = \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" # questions, answerList = getFaqOfLink(link) if __name__==", "return text[0 : 0 + i - 2] else : if whitespaceCount !=", "print(soup1) answer = soup1.getText().lstrip() answer = cleanAnswer(answer) answerList.append(answer) print('A: ', answer) return answerList", "blackListedQuestions = getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions) print(questions) def getFaqOfLink(link): # print(\"LINK : \", link)", "start = bodyText.index(question) + len(question) text = bodyText[start : -1].lstrip() # print(text.lstrip()) whitespaceCount", "+ i - 3) # print(text[0 : 0 + i - 2]) return", "saveToMongo from scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME def cleanQuestions(questions): questionList = [] for", "answer = soup1.getText().lstrip() answer = cleanAnswer(answer) answerList.append(answer) print('A: ', answer) return answerList def", "ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME def cleanQuestions(questions): questionList = [] for question in questions: questionList.append(stripExtra(question.lstrip().rstrip()))", "print('Q: ', questions[i]) if i == questionCount - 1: #Last element answer =", "cleanAnswer(answer) answerList.append(answer) print('A: ', answer) return answerList def processWithCustomQuestions(questions): # isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER)", "print(0 + i - 3) # print(text[0 : 0 + i - 2])", "answerLength = len(answer) whitespaceCount = 0 # print(answerLength) for i in range(0, answerLength):", "end = bodyText.index(questions[i + 1], start, -1) print(\"Start : \", start , \"", "FAQ_LINKS[i] questions, answerList = getFaqOfLink(link) jsonList = convertToJsonList(link, questions, answerList) faqJsonList.extend(jsonList) # saveJsonToFile(faqJsonList,", "for i in range(0, len(text)): # print(answer[i], ' isSpace : ', answer[i].isspace()) if", "- 2]) return text[0 : 0 + i - 2] else : if", "- 2].lstrip() else : if whitespaceCount != 0: whitespaceCount = 0 return answer.rstrip()", "+ 1], start, -1) print(\"Start : \", start , \" End : \",", "return removeDuplicates(questionList) def getLastAnswer(question, bodyText): start = bodyText.index(question) + len(question) text = bodyText[start", "BeautifulSoup(html, 'html.parser') body = soup.body questions = cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) # print(questions) processWithCustomQuestions(questions) answerList =", "= bodyText.index(questions[i]) + len(questions[i]) end = bodyText.index(questions[i + 1], start, -1) print(\"Start :", "getFaqOfLink(link): # print(\"LINK : \", link) http = httplib2.Http() status, html = http.request(link)", "from scraping.faqscrapperutil import stripExtra, removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList, saveToMongo from scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER,", ">= 3: # print(0 + i - 3) return answer[0 : 0 +", "\", end) soup1 = BeautifulSoup(bodyText[start : end], 'html.parser') # print(soup1) answer = soup1.getText().lstrip()", "!= 0: whitespaceCount = 0 def cleanAnswer(answer): answerLength = len(answer) whitespaceCount = 0", "print(text.lstrip()) whitespaceCount = 0 # print(answerLength) for i in range(0, len(text)): # print(answer[i],", "answer = getLastAnswer(questions[i], bodyText) else : start = bodyText.index(questions[i]) + len(questions[i]) end =", "range(0, answerLength): # print(answer[i], ' isSpace : ', answer[i].isspace()) if answer[i].isspace(): whitespaceCount =", "isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print(\"isCustomQuestionsEnabled : \", isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER == False: return", "FAQ_LINKS, COLLECTION_NAME def cleanQuestions(questions): questionList = [] for question in questions: questionList.append(stripExtra(question.lstrip().rstrip())) return", "\"__main__\": with open(FAQ_LINKS, 'r') as myfile: FAQ_LINKS = myfile.read().split('\\n') faqJsonList = [] for", "print(text[0 : 0 + i - 2]) return text[0 : 0 + i", "link) http = httplib2.Http() status, html = http.request(link) soup = BeautifulSoup(html, 'html.parser') body", "as myfile: FAQ_LINKS = myfile.read().split('\\n') faqJsonList = [] for i in range(0, len(FAQ_LINKS)):", "questions: questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList) def getLastAnswer(question, bodyText): start = bodyText.index(question) + len(question) text", ": if whitespaceCount != 0: whitespaceCount = 0 def cleanAnswer(answer): answerLength = len(answer)", "[] for i in range(0, questionCount): print('Q: ', questions[i]) if i == questionCount", "answerList def processWithCustomQuestions(questions): # isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print(\"isCustomQuestionsEnabled : \", isCustomQuestionsEnabled) if", "text[0 : 0 + i - 2] else : if whitespaceCount != 0:", "', questions[i]) if i == questionCount - 1: #Last element answer = getLastAnswer(questions[i],", "removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList, saveToMongo from scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME def cleanQuestions(questions): questionList", "whitespaceCount + 1 if whitespaceCount >= 3: # print(0 + i - 3)", "getFaqOfLink(link) if __name__== \"__main__\": with open(FAQ_LINKS, 'r') as myfile: FAQ_LINKS = myfile.read().split('\\n') faqJsonList", "0 + i - 2]) return text[0 : 0 + i - 2]", "= 0 # print(answerLength) for i in range(0, answerLength): # print(answer[i], ' isSpace", "if answer[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount >= 3: # print(0", "print(answerLength) for i in range(0, len(text)): # print(answer[i], ' isSpace : ', answer[i].isspace())", "+ 1 if whitespaceCount >= 3: # print(0 + i - 3) return", "text[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount >= 3: # print(0 +", "len(questions[i]) end = bodyText.index(questions[i + 1], start, -1) print(\"Start : \", start ,", "getBlackListedQuestions, convertToJsonList, saveToMongo from scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME def cleanQuestions(questions): questionList =", ": ', answer[i].isspace()) if text[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount >=", "question in questions: questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList) def getLastAnswer(question, bodyText): start = bodyText.index(question) +", "open(FAQ_LINKS, 'r') as myfile: FAQ_LINKS = myfile.read().split('\\n') faqJsonList = [] for i in", "whitespaceCount = 0 # print(answerLength) for i in range(0, answerLength): # print(answer[i], '", "1], start, -1) print(\"Start : \", start , \" End : \", end)", "'html.parser') body = soup.body questions = cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) # print(questions) processWithCustomQuestions(questions) answerList = getAnswers(body,", "3) # print(text[0 : 0 + i - 2]) return text[0 : 0", "stripExtra, removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList, saveToMongo from scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME def", "= bodyText.index(question) + len(question) text = bodyText[start : -1].lstrip() # print(text.lstrip()) whitespaceCount =", "isSpace : ', answer[i].isspace()) if text[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount", "bodyText = body.getText() # answerTag = getAnswerTag(body, bodyText, questions) # print(bodyText) questionCount =", "getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions) print(questions) def getFaqOfLink(link): # print(\"LINK : \", link) http =", "in range(0, len(text)): # print(answer[i], ' isSpace : ', answer[i].isspace()) if text[i].isspace(): whitespaceCount", "# print(questions) processWithCustomQuestions(questions) answerList = getAnswers(body, questions) return questions, answerList # link =", "import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME def cleanQuestions(questions): questionList = [] for question in questions:", "questionCount - 1: #Last element answer = getLastAnswer(questions[i], bodyText) else : start =", "text = bodyText[start : -1].lstrip() # print(text.lstrip()) whitespaceCount = 0 # print(answerLength) for", "len(answer) whitespaceCount = 0 # print(answerLength) for i in range(0, answerLength): # print(answer[i],", ": end], 'html.parser') # print(soup1) answer = soup1.getText().lstrip() answer = cleanAnswer(answer) answerList.append(answer) print('A:", "soup.body questions = cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) # print(questions) processWithCustomQuestions(questions) answerList = getAnswers(body, questions) return questions,", "2].lstrip() else : if whitespaceCount != 0: whitespaceCount = 0 return answer.rstrip() def", "+ i - 3) return answer[0 : 0 + i - 2].lstrip() else", "2] else : if whitespaceCount != 0: whitespaceCount = 0 def cleanAnswer(answer): answerLength", "questionCount = len(questions) answerList = [] for i in range(0, questionCount): print('Q: ',", "whitespaceCount >= 3: # print(0 + i - 3) # print(text[0 : 0", "= 0 def cleanAnswer(answer): answerLength = len(answer) whitespaceCount = 0 # print(answerLength) for", "!= 0: whitespaceCount = 0 return answer.rstrip() def getAnswers(body, questions): bodyText = body.getText()", "\", start , \" End : \", end) soup1 = BeautifulSoup(bodyText[start : end],", "element answer = getLastAnswer(questions[i], bodyText) else : start = bodyText.index(questions[i]) + len(questions[i]) end", "= \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" # questions, answerList = getFaqOfLink(link) if __name__== \"__main__\": with open(FAQ_LINKS, 'r')", "print(answer[i], ' isSpace : ', answer[i].isspace()) if text[i].isspace(): whitespaceCount = whitespaceCount + 1", "= soup1.getText().lstrip() answer = cleanAnswer(answer) answerList.append(answer) print('A: ', answer) return answerList def processWithCustomQuestions(questions):", "questions, answerList = getFaqOfLink(link) jsonList = convertToJsonList(link, questions, answerList) faqJsonList.extend(jsonList) # saveJsonToFile(faqJsonList, \"output.txt\")", "if ENABLE_CUSTOM_QUESTIONS_FILTER == False: return blackListedQuestions = getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions) print(questions) def getFaqOfLink(link):", "= len(questions) answerList = [] for i in range(0, questionCount): print('Q: ', questions[i])", "0: whitespaceCount = 0 return answer.rstrip() def getAnswers(body, questions): bodyText = body.getText() #", "0: whitespaceCount = 0 def cleanAnswer(answer): answerLength = len(answer) whitespaceCount = 0 #", "len(questions) answerList = [] for i in range(0, questionCount): print('Q: ', questions[i]) if", "+ len(question) text = bodyText[start : -1].lstrip() # print(text.lstrip()) whitespaceCount = 0 #", "i in range(0, questionCount): print('Q: ', questions[i]) if i == questionCount - 1:", "BeautifulSoup(bodyText[start : end], 'html.parser') # print(soup1) answer = soup1.getText().lstrip() answer = cleanAnswer(answer) answerList.append(answer)", "myfile: FAQ_LINKS = myfile.read().split('\\n') faqJsonList = [] for i in range(0, len(FAQ_LINKS)): link", "= whitespaceCount + 1 if whitespaceCount >= 3: # print(0 + i -", "i - 2] else : if whitespaceCount != 0: whitespaceCount = 0 def", "i in range(0, answerLength): # print(answer[i], ' isSpace : ', answer[i].isspace()) if answer[i].isspace():", "removeBlackListedQuestions(questions, blackListedQuestions) print(questions) def getFaqOfLink(link): # print(\"LINK : \", link) http = httplib2.Http()", "range(0, len(FAQ_LINKS)): link = FAQ_LINKS[i] questions, answerList = getFaqOfLink(link) jsonList = convertToJsonList(link, questions,", "\", isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER == False: return blackListedQuestions = getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions) print(questions)", "'r') as myfile: FAQ_LINKS = myfile.read().split('\\n') faqJsonList = [] for i in range(0,", "print('A: ', answer) return answerList def processWithCustomQuestions(questions): # isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print(\"isCustomQuestionsEnabled", "# isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print(\"isCustomQuestionsEnabled : \", isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER == False:", "len(FAQ_LINKS)): link = FAQ_LINKS[i] questions, answerList = getFaqOfLink(link) jsonList = convertToJsonList(link, questions, answerList)", "= getLastAnswer(questions[i], bodyText) else : start = bodyText.index(questions[i]) + len(questions[i]) end = bodyText.index(questions[i", "= getAnswerTag(body, bodyText, questions) # print(bodyText) questionCount = len(questions) answerList = [] for", "\", link) http = httplib2.Http() status, html = http.request(link) soup = BeautifulSoup(html, 'html.parser')", "range(0, len(text)): # print(answer[i], ' isSpace : ', answer[i].isspace()) if text[i].isspace(): whitespaceCount =", "questions) # print(bodyText) questionCount = len(questions) answerList = [] for i in range(0,", "bodyText.index(question) + len(question) text = bodyText[start : -1].lstrip() # print(text.lstrip()) whitespaceCount = 0", "+ 1 if whitespaceCount >= 3: # print(0 + i - 3) #", "whitespaceCount >= 3: # print(0 + i - 3) return answer[0 : 0", "BeautifulSoup from scraping.faqscrapperutil import stripExtra, removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList, saveToMongo from scraping.Constants import", ": 0 + i - 2] else : if whitespaceCount != 0: whitespaceCount", "blackListedQuestions) print(questions) def getFaqOfLink(link): # print(\"LINK : \", link) http = httplib2.Http() status,", "= soup.body questions = cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) # print(questions) processWithCustomQuestions(questions) answerList = getAnswers(body, questions) return", "= [] for question in questions: questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList) def getLastAnswer(question, bodyText): start", "i - 3) # print(text[0 : 0 + i - 2]) return text[0", "questionList = [] for question in questions: questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList) def getLastAnswer(question, bodyText):", "range(0, questionCount): print('Q: ', questions[i]) if i == questionCount - 1: #Last element", "0 return answer.rstrip() def getAnswers(body, questions): bodyText = body.getText() # answerTag = getAnswerTag(body,", "print(answer[i], ' isSpace : ', answer[i].isspace()) if answer[i].isspace(): whitespaceCount = whitespaceCount + 1", ": 0 + i - 2]) return text[0 : 0 + i -", "bodyText, questions) # print(bodyText) questionCount = len(questions) answerList = [] for i in", "faqJsonList = [] for i in range(0, len(FAQ_LINKS)): link = FAQ_LINKS[i] questions, answerList", "ENABLE_CUSTOM_QUESTIONS_FILTER == False: return blackListedQuestions = getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions) print(questions) def getFaqOfLink(link): #", "= FAQ_LINKS[i] questions, answerList = getFaqOfLink(link) jsonList = convertToJsonList(link, questions, answerList) faqJsonList.extend(jsonList) #", "body = soup.body questions = cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) # print(questions) processWithCustomQuestions(questions) answerList = getAnswers(body, questions)", "', answer[i].isspace()) if text[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount >= 3:", "#Last element answer = getLastAnswer(questions[i], bodyText) else : start = bodyText.index(questions[i]) + len(questions[i])", "whitespaceCount = 0 def cleanAnswer(answer): answerLength = len(answer) whitespaceCount = 0 # print(answerLength)", "= cleanAnswer(answer) answerList.append(answer) print('A: ', answer) return answerList def processWithCustomQuestions(questions): # isCustomQuestionsEnabled =", ": \", end) soup1 = BeautifulSoup(bodyText[start : end], 'html.parser') # print(soup1) answer =", "answerList = getFaqOfLink(link) jsonList = convertToJsonList(link, questions, answerList) faqJsonList.extend(jsonList) # saveJsonToFile(faqJsonList, \"output.txt\") saveToMongo(faqJsonList,", "answerList = [] for i in range(0, questionCount): print('Q: ', questions[i]) if i", ", \" End : \", end) soup1 = BeautifulSoup(bodyText[start : end], 'html.parser') #", "' isSpace : ', answer[i].isspace()) if answer[i].isspace(): whitespaceCount = whitespaceCount + 1 if", "print(questions) def getFaqOfLink(link): # print(\"LINK : \", link) http = httplib2.Http() status, html", "print(\"isCustomQuestionsEnabled : \", isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER == False: return blackListedQuestions = getBlackListedQuestions() removeBlackListedQuestions(questions,", "for i in range(0, questionCount): print('Q: ', questions[i]) if i == questionCount -", "# print(answerLength) for i in range(0, answerLength): # print(answer[i], ' isSpace : ',", "- 3) # print(text[0 : 0 + i - 2]) return text[0 :", "# print(answerLength) for i in range(0, len(text)): # print(answer[i], ' isSpace : ',", "bodyText[start : -1].lstrip() # print(text.lstrip()) whitespaceCount = 0 # print(answerLength) for i in", "else : if whitespaceCount != 0: whitespaceCount = 0 return answer.rstrip() def getAnswers(body,", "import httplib2 from bs4 import BeautifulSoup from scraping.faqscrapperutil import stripExtra, removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions,", "print(answerLength) for i in range(0, answerLength): # print(answer[i], ' isSpace : ', answer[i].isspace())", "body.getText() # answerTag = getAnswerTag(body, bodyText, questions) # print(bodyText) questionCount = len(questions) answerList", "http.request(link) soup = BeautifulSoup(html, 'html.parser') body = soup.body questions = cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) # print(questions)", "COLLECTION_NAME def cleanQuestions(questions): questionList = [] for question in questions: questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList)", "0 # print(answerLength) for i in range(0, len(text)): # print(answer[i], ' isSpace :", "= getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions) print(questions) def getFaqOfLink(link): # print(\"LINK : \", link) http", "answerList # link = \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" # questions, answerList = getFaqOfLink(link) if __name__== \"__main__\":", "i == questionCount - 1: #Last element answer = getLastAnswer(questions[i], bodyText) else :", "0 + i - 2].lstrip() else : if whitespaceCount != 0: whitespaceCount =", "from scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME def cleanQuestions(questions): questionList = [] for question", "1 if whitespaceCount >= 3: # print(0 + i - 3) # print(text[0", "3) return answer[0 : 0 + i - 2].lstrip() else : if whitespaceCount", "# print(0 + i - 3) # print(text[0 : 0 + i -", "# answerTag = getAnswerTag(body, bodyText, questions) # print(bodyText) questionCount = len(questions) answerList =", "if whitespaceCount != 0: whitespaceCount = 0 def cleanAnswer(answer): answerLength = len(answer) whitespaceCount", "getLastAnswer(question, bodyText): start = bodyText.index(question) + len(question) text = bodyText[start : -1].lstrip() #", "len(text)): # print(answer[i], ' isSpace : ', answer[i].isspace()) if text[i].isspace(): whitespaceCount = whitespaceCount", "questions, answerList = getFaqOfLink(link) if __name__== \"__main__\": with open(FAQ_LINKS, 'r') as myfile: FAQ_LINKS", "if i == questionCount - 1: #Last element answer = getLastAnswer(questions[i], bodyText) else", "', answer[i].isspace()) if answer[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount >= 3:", "bodyText) else : start = bodyText.index(questions[i]) + len(questions[i]) end = bodyText.index(questions[i + 1],", ">= 3: # print(0 + i - 3) # print(text[0 : 0 +", "link = FAQ_LINKS[i] questions, answerList = getFaqOfLink(link) jsonList = convertToJsonList(link, questions, answerList) faqJsonList.extend(jsonList)", "3: # print(0 + i - 3) return answer[0 : 0 + i", "End : \", end) soup1 = BeautifulSoup(bodyText[start : end], 'html.parser') # print(soup1) answer", ": \", link) http = httplib2.Http() status, html = http.request(link) soup = BeautifulSoup(html,", "# print(text[0 : 0 + i - 2]) return text[0 : 0 +", "isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER == False: return blackListedQuestions = getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions) print(questions) def", "= http.request(link) soup = BeautifulSoup(html, 'html.parser') body = soup.body questions = cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) #", "soup1.getText().lstrip() answer = cleanAnswer(answer) answerList.append(answer) print('A: ', answer) return answerList def processWithCustomQuestions(questions): #", "3: # print(0 + i - 3) # print(text[0 : 0 + i", "import re import httplib2 from bs4 import BeautifulSoup from scraping.faqscrapperutil import stripExtra, removeDuplicates,", "else : if whitespaceCount != 0: whitespaceCount = 0 def cleanAnswer(answer): answerLength =", "for i in range(0, answerLength): # print(answer[i], ' isSpace : ', answer[i].isspace()) if", "print(\"LINK : \", link) http = httplib2.Http() status, html = http.request(link) soup =", "start , \" End : \", end) soup1 = BeautifulSoup(bodyText[start : end], 'html.parser')", "questionCount): print('Q: ', questions[i]) if i == questionCount - 1: #Last element answer", "if whitespaceCount >= 3: # print(0 + i - 3) return answer[0 :", "isSpace : ', answer[i].isspace()) if answer[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount", ": ', answer[i].isspace()) if answer[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount >=", "FAQ_LINKS = myfile.read().split('\\n') faqJsonList = [] for i in range(0, len(FAQ_LINKS)): link =", "= getFaqOfLink(link) if __name__== \"__main__\": with open(FAQ_LINKS, 'r') as myfile: FAQ_LINKS = myfile.read().split('\\n')", "== questionCount - 1: #Last element answer = getLastAnswer(questions[i], bodyText) else : start", "# print(answer[i], ' isSpace : ', answer[i].isspace()) if text[i].isspace(): whitespaceCount = whitespaceCount +", "= getFaqOfLink(link) jsonList = convertToJsonList(link, questions, answerList) faqJsonList.extend(jsonList) # saveJsonToFile(faqJsonList, \"output.txt\") saveToMongo(faqJsonList, COLLECTION_NAME)", "i - 3) return answer[0 : 0 + i - 2].lstrip() else :", "processWithCustomQuestions(questions): # isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print(\"isCustomQuestionsEnabled : \", isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER ==", "= len(answer) whitespaceCount = 0 # print(answerLength) for i in range(0, answerLength): #", "end) soup1 = BeautifulSoup(bodyText[start : end], 'html.parser') # print(soup1) answer = soup1.getText().lstrip() answer", "answer[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount >= 3: # print(0 +", "# print(\"isCustomQuestionsEnabled : \", isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER == False: return blackListedQuestions = getBlackListedQuestions()", "processWithCustomQuestions(questions) answerList = getAnswers(body, questions) return questions, answerList # link = \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" #", "+ i - 2] else : if whitespaceCount != 0: whitespaceCount = 0" ]
[ "\"bright_cyan\", \"bright_white\", ), range(90, 98)))) BG_COLORS = dict((f\"on_{key}\", val + 10) for key,", "invisibles (for readline); else False. Returns: A string with the original text wrapped", "def readline_disabled(): \"\"\"Context manager to temporarily disable readline features. \"\"\" readline.set_auto_history(False) try: yield", "\"blue\", \"magenta\", \"cyan\", \"white\", ), range(30, 38)), zip((\"bright_black\", \"bright_red\", \"bright_green\", \"bright_yellow\", \"bright_blue\", \"bright_magenta\",", "the prompt; else False. \"\"\" replies = { \"yes\": True, \"no\": False, }", "replies = { \"yes\": True, \"no\": False, } prompt = \"%s (yes/no): \"", "\"strikethrough\", ), range(1, 10))) def colored(text, color=None, on_color=None, attrs=None, escape=False): \"\"\"Wraps text with", "\"bright_blue\", \"bright_magenta\", \"bright_cyan\", \"bright_white\", ), range(90, 98)))) BG_COLORS = dict((f\"on_{key}\", val + 10)", "A string with the original text wrapped by escape codes. \"\"\" def sgr(*codes):", "\"bright_magenta\", \"bright_cyan\", \"bright_white\", ), range(90, 98)))) BG_COLORS = dict((f\"on_{key}\", val + 10) for", "finally: readline.set_auto_history(True) def confirm(text): \"\"\"Presents a yes/no prompt to the user and handles", "for key, val in FG_COLORS.items()) ATTRIBUTES = dict( zip((\"bold\", \"faint\", \"italic\", \"underline\", \"slow_blink\",", "FG_COLORS = dict(itertools.chain( zip((\"black\", \"red\", \"green\", \"yellow\", \"blue\", \"magenta\", \"cyan\", \"white\", ), range(30,", "color: codes.append(FG_COLORS[color]) if on_color: codes.append(BG_COLORS[on_color]) if attrs: codes.extend(ATTRIBUTES[attr] for attr in attrs) if", "message string to present before confirmation. Returns: True if the user confirmed the", "desired look. Args: color: The foreground color. on_color: The background color. attrs: A", "reply not in replies: try: reply = input(prompt).casefold() except (EOFError, KeyboardInterrupt): reply =", "on_color: The background color. attrs: A list of effects. escape: True to escape", "\"bright_white\", ), range(90, 98)))) BG_COLORS = dict((f\"on_{key}\", val + 10) for key, val", "confirmation. Returns: True if the user confirmed the prompt; else False. \"\"\" replies", "while reply not in replies: try: reply = input(prompt).casefold() except (EOFError, KeyboardInterrupt): reply", "\"%s%s%s\" % (esc(sgr(*codes)), text, esc(sgr(0))) @contextmanager def readline_disabled(): \"\"\"Context manager to temporarily disable", "True if the user confirmed the prompt; else False. \"\"\" replies = {", "attrs: codes.extend(ATTRIBUTES[attr] for attr in attrs) if not escape: esc = lambda n:", "escape invisibles (for readline); else False. Returns: A string with the original text", "look. Args: color: The foreground color. on_color: The background color. attrs: A list", "list of effects. escape: True to escape invisibles (for readline); else False. Returns:", "10))) def colored(text, color=None, on_color=None, attrs=None, escape=False): \"\"\"Wraps text with ANSI escape codes", "colored text and helps write Messages output. \"\"\" from contextlib import contextmanager import", "color: The foreground color. on_color: The background color. attrs: A list of effects.", "attrs) if not escape: esc = lambda n: n return \"%s%s%s\" % (esc(sgr(*codes)),", "A message string to present before confirmation. Returns: True if the user confirmed", "present before confirmation. Returns: True if the user confirmed the prompt; else False.", "message archives. Creates colored text and helps write Messages output. \"\"\" from contextlib", "if the user confirmed the prompt; else False. \"\"\" replies = { \"yes\":", "archives. Creates colored text and helps write Messages output. \"\"\" from contextlib import", "zip((\"black\", \"red\", \"green\", \"yellow\", \"blue\", \"magenta\", \"cyan\", \"white\", ), range(30, 38)), zip((\"bright_black\", \"bright_red\",", "= { \"yes\": True, \"no\": False, } prompt = \"%s (yes/no): \" %", "color. attrs: A list of effects. escape: True to escape invisibles (for readline);", "achieve the desired look. Args: color: The foreground color. on_color: The background color.", "not in replies: try: reply = input(prompt).casefold() except (EOFError, KeyboardInterrupt): reply = \"no\"", "specific to message archives. Creates colored text and helps write Messages output. \"\"\"", "attr in attrs) if not escape: esc = lambda n: n return \"%s%s%s\"", "\"red\", attrs=[\"bold\"], escape=True) reply = \"\" with readline_disabled(): print(text) while reply not in", "\"underline\", \"slow_blink\", \"rapid_blink\", \"reverse\", \"conceal\", \"strikethrough\", ), range(1, 10))) def colored(text, color=None, on_color=None,", "def sgr(*codes): return \"\\x1b[%sm\" % \";\".join(map(str, codes)) def esc(text): return \"\\x01%s\\x02\" % text", "codes.append(FG_COLORS[color]) if on_color: codes.append(BG_COLORS[on_color]) if attrs: codes.extend(ATTRIBUTES[attr] for attr in attrs) if not", "False, } prompt = \"%s (yes/no): \" % colored(\"Are you sure?\", \"red\", attrs=[\"bold\"],", "Args: color: The foreground color. on_color: The background color. attrs: A list of", "the original text wrapped by escape codes. \"\"\" def sgr(*codes): return \"\\x1b[%sm\" %", "@contextmanager def readline_disabled(): \"\"\"Context manager to temporarily disable readline features. \"\"\" readline.set_auto_history(False) try:", "disable readline features. \"\"\" readline.set_auto_history(False) try: yield finally: readline.set_auto_history(True) def confirm(text): \"\"\"Presents a", "A list of effects. escape: True to escape invisibles (for readline); else False.", "import readline FG_COLORS = dict(itertools.chain( zip((\"black\", \"red\", \"green\", \"yellow\", \"blue\", \"magenta\", \"cyan\", \"white\",", "in attrs) if not escape: esc = lambda n: n return \"%s%s%s\" %", "confirm(text): \"\"\"Presents a yes/no prompt to the user and handles replies. Args: text:", "color. on_color: The background color. attrs: A list of effects. escape: True to", "and helps write Messages output. \"\"\" from contextlib import contextmanager import itertools import", "), range(1, 10))) def colored(text, color=None, on_color=None, attrs=None, escape=False): \"\"\"Wraps text with ANSI", "for attr in attrs) if not escape: esc = lambda n: n return", "False. Returns: A string with the original text wrapped by escape codes. \"\"\"", "dict((f\"on_{key}\", val + 10) for key, val in FG_COLORS.items()) ATTRIBUTES = dict( zip((\"bold\",", "itertools import readline FG_COLORS = dict(itertools.chain( zip((\"black\", \"red\", \"green\", \"yellow\", \"blue\", \"magenta\", \"cyan\",", "The background color. attrs: A list of effects. escape: True to escape invisibles", "string with the original text wrapped by escape codes. \"\"\" def sgr(*codes): return", "n return \"%s%s%s\" % (esc(sgr(*codes)), text, esc(sgr(0))) @contextmanager def readline_disabled(): \"\"\"Context manager to", "\"cyan\", \"white\", ), range(30, 38)), zip((\"bright_black\", \"bright_red\", \"bright_green\", \"bright_yellow\", \"bright_blue\", \"bright_magenta\", \"bright_cyan\", \"bright_white\",", "text codes = [] if color: codes.append(FG_COLORS[color]) if on_color: codes.append(BG_COLORS[on_color]) if attrs: codes.extend(ATTRIBUTES[attr]", "Returns: A string with the original text wrapped by escape codes. \"\"\" def", "True to escape invisibles (for readline); else False. Returns: A string with the", "\"conceal\", \"strikethrough\", ), range(1, 10))) def colored(text, color=None, on_color=None, attrs=None, escape=False): \"\"\"Wraps text", "esc(sgr(0))) @contextmanager def readline_disabled(): \"\"\"Context manager to temporarily disable readline features. \"\"\" readline.set_auto_history(False)", "\"faint\", \"italic\", \"underline\", \"slow_blink\", \"rapid_blink\", \"reverse\", \"conceal\", \"strikethrough\", ), range(1, 10))) def colored(text,", "key, val in FG_COLORS.items()) ATTRIBUTES = dict( zip((\"bold\", \"faint\", \"italic\", \"underline\", \"slow_blink\", \"rapid_blink\",", "\"yes\": True, \"no\": False, } prompt = \"%s (yes/no): \" % colored(\"Are you", "\"bright_green\", \"bright_yellow\", \"bright_blue\", \"bright_magenta\", \"bright_cyan\", \"bright_white\", ), range(90, 98)))) BG_COLORS = dict((f\"on_{key}\", val", "\"\"\"Terminal utilities specific to message archives. Creates colored text and helps write Messages", "val + 10) for key, val in FG_COLORS.items()) ATTRIBUTES = dict( zip((\"bold\", \"faint\",", "\"bright_yellow\", \"bright_blue\", \"bright_magenta\", \"bright_cyan\", \"bright_white\", ), range(90, 98)))) BG_COLORS = dict((f\"on_{key}\", val +", "not escape: esc = lambda n: n return \"%s%s%s\" % (esc(sgr(*codes)), text, esc(sgr(0)))", "try: yield finally: readline.set_auto_history(True) def confirm(text): \"\"\"Presents a yes/no prompt to the user", "= dict(itertools.chain( zip((\"black\", \"red\", \"green\", \"yellow\", \"blue\", \"magenta\", \"cyan\", \"white\", ), range(30, 38)),", "output. \"\"\" from contextlib import contextmanager import itertools import readline FG_COLORS = dict(itertools.chain(", "on_color=None, attrs=None, escape=False): \"\"\"Wraps text with ANSI escape codes to achieve the desired", "codes)) def esc(text): return \"\\x01%s\\x02\" % text codes = [] if color: codes.append(FG_COLORS[color])", "text, esc(sgr(0))) @contextmanager def readline_disabled(): \"\"\"Context manager to temporarily disable readline features. \"\"\"", "\"\"\"Context manager to temporarily disable readline features. \"\"\" readline.set_auto_history(False) try: yield finally: readline.set_auto_history(True)", "try: reply = input(prompt).casefold() except (EOFError, KeyboardInterrupt): reply = \"no\" print(reply) return replies[reply]", "by escape codes. \"\"\" def sgr(*codes): return \"\\x1b[%sm\" % \";\".join(map(str, codes)) def esc(text):", "escape=True) reply = \"\" with readline_disabled(): print(text) while reply not in replies: try:", "} prompt = \"%s (yes/no): \" % colored(\"Are you sure?\", \"red\", attrs=[\"bold\"], escape=True)", "n: n return \"%s%s%s\" % (esc(sgr(*codes)), text, esc(sgr(0))) @contextmanager def readline_disabled(): \"\"\"Context manager", "replies: try: reply = input(prompt).casefold() except (EOFError, KeyboardInterrupt): reply = \"no\" print(reply) return", "readline FG_COLORS = dict(itertools.chain( zip((\"black\", \"red\", \"green\", \"yellow\", \"blue\", \"magenta\", \"cyan\", \"white\", ),", "if attrs: codes.extend(ATTRIBUTES[attr] for attr in attrs) if not escape: esc = lambda", "to achieve the desired look. Args: color: The foreground color. on_color: The background", "a yes/no prompt to the user and handles replies. Args: text: A message", "text: A message string to present before confirmation. Returns: True if the user", "before confirmation. Returns: True if the user confirmed the prompt; else False. \"\"\"", "\"green\", \"yellow\", \"blue\", \"magenta\", \"cyan\", \"white\", ), range(30, 38)), zip((\"bright_black\", \"bright_red\", \"bright_green\", \"bright_yellow\",", "), range(30, 38)), zip((\"bright_black\", \"bright_red\", \"bright_green\", \"bright_yellow\", \"bright_blue\", \"bright_magenta\", \"bright_cyan\", \"bright_white\", ), range(90,", "The foreground color. on_color: The background color. attrs: A list of effects. escape:", "def esc(text): return \"\\x01%s\\x02\" % text codes = [] if color: codes.append(FG_COLORS[color]) if", "\"\\x1b[%sm\" % \";\".join(map(str, codes)) def esc(text): return \"\\x01%s\\x02\" % text codes = []", "import contextmanager import itertools import readline FG_COLORS = dict(itertools.chain( zip((\"black\", \"red\", \"green\", \"yellow\",", "escape codes. \"\"\" def sgr(*codes): return \"\\x1b[%sm\" % \";\".join(map(str, codes)) def esc(text): return", "\"\" with readline_disabled(): print(text) while reply not in replies: try: reply = input(prompt).casefold()", "color=None, on_color=None, attrs=None, escape=False): \"\"\"Wraps text with ANSI escape codes to achieve the", "replies. Args: text: A message string to present before confirmation. Returns: True if", "\"\"\"Presents a yes/no prompt to the user and handles replies. Args: text: A", "= [] if color: codes.append(FG_COLORS[color]) if on_color: codes.append(BG_COLORS[on_color]) if attrs: codes.extend(ATTRIBUTES[attr] for attr", "\" % colored(\"Are you sure?\", \"red\", attrs=[\"bold\"], escape=True) reply = \"\" with readline_disabled():", "else False. \"\"\" replies = { \"yes\": True, \"no\": False, } prompt =", "False. \"\"\" replies = { \"yes\": True, \"no\": False, } prompt = \"%s", "\"red\", \"green\", \"yellow\", \"blue\", \"magenta\", \"cyan\", \"white\", ), range(30, 38)), zip((\"bright_black\", \"bright_red\", \"bright_green\",", "(for readline); else False. Returns: A string with the original text wrapped by", "dict(itertools.chain( zip((\"black\", \"red\", \"green\", \"yellow\", \"blue\", \"magenta\", \"cyan\", \"white\", ), range(30, 38)), zip((\"bright_black\",", "% colored(\"Are you sure?\", \"red\", attrs=[\"bold\"], escape=True) reply = \"\" with readline_disabled(): print(text)", "\"reverse\", \"conceal\", \"strikethrough\", ), range(1, 10))) def colored(text, color=None, on_color=None, attrs=None, escape=False): \"\"\"Wraps", "codes to achieve the desired look. Args: color: The foreground color. on_color: The", "\"rapid_blink\", \"reverse\", \"conceal\", \"strikethrough\", ), range(1, 10))) def colored(text, color=None, on_color=None, attrs=None, escape=False):", "% (esc(sgr(*codes)), text, esc(sgr(0))) @contextmanager def readline_disabled(): \"\"\"Context manager to temporarily disable readline", "in replies: try: reply = input(prompt).casefold() except (EOFError, KeyboardInterrupt): reply = \"no\" print(reply)", "attrs: A list of effects. escape: True to escape invisibles (for readline); else", "FG_COLORS.items()) ATTRIBUTES = dict( zip((\"bold\", \"faint\", \"italic\", \"underline\", \"slow_blink\", \"rapid_blink\", \"reverse\", \"conceal\", \"strikethrough\",", "(esc(sgr(*codes)), text, esc(sgr(0))) @contextmanager def readline_disabled(): \"\"\"Context manager to temporarily disable readline features.", "codes = [] if color: codes.append(FG_COLORS[color]) if on_color: codes.append(BG_COLORS[on_color]) if attrs: codes.extend(ATTRIBUTES[attr] for", "colored(\"Are you sure?\", \"red\", attrs=[\"bold\"], escape=True) reply = \"\" with readline_disabled(): print(text) while", "effects. escape: True to escape invisibles (for readline); else False. Returns: A string", "zip((\"bright_black\", \"bright_red\", \"bright_green\", \"bright_yellow\", \"bright_blue\", \"bright_magenta\", \"bright_cyan\", \"bright_white\", ), range(90, 98)))) BG_COLORS =", "the desired look. Args: color: The foreground color. on_color: The background color. attrs:", "prompt to the user and handles replies. Args: text: A message string to", "(yes/no): \" % colored(\"Are you sure?\", \"red\", attrs=[\"bold\"], escape=True) reply = \"\" with", "dict( zip((\"bold\", \"faint\", \"italic\", \"underline\", \"slow_blink\", \"rapid_blink\", \"reverse\", \"conceal\", \"strikethrough\", ), range(1, 10)))", "else False. Returns: A string with the original text wrapped by escape codes.", "attrs=[\"bold\"], escape=True) reply = \"\" with readline_disabled(): print(text) while reply not in replies:", "the user and handles replies. Args: text: A message string to present before", "print(text) while reply not in replies: try: reply = input(prompt).casefold() except (EOFError, KeyboardInterrupt):", "ATTRIBUTES = dict( zip((\"bold\", \"faint\", \"italic\", \"underline\", \"slow_blink\", \"rapid_blink\", \"reverse\", \"conceal\", \"strikethrough\", ),", "to message archives. Creates colored text and helps write Messages output. \"\"\" from", "return \"%s%s%s\" % (esc(sgr(*codes)), text, esc(sgr(0))) @contextmanager def readline_disabled(): \"\"\"Context manager to temporarily", "readline_disabled(): \"\"\"Context manager to temporarily disable readline features. \"\"\" readline.set_auto_history(False) try: yield finally:", "write Messages output. \"\"\" from contextlib import contextmanager import itertools import readline FG_COLORS", "escape: True to escape invisibles (for readline); else False. Returns: A string with", "foreground color. on_color: The background color. attrs: A list of effects. escape: True", "codes.extend(ATTRIBUTES[attr] for attr in attrs) if not escape: esc = lambda n: n", "readline features. \"\"\" readline.set_auto_history(False) try: yield finally: readline.set_auto_history(True) def confirm(text): \"\"\"Presents a yes/no", "{ \"yes\": True, \"no\": False, } prompt = \"%s (yes/no): \" % colored(\"Are", "string to present before confirmation. Returns: True if the user confirmed the prompt;", "with ANSI escape codes to achieve the desired look. Args: color: The foreground", "\"italic\", \"underline\", \"slow_blink\", \"rapid_blink\", \"reverse\", \"conceal\", \"strikethrough\", ), range(1, 10))) def colored(text, color=None,", "\"\"\" def sgr(*codes): return \"\\x1b[%sm\" % \";\".join(map(str, codes)) def esc(text): return \"\\x01%s\\x02\" %", "), range(90, 98)))) BG_COLORS = dict((f\"on_{key}\", val + 10) for key, val in", "if color: codes.append(FG_COLORS[color]) if on_color: codes.append(BG_COLORS[on_color]) if attrs: codes.extend(ATTRIBUTES[attr] for attr in attrs)", "text and helps write Messages output. \"\"\" from contextlib import contextmanager import itertools", "\"\"\"Wraps text with ANSI escape codes to achieve the desired look. Args: color:", "codes. \"\"\" def sgr(*codes): return \"\\x1b[%sm\" % \";\".join(map(str, codes)) def esc(text): return \"\\x01%s\\x02\"", "[] if color: codes.append(FG_COLORS[color]) if on_color: codes.append(BG_COLORS[on_color]) if attrs: codes.extend(ATTRIBUTES[attr] for attr in", "if not escape: esc = lambda n: n return \"%s%s%s\" % (esc(sgr(*codes)), text,", "def colored(text, color=None, on_color=None, attrs=None, escape=False): \"\"\"Wraps text with ANSI escape codes to", "you sure?\", \"red\", attrs=[\"bold\"], escape=True) reply = \"\" with readline_disabled(): print(text) while reply", "\"\"\" from contextlib import contextmanager import itertools import readline FG_COLORS = dict(itertools.chain( zip((\"black\",", "contextlib import contextmanager import itertools import readline FG_COLORS = dict(itertools.chain( zip((\"black\", \"red\", \"green\",", "escape codes to achieve the desired look. Args: color: The foreground color. on_color:", "in FG_COLORS.items()) ATTRIBUTES = dict( zip((\"bold\", \"faint\", \"italic\", \"underline\", \"slow_blink\", \"rapid_blink\", \"reverse\", \"conceal\",", "\"%s (yes/no): \" % colored(\"Are you sure?\", \"red\", attrs=[\"bold\"], escape=True) reply = \"\"", "\"magenta\", \"cyan\", \"white\", ), range(30, 38)), zip((\"bright_black\", \"bright_red\", \"bright_green\", \"bright_yellow\", \"bright_blue\", \"bright_magenta\", \"bright_cyan\",", "range(30, 38)), zip((\"bright_black\", \"bright_red\", \"bright_green\", \"bright_yellow\", \"bright_blue\", \"bright_magenta\", \"bright_cyan\", \"bright_white\", ), range(90, 98))))", "readline.set_auto_history(True) def confirm(text): \"\"\"Presents a yes/no prompt to the user and handles replies.", "confirmed the prompt; else False. \"\"\" replies = { \"yes\": True, \"no\": False,", "ANSI escape codes to achieve the desired look. Args: color: The foreground color.", "text wrapped by escape codes. \"\"\" def sgr(*codes): return \"\\x1b[%sm\" % \";\".join(map(str, codes))", "esc(text): return \"\\x01%s\\x02\" % text codes = [] if color: codes.append(FG_COLORS[color]) if on_color:", "to temporarily disable readline features. \"\"\" readline.set_auto_history(False) try: yield finally: readline.set_auto_history(True) def confirm(text):", "text with ANSI escape codes to achieve the desired look. Args: color: The", "wrapped by escape codes. \"\"\" def sgr(*codes): return \"\\x1b[%sm\" % \";\".join(map(str, codes)) def", "yes/no prompt to the user and handles replies. Args: text: A message string", "reply = \"\" with readline_disabled(): print(text) while reply not in replies: try: reply", "% text codes = [] if color: codes.append(FG_COLORS[color]) if on_color: codes.append(BG_COLORS[on_color]) if attrs:", "98)))) BG_COLORS = dict((f\"on_{key}\", val + 10) for key, val in FG_COLORS.items()) ATTRIBUTES", "= \"\" with readline_disabled(): print(text) while reply not in replies: try: reply =", "with readline_disabled(): print(text) while reply not in replies: try: reply = input(prompt).casefold() except", "\"\\x01%s\\x02\" % text codes = [] if color: codes.append(FG_COLORS[color]) if on_color: codes.append(BG_COLORS[on_color]) if", "features. \"\"\" readline.set_auto_history(False) try: yield finally: readline.set_auto_history(True) def confirm(text): \"\"\"Presents a yes/no prompt", "readline); else False. Returns: A string with the original text wrapped by escape", "\"\"\" replies = { \"yes\": True, \"no\": False, } prompt = \"%s (yes/no):", "= dict((f\"on_{key}\", val + 10) for key, val in FG_COLORS.items()) ATTRIBUTES = dict(", "\"yellow\", \"blue\", \"magenta\", \"cyan\", \"white\", ), range(30, 38)), zip((\"bright_black\", \"bright_red\", \"bright_green\", \"bright_yellow\", \"bright_blue\",", "contextmanager import itertools import readline FG_COLORS = dict(itertools.chain( zip((\"black\", \"red\", \"green\", \"yellow\", \"blue\",", "sgr(*codes): return \"\\x1b[%sm\" % \";\".join(map(str, codes)) def esc(text): return \"\\x01%s\\x02\" % text codes", "codes.append(BG_COLORS[on_color]) if attrs: codes.extend(ATTRIBUTES[attr] for attr in attrs) if not escape: esc =", "True, \"no\": False, } prompt = \"%s (yes/no): \" % colored(\"Are you sure?\",", "import itertools import readline FG_COLORS = dict(itertools.chain( zip((\"black\", \"red\", \"green\", \"yellow\", \"blue\", \"magenta\",", "\"\"\" readline.set_auto_history(False) try: yield finally: readline.set_auto_history(True) def confirm(text): \"\"\"Presents a yes/no prompt to", "if on_color: codes.append(BG_COLORS[on_color]) if attrs: codes.extend(ATTRIBUTES[attr] for attr in attrs) if not escape:", "% \";\".join(map(str, codes)) def esc(text): return \"\\x01%s\\x02\" % text codes = [] if", "escape: esc = lambda n: n return \"%s%s%s\" % (esc(sgr(*codes)), text, esc(sgr(0))) @contextmanager", "\"bright_red\", \"bright_green\", \"bright_yellow\", \"bright_blue\", \"bright_magenta\", \"bright_cyan\", \"bright_white\", ), range(90, 98)))) BG_COLORS = dict((f\"on_{key}\",", "Args: text: A message string to present before confirmation. Returns: True if the", "BG_COLORS = dict((f\"on_{key}\", val + 10) for key, val in FG_COLORS.items()) ATTRIBUTES =", "user and handles replies. Args: text: A message string to present before confirmation.", "\"white\", ), range(30, 38)), zip((\"bright_black\", \"bright_red\", \"bright_green\", \"bright_yellow\", \"bright_blue\", \"bright_magenta\", \"bright_cyan\", \"bright_white\", ),", "esc = lambda n: n return \"%s%s%s\" % (esc(sgr(*codes)), text, esc(sgr(0))) @contextmanager def", "colored(text, color=None, on_color=None, attrs=None, escape=False): \"\"\"Wraps text with ANSI escape codes to achieve", "Returns: True if the user confirmed the prompt; else False. \"\"\" replies =", "utilities specific to message archives. Creates colored text and helps write Messages output.", "range(90, 98)))) BG_COLORS = dict((f\"on_{key}\", val + 10) for key, val in FG_COLORS.items())", "38)), zip((\"bright_black\", \"bright_red\", \"bright_green\", \"bright_yellow\", \"bright_blue\", \"bright_magenta\", \"bright_cyan\", \"bright_white\", ), range(90, 98)))) BG_COLORS", "range(1, 10))) def colored(text, color=None, on_color=None, attrs=None, escape=False): \"\"\"Wraps text with ANSI escape", "return \"\\x01%s\\x02\" % text codes = [] if color: codes.append(FG_COLORS[color]) if on_color: codes.append(BG_COLORS[on_color])", "handles replies. Args: text: A message string to present before confirmation. Returns: True", "on_color: codes.append(BG_COLORS[on_color]) if attrs: codes.extend(ATTRIBUTES[attr] for attr in attrs) if not escape: esc", "with the original text wrapped by escape codes. \"\"\" def sgr(*codes): return \"\\x1b[%sm\"", "prompt = \"%s (yes/no): \" % colored(\"Are you sure?\", \"red\", attrs=[\"bold\"], escape=True) reply", "the user confirmed the prompt; else False. \"\"\" replies = { \"yes\": True,", "val in FG_COLORS.items()) ATTRIBUTES = dict( zip((\"bold\", \"faint\", \"italic\", \"underline\", \"slow_blink\", \"rapid_blink\", \"reverse\",", "lambda n: n return \"%s%s%s\" % (esc(sgr(*codes)), text, esc(sgr(0))) @contextmanager def readline_disabled(): \"\"\"Context", "original text wrapped by escape codes. \"\"\" def sgr(*codes): return \"\\x1b[%sm\" % \";\".join(map(str,", "= lambda n: n return \"%s%s%s\" % (esc(sgr(*codes)), text, esc(sgr(0))) @contextmanager def readline_disabled():", "+ 10) for key, val in FG_COLORS.items()) ATTRIBUTES = dict( zip((\"bold\", \"faint\", \"italic\",", "manager to temporarily disable readline features. \"\"\" readline.set_auto_history(False) try: yield finally: readline.set_auto_history(True) def", "attrs=None, escape=False): \"\"\"Wraps text with ANSI escape codes to achieve the desired look.", "background color. attrs: A list of effects. escape: True to escape invisibles (for", "user confirmed the prompt; else False. \"\"\" replies = { \"yes\": True, \"no\":", "to present before confirmation. Returns: True if the user confirmed the prompt; else", "\"slow_blink\", \"rapid_blink\", \"reverse\", \"conceal\", \"strikethrough\", ), range(1, 10))) def colored(text, color=None, on_color=None, attrs=None,", "return \"\\x1b[%sm\" % \";\".join(map(str, codes)) def esc(text): return \"\\x01%s\\x02\" % text codes =", "readline.set_auto_history(False) try: yield finally: readline.set_auto_history(True) def confirm(text): \"\"\"Presents a yes/no prompt to the", "def confirm(text): \"\"\"Presents a yes/no prompt to the user and handles replies. Args:", "helps write Messages output. \"\"\" from contextlib import contextmanager import itertools import readline", "readline_disabled(): print(text) while reply not in replies: try: reply = input(prompt).casefold() except (EOFError,", "from contextlib import contextmanager import itertools import readline FG_COLORS = dict(itertools.chain( zip((\"black\", \"red\",", "\"no\": False, } prompt = \"%s (yes/no): \" % colored(\"Are you sure?\", \"red\",", "Creates colored text and helps write Messages output. \"\"\" from contextlib import contextmanager", "yield finally: readline.set_auto_history(True) def confirm(text): \"\"\"Presents a yes/no prompt to the user and", "and handles replies. Args: text: A message string to present before confirmation. Returns:", "to escape invisibles (for readline); else False. Returns: A string with the original", "zip((\"bold\", \"faint\", \"italic\", \"underline\", \"slow_blink\", \"rapid_blink\", \"reverse\", \"conceal\", \"strikethrough\", ), range(1, 10))) def", "prompt; else False. \"\"\" replies = { \"yes\": True, \"no\": False, } prompt", "10) for key, val in FG_COLORS.items()) ATTRIBUTES = dict( zip((\"bold\", \"faint\", \"italic\", \"underline\",", "Messages output. \"\"\" from contextlib import contextmanager import itertools import readline FG_COLORS =", "<gh_stars>0 \"\"\"Terminal utilities specific to message archives. Creates colored text and helps write", "temporarily disable readline features. \"\"\" readline.set_auto_history(False) try: yield finally: readline.set_auto_history(True) def confirm(text): \"\"\"Presents", "escape=False): \"\"\"Wraps text with ANSI escape codes to achieve the desired look. Args:", "of effects. escape: True to escape invisibles (for readline); else False. Returns: A", "sure?\", \"red\", attrs=[\"bold\"], escape=True) reply = \"\" with readline_disabled(): print(text) while reply not", "= \"%s (yes/no): \" % colored(\"Are you sure?\", \"red\", attrs=[\"bold\"], escape=True) reply =", "= dict( zip((\"bold\", \"faint\", \"italic\", \"underline\", \"slow_blink\", \"rapid_blink\", \"reverse\", \"conceal\", \"strikethrough\", ), range(1,", "to the user and handles replies. Args: text: A message string to present", "\";\".join(map(str, codes)) def esc(text): return \"\\x01%s\\x02\" % text codes = [] if color:" ]
[ "kernel_size=3, stride=1, padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2,", "writing, software # distributed under the License is distributed on an \"AS IS\"", "1, 16, 8, 4), # different size for H, W and D (2,", "nn from parameterized import parameterized from monai.networks import eval_mode from monai.networks.blocks import SubpixelUpsample", "eval_mode from monai.networks.blocks import SubpixelUpsample from monai.networks.layers.factories import Conv TEST_CASE_SUBPIXEL = [] for", "KIND, either express or implied. # See the License for the specific language", "stride=1, padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2, \"conv_block\":", "Unless required by applicable law or agreed to in writing, software # distributed", "# See the License for the specific language governing permissions and # limitations", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "Conv[Conv.CONV, 3](4, 8, kernel_size=3, stride=1, padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [ {\"dimensions\": 3, \"in_channels\":", "{\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2, \"conv_block\": conv_block}, (2, 1, 16, 8, 4),", "16, 8), ] conv_block = nn.Sequential( Conv[Conv.CONV, 3](1, 4, kernel_size=1), Conv[Conv.CONV, 3](4, 8,", "\"conv_block\": conv_block}, (2, 1, 16, 8, 4), # different size for H, W", "\"scale_factor\": 2, \"conv_block\": conv_block}, (2, 1, 16, 8, 4), # different size for", "W and D (2, 1, 32, 16, 8), ] conv_block = nn.Sequential( Conv[Conv.CONV,", "(2, 1, 32, 16, 8), ] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # add every test", "the License. import unittest import torch import torch.nn as nn from parameterized import", "dim)), (2, inch, *([8 * factor] * dim)), ] TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA = [", "a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable", "\"scale_factor\": 2}, (2, 1, 16, 8, 4), # different size for H, W", "inch, *([8] * dim)), (2, inch, *([8 * factor] * dim)), ] TEST_CASE_SUBPIXEL.append(test_case)", "back with the pad/pool sequential component omitted for tests in list(TEST_CASE_SUBPIXEL): args: dict", "parameterized from monai.networks import eval_mode from monai.networks.blocks import SubpixelUpsample from monai.networks.layers.factories import Conv", "monai.networks.layers.factories import Conv TEST_CASE_SUBPIXEL = [] for inch in range(1, 5): for dim", "omitted for tests in list(TEST_CASE_SUBPIXEL): args: dict = tests[0] # type: ignore args", "law or agreed to in writing, software # distributed under the License is", "the License for the specific language governing permissions and # limitations under the", "24, 12), ] TEST_CASE_SUBPIXEL_3D_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2}, (2,", "compliance with the License. # You may obtain a copy of the License", "# type: ignore args = dict(args) args[\"apply_pad_pool\"] = False TEST_CASE_SUBPIXEL.append([args, tests[1], tests[2]]) class", "kernel_size=1), Conv[Conv.CONV, 3](4, 8, kernel_size=3, stride=1, padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [ {\"dimensions\": 3,", "test back with the pad/pool sequential component omitted for tests in list(TEST_CASE_SUBPIXEL): args:", "[ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2}, (2, 1, 16, 8, 4), #", "* dim)), (2, inch, *([8 * factor] * dim)), ] TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA =", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "3](4, 8, kernel_size=3, stride=1, padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1,", "this file except in compliance with the License. # You may obtain a", "= False TEST_CASE_SUBPIXEL.append([args, tests[1], tests[2]]) class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self, input_param, input_shape, expected_shape):", "input_param, input_shape, expected_shape): net = SubpixelUpsample(**input_param) with eval_mode(net): result = net.forward(torch.randn(input_shape)) self.assertEqual(result.shape, expected_shape)", "SubpixelUpsample(**input_param) with eval_mode(net): result = net.forward(torch.randn(input_shape)) self.assertEqual(result.shape, expected_shape) if __name__ == \"__main__\": unittest.main()", "ignore args = dict(args) args[\"apply_pad_pool\"] = False TEST_CASE_SUBPIXEL.append([args, tests[1], tests[2]]) class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL)", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed", "you may not use this file except in compliance with the License. #", "for the specific language governing permissions and # limitations under the License. import", "*([8 * factor] * dim)), ] TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA = [ {\"dimensions\": 2, \"in_channels\":", "for H and W (2, 2, 24, 12), ] TEST_CASE_SUBPIXEL_3D_EXTRA = [ {\"dimensions\":", "sequential component omitted for tests in list(TEST_CASE_SUBPIXEL): args: dict = tests[0] # type:", "H and W (2, 2, 24, 12), ] TEST_CASE_SUBPIXEL_3D_EXTRA = [ {\"dimensions\": 3,", "http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software", "input_shape, expected_shape): net = SubpixelUpsample(**input_param) with eval_mode(net): result = net.forward(torch.randn(input_shape)) self.assertEqual(result.shape, expected_shape) if", "*([8] * dim)), (2, inch, *([8 * factor] * dim)), ] TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA", "\"scale_factor\": 3}, (2, 2, 8, 4), # different size for H and W", "inch, \"scale_factor\": factor}, (2, inch, *([8] * dim)), (2, inch, *([8 * factor]", "# add every test back with the pad/pool sequential component omitted for tests", "TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA = [ {\"dimensions\": 2, \"in_channels\": 2, \"scale_factor\": 3}, (2, 2, 8,", "# http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing,", "ANY KIND, either express or implied. # See the License for the specific", "8), ] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # add every test back with the pad/pool", "4), # different size for H, W and D (2, 1, 32, 16,", "= [ {\"dimensions\": dim, \"in_channels\": inch, \"scale_factor\": factor}, (2, inch, *([8] * dim)),", "\"in_channels\": inch, \"scale_factor\": factor}, (2, inch, *([8] * dim)), (2, inch, *([8 *", "conv_block}, (2, 1, 16, 8, 4), # different size for H, W and", "(2, 1, 32, 16, 8), ] conv_block = nn.Sequential( Conv[Conv.CONV, 3](1, 4, kernel_size=1),", "class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self, input_param, input_shape, expected_shape): net = SubpixelUpsample(**input_param) with eval_mode(net):", "in compliance with the License. # You may obtain a copy of the", ") TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2, \"conv_block\": conv_block}, (2,", "tests in list(TEST_CASE_SUBPIXEL): args: dict = tests[0] # type: ignore args = dict(args)", "different size for H and W (2, 2, 24, 12), ] TEST_CASE_SUBPIXEL_3D_EXTRA =", "[ {\"dimensions\": 2, \"in_channels\": 2, \"scale_factor\": 3}, (2, 2, 8, 4), # different", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "# Copyright 2020 - 2021 MONAI Consortium # Licensed under the Apache License,", "(2, 2, 8, 4), # different size for H and W (2, 2,", "use this file except in compliance with the License. # You may obtain", "] TEST_CASE_SUBPIXEL_3D_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2}, (2, 1, 16,", "not use this file except in compliance with the License. # You may", "torch import torch.nn as nn from parameterized import parameterized from monai.networks import eval_mode", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "4): for factor in range(1, 3): test_case = [ {\"dimensions\": dim, \"in_channels\": inch,", "import eval_mode from monai.networks.blocks import SubpixelUpsample from monai.networks.layers.factories import Conv TEST_CASE_SUBPIXEL = []", "and D (2, 1, 32, 16, 8), ] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # add", "add every test back with the pad/pool sequential component omitted for tests in", "size for H and W (2, 2, 24, 12), ] TEST_CASE_SUBPIXEL_3D_EXTRA = [", "pad/pool sequential component omitted for tests in list(TEST_CASE_SUBPIXEL): args: dict = tests[0] #", "dict(args) args[\"apply_pad_pool\"] = False TEST_CASE_SUBPIXEL.append([args, tests[1], tests[2]]) class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self, input_param,", "for H, W and D (2, 1, 32, 16, 8), ] conv_block =", "= nn.Sequential( Conv[Conv.CONV, 3](1, 4, kernel_size=1), Conv[Conv.CONV, 3](4, 8, kernel_size=3, stride=1, padding=1) )", "import torch.nn as nn from parameterized import parameterized from monai.networks import eval_mode from", "2}, (2, 1, 16, 8, 4), # different size for H, W and", "test_case = [ {\"dimensions\": dim, \"in_channels\": inch, \"scale_factor\": factor}, (2, inch, *([8] *", "See the License for the specific language governing permissions and # limitations under", "and D (2, 1, 32, 16, 8), ] conv_block = nn.Sequential( Conv[Conv.CONV, 3](1,", "[ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2, \"conv_block\": conv_block}, (2, 1, 16, 8,", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "inch, *([8 * factor] * dim)), ] TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA = [ {\"dimensions\": 2,", "in range(1, 4): for factor in range(1, 3): test_case = [ {\"dimensions\": dim,", "License, Version 2.0 (the \"License\"); # you may not use this file except", "3, \"in_channels\": 1, \"scale_factor\": 2, \"conv_block\": conv_block}, (2, 1, 16, 8, 4), #", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or", "3): test_case = [ {\"dimensions\": dim, \"in_channels\": inch, \"scale_factor\": factor}, (2, inch, *([8]", "factor] * dim)), ] TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA = [ {\"dimensions\": 2, \"in_channels\": 2, \"scale_factor\":", "[] for inch in range(1, 5): for dim in range(1, 4): for factor", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "for H, W and D (2, 1, 32, 16, 8), ] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA)", "] TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA = [ {\"dimensions\": 2, \"in_channels\": 2, \"scale_factor\": 3}, (2, 2,", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "TEST_CASE_SUBPIXEL = [] for inch in range(1, 5): for dim in range(1, 4):", "= [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2, \"conv_block\": conv_block}, (2, 1, 16,", "in list(TEST_CASE_SUBPIXEL): args: dict = tests[0] # type: ignore args = dict(args) args[\"apply_pad_pool\"]", "= SubpixelUpsample(**input_param) with eval_mode(net): result = net.forward(torch.randn(input_shape)) self.assertEqual(result.shape, expected_shape) if __name__ == \"__main__\":", "8), ] conv_block = nn.Sequential( Conv[Conv.CONV, 3](1, 4, kernel_size=1), Conv[Conv.CONV, 3](4, 8, kernel_size=3,", "OF ANY KIND, either express or implied. # See the License for the", "= tests[0] # type: ignore args = dict(args) args[\"apply_pad_pool\"] = False TEST_CASE_SUBPIXEL.append([args, tests[1],", "factor}, (2, inch, *([8] * dim)), (2, inch, *([8 * factor] * dim)),", "2.0 (the \"License\"); # you may not use this file except in compliance", "obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by", "MONAI Consortium # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "H, W and D (2, 1, 32, 16, 8), ] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA)", "copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law", "* dim)), ] TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA = [ {\"dimensions\": 2, \"in_channels\": 2, \"scale_factor\": 3},", "# you may not use this file except in compliance with the License.", "size for H, W and D (2, 1, 32, 16, 8), ] conv_block", "type: ignore args = dict(args) args[\"apply_pad_pool\"] = False TEST_CASE_SUBPIXEL.append([args, tests[1], tests[2]]) class TestSUBPIXEL(unittest.TestCase):", "(2, inch, *([8] * dim)), (2, inch, *([8 * factor] * dim)), ]", "expected_shape): net = SubpixelUpsample(**input_param) with eval_mode(net): result = net.forward(torch.randn(input_shape)) self.assertEqual(result.shape, expected_shape) if __name__", "limitations under the License. import unittest import torch import torch.nn as nn from", "16, 8, 4), # different size for H, W and D (2, 1,", "and W (2, 2, 24, 12), ] TEST_CASE_SUBPIXEL_3D_EXTRA = [ {\"dimensions\": 3, \"in_channels\":", "size for H, W and D (2, 1, 32, 16, 8), ] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA)", "range(1, 5): for dim in range(1, 4): for factor in range(1, 3): test_case", "conv_block = nn.Sequential( Conv[Conv.CONV, 3](1, 4, kernel_size=1), Conv[Conv.CONV, 3](4, 8, kernel_size=3, stride=1, padding=1)", "agreed to in writing, software # distributed under the License is distributed on", "{\"dimensions\": dim, \"in_channels\": inch, \"scale_factor\": factor}, (2, inch, *([8] * dim)), (2, inch,", "[ {\"dimensions\": dim, \"in_channels\": inch, \"scale_factor\": factor}, (2, inch, *([8] * dim)), (2,", "* factor] * dim)), ] TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA = [ {\"dimensions\": 2, \"in_channels\": 2,", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "\"in_channels\": 2, \"scale_factor\": 3}, (2, 2, 8, 4), # different size for H", "torch.nn as nn from parameterized import parameterized from monai.networks import eval_mode from monai.networks.blocks", "# different size for H and W (2, 2, 24, 12), ] TEST_CASE_SUBPIXEL_3D_EXTRA", "at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in", "= [] for inch in range(1, 5): for dim in range(1, 4): for", "(the \"License\"); # you may not use this file except in compliance with", "import torch import torch.nn as nn from parameterized import parameterized from monai.networks import", "{\"dimensions\": 2, \"in_channels\": 2, \"scale_factor\": 3}, (2, 2, 8, 4), # different size", "License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to", "dict = tests[0] # type: ignore args = dict(args) args[\"apply_pad_pool\"] = False TEST_CASE_SUBPIXEL.append([args,", "4), # different size for H and W (2, 2, 24, 12), ]", "1, \"scale_factor\": 2}, (2, 1, 16, 8, 4), # different size for H,", "unittest import torch import torch.nn as nn from parameterized import parameterized from monai.networks", "from monai.networks.blocks import SubpixelUpsample from monai.networks.layers.factories import Conv TEST_CASE_SUBPIXEL = [] for inch", "net = SubpixelUpsample(**input_param) with eval_mode(net): result = net.forward(torch.randn(input_shape)) self.assertEqual(result.shape, expected_shape) if __name__ ==", "TEST_CASE_SUBPIXEL_2D_EXTRA = [ {\"dimensions\": 2, \"in_channels\": 2, \"scale_factor\": 3}, (2, 2, 8, 4),", "TEST_CASE_SUBPIXEL.append([args, tests[1], tests[2]]) class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self, input_param, input_shape, expected_shape): net =", "express or implied. # See the License for the specific language governing permissions", "\"scale_factor\": factor}, (2, inch, *([8] * dim)), (2, inch, *([8 * factor] *", "W and D (2, 1, 32, 16, 8), ] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) #", "Version 2.0 (the \"License\"); # you may not use this file except in", "# Unless required by applicable law or agreed to in writing, software #", "as nn from parameterized import parameterized from monai.networks import eval_mode from monai.networks.blocks import", "except in compliance with the License. # You may obtain a copy of", "# different size for H, W and D (2, 1, 32, 16, 8),", "32, 16, 8), ] conv_block = nn.Sequential( Conv[Conv.CONV, 3](1, 4, kernel_size=1), Conv[Conv.CONV, 3](4,", "TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # add every test back with the pad/pool sequential component omitted", "by applicable law or agreed to in writing, software # distributed under the", "import Conv TEST_CASE_SUBPIXEL = [] for inch in range(1, 5): for dim in", "range(1, 4): for factor in range(1, 3): test_case = [ {\"dimensions\": dim, \"in_channels\":", "args: dict = tests[0] # type: ignore args = dict(args) args[\"apply_pad_pool\"] = False", "under the License. import unittest import torch import torch.nn as nn from parameterized", "import SubpixelUpsample from monai.networks.layers.factories import Conv TEST_CASE_SUBPIXEL = [] for inch in range(1,", "nn.Sequential( Conv[Conv.CONV, 3](1, 4, kernel_size=1), Conv[Conv.CONV, 3](4, 8, kernel_size=3, stride=1, padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA", "for factor in range(1, 3): test_case = [ {\"dimensions\": dim, \"in_channels\": inch, \"scale_factor\":", "2, 8, 4), # different size for H and W (2, 2, 24,", "either express or implied. # See the License for the specific language governing", "8, 4), # different size for H, W and D (2, 1, 32,", "tests[2]]) class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self, input_param, input_shape, expected_shape): net = SubpixelUpsample(**input_param) with", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "import parameterized from monai.networks import eval_mode from monai.networks.blocks import SubpixelUpsample from monai.networks.layers.factories import", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "# You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 #", "with the pad/pool sequential component omitted for tests in list(TEST_CASE_SUBPIXEL): args: dict =", "2, \"conv_block\": conv_block}, (2, 1, 16, 8, 4), # different size for H,", "False TEST_CASE_SUBPIXEL.append([args, tests[1], tests[2]]) class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self, input_param, input_shape, expected_shape): net", "@parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self, input_param, input_shape, expected_shape): net = SubpixelUpsample(**input_param) with eval_mode(net): result =", "may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "different size for H, W and D (2, 1, 32, 16, 8), ]", "H, W and D (2, 1, 32, 16, 8), ] conv_block = nn.Sequential(", "2020 - 2021 MONAI Consortium # Licensed under the Apache License, Version 2.0", "the pad/pool sequential component omitted for tests in list(TEST_CASE_SUBPIXEL): args: dict = tests[0]", "from monai.networks.layers.factories import Conv TEST_CASE_SUBPIXEL = [] for inch in range(1, 5): for", "] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # add every test back with the pad/pool sequential", "tests[0] # type: ignore args = dict(args) args[\"apply_pad_pool\"] = False TEST_CASE_SUBPIXEL.append([args, tests[1], tests[2]])", "12), ] TEST_CASE_SUBPIXEL_3D_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2}, (2, 1,", "file except in compliance with the License. # You may obtain a copy", "1, 32, 16, 8), ] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # add every test back", "License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0", "def test_subpixel_shape(self, input_param, input_shape, expected_shape): net = SubpixelUpsample(**input_param) with eval_mode(net): result = net.forward(torch.randn(input_shape))", "] conv_block = nn.Sequential( Conv[Conv.CONV, 3](1, 4, kernel_size=1), Conv[Conv.CONV, 3](4, 8, kernel_size=3, stride=1,", "Conv TEST_CASE_SUBPIXEL = [] for inch in range(1, 5): for dim in range(1,", "= [ {\"dimensions\": 2, \"in_channels\": 2, \"scale_factor\": 3}, (2, 2, 8, 4), #", "= [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2}, (2, 1, 16, 8, 4),", "Conv[Conv.CONV, 3](1, 4, kernel_size=1), Conv[Conv.CONV, 3](4, 8, kernel_size=3, stride=1, padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA =", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "(2, 1, 16, 8, 4), # different size for H, W and D", "specific language governing permissions and # limitations under the License. import unittest import", "permissions and # limitations under the License. import unittest import torch import torch.nn", "3}, (2, 2, 8, 4), # different size for H and W (2,", "License for the specific language governing permissions and # limitations under the License.", "for dim in range(1, 4): for factor in range(1, 3): test_case = [", "D (2, 1, 32, 16, 8), ] conv_block = nn.Sequential( Conv[Conv.CONV, 3](1, 4,", "1, \"scale_factor\": 2, \"conv_block\": conv_block}, (2, 1, 16, 8, 4), # different size", "16, 8), ] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # add every test back with the", "(2, 2, 24, 12), ] TEST_CASE_SUBPIXEL_3D_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\":", "for inch in range(1, 5): for dim in range(1, 4): for factor in", "1, 32, 16, 8), ] conv_block = nn.Sequential( Conv[Conv.CONV, 3](1, 4, kernel_size=1), Conv[Conv.CONV,", "TEST_CASE_SUBPIXEL_3D_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2}, (2, 1, 16, 8,", "the License. # You may obtain a copy of the License at #", "2, \"scale_factor\": 3}, (2, 2, 8, 4), # different size for H and", "every test back with the pad/pool sequential component omitted for tests in list(TEST_CASE_SUBPIXEL):", "args = dict(args) args[\"apply_pad_pool\"] = False TEST_CASE_SUBPIXEL.append([args, tests[1], tests[2]]) class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def", "dim, \"in_channels\": inch, \"scale_factor\": factor}, (2, inch, *([8] * dim)), (2, inch, *([8", "to in writing, software # distributed under the License is distributed on an", "Consortium # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "parameterized import parameterized from monai.networks import eval_mode from monai.networks.blocks import SubpixelUpsample from monai.networks.layers.factories", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "factor in range(1, 3): test_case = [ {\"dimensions\": dim, \"in_channels\": inch, \"scale_factor\": factor},", "implied. # See the License for the specific language governing permissions and #", "monai.networks.blocks import SubpixelUpsample from monai.networks.layers.factories import Conv TEST_CASE_SUBPIXEL = [] for inch in", "\"License\"); # you may not use this file except in compliance with the", "dim)), ] TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA = [ {\"dimensions\": 2, \"in_channels\": 2, \"scale_factor\": 3}, (2,", "for tests in list(TEST_CASE_SUBPIXEL): args: dict = tests[0] # type: ignore args =", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "test_subpixel_shape(self, input_param, input_shape, expected_shape): net = SubpixelUpsample(**input_param) with eval_mode(net): result = net.forward(torch.randn(input_shape)) self.assertEqual(result.shape,", "required by applicable law or agreed to in writing, software # distributed under", "License. import unittest import torch import torch.nn as nn from parameterized import parameterized", "TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # add every test back with the pad/pool sequential component omitted for", "applicable law or agreed to in writing, software # distributed under the License", "You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless", "2, 24, 12), ] TEST_CASE_SUBPIXEL_3D_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2},", "3](1, 4, kernel_size=1), Conv[Conv.CONV, 3](4, 8, kernel_size=3, stride=1, padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [", "inch in range(1, 5): for dim in range(1, 4): for factor in range(1,", "list(TEST_CASE_SUBPIXEL): args: dict = tests[0] # type: ignore args = dict(args) args[\"apply_pad_pool\"] =", "\"in_channels\": 1, \"scale_factor\": 2}, (2, 1, 16, 8, 4), # different size for", "args[\"apply_pad_pool\"] = False TEST_CASE_SUBPIXEL.append([args, tests[1], tests[2]]) class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self, input_param, input_shape,", "dim in range(1, 4): for factor in range(1, 3): test_case = [ {\"dimensions\":", "range(1, 3): test_case = [ {\"dimensions\": dim, \"in_channels\": inch, \"scale_factor\": factor}, (2, inch,", "\"in_channels\": 1, \"scale_factor\": 2, \"conv_block\": conv_block}, (2, 1, 16, 8, 4), # different", "Copyright 2020 - 2021 MONAI Consortium # Licensed under the Apache License, Version", "32, 16, 8), ] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # add every test back with", "TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # add every test back with the pad/pool sequential component", "or agreed to in writing, software # distributed under the License is distributed", "W (2, 2, 24, 12), ] TEST_CASE_SUBPIXEL_3D_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1,", "and # limitations under the License. import unittest import torch import torch.nn as", "or implied. # See the License for the specific language governing permissions and", "D (2, 1, 32, 16, 8), ] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # add every", "monai.networks import eval_mode from monai.networks.blocks import SubpixelUpsample from monai.networks.layers.factories import Conv TEST_CASE_SUBPIXEL =", "in range(1, 5): for dim in range(1, 4): for factor in range(1, 3):", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "the specific language governing permissions and # limitations under the License. import unittest", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "governing permissions and # limitations under the License. import unittest import torch import", "5): for dim in range(1, 4): for factor in range(1, 3): test_case =", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "2021 MONAI Consortium # Licensed under the Apache License, Version 2.0 (the \"License\");", "from monai.networks import eval_mode from monai.networks.blocks import SubpixelUpsample from monai.networks.layers.factories import Conv TEST_CASE_SUBPIXEL", "from parameterized import parameterized from monai.networks import eval_mode from monai.networks.blocks import SubpixelUpsample from", "in range(1, 3): test_case = [ {\"dimensions\": dim, \"in_channels\": inch, \"scale_factor\": factor}, (2,", "(2, inch, *([8 * factor] * dim)), ] TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA = [ {\"dimensions\":", "{\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2}, (2, 1, 16, 8, 4), # different", "4, kernel_size=1), Conv[Conv.CONV, 3](4, 8, kernel_size=3, stride=1, padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [ {\"dimensions\":", "language governing permissions and # limitations under the License. import unittest import torch", "= dict(args) args[\"apply_pad_pool\"] = False TEST_CASE_SUBPIXEL.append([args, tests[1], tests[2]]) class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self,", "tests[1], tests[2]]) class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self, input_param, input_shape, expected_shape): net = SubpixelUpsample(**input_param)", "with the License. # You may obtain a copy of the License at", "import unittest import torch import torch.nn as nn from parameterized import parameterized from", "2, \"in_channels\": 2, \"scale_factor\": 3}, (2, 2, 8, 4), # different size for", "# limitations under the License. import unittest import torch import torch.nn as nn", "- 2021 MONAI Consortium # Licensed under the Apache License, Version 2.0 (the", "SubpixelUpsample from monai.networks.layers.factories import Conv TEST_CASE_SUBPIXEL = [] for inch in range(1, 5):", "8, 4), # different size for H and W (2, 2, 24, 12),", "3, \"in_channels\": 1, \"scale_factor\": 2}, (2, 1, 16, 8, 4), # different size", "in writing, software # distributed under the License is distributed on an \"AS", "8, kernel_size=3, stride=1, padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\":", "TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self, input_param, input_shape, expected_shape): net = SubpixelUpsample(**input_param) with eval_mode(net): result", "padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2, \"conv_block\": conv_block},", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "component omitted for tests in list(TEST_CASE_SUBPIXEL): args: dict = tests[0] # type: ignore", "TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2, \"conv_block\": conv_block}, (2, 1," ]
[ "CFGBuilder userCfg = CFGBuilder().build_from_file('user.py', './auction/user.py') bidCfg = CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg", "userCfg = CFGBuilder().build_from_file('user.py', './auction/user.py') bidCfg = CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg =", "bidCfg = CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg = CFGBuilder().build_from_file('auction_event.py','./auction/auction_event.py') bidCfg.build_visual('bidCfg', 'pdf') auctionCfg.build_visual('auctionCfg',", "= CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg = CFGBuilder().build_from_file('auction_event.py','./auction/auction_event.py') bidCfg.build_visual('bidCfg', 'pdf') auctionCfg.build_visual('auctionCfg', 'pdf')", "CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg = CFGBuilder().build_from_file('auction_event.py','./auction/auction_event.py') bidCfg.build_visual('bidCfg', 'pdf') auctionCfg.build_visual('auctionCfg', 'pdf') #auctionEventCfg.build_visual('auctionEventCfg.pdf',", "<filename>gen-cfg.py from staticfg import CFGBuilder userCfg = CFGBuilder().build_from_file('user.py', './auction/user.py') bidCfg = CFGBuilder().build_from_file('bid.py', './auction/bid.py')", "= CFGBuilder().build_from_file('user.py', './auction/user.py') bidCfg = CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg = CFGBuilder().build_from_file('auction_event.py','./auction/auction_event.py')", "import CFGBuilder userCfg = CFGBuilder().build_from_file('user.py', './auction/user.py') bidCfg = CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py')", "CFGBuilder().build_from_file('user.py', './auction/user.py') bidCfg = CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg = CFGBuilder().build_from_file('auction_event.py','./auction/auction_event.py') bidCfg.build_visual('bidCfg',", "staticfg import CFGBuilder userCfg = CFGBuilder().build_from_file('user.py', './auction/user.py') bidCfg = CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg =", "'./auction/bid.py') auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg = CFGBuilder().build_from_file('auction_event.py','./auction/auction_event.py') bidCfg.build_visual('bidCfg', 'pdf') auctionCfg.build_visual('auctionCfg', 'pdf') #auctionEventCfg.build_visual('auctionEventCfg.pdf', 'pdf')", "from staticfg import CFGBuilder userCfg = CFGBuilder().build_from_file('user.py', './auction/user.py') bidCfg = CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg", "'./auction/user.py') bidCfg = CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg = CFGBuilder().build_from_file('auction_event.py','./auction/auction_event.py') bidCfg.build_visual('bidCfg', 'pdf')" ]
[ "= float(input()) while True: command = input() if command == \"End\": break money", "minimal_budget = float(input()) while True: command = input() if command == \"End\": break", "money = float(command) total_budget += money if total_budget >= minimal_budget: print(f\"Going to {destination}!\")", "= float(command) total_budget += money if total_budget >= minimal_budget: print(f\"Going to {destination}!\") total_budget", "= input() if destination == \"End\": break minimal_budget = float(input()) while True: command", "0 while True: destination = input() if destination == \"End\": break minimal_budget =", "True: command = input() if command == \"End\": break money = float(command) total_budget", "== \"End\": break minimal_budget = float(input()) while True: command = input() if command", "\"End\": break minimal_budget = float(input()) while True: command = input() if command ==", "if destination == \"End\": break minimal_budget = float(input()) while True: command = input()", "total_budget = 0 while True: destination = input() if destination == \"End\": break", "total_budget += money if total_budget >= minimal_budget: print(f\"Going to {destination}!\") total_budget = 0", "destination == \"End\": break minimal_budget = float(input()) while True: command = input() if", "= input() if command == \"End\": break money = float(command) total_budget += money", "Ladder/softuni_problem.py total_budget = 0 while True: destination = input() if destination == \"End\":", "float(command) total_budget += money if total_budget >= minimal_budget: print(f\"Going to {destination}!\") total_budget =", "<filename>CodeForces/A2OJ Ladder/softuni_problem.py total_budget = 0 while True: destination = input() if destination ==", "command = input() if command == \"End\": break money = float(command) total_budget +=", "float(input()) while True: command = input() if command == \"End\": break money =", "break money = float(command) total_budget += money if total_budget >= minimal_budget: print(f\"Going to", "\"End\": break money = float(command) total_budget += money if total_budget >= minimal_budget: print(f\"Going", "= 0 while True: destination = input() if destination == \"End\": break minimal_budget", "if command == \"End\": break money = float(command) total_budget += money if total_budget", "+= money if total_budget >= minimal_budget: print(f\"Going to {destination}!\") total_budget = 0 break", "break minimal_budget = float(input()) while True: command = input() if command == \"End\":", "True: destination = input() if destination == \"End\": break minimal_budget = float(input()) while", "while True: command = input() if command == \"End\": break money = float(command)", "input() if command == \"End\": break money = float(command) total_budget += money if", "input() if destination == \"End\": break minimal_budget = float(input()) while True: command =", "while True: destination = input() if destination == \"End\": break minimal_budget = float(input())", "destination = input() if destination == \"End\": break minimal_budget = float(input()) while True:", "== \"End\": break money = float(command) total_budget += money if total_budget >= minimal_budget:", "command == \"End\": break money = float(command) total_budget += money if total_budget >=" ]
[ "from footmark.regioninfo import RegionInfo class RAMRegionInfo(RegionInfo): \"\"\" Represents an ram Region \"\"\" def", "def __init__(self, connection=None, name=None, id=None, connection_cls=None): from footmark.ram.connection import RAMConnection super(RAMRegionInfo, self).__init__(connection, name,", "import RegionInfo class RAMRegionInfo(RegionInfo): \"\"\" Represents an ram Region \"\"\" def __init__(self, connection=None,", "__init__(self, connection=None, name=None, id=None, connection_cls=None): from footmark.ram.connection import RAMConnection super(RAMRegionInfo, self).__init__(connection, name, id,", "connection=None, name=None, id=None, connection_cls=None): from footmark.ram.connection import RAMConnection super(RAMRegionInfo, self).__init__(connection, name, id, RAMConnection)", "class RAMRegionInfo(RegionInfo): \"\"\" Represents an ram Region \"\"\" def __init__(self, connection=None, name=None, id=None,", "Region \"\"\" def __init__(self, connection=None, name=None, id=None, connection_cls=None): from footmark.ram.connection import RAMConnection super(RAMRegionInfo,", "an ram Region \"\"\" def __init__(self, connection=None, name=None, id=None, connection_cls=None): from footmark.ram.connection import", "Represents an ram Region \"\"\" def __init__(self, connection=None, name=None, id=None, connection_cls=None): from footmark.ram.connection", "RAMRegionInfo(RegionInfo): \"\"\" Represents an ram Region \"\"\" def __init__(self, connection=None, name=None, id=None, connection_cls=None):", "footmark.regioninfo import RegionInfo class RAMRegionInfo(RegionInfo): \"\"\" Represents an ram Region \"\"\" def __init__(self,", "\"\"\" Represents an ram Region \"\"\" def __init__(self, connection=None, name=None, id=None, connection_cls=None): from", "\"\"\" def __init__(self, connection=None, name=None, id=None, connection_cls=None): from footmark.ram.connection import RAMConnection super(RAMRegionInfo, self).__init__(connection,", "ram Region \"\"\" def __init__(self, connection=None, name=None, id=None, connection_cls=None): from footmark.ram.connection import RAMConnection", "RegionInfo class RAMRegionInfo(RegionInfo): \"\"\" Represents an ram Region \"\"\" def __init__(self, connection=None, name=None," ]
[ "a single histogram to a D3PO plot :param plot: Glue histogram :type plot:", "plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param index: 1D index of plot on the page :type index:", "- The Glue session must have only one dataset open, and 0 or", "save_page(page, page_number, label, subset): \"\"\" Convert a tab of a glue session into", "<script type=\"text/javascript\"> $(document).ready(function() { initialize('states.json', 'data.csv'); } ); </script> </body> </html> \"\"\" try:", "for c in data.components]) for i, subset in enumerate(subsets): if subset is None:", "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/style.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'> <style>", "result def save_plot_base(plot, index): result = {} result['gridPosition'] = [0, index] return result", "range(len(page)))) return result def save_plot_base(plot, index): result = {} result['gridPosition'] = [0, index]", "log scales return result def save_histogram(plot, index): \"\"\" Convert a single histogram to", "names=[c.label for c in data.components]) for i, subset in enumerate(subsets): if subset is", "a server to view an exported D3PO bundle, and open a browser. :param", "HTML = \"\"\" <!DOCTYPE html> <html> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" type=\"text/css\"", "layer_artist in viewer.layers: if not layer_artist.visible: continue s = layer_artist.layer if not isinstance(s,", "os.unlink(path) if not os.path.exists(path): os.mkdir(path) data = application.session.data_collection[0] subsets = stage_subsets(application) viewers =", "to save :param path: Path to directory to save in. Will be created", "# states.json result = {} result['filename'] = 'data.csv' # XXX don't think this", "a D3PO plot :param plot: Glue scatter plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param index: 1D index", "result = save_plot_base(plot, index) result['type'] = 'histogram' result['xAxis'] = dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)])", "subsets)) state_path = os.path.join(path, 'states.json') with open(state_path, 'w') as outfile: json.dump(result, outfile, indent=2,", "if os.path.exists(path) and not os.path.isdir(path): os.unlink(path) if not os.path.exists(path): os.mkdir(path) data = application.session.data_collection[0]", "exporters.add('D3PO', save_d3po, can_save_d3po, outmode='directory') HTML = \"\"\" <!DOCTYPE html> <html> <head> <meta charset=\"utf-8\"", "src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head> <body> <div id=\"svg\"><svg></svg></div> <div id=\"controls\"> <ul class=\"navigation\"> </ul> </div> <div id=\"caption\"></div>", "ScatterViewer from glue.viewers.histogram.qt import HistogramViewer except ImportError: pass else: DISPATCH[ScatterViewer] = save_scatter DISPATCH[HistogramViewer]", "__future__ import absolute_import, division, print_function import os import json from glue.core import Subset", "not isinstance(viewer, tuple(DISPATCH.keys())): raise ValueError(\"D3PO Export only supports scatter \" \"and histogram plots\")", "= Table([data[c] for c in data.components], names=[c.label for c in data.components]) for i,", "= os.path.join(path, 'data.csv') t = Table([data[c] for c in data.components], names=[c.label for c", "visible \" \"in each tab\") def make_data_file(data, subsets, path): \"\"\" Create the data.csv", "html_path = os.path.join(path, 'index.html') with open(html_path, 'w') as outfile: outfile.write(HTML) # show the", "return result def stage_subsets(application): \"\"\" Return a tuple of the subset to use", "print_function import os import json from glue.core import Subset DISPATCH = {} def", "plot to a D3PO plot :param plot: Glue scatter plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param index:", "if sum(len(tab) for tab in application.viewers) == 0: raise ValueError(\"D3PO Export requires at", "save_d3po(application, path, launch=True): \"\"\"Save a Glue session to a D3PO bundle. Currently, this", "the tab has no subset If more than one subset is used per", "than one subset is used per stage/tab, returns None \"\"\" result = []", "export of %s\" % data.label result['states'] = list(map(save_page, application.viewers, range(len(viewers)), application.tab_names, subsets)) state_path", "print('Serving D3PO on port 0.0.0.0:%i' % PORT) server.server_activate() thread = Thread(target=server.serve_forever) thread.setDaemon(True) #", "dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min), float(plot.state.x_max)]) result['yAxis'] = dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min), float(plot.state.y_max)]) # XXX log scales return", "not \"\"\" dc = application.session.data_collection if len(dc) != 1: raise ValueError(\"D3PO Export only", "return None if subset is None: subset = s result.append(subset) return tuple(result) def", "size=d.style.markersize / 2, color=d.style.color) result['markerStyle'] = dict(unselected=unselected) if subset is not None: s", "if not isinstance(viewer, tuple(DISPATCH.keys())): raise ValueError(\"D3PO Export only supports scatter \" \"and histogram", "# XXX log scales return result def save_histogram(plot, index): \"\"\" Convert a single", "None: continue c = Column(data=subset.to_mask().astype('i'), name='selection_%i' % i) t.add_column(c) t.write(data_path, format='ascii', delimiter=',') def", "'data.csv' # XXX don't think this is needed? result['title'] = \"Glue export of", "error: # port already taken pass print('Serving D3PO on port 0.0.0.0:%i' % PORT)", "Tuple of data viewers to save :param label: Tab label \"\"\" result =", "PORT) server.server_activate() thread = Thread(target=server.serve_forever) thread.setDaemon(True) # do not prevent shutdown thread.start() webbrowser.open('http://0.0.0.0:%i'", "len(dc) != 1: raise ValueError(\"D3PO Export only supports a single dataset\") for tab", "= dict(opacity=d.style.alpha, size=d.style.markersize / 2, color=d.style.color) result['markerStyle'] = dict(unselected=unselected) if subset is not", "index): typ = type(plot) return DISPATCH[typ](plot, index) def save_scatter(plot, index): \"\"\" Convert a", "continue s = layer_artist.layer if not isinstance(s, Subset): continue if subset is not", "= \"Glue export of %s\" % data.label result['states'] = list(map(save_page, application.viewers, range(len(viewers)), application.tab_names,", "port already taken pass print('Serving D3PO on port 0.0.0.0:%i' % PORT) server.server_activate() thread", "sort_keys=True) # index.html html_path = os.path.join(path, 'index.html') with open(html_path, 'w') as outfile: outfile.write(HTML)", "data viewers to save :param label: Tab label \"\"\" result = {} #", "scatter plots or histograms are present - At least one plot is present", "os import json from glue.core import Subset DISPATCH = {} def save_page(page, page_number,", "result['title'] = \"Glue export of %s\" % data.label result['states'] = list(map(save_page, application.viewers, range(len(viewers)),", "only supports a single dataset\") for tab in application.viewers: for viewer in tab:", "scatterplot \" \"or histogram\") if stage_subsets(application) is None: raise ValueError(\"D3PO Export restricted to", "= {} result['filename'] = 'data.csv' # XXX don't think this is needed? result['title']", "<script src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head> <body> <div id=\"svg\"><svg></svg></div> <div id=\"controls\"> <ul class=\"navigation\"> </ul> </div> <div", "this has the following restrictions: - The Glue session must have only one", "The TLD of the bundle \"\"\" from glue.external.six.moves.socketserver import TCPServer from glue.external.six.moves.SimpleHTTPServer import", "try: PORT = randrange(8000, 9000) server = TCPServer((\"\", PORT), SimpleHTTPRequestHandler, False) server.allow_reuse_address =", "prevent shutdown thread.start() webbrowser.open('http://0.0.0.0:%i' % PORT) def setup(): from glue.config import exporters exporters.add('D3PO',", "if not isinstance(s, Subset): continue if subset is not None and s is", "--> <script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script> <script src=\"http://d3po.org/static/js/util.js\"></script> <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script src=\"http://d3po.org/static/js/d3po.js\"></script> <script src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head>", "glue.config import exporters exporters.add('D3PO', save_d3po, can_save_d3po, outmode='directory') HTML = \"\"\" <!DOCTYPE html> <html>", "application.session.data_collection[0] subsets = stage_subsets(application) viewers = application.viewers # data.csv make_data_file(data, subsets, path) #", "layer_artist.visible: continue s = layer_artist.layer if not isinstance(s, Subset): continue if subset is", "stage_subsets(application): \"\"\" Return a tuple of the subset to use for each stage/tab,", "TCPServer from glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler from random import randrange from socket import error", "{} result['filename'] = 'data.csv' # XXX don't think this is needed? result['title'] =", "float(plot.state.y_max)]) # XXX log scales return result def save_histogram(plot, index): \"\"\" Convert a", "src=\"http://d3po.org/static/js/d3po.js\"></script> <script src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head> <body> <div id=\"svg\"><svg></svg></div> <div id=\"controls\"> <ul class=\"navigation\"> </ul> </div>", "of subsets \"\"\" from astropy.table import Table, Column data_path = os.path.join(path, 'data.csv') t", "import absolute_import, division, print_function import os import json from glue.core import Subset DISPATCH", "index: int :rtype: json-serializable dict \"\"\" result = save_plot_base(plot, index) result['type'] = 'histogram'", "Glue appication to save :param path: Path to directory to save in. Will", "# XXX don't think this is needed? result['title'] = \"Glue export of %s\"", "tuple(result) def can_save_d3po(application): \"\"\" Check whether an application can be exported to D3PO.", "plots\") if sum(len(tab) for tab in application.viewers) == 0: raise ValueError(\"D3PO Export requires", "file, given Data and tuple of subsets \"\"\" from astropy.table import Table, Column", "\"\"\" Check whether an application can be exported to D3PO. Raises an exception", "application.tab_names, subsets)) state_path = os.path.join(path, 'states.json') with open(state_path, 'w') as outfile: json.dump(result, outfile,", "% PORT) def setup(): from glue.config import exporters exporters.add('D3PO', save_d3po, can_save_d3po, outmode='directory') HTML", "import ScatterViewer from glue.viewers.histogram.qt import HistogramViewer except ImportError: pass else: DISPATCH[ScatterViewer] = save_scatter", "json-serializable dict \"\"\" result = save_plot_base(plot, index) result['type'] = 'scatter' result['xAxis'] = dict(columnName=plot.state.x_att.label,", "<ul class=\"navigation\"> </ul> </div> <div id=\"caption\"></div> <div id=\"footer\"> More information: <a href=\"http://d3po.org\">d3po.org</a> </div>", "no subset If more than one subset is used per stage/tab, returns None", "pass print('Serving D3PO on port 0.0.0.0:%i' % PORT) server.server_activate() thread = Thread(target=server.serve_forever) thread.setDaemon(True)", "not None: s = subset.style selected = dict(opacity=s.alpha, size=s.markersize / 2, color=s.color) result['markerStyle']['selected']", "Glue scatter plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param index: 1D index of plot on the page", "def save_page(page, page_number, label, subset): \"\"\" Convert a tab of a glue session", ":type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer` :param index: 1D index of plot on the page :type", "sum(len(tab) for tab in application.viewers) == 0: raise ValueError(\"D3PO Export requires at least", "os.path.join(path, 'index.html') with open(html_path, 'w') as outfile: outfile.write(HTML) # show the result if", "If more than one subset is used per stage/tab, returns None \"\"\" result", "histogram :type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer` :param index: 1D index of plot on the page", "size=s.markersize / 2, color=s.color) result['markerStyle']['selected'] = selected result['selection'] = {'type': 'booleanColumn', 'columnName': 'selection_%i'", "0 or 1 subsets visible \" \"in each tab\") def make_data_file(data, subsets, path):", ":param path: Path to directory to save in. Will be created if needed", "isinstance(s, Subset): continue if subset is not None and s is not subset:", "= {} def save_page(page, page_number, label, subset): \"\"\" Convert a tab of a", "least one scatterplot \" \"or histogram\") if stage_subsets(application) is None: raise ValueError(\"D3PO Export", "dataset\") for tab in application.viewers: for viewer in tab: if not isinstance(viewer, tuple(DISPATCH.keys())):", "result['histogramStyle'] = result['markerStyle'] # save each plot result['plots'] = list(map(save_plot, page, range(len(page)))) return", "each plot result['plots'] = list(map(save_plot, page, range(len(page)))) return result def save_plot_base(plot, index): result", "bottom: 0; right: 0; } </style> <!-- not to be confused with Planet", "an exported D3PO bundle, and open a browser. :param path: The TLD of", "<div id=\"controls\"> <ul class=\"navigation\"> </ul> </div> <div id=\"caption\"></div> <div id=\"footer\"> More information: <a", "is needed? result['title'] = \"Glue export of %s\" % data.label result['states'] = list(map(save_page,", "subsets, path) # states.json result = {} result['filename'] = 'data.csv' # XXX don't", ":rtype: json-serializable dict \"\"\" result = save_plot_base(plot, index) result['type'] = 'histogram' result['xAxis'] =", "confused with Planet Telex --> <!-- Javscript dependencies --> <script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script> <script", "# do not prevent shutdown thread.start() webbrowser.open('http://0.0.0.0:%i' % PORT) def setup(): from glue.config", "each stage/tab, or None if the tab has no subset If more than", "single dataset\") for tab in application.viewers: for viewer in tab: if not isinstance(viewer,", "range=[float(plot.state.x_min), float(plot.state.x_max)]) result['yAxis'] = dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min), float(plot.state.y_max)]) # XXX log scales return result", "\"\"\" from astropy.table import Table, Column data_path = os.path.join(path, 'data.csv') t = Table([data[c]", "import TCPServer from glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler from random import randrange from socket import", "a D3PO bundle. Currently, this has the following restrictions: - The Glue session", "Column data_path = os.path.join(path, 'data.csv') t = Table([data[c] for c in data.components], names=[c.label", "<script src=\"http://d3po.org/static/js/util.js\"></script> <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script src=\"http://d3po.org/static/js/d3po.js\"></script> <script src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head> <body> <div id=\"svg\"><svg></svg></div> <div", "exported D3PO bundle, and open a browser. :param path: The TLD of the", "return result def save_plot_base(plot, index): result = {} result['gridPosition'] = [0, index] return", "c = Column(data=subset.to_mask().astype('i'), name='selection_%i' % i) t.add_column(c) t.write(data_path, format='ascii', delimiter=',') def save_d3po(application, path,", "= subset.style selected = dict(opacity=s.alpha, size=s.markersize / 2, color=s.color) result['markerStyle']['selected'] = selected result['selection']", "directory to save in. Will be created if needed \"\"\" if os.path.exists(path) and", "while True: try: PORT = randrange(8000, 9000) server = TCPServer((\"\", PORT), SimpleHTTPRequestHandler, False)", "1 subsets visible \" \"in each tab\") def make_data_file(data, subsets, path): \"\"\" Create", "<div id=\"caption\"></div> <div id=\"footer\"> More information: <a href=\"http://d3po.org\">d3po.org</a> </div> <script type=\"text/javascript\"> $(document).ready(function() {", "port 0.0.0.0:%i' % PORT) server.server_activate() thread = Thread(target=server.serve_forever) thread.setDaemon(True) # do not prevent", "used per stage/tab, returns None \"\"\" result = [] for page in application.viewers:", "index) def save_scatter(plot, index): \"\"\" Convert a single glue scatter plot to a", "dc = application.session.data_collection if len(dc) != 1: raise ValueError(\"D3PO Export only supports a", "application.viewers) == 0: raise ValueError(\"D3PO Export requires at least one scatterplot \" \"or", "or 1 subsets visible \" \"in each tab\") def make_data_file(data, subsets, path): \"\"\"", "to save in. Will be created if needed \"\"\" if os.path.exists(path) and not", "bundle, and open a browser. :param path: The TLD of the bundle \"\"\"", "subset: return None if subset is None: subset = s result.append(subset) return tuple(result)", "= list(map(save_plot, page, range(len(page)))) return result def save_plot_base(plot, index): result = {} result['gridPosition']", "this is needed? result['title'] = \"Glue export of %s\" % data.label result['states'] =", "= TCPServer((\"\", PORT), SimpleHTTPRequestHandler, False) server.allow_reuse_address = True server.server_bind() break except error: #", "Convert a single glue scatter plot to a D3PO plot :param plot: Glue", "True server.server_bind() break except error: # port already taken pass print('Serving D3PO on", "t = Table([data[c] for c in data.components], names=[c.label for c in data.components]) for", "'scatter' result['xAxis'] = dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min), float(plot.state.x_max)]) result['yAxis'] = dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min), float(plot.state.y_max)]) # XXX", "result['type'] = 'scatter' result['xAxis'] = dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min), float(plot.state.x_max)]) result['yAxis'] = dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min), float(plot.state.y_max)])", "import webbrowser from threading import Thread os.chdir(path) while True: try: PORT = randrange(8000,", "1: raise ValueError(\"D3PO Export only supports a single dataset\") for tab in application.viewers:", "plot result['plots'] = list(map(save_plot, page, range(len(page)))) return result def save_plot_base(plot, index): result =", "Path to directory to save in. Will be created if needed \"\"\" if", "# show the result if launch: launch_d3po(path) def launch_d3po(path): \"\"\"Start a server to", "server.server_bind() break except error: # port already taken pass print('Serving D3PO on port", "state_path = os.path.join(path, 'states.json') with open(state_path, 'w') as outfile: json.dump(result, outfile, indent=2, sort_keys=True)", "DISPATCH[typ](plot, index) def save_scatter(plot, index): \"\"\" Convert a single glue scatter plot to", "\" \"and histogram plots\") if sum(len(tab) for tab in application.viewers) == 0: raise", "per stage/tab, returns None \"\"\" result = [] for page in application.viewers: subset", "os.path.join(path, 'states.json') with open(state_path, 'w') as outfile: json.dump(result, outfile, indent=2, sort_keys=True) # index.html", "} ); </script> </body> </html> \"\"\" try: from glue.viewers.scatter.qt import ScatterViewer from glue.viewers.histogram.qt", "histogram to a D3PO plot :param plot: Glue histogram :type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer` :param", "% page_number} result['histogramStyle'] = result['markerStyle'] # save each plot result['plots'] = list(map(save_plot, page,", "selected result['selection'] = {'type': 'booleanColumn', 'columnName': 'selection_%i' % page_number} result['histogramStyle'] = result['markerStyle'] #", "= os.path.join(path, 'states.json') with open(state_path, 'w') as outfile: json.dump(result, outfile, indent=2, sort_keys=True) #", "open a browser. :param path: The TLD of the bundle \"\"\" from glue.external.six.moves.socketserver", "ValueError(\"D3PO Export requires at least one scatterplot \" \"or histogram\") if stage_subsets(application) is", "{ position: fixed; bottom: 0; right: 0; } </style> <!-- not to be", "None for viewer in page: for layer_artist in viewer.layers: if not layer_artist.visible: continue", "server.allow_reuse_address = True server.server_bind() break except error: # port already taken pass print('Serving", ":param path: The TLD of the bundle \"\"\" from glue.external.six.moves.socketserver import TCPServer from", "present :param application: Glue appication to save :param path: Path to directory to", "\"\"\" dc = application.session.data_collection if len(dc) != 1: raise ValueError(\"D3PO Export only supports", "index.html html_path = os.path.join(path, 'index.html') with open(html_path, 'w') as outfile: outfile.write(HTML) # show", "is not None: s = subset.style selected = dict(opacity=s.alpha, size=s.markersize / 2, color=s.color)", "be confused with Planet Telex --> <!-- Javscript dependencies --> <script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script>", "= 'histogram' result['xAxis'] = dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)]) # XXX normed, cumultive, log", "glue.viewers.histogram.qt import HistogramViewer except ImportError: pass else: DISPATCH[ScatterViewer] = save_scatter DISPATCH[HistogramViewer] = save_histogram", "= result['markerStyle'] # save each plot result['plots'] = list(map(save_plot, page, range(len(page)))) return result", "'histogram' result['xAxis'] = dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)]) # XXX normed, cumultive, log return", "return result def save_histogram(plot, index): \"\"\" Convert a single histogram to a D3PO", "\"\"\" from glue.external.six.moves.socketserver import TCPServer from glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler from random import randrange", "D3PO plot :param plot: Glue histogram :type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer` :param index: 1D index", "dataset open, and 0 or 1 subsets - Only scatter plots or histograms", "for layer_artist in viewer.layers: if not layer_artist.visible: continue s = layer_artist.layer if not", "= [0, index] return result def save_plot(plot, index): typ = type(plot) return DISPATCH[typ](plot,", "an exception if not \"\"\" dc = application.session.data_collection if len(dc) != 1: raise", "outfile: json.dump(result, outfile, indent=2, sort_keys=True) # index.html html_path = os.path.join(path, 'index.html') with open(html_path,", "server = TCPServer((\"\", PORT), SimpleHTTPRequestHandler, False) server.allow_reuse_address = True server.server_bind() break except error:", "XXX normed, cumultive, log return result def stage_subsets(application): \"\"\" Return a tuple of", "a glue session into a D3PO page :param page: Tuple of data viewers", "{} # layout settings result['grid'] = {'nRows': 1, 'nColumns': len(page)} result['name'] = str(label)", "t.add_column(c) t.write(data_path, format='ascii', delimiter=',') def save_d3po(application, path, launch=True): \"\"\"Save a Glue session to", "application.viewers: subset = None for viewer in page: for layer_artist in viewer.layers: if", "list(map(save_page, application.viewers, range(len(viewers)), application.tab_names, subsets)) state_path = os.path.join(path, 'states.json') with open(state_path, 'w') as", "result['grid'] = {'nRows': 1, 'nColumns': len(page)} result['name'] = str(label) result['caption'] = 'Generated by", "'w') as outfile: outfile.write(HTML) # show the result if launch: launch_d3po(path) def launch_d3po(path):", "os.path.exists(path): os.mkdir(path) data = application.session.data_collection[0] subsets = stage_subsets(application) viewers = application.viewers # data.csv", "has no subset If more than one subset is used per stage/tab, returns", "More information: <a href=\"http://d3po.org\">d3po.org</a> </div> <script type=\"text/javascript\"> $(document).ready(function() { initialize('states.json', 'data.csv'); } );", "is None: raise ValueError(\"D3PO Export restricted to 0 or 1 subsets visible \"", "Currently, this has the following restrictions: - The Glue session must have only", "d = page[0]._data[0] unselected = dict(opacity=d.style.alpha, size=d.style.markersize / 2, color=d.style.color) result['markerStyle'] = dict(unselected=unselected)", "color=d.style.color) result['markerStyle'] = dict(unselected=unselected) if subset is not None: s = subset.style selected", "save_histogram(plot, index): \"\"\" Convert a single histogram to a D3PO plot :param plot:", "class=\"navigation\"> </ul> </div> <div id=\"caption\"></div> <div id=\"footer\"> More information: <a href=\"http://d3po.org\">d3po.org</a> </div> <script", "plot is present :param application: Glue appication to save :param path: Path to", "/ 2, color=s.color) result['markerStyle']['selected'] = selected result['selection'] = {'type': 'booleanColumn', 'columnName': 'selection_%i' %", "index: 1D index of plot on the page :type index: int :rtype: json-serializable", "of the bundle \"\"\" from glue.external.six.moves.socketserver import TCPServer from glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler from", "SimpleHTTPRequestHandler from random import randrange from socket import error import webbrowser from threading", "application: Glue appication to save :param path: Path to directory to save in.", "not os.path.isdir(path): os.unlink(path) if not os.path.exists(path): os.mkdir(path) data = application.session.data_collection[0] subsets = stage_subsets(application)", "or None if the tab has no subset If more than one subset", "i) t.add_column(c) t.write(data_path, format='ascii', delimiter=',') def save_d3po(application, path, launch=True): \"\"\"Save a Glue session", "page :type index: int :rtype: json-serializable dict \"\"\" result = save_plot_base(plot, index) result['type']", "subset is not None and s is not subset: return None if subset", "Convert a single histogram to a D3PO plot :param plot: Glue histogram :type", "in data.components], names=[c.label for c in data.components]) for i, subset in enumerate(subsets): if", "fixed; bottom: 0; right: 0; } </style> <!-- not to be confused with", "Telex --> <!-- Javscript dependencies --> <script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script> <script src=\"http://d3po.org/static/js/util.js\"></script> <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script>", "initialize('states.json', 'data.csv'); } ); </script> </body> </html> \"\"\" try: from glue.viewers.scatter.qt import ScatterViewer", "= dict(opacity=s.alpha, size=s.markersize / 2, color=s.color) result['markerStyle']['selected'] = selected result['selection'] = {'type': 'booleanColumn',", "launch_d3po(path) def launch_d3po(path): \"\"\"Start a server to view an exported D3PO bundle, and", "result['xAxis'] = dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min), float(plot.state.x_max)]) result['yAxis'] = dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min), float(plot.state.y_max)]) # XXX log", "scatter \" \"and histogram plots\") if sum(len(tab) for tab in application.viewers) == 0:", "single glue scatter plot to a D3PO plot :param plot: Glue scatter plot", "a single dataset\") for tab in application.viewers: for viewer in tab: if not", "<!DOCTYPE html> <html> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/style.css\"> <link rel=\"stylesheet\"", "0: raise ValueError(\"D3PO Export requires at least one scatterplot \" \"or histogram\") if", "= type(plot) return DISPATCH[typ](plot, index) def save_scatter(plot, index): \"\"\" Convert a single glue", "for tab in application.viewers) == 0: raise ValueError(\"D3PO Export requires at least one", "import os import json from glue.core import Subset DISPATCH = {} def save_page(page,", "= str(label) result['caption'] = 'Generated by Glue' # style settings d = page[0]._data[0]", "result['gridPosition'] = [0, index] return result def save_plot(plot, index): typ = type(plot) return", "to be confused with Planet Telex --> <!-- Javscript dependencies --> <script src=\"http://d3js.org/d3.v3.min.js\"", "int :rtype: json-serializable dict \"\"\" result = save_plot_base(plot, index) result['type'] = 'histogram' result['xAxis']", "if stage_subsets(application) is None: raise ValueError(\"D3PO Export restricted to 0 or 1 subsets", "with Planet Telex --> <!-- Javscript dependencies --> <script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script> <script src=\"http://d3po.org/static/js/util.js\"></script>", "application can be exported to D3PO. Raises an exception if not \"\"\" dc", "layer_artist.layer if not isinstance(s, Subset): continue if subset is not None and s", "subset to use for each stage/tab, or None if the tab has no", "Glue session must have only one dataset open, and 0 or 1 subsets", "); </script> </body> </html> \"\"\" try: from glue.viewers.scatter.qt import ScatterViewer from glue.viewers.histogram.qt import", "into a D3PO page :param page: Tuple of data viewers to save :param", "settings d = page[0]._data[0] unselected = dict(opacity=d.style.alpha, size=d.style.markersize / 2, color=d.style.color) result['markerStyle'] =", "be created if needed \"\"\" if os.path.exists(path) and not os.path.isdir(path): os.unlink(path) if not", "TCPServer((\"\", PORT), SimpleHTTPRequestHandler, False) server.allow_reuse_address = True server.server_bind() break except error: # port", "to D3PO. Raises an exception if not \"\"\" dc = application.session.data_collection if len(dc)", "<div id=\"svg\"><svg></svg></div> <div id=\"controls\"> <ul class=\"navigation\"> </ul> </div> <div id=\"caption\"></div> <div id=\"footer\"> More", "indent=2, sort_keys=True) # index.html html_path = os.path.join(path, 'index.html') with open(html_path, 'w') as outfile:", "at least one scatterplot \" \"or histogram\") if stage_subsets(application) is None: raise ValueError(\"D3PO", "int :rtype: json-serializable dict \"\"\" result = save_plot_base(plot, index) result['type'] = 'scatter' result['xAxis']", "</div> <div id=\"caption\"></div> <div id=\"footer\"> More information: <a href=\"http://d3po.org\">d3po.org</a> </div> <script type=\"text/javascript\"> $(document).ready(function()", "absolute_import, division, print_function import os import json from glue.core import Subset DISPATCH =", "- Only scatter plots or histograms are present - At least one plot", "result = {} # layout settings result['grid'] = {'nRows': 1, 'nColumns': len(page)} result['name']", "plot: Glue scatter plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param index: 1D index of plot on the", "is None: subset = s result.append(subset) return tuple(result) def can_save_d3po(application): \"\"\" Check whether", "needed \"\"\" if os.path.exists(path) and not os.path.isdir(path): os.unlink(path) if not os.path.exists(path): os.mkdir(path) data", "subset is not None: s = subset.style selected = dict(opacity=s.alpha, size=s.markersize / 2,", "on port 0.0.0.0:%i' % PORT) server.server_activate() thread = Thread(target=server.serve_forever) thread.setDaemon(True) # do not", "in application.viewers: for viewer in tab: if not isinstance(viewer, tuple(DISPATCH.keys())): raise ValueError(\"D3PO Export", ":param page: Tuple of data viewers to save :param label: Tab label \"\"\"", "href=\"http://d3po.org/static/css/d3po.css\"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'> <style> #footer { position: fixed; bottom: 0; right:", "page_number} result['histogramStyle'] = result['markerStyle'] # save each plot result['plots'] = list(map(save_plot, page, range(len(page))))", "s result.append(subset) return tuple(result) def can_save_d3po(application): \"\"\" Check whether an application can be", "for c in data.components], names=[c.label for c in data.components]) for i, subset in", "socket import error import webbrowser from threading import Thread os.chdir(path) while True: try:", "</ul> </div> <div id=\"caption\"></div> <div id=\"footer\"> More information: <a href=\"http://d3po.org\">d3po.org</a> </div> <script type=\"text/javascript\">", "if subset is not None and s is not subset: return None if", "glue scatter plot to a D3PO plot :param plot: Glue scatter plot :class:`~glue.viewers.scatter.qt.ScatterViewer`", "= {'type': 'booleanColumn', 'columnName': 'selection_%i' % page_number} result['histogramStyle'] = result['markerStyle'] # save each", "plot :param plot: Glue scatter plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param index: 1D index of plot", "stage/tab, or None if the tab has no subset If more than one", "return DISPATCH[typ](plot, index) def save_scatter(plot, index): \"\"\" Convert a single glue scatter plot", "one plot is present :param application: Glue appication to save :param path: Path", "# index.html html_path = os.path.join(path, 'index.html') with open(html_path, 'w') as outfile: outfile.write(HTML) #", "href=\"http://d3po.org\">d3po.org</a> </div> <script type=\"text/javascript\"> $(document).ready(function() { initialize('states.json', 'data.csv'); } ); </script> </body> </html>", "on the page :type index: int :rtype: json-serializable dict \"\"\" result = save_plot_base(plot,", "{} def save_page(page, page_number, label, subset): \"\"\" Convert a tab of a glue", "the data.csv file, given Data and tuple of subsets \"\"\" from astropy.table import", "from random import randrange from socket import error import webbrowser from threading import", "Javscript dependencies --> <script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script> <script src=\"http://d3po.org/static/js/util.js\"></script> <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script src=\"http://d3po.org/static/js/d3po.js\"></script> <script", "be exported to D3PO. Raises an exception if not \"\"\" dc = application.session.data_collection", "to 0 or 1 subsets visible \" \"in each tab\") def make_data_file(data, subsets,", "result = save_plot_base(plot, index) result['type'] = 'scatter' result['xAxis'] = dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min), float(plot.state.x_max)]) result['yAxis']", "False) server.allow_reuse_address = True server.server_bind() break except error: # port already taken pass", "if subset is not None: s = subset.style selected = dict(opacity=s.alpha, size=s.markersize /", "} </style> <!-- not to be confused with Planet Telex --> <!-- Javscript", "9000) server = TCPServer((\"\", PORT), SimpleHTTPRequestHandler, False) server.allow_reuse_address = True server.server_bind() break except", "states.json result = {} result['filename'] = 'data.csv' # XXX don't think this is", "only supports scatter \" \"and histogram plots\") if sum(len(tab) for tab in application.viewers)", "json.dump(result, outfile, indent=2, sort_keys=True) # index.html html_path = os.path.join(path, 'index.html') with open(html_path, 'w')", "</script> </body> </html> \"\"\" try: from glue.viewers.scatter.qt import ScatterViewer from glue.viewers.histogram.qt import HistogramViewer", "# style settings d = page[0]._data[0] unselected = dict(opacity=d.style.alpha, size=d.style.markersize / 2, color=d.style.color)", "subset = s result.append(subset) return tuple(result) def can_save_d3po(application): \"\"\" Check whether an application", "id=\"caption\"></div> <div id=\"footer\"> More information: <a href=\"http://d3po.org\">d3po.org</a> </div> <script type=\"text/javascript\"> $(document).ready(function() { initialize('states.json',", "viewer in page: for layer_artist in viewer.layers: if not layer_artist.visible: continue s =", "by Glue' # style settings d = page[0]._data[0] unselected = dict(opacity=d.style.alpha, size=d.style.markersize /", "'index.html') with open(html_path, 'w') as outfile: outfile.write(HTML) # show the result if launch:", "created if needed \"\"\" if os.path.exists(path) and not os.path.isdir(path): os.unlink(path) if not os.path.exists(path):", "outfile: outfile.write(HTML) # show the result if launch: launch_d3po(path) def launch_d3po(path): \"\"\"Start a", "launch=True): \"\"\"Save a Glue session to a D3PO bundle. Currently, this has the", "{} result['gridPosition'] = [0, index] return result def save_plot(plot, index): typ = type(plot)", "viewer.layers: if not layer_artist.visible: continue s = layer_artist.layer if not isinstance(s, Subset): continue", "server to view an exported D3PO bundle, and open a browser. :param path:", "\"\"\" Convert a tab of a glue session into a D3PO page :param", "plot :param plot: Glue histogram :type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer` :param index: 1D index of", "id=\"controls\"> <ul class=\"navigation\"> </ul> </div> <div id=\"caption\"></div> <div id=\"footer\"> More information: <a href=\"http://d3po.org\">d3po.org</a>", ":type index: int :rtype: json-serializable dict \"\"\" result = save_plot_base(plot, index) result['type'] =", "plots or histograms are present - At least one plot is present :param", "supports scatter \" \"and histogram plots\") if sum(len(tab) for tab in application.viewers) ==", "index of plot on the page :type index: int :rtype: json-serializable dict \"\"\"", "from socket import error import webbrowser from threading import Thread os.chdir(path) while True:", "page in application.viewers: subset = None for viewer in page: for layer_artist in", "\" \"or histogram\") if stage_subsets(application) is None: raise ValueError(\"D3PO Export restricted to 0", "isinstance(viewer, tuple(DISPATCH.keys())): raise ValueError(\"D3PO Export only supports scatter \" \"and histogram plots\") if", "\"\"\" result = save_plot_base(plot, index) result['type'] = 'histogram' result['xAxis'] = dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min),", "def save_histogram(plot, index): \"\"\" Convert a single histogram to a D3PO plot :param", "0; right: 0; } </style> <!-- not to be confused with Planet Telex", "Subset DISPATCH = {} def save_page(page, page_number, label, subset): \"\"\" Convert a tab", "len(page)} result['name'] = str(label) result['caption'] = 'Generated by Glue' # style settings d", "'states.json') with open(state_path, 'w') as outfile: json.dump(result, outfile, indent=2, sort_keys=True) # index.html html_path", "histogram plots\") if sum(len(tab) for tab in application.viewers) == 0: raise ValueError(\"D3PO Export", "as outfile: outfile.write(HTML) # show the result if launch: launch_d3po(path) def launch_d3po(path): \"\"\"Start", "ValueError(\"D3PO Export only supports a single dataset\") for tab in application.viewers: for viewer", "i, subset in enumerate(subsets): if subset is None: continue c = Column(data=subset.to_mask().astype('i'), name='selection_%i'", "D3PO plot :param plot: Glue scatter plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param index: 1D index of", "result['name'] = str(label) result['caption'] = 'Generated by Glue' # style settings d =", "Tab label \"\"\" result = {} # layout settings result['grid'] = {'nRows': 1,", "Export only supports scatter \" \"and histogram plots\") if sum(len(tab) for tab in", "src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script src=\"http://d3po.org/static/js/d3po.js\"></script> <script src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head> <body> <div id=\"svg\"><svg></svg></div> <div id=\"controls\"> <ul class=\"navigation\">", "result['caption'] = 'Generated by Glue' # style settings d = page[0]._data[0] unselected =", "type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'> <style> #footer { position: fixed; bottom: 0;", "a tuple of the subset to use for each stage/tab, or None if", "# XXX normed, cumultive, log return result def stage_subsets(application): \"\"\" Return a tuple", "stage_subsets(application) viewers = application.viewers # data.csv make_data_file(data, subsets, path) # states.json result =", "\"\"\" result = {} # layout settings result['grid'] = {'nRows': 1, 'nColumns': len(page)}", ":class:`~glue.viewers.histogram.qt.HistogramViewer` :param index: 1D index of plot on the page :type index: int", "return tuple(result) def can_save_d3po(application): \"\"\" Check whether an application can be exported to", "not prevent shutdown thread.start() webbrowser.open('http://0.0.0.0:%i' % PORT) def setup(): from glue.config import exporters", "with open(html_path, 'w') as outfile: outfile.write(HTML) # show the result if launch: launch_d3po(path)", "save :param label: Tab label \"\"\" result = {} # layout settings result['grid']", "page_number, label, subset): \"\"\" Convert a tab of a glue session into a", "subsets = stage_subsets(application) viewers = application.viewers # data.csv make_data_file(data, subsets, path) # states.json", "for page in application.viewers: subset = None for viewer in page: for layer_artist", "path) # states.json result = {} result['filename'] = 'data.csv' # XXX don't think", "= selected result['selection'] = {'type': 'booleanColumn', 'columnName': 'selection_%i' % page_number} result['histogramStyle'] = result['markerStyle']", "an application can be exported to D3PO. Raises an exception if not \"\"\"", "= application.viewers # data.csv make_data_file(data, subsets, path) # states.json result = {} result['filename']", "- At least one plot is present :param application: Glue appication to save", "dict \"\"\" result = save_plot_base(plot, index) result['type'] = 'histogram' result['xAxis'] = dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin),", "def save_scatter(plot, index): \"\"\" Convert a single glue scatter plot to a D3PO", "of data viewers to save :param label: Tab label \"\"\" result = {}", "{'nRows': 1, 'nColumns': len(page)} result['name'] = str(label) result['caption'] = 'Generated by Glue' #", "page[0]._data[0] unselected = dict(opacity=d.style.alpha, size=d.style.markersize / 2, color=d.style.color) result['markerStyle'] = dict(unselected=unselected) if subset", "'data.csv') t = Table([data[c] for c in data.components], names=[c.label for c in data.components])", "tuple of subsets \"\"\" from astropy.table import Table, Column data_path = os.path.join(path, 'data.csv')", "\"\"\" if os.path.exists(path) and not os.path.isdir(path): os.unlink(path) if not os.path.exists(path): os.mkdir(path) data =", "At least one plot is present :param application: Glue appication to save :param", "break except error: # port already taken pass print('Serving D3PO on port 0.0.0.0:%i'", "Export requires at least one scatterplot \" \"or histogram\") if stage_subsets(application) is None:", "</div> <script type=\"text/javascript\"> $(document).ready(function() { initialize('states.json', 'data.csv'); } ); </script> </body> </html> \"\"\"", "normed, cumultive, log return result def stage_subsets(application): \"\"\" Return a tuple of the", "subsets visible \" \"in each tab\") def make_data_file(data, subsets, path): \"\"\" Create the", "import json from glue.core import Subset DISPATCH = {} def save_page(page, page_number, label,", "from glue.viewers.scatter.qt import ScatterViewer from glue.viewers.histogram.qt import HistogramViewer except ImportError: pass else: DISPATCH[ScatterViewer]", "astropy.table import Table, Column data_path = os.path.join(path, 'data.csv') t = Table([data[c] for c", "float(plot.state.x_max)]) result['yAxis'] = dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min), float(plot.state.y_max)]) # XXX log scales return result def", "os.mkdir(path) data = application.session.data_collection[0] subsets = stage_subsets(application) viewers = application.viewers # data.csv make_data_file(data,", "Table([data[c] for c in data.components], names=[c.label for c in data.components]) for i, subset", "information: <a href=\"http://d3po.org\">d3po.org</a> </div> <script type=\"text/javascript\"> $(document).ready(function() { initialize('states.json', 'data.csv'); } ); </script>", "open, and 0 or 1 subsets - Only scatter plots or histograms are", "the page :type index: int :rtype: json-serializable dict \"\"\" result = save_plot_base(plot, index)", "path, launch=True): \"\"\"Save a Glue session to a D3PO bundle. Currently, this has", "and 0 or 1 subsets - Only scatter plots or histograms are present", "and s is not subset: return None if subset is None: subset =", "data.label result['states'] = list(map(save_page, application.viewers, range(len(viewers)), application.tab_names, subsets)) state_path = os.path.join(path, 'states.json') with", "D3PO page :param page: Tuple of data viewers to save :param label: Tab", "of plot on the page :type index: int :rtype: json-serializable dict \"\"\" result", "os.path.exists(path) and not os.path.isdir(path): os.unlink(path) if not os.path.exists(path): os.mkdir(path) data = application.session.data_collection[0] subsets", "0.0.0.0:%i' % PORT) server.server_activate() thread = Thread(target=server.serve_forever) thread.setDaemon(True) # do not prevent shutdown", "or histograms are present - At least one plot is present :param application:", "Planet Telex --> <!-- Javscript dependencies --> <script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script> <script src=\"http://d3po.org/static/js/util.js\"></script> <script", "id=\"footer\"> More information: <a href=\"http://d3po.org\">d3po.org</a> </div> <script type=\"text/javascript\"> $(document).ready(function() { initialize('states.json', 'data.csv'); }", "if not layer_artist.visible: continue s = layer_artist.layer if not isinstance(s, Subset): continue if", "outfile.write(HTML) # show the result if launch: launch_d3po(path) def launch_d3po(path): \"\"\"Start a server", "subsets \"\"\" from astropy.table import Table, Column data_path = os.path.join(path, 'data.csv') t =", "1, 'nColumns': len(page)} result['name'] = str(label) result['caption'] = 'Generated by Glue' # style", "id=\"svg\"><svg></svg></div> <div id=\"controls\"> <ul class=\"navigation\"> </ul> </div> <div id=\"caption\"></div> <div id=\"footer\"> More information:", "save each plot result['plots'] = list(map(save_plot, page, range(len(page)))) return result def save_plot_base(plot, index):", "subsets, path): \"\"\" Create the data.csv file, given Data and tuple of subsets", "to use for each stage/tab, or None if the tab has no subset", "Export restricted to 0 or 1 subsets visible \" \"in each tab\") def", "to save :param label: Tab label \"\"\" result = {} # layout settings", "format='ascii', delimiter=',') def save_d3po(application, path, launch=True): \"\"\"Save a Glue session to a D3PO", "def save_plot_base(plot, index): result = {} result['gridPosition'] = [0, index] return result def", "more than one subset is used per stage/tab, returns None \"\"\" result =", "rel='stylesheet' type='text/css'> <style> #footer { position: fixed; bottom: 0; right: 0; } </style>", "[] for page in application.viewers: subset = None for viewer in page: for", "from glue.viewers.histogram.qt import HistogramViewer except ImportError: pass else: DISPATCH[ScatterViewer] = save_scatter DISPATCH[HistogramViewer] =", "Column(data=subset.to_mask().astype('i'), name='selection_%i' % i) t.add_column(c) t.write(data_path, format='ascii', delimiter=',') def save_d3po(application, path, launch=True): \"\"\"Save", "histograms are present - At least one plot is present :param application: Glue", "tab: if not isinstance(viewer, tuple(DISPATCH.keys())): raise ValueError(\"D3PO Export only supports scatter \" \"and", "restrictions: - The Glue session must have only one dataset open, and 0", "% data.label result['states'] = list(map(save_page, application.viewers, range(len(viewers)), application.tab_names, subsets)) state_path = os.path.join(path, 'states.json')", "PORT) def setup(): from glue.config import exporters exporters.add('D3PO', save_d3po, can_save_d3po, outmode='directory') HTML =", "dict(opacity=s.alpha, size=s.markersize / 2, color=s.color) result['markerStyle']['selected'] = selected result['selection'] = {'type': 'booleanColumn', 'columnName':", "are present - At least one plot is present :param application: Glue appication", "<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'> <style> #footer { position: fixed; bottom: 0; right: 0;", "settings result['grid'] = {'nRows': 1, 'nColumns': len(page)} result['name'] = str(label) result['caption'] = 'Generated", "def can_save_d3po(application): \"\"\" Check whether an application can be exported to D3PO. Raises", "returns None \"\"\" result = [] for page in application.viewers: subset = None", "<!-- Javscript dependencies --> <script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script> <script src=\"http://d3po.org/static/js/util.js\"></script> <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script src=\"http://d3po.org/static/js/d3po.js\"></script>", "\"\"\" Convert a single histogram to a D3PO plot :param plot: Glue histogram", "Glue histogram :type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer` :param index: 1D index of plot on the", "data.components], names=[c.label for c in data.components]) for i, subset in enumerate(subsets): if subset", "one dataset open, and 0 or 1 subsets - Only scatter plots or", "type='text/css'> <style> #footer { position: fixed; bottom: 0; right: 0; } </style> <!--", "webbrowser from threading import Thread os.chdir(path) while True: try: PORT = randrange(8000, 9000)", "can_save_d3po, outmode='directory') HTML = \"\"\" <!DOCTYPE html> <html> <head> <meta charset=\"utf-8\" /> <link", "open(state_path, 'w') as outfile: json.dump(result, outfile, indent=2, sort_keys=True) # index.html html_path = os.path.join(path,", "= dict(unselected=unselected) if subset is not None: s = subset.style selected = dict(opacity=s.alpha,", "make_data_file(data, subsets, path) # states.json result = {} result['filename'] = 'data.csv' # XXX", "continue c = Column(data=subset.to_mask().astype('i'), name='selection_%i' % i) t.add_column(c) t.write(data_path, format='ascii', delimiter=',') def save_d3po(application,", "save_plot_base(plot, index) result['type'] = 'histogram' result['xAxis'] = dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)]) # XXX", "plot: :class:`~glue.viewers.histogram.qt.HistogramViewer` :param index: 1D index of plot on the page :type index:", "if not os.path.exists(path): os.mkdir(path) data = application.session.data_collection[0] subsets = stage_subsets(application) viewers = application.viewers", "make_data_file(data, subsets, path): \"\"\" Create the data.csv file, given Data and tuple of", "import SimpleHTTPRequestHandler from random import randrange from socket import error import webbrowser from", "each tab\") def make_data_file(data, subsets, path): \"\"\" Create the data.csv file, given Data", "one scatterplot \" \"or histogram\") if stage_subsets(application) is None: raise ValueError(\"D3PO Export restricted", "try: from glue.viewers.scatter.qt import ScatterViewer from glue.viewers.histogram.qt import HistogramViewer except ImportError: pass else:", "DISPATCH = {} def save_page(page, page_number, label, subset): \"\"\" Convert a tab of", "c in data.components]) for i, subset in enumerate(subsets): if subset is None: continue", "tuple(DISPATCH.keys())): raise ValueError(\"D3PO Export only supports scatter \" \"and histogram plots\") if sum(len(tab)", "subset is None: continue c = Column(data=subset.to_mask().astype('i'), name='selection_%i' % i) t.add_column(c) t.write(data_path, format='ascii',", "for tab in application.viewers: for viewer in tab: if not isinstance(viewer, tuple(DISPATCH.keys())): raise", "'selection_%i' % page_number} result['histogramStyle'] = result['markerStyle'] # save each plot result['plots'] = list(map(save_plot,", "result def stage_subsets(application): \"\"\" Return a tuple of the subset to use for", "one subset is used per stage/tab, returns None \"\"\" result = [] for", "Table, Column data_path = os.path.join(path, 'data.csv') t = Table([data[c] for c in data.components],", "from glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler from random import randrange from socket import error import", ":param plot: Glue histogram :type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer` :param index: 1D index of plot", "s = layer_artist.layer if not isinstance(s, Subset): continue if subset is not None", "tab\") def make_data_file(data, subsets, path): \"\"\" Create the data.csv file, given Data and", "D3PO bundle, and open a browser. :param path: The TLD of the bundle", "result['markerStyle'] # save each plot result['plots'] = list(map(save_plot, page, range(len(page)))) return result def", "<body> <div id=\"svg\"><svg></svg></div> <div id=\"controls\"> <ul class=\"navigation\"> </ul> </div> <div id=\"caption\"></div> <div id=\"footer\">", "result['selection'] = {'type': 'booleanColumn', 'columnName': 'selection_%i' % page_number} result['histogramStyle'] = result['markerStyle'] # save", "shutdown thread.start() webbrowser.open('http://0.0.0.0:%i' % PORT) def setup(): from glue.config import exporters exporters.add('D3PO', save_d3po,", "the result if launch: launch_d3po(path) def launch_d3po(path): \"\"\"Start a server to view an", "if subset is None: subset = s result.append(subset) return tuple(result) def can_save_d3po(application): \"\"\"", "from __future__ import absolute_import, division, print_function import os import json from glue.core import", "subset.style selected = dict(opacity=s.alpha, size=s.markersize / 2, color=s.color) result['markerStyle']['selected'] = selected result['selection'] =", "session into a D3PO page :param page: Tuple of data viewers to save", "or 1 subsets - Only scatter plots or histograms are present - At", "def setup(): from glue.config import exporters exporters.add('D3PO', save_d3po, can_save_d3po, outmode='directory') HTML = \"\"\"", "randrange(8000, 9000) server = TCPServer((\"\", PORT), SimpleHTTPRequestHandler, False) server.allow_reuse_address = True server.server_bind() break", "= {} # layout settings result['grid'] = {'nRows': 1, 'nColumns': len(page)} result['name'] =", "needed? result['title'] = \"Glue export of %s\" % data.label result['states'] = list(map(save_page, application.viewers,", "rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'> <style> #footer { position: fixed; bottom:", "the bundle \"\"\" from glue.external.six.moves.socketserver import TCPServer from glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler from random", "threading import Thread os.chdir(path) while True: try: PORT = randrange(8000, 9000) server =", "% i) t.add_column(c) t.write(data_path, format='ascii', delimiter=',') def save_d3po(application, path, launch=True): \"\"\"Save a Glue", "can be exported to D3PO. Raises an exception if not \"\"\" dc =", "save_plot_base(plot, index): result = {} result['gridPosition'] = [0, index] return result def save_plot(plot,", "result.append(subset) return tuple(result) def can_save_d3po(application): \"\"\" Check whether an application can be exported", "result def save_histogram(plot, index): \"\"\" Convert a single histogram to a D3PO plot", "application.viewers: for viewer in tab: if not isinstance(viewer, tuple(DISPATCH.keys())): raise ValueError(\"D3PO Export only", "don't think this is needed? result['title'] = \"Glue export of %s\" % data.label", "save in. Will be created if needed \"\"\" if os.path.exists(path) and not os.path.isdir(path):", "dependencies --> <script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script> <script src=\"http://d3po.org/static/js/util.js\"></script> <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script src=\"http://d3po.org/static/js/d3po.js\"></script> <script src=\"http://d3po.org/static/js/d3po.init.js\"></script>", "selected = dict(opacity=s.alpha, size=s.markersize / 2, color=s.color) result['markerStyle']['selected'] = selected result['selection'] = {'type':", "type(plot) return DISPATCH[typ](plot, index) def save_scatter(plot, index): \"\"\" Convert a single glue scatter", "right: 0; } </style> <!-- not to be confused with Planet Telex -->", "already taken pass print('Serving D3PO on port 0.0.0.0:%i' % PORT) server.server_activate() thread =", "not subset: return None if subset is None: subset = s result.append(subset) return", "\"\"\" Convert a single glue scatter plot to a D3PO plot :param plot:", "\" \"in each tab\") def make_data_file(data, subsets, path): \"\"\" Create the data.csv file,", "src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script> <script src=\"http://d3po.org/static/js/util.js\"></script> <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script src=\"http://d3po.org/static/js/d3po.js\"></script> <script src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head> <body> <div", "Return a tuple of the subset to use for each stage/tab, or None", "is not None and s is not subset: return None if subset is", "save_d3po, can_save_d3po, outmode='directory') HTML = \"\"\" <!DOCTYPE html> <html> <head> <meta charset=\"utf-8\" />", "D3PO on port 0.0.0.0:%i' % PORT) server.server_activate() thread = Thread(target=server.serve_forever) thread.setDaemon(True) # do", ":class:`~glue.viewers.scatter.qt.ScatterViewer` :param index: 1D index of plot on the page :type index: int", "path): \"\"\" Create the data.csv file, given Data and tuple of subsets \"\"\"", "= randrange(8000, 9000) server = TCPServer((\"\", PORT), SimpleHTTPRequestHandler, False) server.allow_reuse_address = True server.server_bind()", "and open a browser. :param path: The TLD of the bundle \"\"\" from", "result = {} result['gridPosition'] = [0, index] return result def save_plot(plot, index): typ", "= {'nRows': 1, 'nColumns': len(page)} result['name'] = str(label) result['caption'] = 'Generated by Glue'", "TLD of the bundle \"\"\" from glue.external.six.moves.socketserver import TCPServer from glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler", "thread.start() webbrowser.open('http://0.0.0.0:%i' % PORT) def setup(): from glue.config import exporters exporters.add('D3PO', save_d3po, can_save_d3po,", "/> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/style.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'>", "def stage_subsets(application): \"\"\" Return a tuple of the subset to use for each", "Only scatter plots or histograms are present - At least one plot is", "taken pass print('Serving D3PO on port 0.0.0.0:%i' % PORT) server.server_activate() thread = Thread(target=server.serve_forever)", "<a href=\"http://d3po.org\">d3po.org</a> </div> <script type=\"text/javascript\"> $(document).ready(function() { initialize('states.json', 'data.csv'); } ); </script> </body>", "is present :param application: Glue appication to save :param path: Path to directory", "exporters exporters.add('D3PO', save_d3po, can_save_d3po, outmode='directory') HTML = \"\"\" <!DOCTYPE html> <html> <head> <meta", "= list(map(save_page, application.viewers, range(len(viewers)), application.tab_names, subsets)) state_path = os.path.join(path, 'states.json') with open(state_path, 'w')", "<html> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/style.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\">", "<style> #footer { position: fixed; bottom: 0; right: 0; } </style> <!-- not", "return result def save_plot(plot, index): typ = type(plot) return DISPATCH[typ](plot, index) def save_scatter(plot,", "bundle \"\"\" from glue.external.six.moves.socketserver import TCPServer from glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler from random import", "\"\"\"Save a Glue session to a D3PO bundle. Currently, this has the following", "label, subset): \"\"\" Convert a tab of a glue session into a D3PO", "show the result if launch: launch_d3po(path) def launch_d3po(path): \"\"\"Start a server to view", "viewer in tab: if not isinstance(viewer, tuple(DISPATCH.keys())): raise ValueError(\"D3PO Export only supports scatter", "$(document).ready(function() { initialize('states.json', 'data.csv'); } ); </script> </body> </html> \"\"\" try: from glue.viewers.scatter.qt", "to directory to save in. Will be created if needed \"\"\" if os.path.exists(path)", "dict \"\"\" result = save_plot_base(plot, index) result['type'] = 'scatter' result['xAxis'] = dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min),", "Subset): continue if subset is not None and s is not subset: return", "= dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)]) # XXX normed, cumultive, log return result def", "def launch_d3po(path): \"\"\"Start a server to view an exported D3PO bundle, and open", "in application.viewers) == 0: raise ValueError(\"D3PO Export requires at least one scatterplot \"", "Create the data.csv file, given Data and tuple of subsets \"\"\" from astropy.table", "s = subset.style selected = dict(opacity=s.alpha, size=s.markersize / 2, color=s.color) result['markerStyle']['selected'] = selected", "of a glue session into a D3PO page :param page: Tuple of data", "True: try: PORT = randrange(8000, 9000) server = TCPServer((\"\", PORT), SimpleHTTPRequestHandler, False) server.allow_reuse_address", "def save_plot(plot, index): typ = type(plot) return DISPATCH[typ](plot, index) def save_scatter(plot, index): \"\"\"", "glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler from random import randrange from socket import error import webbrowser", "Thread os.chdir(path) while True: try: PORT = randrange(8000, 9000) server = TCPServer((\"\", PORT),", "= application.session.data_collection[0] subsets = stage_subsets(application) viewers = application.viewers # data.csv make_data_file(data, subsets, path)", "<script src=\"http://d3po.org/static/js/d3po.js\"></script> <script src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head> <body> <div id=\"svg\"><svg></svg></div> <div id=\"controls\"> <ul class=\"navigation\"> </ul>", "in enumerate(subsets): if subset is None: continue c = Column(data=subset.to_mask().astype('i'), name='selection_%i' % i)", "style settings d = page[0]._data[0] unselected = dict(opacity=d.style.alpha, size=d.style.markersize / 2, color=d.style.color) result['markerStyle']", "index): \"\"\" Convert a single glue scatter plot to a D3PO plot :param", "None if the tab has no subset If more than one subset is", "open(html_path, 'w') as outfile: outfile.write(HTML) # show the result if launch: launch_d3po(path) def", "a single glue scatter plot to a D3PO plot :param plot: Glue scatter", "--> <!-- Javscript dependencies --> <script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script> <script src=\"http://d3po.org/static/js/util.js\"></script> <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script", "result['yAxis'] = dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min), float(plot.state.y_max)]) # XXX log scales return result def save_histogram(plot,", "not None and s is not subset: return None if subset is None:", "exception if not \"\"\" dc = application.session.data_collection if len(dc) != 1: raise ValueError(\"D3PO", "= True server.server_bind() break except error: # port already taken pass print('Serving D3PO", "supports a single dataset\") for tab in application.viewers: for viewer in tab: if", ":param label: Tab label \"\"\" result = {} # layout settings result['grid'] =", "a tab of a glue session into a D3PO page :param page: Tuple", "index] return result def save_plot(plot, index): typ = type(plot) return DISPATCH[typ](plot, index) def", "continue if subset is not None and s is not subset: return None", "not isinstance(s, Subset): continue if subset is not None and s is not", "data.csv file, given Data and tuple of subsets \"\"\" from astropy.table import Table,", "json from glue.core import Subset DISPATCH = {} def save_page(page, page_number, label, subset):", "present - At least one plot is present :param application: Glue appication to", "page :param page: Tuple of data viewers to save :param label: Tab label", "= \"\"\" <!DOCTYPE html> <html> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/style.css\">", "page, range(len(page)))) return result def save_plot_base(plot, index): result = {} result['gridPosition'] = [0,", "result['xAxis'] = dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)]) # XXX normed, cumultive, log return result", "in page: for layer_artist in viewer.layers: if not layer_artist.visible: continue s = layer_artist.layer", "Convert a tab of a glue session into a D3PO page :param page:", "= Thread(target=server.serve_forever) thread.setDaemon(True) # do not prevent shutdown thread.start() webbrowser.open('http://0.0.0.0:%i' % PORT) def", "in. Will be created if needed \"\"\" if os.path.exists(path) and not os.path.isdir(path): os.unlink(path)", "to a D3PO plot :param plot: Glue scatter plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param index: 1D", "ValueError(\"D3PO Export only supports scatter \" \"and histogram plots\") if sum(len(tab) for tab", "as outfile: json.dump(result, outfile, indent=2, sort_keys=True) # index.html html_path = os.path.join(path, 'index.html') with", "None: s = subset.style selected = dict(opacity=s.alpha, size=s.markersize / 2, color=s.color) result['markerStyle']['selected'] =", "s is not subset: return None if subset is None: subset = s", ":param application: Glue appication to save :param path: Path to directory to save", "can_save_d3po(application): \"\"\" Check whether an application can be exported to D3PO. Raises an", "to a D3PO bundle. Currently, this has the following restrictions: - The Glue", "data_path = os.path.join(path, 'data.csv') t = Table([data[c] for c in data.components], names=[c.label for", "= layer_artist.layer if not isinstance(s, Subset): continue if subset is not None and", "scatter plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param index: 1D index of plot on the page :type", "to view an exported D3PO bundle, and open a browser. :param path: The", "os.path.isdir(path): os.unlink(path) if not os.path.exists(path): os.mkdir(path) data = application.session.data_collection[0] subsets = stage_subsets(application) viewers", "import Thread os.chdir(path) while True: try: PORT = randrange(8000, 9000) server = TCPServer((\"\",", "page: Tuple of data viewers to save :param label: Tab label \"\"\" result", "result['markerStyle'] = dict(unselected=unselected) if subset is not None: s = subset.style selected =", "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'> <style> #footer { position: fixed;", "'columnName': 'selection_%i' % page_number} result['histogramStyle'] = result['markerStyle'] # save each plot result['plots'] =", "# layout settings result['grid'] = {'nRows': 1, 'nColumns': len(page)} result['name'] = str(label) result['caption']", "must have only one dataset open, and 0 or 1 subsets - Only", "exported to D3PO. Raises an exception if not \"\"\" dc = application.session.data_collection if", "if not \"\"\" dc = application.session.data_collection if len(dc) != 1: raise ValueError(\"D3PO Export", "in viewer.layers: if not layer_artist.visible: continue s = layer_artist.layer if not isinstance(s, Subset):", "has the following restrictions: - The Glue session must have only one dataset", "raise ValueError(\"D3PO Export only supports a single dataset\") for tab in application.viewers: for", "outfile, indent=2, sort_keys=True) # index.html html_path = os.path.join(path, 'index.html') with open(html_path, 'w') as", "tab of a glue session into a D3PO page :param page: Tuple of", "is not subset: return None if subset is None: subset = s result.append(subset)", "list(map(save_plot, page, range(len(page)))) return result def save_plot_base(plot, index): result = {} result['gridPosition'] =", "save_scatter(plot, index): \"\"\" Convert a single glue scatter plot to a D3PO plot", "launch: launch_d3po(path) def launch_d3po(path): \"\"\"Start a server to view an exported D3PO bundle,", "thread.setDaemon(True) # do not prevent shutdown thread.start() webbrowser.open('http://0.0.0.0:%i' % PORT) def setup(): from", "\"\"\" try: from glue.viewers.scatter.qt import ScatterViewer from glue.viewers.histogram.qt import HistogramViewer except ImportError: pass", "%s\" % data.label result['states'] = list(map(save_page, application.viewers, range(len(viewers)), application.tab_names, subsets)) state_path = os.path.join(path,", "{'type': 'booleanColumn', 'columnName': 'selection_%i' % page_number} result['histogramStyle'] = result['markerStyle'] # save each plot", "raise ValueError(\"D3PO Export requires at least one scatterplot \" \"or histogram\") if stage_subsets(application)", "os.path.join(path, 'data.csv') t = Table([data[c] for c in data.components], names=[c.label for c in", "and not os.path.isdir(path): os.unlink(path) if not os.path.exists(path): os.mkdir(path) data = application.session.data_collection[0] subsets =", "in data.components]) for i, subset in enumerate(subsets): if subset is None: continue c", "random import randrange from socket import error import webbrowser from threading import Thread", "'booleanColumn', 'columnName': 'selection_%i' % page_number} result['histogramStyle'] = result['markerStyle'] # save each plot result['plots']", "server.server_activate() thread = Thread(target=server.serve_forever) thread.setDaemon(True) # do not prevent shutdown thread.start() webbrowser.open('http://0.0.0.0:%i' %", "not os.path.exists(path): os.mkdir(path) data = application.session.data_collection[0] subsets = stage_subsets(application) viewers = application.viewers #", "result = {} result['filename'] = 'data.csv' # XXX don't think this is needed?", "\"\"\"Start a server to view an exported D3PO bundle, and open a browser.", "if subset is None: continue c = Column(data=subset.to_mask().astype('i'), name='selection_%i' % i) t.add_column(c) t.write(data_path,", "error import webbrowser from threading import Thread os.chdir(path) while True: try: PORT =", "\"Glue export of %s\" % data.label result['states'] = list(map(save_page, application.viewers, range(len(viewers)), application.tab_names, subsets))", "charset=\"utf-8\"></script> <script src=\"http://d3po.org/static/js/util.js\"></script> <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script src=\"http://d3po.org/static/js/d3po.js\"></script> <script src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head> <body> <div id=\"svg\"><svg></svg></div>", ":rtype: json-serializable dict \"\"\" result = save_plot_base(plot, index) result['type'] = 'scatter' result['xAxis'] =", "</head> <body> <div id=\"svg\"><svg></svg></div> <div id=\"controls\"> <ul class=\"navigation\"> </ul> </div> <div id=\"caption\"></div> <div", "'data.csv'); } ); </script> </body> </html> \"\"\" try: from glue.viewers.scatter.qt import ScatterViewer from", "save_plot(plot, index): typ = type(plot) return DISPATCH[typ](plot, index) def save_scatter(plot, index): \"\"\" Convert", "XXX don't think this is needed? result['title'] = \"Glue export of %s\" %", "<script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script src=\"http://d3po.org/static/js/d3po.js\"></script> <script src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head> <body> <div id=\"svg\"><svg></svg></div> <div id=\"controls\"> <ul", "\"\"\" result = save_plot_base(plot, index) result['type'] = 'scatter' result['xAxis'] = dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min), float(plot.state.x_max)])", "for each stage/tab, or None if the tab has no subset If more", "\"\"\" result = [] for page in application.viewers: subset = None for viewer", "<meta charset=\"utf-8\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/style.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700'", "2, color=s.color) result['markerStyle']['selected'] = selected result['selection'] = {'type': 'booleanColumn', 'columnName': 'selection_%i' % page_number}", "str(label) result['caption'] = 'Generated by Glue' # style settings d = page[0]._data[0] unselected", "given Data and tuple of subsets \"\"\" from astropy.table import Table, Column data_path", "in application.viewers: subset = None for viewer in page: for layer_artist in viewer.layers:", "color=s.color) result['markerStyle']['selected'] = selected result['selection'] = {'type': 'booleanColumn', 'columnName': 'selection_%i' % page_number} result['histogramStyle']", "'nColumns': len(page)} result['name'] = str(label) result['caption'] = 'Generated by Glue' # style settings", "t.write(data_path, format='ascii', delimiter=',') def save_d3po(application, path, launch=True): \"\"\"Save a Glue session to a", "subset is None: subset = s result.append(subset) return tuple(result) def can_save_d3po(application): \"\"\" Check", ":param plot: Glue scatter plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param index: 1D index of plot on", "<div id=\"footer\"> More information: <a href=\"http://d3po.org\">d3po.org</a> </div> <script type=\"text/javascript\"> $(document).ready(function() { initialize('states.json', 'data.csv');", "#footer { position: fixed; bottom: 0; right: 0; } </style> <!-- not to", "division, print_function import os import json from glue.core import Subset DISPATCH = {}", "index): result = {} result['gridPosition'] = [0, index] return result def save_plot(plot, index):", "histogram\") if stage_subsets(application) is None: raise ValueError(\"D3PO Export restricted to 0 or 1", "</body> </html> \"\"\" try: from glue.viewers.scatter.qt import ScatterViewer from glue.viewers.histogram.qt import HistogramViewer except", "enumerate(subsets): if subset is None: continue c = Column(data=subset.to_mask().astype('i'), name='selection_%i' % i) t.add_column(c)", "application.viewers # data.csv make_data_file(data, subsets, path) # states.json result = {} result['filename'] =", "SimpleHTTPRequestHandler, False) server.allow_reuse_address = True server.server_bind() break except error: # port already taken", "= [] for page in application.viewers: subset = None for viewer in page:", "2, color=d.style.color) result['markerStyle'] = dict(unselected=unselected) if subset is not None: s = subset.style", "not layer_artist.visible: continue s = layer_artist.layer if not isinstance(s, Subset): continue if subset", "session must have only one dataset open, and 0 or 1 subsets -", "{ initialize('states.json', 'data.csv'); } ); </script> </body> </html> \"\"\" try: from glue.viewers.scatter.qt import", "position: fixed; bottom: 0; right: 0; } </style> <!-- not to be confused", "PORT = randrange(8000, 9000) server = TCPServer((\"\", PORT), SimpleHTTPRequestHandler, False) server.allow_reuse_address = True", "Raises an exception if not \"\"\" dc = application.session.data_collection if len(dc) != 1:", "Data and tuple of subsets \"\"\" from astropy.table import Table, Column data_path =", "if needed \"\"\" if os.path.exists(path) and not os.path.isdir(path): os.unlink(path) if not os.path.exists(path): os.mkdir(path)", "data.csv make_data_file(data, subsets, path) # states.json result = {} result['filename'] = 'data.csv' #", "data.components]) for i, subset in enumerate(subsets): if subset is None: continue c =", "result['type'] = 'histogram' result['xAxis'] = dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)]) # XXX normed, cumultive,", "range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)]) # XXX normed, cumultive, log return result def stage_subsets(application): \"\"\" Return", "name='selection_%i' % i) t.add_column(c) t.write(data_path, format='ascii', delimiter=',') def save_d3po(application, path, launch=True): \"\"\"Save a", "if launch: launch_d3po(path) def launch_d3po(path): \"\"\"Start a server to view an exported D3PO", "Will be created if needed \"\"\" if os.path.exists(path) and not os.path.isdir(path): os.unlink(path) if", "viewers to save :param label: Tab label \"\"\" result = {} # layout", "index) result['type'] = 'histogram' result['xAxis'] = dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)]) # XXX normed,", "\"\"\" Create the data.csv file, given Data and tuple of subsets \"\"\" from", "webbrowser.open('http://0.0.0.0:%i' % PORT) def setup(): from glue.config import exporters exporters.add('D3PO', save_d3po, can_save_d3po, outmode='directory')", "subset = None for viewer in page: for layer_artist in viewer.layers: if not", "= page[0]._data[0] unselected = dict(opacity=d.style.alpha, size=d.style.markersize / 2, color=d.style.color) result['markerStyle'] = dict(unselected=unselected) if", "and tuple of subsets \"\"\" from astropy.table import Table, Column data_path = os.path.join(path,", "import Subset DISPATCH = {} def save_page(page, page_number, label, subset): \"\"\" Convert a", "import exporters exporters.add('D3PO', save_d3po, can_save_d3po, outmode='directory') HTML = \"\"\" <!DOCTYPE html> <html> <head>", "plot on the page :type index: int :rtype: json-serializable dict \"\"\" result =", "of %s\" % data.label result['states'] = list(map(save_page, application.viewers, range(len(viewers)), application.tab_names, subsets)) state_path =", "c in data.components], names=[c.label for c in data.components]) for i, subset in enumerate(subsets):", "a D3PO page :param page: Tuple of data viewers to save :param label:", "result def save_plot(plot, index): typ = type(plot) return DISPATCH[typ](plot, index) def save_scatter(plot, index):", "for viewer in page: for layer_artist in viewer.layers: if not layer_artist.visible: continue s", "1 subsets - Only scatter plots or histograms are present - At least", "1D index of plot on the page :type index: int :rtype: json-serializable dict", "unselected = dict(opacity=d.style.alpha, size=d.style.markersize / 2, color=d.style.color) result['markerStyle'] = dict(unselected=unselected) if subset is", "dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)]) # XXX normed, cumultive, log return result def stage_subsets(application):", "is used per stage/tab, returns None \"\"\" result = [] for page in", "0; } </style> <!-- not to be confused with Planet Telex --> <!--", "scales return result def save_histogram(plot, index): \"\"\" Convert a single histogram to a", "save :param path: Path to directory to save in. Will be created if", "tab has no subset If more than one subset is used per stage/tab,", "save_plot_base(plot, index) result['type'] = 'scatter' result['xAxis'] = dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min), float(plot.state.x_max)]) result['yAxis'] = dict(columnName=plot.state.y_att.label,", "# data.csv make_data_file(data, subsets, path) # states.json result = {} result['filename'] = 'data.csv'", "</style> <!-- not to be confused with Planet Telex --> <!-- Javscript dependencies", "subset): \"\"\" Convert a tab of a glue session into a D3PO page", "Export only supports a single dataset\") for tab in application.viewers: for viewer in", "for viewer in tab: if not isinstance(viewer, tuple(DISPATCH.keys())): raise ValueError(\"D3PO Export only supports", "D3PO bundle. Currently, this has the following restrictions: - The Glue session must", "dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min), float(plot.state.y_max)]) # XXX log scales return result def save_histogram(plot, index): \"\"\"", "result['filename'] = 'data.csv' # XXX don't think this is needed? result['title'] = \"Glue", "outmode='directory') HTML = \"\"\" <!DOCTYPE html> <html> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\"", "None and s is not subset: return None if subset is None: subset", "dict(unselected=unselected) if subset is not None: s = subset.style selected = dict(opacity=s.alpha, size=s.markersize", "= None for viewer in page: for layer_artist in viewer.layers: if not layer_artist.visible:", "import Table, Column data_path = os.path.join(path, 'data.csv') t = Table([data[c] for c in", "setup(): from glue.config import exporters exporters.add('D3PO', save_d3po, can_save_d3po, outmode='directory') HTML = \"\"\" <!DOCTYPE", "range(len(viewers)), application.tab_names, subsets)) state_path = os.path.join(path, 'states.json') with open(state_path, 'w') as outfile: json.dump(result,", "type=\"text/javascript\"> $(document).ready(function() { initialize('states.json', 'data.csv'); } ); </script> </body> </html> \"\"\" try: from", "a D3PO plot :param plot: Glue histogram :type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer` :param index: 1D", "for i, subset in enumerate(subsets): if subset is None: continue c = Column(data=subset.to_mask().astype('i'),", "Check whether an application can be exported to D3PO. Raises an exception if", "plot: Glue histogram :type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer` :param index: 1D index of plot on", "def make_data_file(data, subsets, path): \"\"\" Create the data.csv file, given Data and tuple", "Glue' # style settings d = page[0]._data[0] unselected = dict(opacity=d.style.alpha, size=d.style.markersize / 2,", "glue session into a D3PO page :param page: Tuple of data viewers to", "== 0: raise ValueError(\"D3PO Export requires at least one scatterplot \" \"or histogram\")", "raise ValueError(\"D3PO Export restricted to 0 or 1 subsets visible \" \"in each", "type=\"text/css\" href=\"http://d3po.org/static/css/style.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'> <style> #footer {", "glue.external.six.moves.socketserver import TCPServer from glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler from random import randrange from socket", "stage/tab, returns None \"\"\" result = [] for page in application.viewers: subset =", "launch_d3po(path): \"\"\"Start a server to view an exported D3PO bundle, and open a", "None: subset = s result.append(subset) return tuple(result) def can_save_d3po(application): \"\"\" Check whether an", "'Generated by Glue' # style settings d = page[0]._data[0] unselected = dict(opacity=d.style.alpha, size=d.style.markersize", "of the subset to use for each stage/tab, or None if the tab", "\"in each tab\") def make_data_file(data, subsets, path): \"\"\" Create the data.csv file, given", "bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)]) # XXX normed, cumultive, log return result def stage_subsets(application): \"\"\"", "think this is needed? result['title'] = \"Glue export of %s\" % data.label result['states']", "range=[float(plot.state.y_min), float(plot.state.y_max)]) # XXX log scales return result def save_histogram(plot, index): \"\"\" Convert", "a browser. :param path: The TLD of the bundle \"\"\" from glue.external.six.moves.socketserver import", "= save_plot_base(plot, index) result['type'] = 'histogram' result['xAxis'] = dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)]) #", "have only one dataset open, and 0 or 1 subsets - Only scatter", "from glue.external.six.moves.socketserver import TCPServer from glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler from random import randrange from", "randrange from socket import error import webbrowser from threading import Thread os.chdir(path) while", "html> <html> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/style.css\"> <link rel=\"stylesheet\" type=\"text/css\"", "subset in enumerate(subsets): if subset is None: continue c = Column(data=subset.to_mask().astype('i'), name='selection_%i' %", "layout settings result['grid'] = {'nRows': 1, 'nColumns': len(page)} result['name'] = str(label) result['caption'] =", "= os.path.join(path, 'index.html') with open(html_path, 'w') as outfile: outfile.write(HTML) # show the result", "log return result def stage_subsets(application): \"\"\" Return a tuple of the subset to", "None if subset is None: subset = s result.append(subset) return tuple(result) def can_save_d3po(application):", "result if launch: launch_d3po(path) def launch_d3po(path): \"\"\"Start a server to view an exported", "subsets - Only scatter plots or histograms are present - At least one", "[0, index] return result def save_plot(plot, index): typ = type(plot) return DISPATCH[typ](plot, index)", "result['states'] = list(map(save_page, application.viewers, range(len(viewers)), application.tab_names, subsets)) state_path = os.path.join(path, 'states.json') with open(state_path,", "<script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script> <script src=\"http://d3po.org/static/js/util.js\"></script> <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script src=\"http://d3po.org/static/js/d3po.js\"></script> <script src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head> <body>", "D3PO. Raises an exception if not \"\"\" dc = application.session.data_collection if len(dc) !=", "Glue session to a D3PO bundle. Currently, this has the following restrictions: -", "result = [] for page in application.viewers: subset = None for viewer in", "= dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min), float(plot.state.x_max)]) result['yAxis'] = dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min), float(plot.state.y_max)]) # XXX log scales", "<!-- not to be confused with Planet Telex --> <!-- Javscript dependencies -->", "tab in application.viewers: for viewer in tab: if not isinstance(viewer, tuple(DISPATCH.keys())): raise ValueError(\"D3PO", "cumultive, log return result def stage_subsets(application): \"\"\" Return a tuple of the subset", "index: int :rtype: json-serializable dict \"\"\" result = save_plot_base(plot, index) result['type'] = 'scatter'", "if len(dc) != 1: raise ValueError(\"D3PO Export only supports a single dataset\") for", "result['plots'] = list(map(save_plot, page, range(len(page)))) return result def save_plot_base(plot, index): result = {}", "<head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/style.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\"> <link", "viewers = application.viewers # data.csv make_data_file(data, subsets, path) # states.json result = {}", "dict(opacity=d.style.alpha, size=d.style.markersize / 2, color=d.style.color) result['markerStyle'] = dict(unselected=unselected) if subset is not None:", "path: Path to directory to save in. Will be created if needed \"\"\"", "\"\"\" Return a tuple of the subset to use for each stage/tab, or", "\"\"\" <!DOCTYPE html> <html> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/style.css\"> <link", "page: for layer_artist in viewer.layers: if not layer_artist.visible: continue s = layer_artist.layer if", "bundle. Currently, this has the following restrictions: - The Glue session must have", "# port already taken pass print('Serving D3PO on port 0.0.0.0:%i' % PORT) server.server_activate()", "from glue.config import exporters exporters.add('D3PO', save_d3po, can_save_d3po, outmode='directory') HTML = \"\"\" <!DOCTYPE html>", "rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/style.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'> <style> #footer", "href=\"http://d3po.org/static/css/style.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'> <style> #footer { position:", "= dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min), float(plot.state.y_max)]) # XXX log scales return result def save_histogram(plot, index):", "restricted to 0 or 1 subsets visible \" \"in each tab\") def make_data_file(data,", "from astropy.table import Table, Column data_path = os.path.join(path, 'data.csv') t = Table([data[c] for", "delimiter=',') def save_d3po(application, path, launch=True): \"\"\"Save a Glue session to a D3PO bundle.", "application.session.data_collection if len(dc) != 1: raise ValueError(\"D3PO Export only supports a single dataset\")", "def save_d3po(application, path, launch=True): \"\"\"Save a Glue session to a D3PO bundle. Currently,", "data = application.session.data_collection[0] subsets = stage_subsets(application) viewers = application.viewers # data.csv make_data_file(data, subsets,", "= 'scatter' result['xAxis'] = dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min), float(plot.state.x_max)]) result['yAxis'] = dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min), float(plot.state.y_max)]) #", "following restrictions: - The Glue session must have only one dataset open, and", "json-serializable dict \"\"\" result = save_plot_base(plot, index) result['type'] = 'histogram' result['xAxis'] = dict(columnName=plot.state.x_att.label,", "typ = type(plot) return DISPATCH[typ](plot, index) def save_scatter(plot, index): \"\"\" Convert a single", "label \"\"\" result = {} # layout settings result['grid'] = {'nRows': 1, 'nColumns':", "is None: continue c = Column(data=subset.to_mask().astype('i'), name='selection_%i' % i) t.add_column(c) t.write(data_path, format='ascii', delimiter=',')", "= s result.append(subset) return tuple(result) def can_save_d3po(application): \"\"\" Check whether an application can", "a Glue session to a D3PO bundle. Currently, this has the following restrictions:", "subset is used per stage/tab, returns None \"\"\" result = [] for page", "% PORT) server.server_activate() thread = Thread(target=server.serve_forever) thread.setDaemon(True) # do not prevent shutdown thread.start()", "single histogram to a D3PO plot :param plot: Glue histogram :type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer`", "requires at least one scatterplot \" \"or histogram\") if stage_subsets(application) is None: raise", "appication to save :param path: Path to directory to save in. Will be", "os.chdir(path) while True: try: PORT = randrange(8000, 9000) server = TCPServer((\"\", PORT), SimpleHTTPRequestHandler,", "index) result['type'] = 'scatter' result['xAxis'] = dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min), float(plot.state.x_max)]) result['yAxis'] = dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min),", "if the tab has no subset If more than one subset is used", "only one dataset open, and 0 or 1 subsets - Only scatter plots", "to a D3PO plot :param plot: Glue histogram :type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer` :param index:", "ValueError(\"D3PO Export restricted to 0 or 1 subsets visible \" \"in each tab\")", "in tab: if not isinstance(viewer, tuple(DISPATCH.keys())): raise ValueError(\"D3PO Export only supports scatter \"", "thread = Thread(target=server.serve_forever) thread.setDaemon(True) # do not prevent shutdown thread.start() webbrowser.open('http://0.0.0.0:%i' % PORT)", "not to be confused with Planet Telex --> <!-- Javscript dependencies --> <script", "subset If more than one subset is used per stage/tab, returns None \"\"\"", "None \"\"\" result = [] for page in application.viewers: subset = None for", "The Glue session must have only one dataset open, and 0 or 1", "browser. :param path: The TLD of the bundle \"\"\" from glue.external.six.moves.socketserver import TCPServer", "stage_subsets(application) is None: raise ValueError(\"D3PO Export restricted to 0 or 1 subsets visible", "float(plot.state.hist_x_max)]) # XXX normed, cumultive, log return result def stage_subsets(application): \"\"\" Return a", "use for each stage/tab, or None if the tab has no subset If", "'w') as outfile: json.dump(result, outfile, indent=2, sort_keys=True) # index.html html_path = os.path.join(path, 'index.html')", "from glue.core import Subset DISPATCH = {} def save_page(page, page_number, label, subset): \"\"\"", "\"or histogram\") if stage_subsets(application) is None: raise ValueError(\"D3PO Export restricted to 0 or", "= {} result['gridPosition'] = [0, index] return result def save_plot(plot, index): typ =", "result['markerStyle']['selected'] = selected result['selection'] = {'type': 'booleanColumn', 'columnName': 'selection_%i' % page_number} result['histogramStyle'] =", "= save_plot_base(plot, index) result['type'] = 'scatter' result['xAxis'] = dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min), float(plot.state.x_max)]) result['yAxis'] =", "= Column(data=subset.to_mask().astype('i'), name='selection_%i' % i) t.add_column(c) t.write(data_path, format='ascii', delimiter=',') def save_d3po(application, path, launch=True):", "/ 2, color=d.style.color) result['markerStyle'] = dict(unselected=unselected) if subset is not None: s =", "whether an application can be exported to D3PO. Raises an exception if not", "None: raise ValueError(\"D3PO Export restricted to 0 or 1 subsets visible \" \"in", "\"and histogram plots\") if sum(len(tab) for tab in application.viewers) == 0: raise ValueError(\"D3PO", "tuple of the subset to use for each stage/tab, or None if the", "XXX log scales return result def save_histogram(plot, index): \"\"\" Convert a single histogram", "= 'Generated by Glue' # style settings d = page[0]._data[0] unselected = dict(opacity=d.style.alpha,", "!= 1: raise ValueError(\"D3PO Export only supports a single dataset\") for tab in", "charset=\"utf-8\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/style.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet'", "scatter plot to a D3PO plot :param plot: Glue scatter plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param", "view an exported D3PO bundle, and open a browser. :param path: The TLD", "session to a D3PO bundle. Currently, this has the following restrictions: - The", "least one plot is present :param application: Glue appication to save :param path:", "0 or 1 subsets - Only scatter plots or histograms are present -", "from threading import Thread os.chdir(path) while True: try: PORT = randrange(8000, 9000) server", "path: The TLD of the bundle \"\"\" from glue.external.six.moves.socketserver import TCPServer from glue.external.six.moves.SimpleHTTPServer", "raise ValueError(\"D3PO Export only supports scatter \" \"and histogram plots\") if sum(len(tab) for", "PORT), SimpleHTTPRequestHandler, False) server.allow_reuse_address = True server.server_bind() break except error: # port already", "except error: # port already taken pass print('Serving D3PO on port 0.0.0.0:%i' %", "= application.session.data_collection if len(dc) != 1: raise ValueError(\"D3PO Export only supports a single", "</html> \"\"\" try: from glue.viewers.scatter.qt import ScatterViewer from glue.viewers.histogram.qt import HistogramViewer except ImportError:", "glue.viewers.scatter.qt import ScatterViewer from glue.viewers.histogram.qt import HistogramViewer except ImportError: pass else: DISPATCH[ScatterViewer] =", "= stage_subsets(application) viewers = application.viewers # data.csv make_data_file(data, subsets, path) # states.json result", "the following restrictions: - The Glue session must have only one dataset open,", "href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'> <style> #footer { position: fixed; bottom: 0; right: 0; }", "= 'data.csv' # XXX don't think this is needed? result['title'] = \"Glue export", "glue.core import Subset DISPATCH = {} def save_page(page, page_number, label, subset): \"\"\" Convert", "do not prevent shutdown thread.start() webbrowser.open('http://0.0.0.0:%i' % PORT) def setup(): from glue.config import", "application.viewers, range(len(viewers)), application.tab_names, subsets)) state_path = os.path.join(path, 'states.json') with open(state_path, 'w') as outfile:", "# save each plot result['plots'] = list(map(save_plot, page, range(len(page)))) return result def save_plot_base(plot,", "tab in application.viewers) == 0: raise ValueError(\"D3PO Export requires at least one scatterplot", "src=\"http://d3po.org/static/js/util.js\"></script> <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script src=\"http://d3po.org/static/js/d3po.js\"></script> <script src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head> <body> <div id=\"svg\"><svg></svg></div> <div id=\"controls\">", "index): \"\"\" Convert a single histogram to a D3PO plot :param plot: Glue", "label: Tab label \"\"\" result = {} # layout settings result['grid'] = {'nRows':", "import randrange from socket import error import webbrowser from threading import Thread os.chdir(path)", "import error import webbrowser from threading import Thread os.chdir(path) while True: try: PORT", "with open(state_path, 'w') as outfile: json.dump(result, outfile, indent=2, sort_keys=True) # index.html html_path =", "the subset to use for each stage/tab, or None if the tab has", ":param index: 1D index of plot on the page :type index: int :rtype:", "Thread(target=server.serve_forever) thread.setDaemon(True) # do not prevent shutdown thread.start() webbrowser.open('http://0.0.0.0:%i' % PORT) def setup():" ]
[ "P.A. é (', end='') while c <= 10: print('{}'.format(termo), end='') print(', ' if", "(', end='') while c <= 10: print('{}'.format(termo), end='') print(', ' if c <", "print(', ' if c < 10 else '', end='') termo += r c", "termo da P.A.: ')) r = int(input('Digite a razão: ')) termo = n1", "n1 c = 1 print('A P.A. é (', end='') while c <= 10:", "print('Crie sua P.A. de 10 termos') n1 = int(input('Digite o primeiro termo da", "P.A.: ')) r = int(input('Digite a razão: ')) termo = n1 c =", "= int(input('Digite o primeiro termo da P.A.: ')) r = int(input('Digite a razão:", "10 termos') n1 = int(input('Digite o primeiro termo da P.A.: ')) r =", "de 10 termos') n1 = int(input('Digite o primeiro termo da P.A.: ')) r", "<= 10: print('{}'.format(termo), end='') print(', ' if c < 10 else '', end='')", "c = 1 print('A P.A. é (', end='') while c <= 10: print('{}'.format(termo),", "<gh_stars>0 print('Crie sua P.A. de 10 termos') n1 = int(input('Digite o primeiro termo", "print('{}'.format(termo), end='') print(', ' if c < 10 else '', end='') termo +=", "razão: ')) termo = n1 c = 1 print('A P.A. é (', end='')", "')) r = int(input('Digite a razão: ')) termo = n1 c = 1", "end='') while c <= 10: print('{}'.format(termo), end='') print(', ' if c < 10", "r = int(input('Digite a razão: ')) termo = n1 c = 1 print('A", "c < 10 else '', end='') termo += r c += 1 print(')')", "10: print('{}'.format(termo), end='') print(', ' if c < 10 else '', end='') termo", "int(input('Digite o primeiro termo da P.A.: ')) r = int(input('Digite a razão: '))", "while c <= 10: print('{}'.format(termo), end='') print(', ' if c < 10 else", "n1 = int(input('Digite o primeiro termo da P.A.: ')) r = int(input('Digite a", "' if c < 10 else '', end='') termo += r c +=", "c <= 10: print('{}'.format(termo), end='') print(', ' if c < 10 else '',", "print('A P.A. é (', end='') while c <= 10: print('{}'.format(termo), end='') print(', '", "da P.A.: ')) r = int(input('Digite a razão: ')) termo = n1 c", "end='') print(', ' if c < 10 else '', end='') termo += r", "= int(input('Digite a razão: ')) termo = n1 c = 1 print('A P.A.", "1 print('A P.A. é (', end='') while c <= 10: print('{}'.format(termo), end='') print(',", "é (', end='') while c <= 10: print('{}'.format(termo), end='') print(', ' if c", "if c < 10 else '', end='') termo += r c += 1", "= n1 c = 1 print('A P.A. é (', end='') while c <=", "termo = n1 c = 1 print('A P.A. é (', end='') while c", "int(input('Digite a razão: ')) termo = n1 c = 1 print('A P.A. é", "termos') n1 = int(input('Digite o primeiro termo da P.A.: ')) r = int(input('Digite", "P.A. de 10 termos') n1 = int(input('Digite o primeiro termo da P.A.: '))", "a razão: ')) termo = n1 c = 1 print('A P.A. é (',", "primeiro termo da P.A.: ')) r = int(input('Digite a razão: ')) termo =", "= 1 print('A P.A. é (', end='') while c <= 10: print('{}'.format(termo), end='')", "sua P.A. de 10 termos') n1 = int(input('Digite o primeiro termo da P.A.:", "')) termo = n1 c = 1 print('A P.A. é (', end='') while", "o primeiro termo da P.A.: ')) r = int(input('Digite a razão: ')) termo" ]
[ "a connection without committing the changes first will cause an implicit rollback to", ".extensions import PARSE_DECLTYPES, PARSE_COLNAMES class Connection(object): from .exceptions import ( Warning, Error, InterfaceError,", "self._connection.request(method, uri, body=body, headers=dict(self._headers, **headers)) return self._connection.getresponse() except Exception: if not tries: raise", "The same applies to all cursor objects trying to use the connection. Note", "!= location.port: self._connection.close() self.host = location.hostname self.port = location.port self._connection = self._init_connection() response", "import PARSE_DECLTYPES, PARSE_COLNAMES class Connection(object): from .exceptions import ( Warning, Error, InterfaceError, DatabaseError,", "will be unusable from this point forward; an Error (or subclass) exception will", "method, uri, body=None, headers={}): \"\"\" Fetch a response, handling redirection. \"\"\" response =", "from urllib.parse import urlparse except ImportError: # pylint: disable=import-error from urlparse import urlparse", "self.host = location.hostname self.port = location.port self._connection = self._init_connection() response = self._retry_request(method, uri,", "urllib.parse import urlparse except ImportError: # pylint: disable=import-error from urlparse import urlparse from", "self.parse_decltypes = detect_types & PARSE_DECLTYPES self.parse_colnames = detect_types & PARSE_COLNAMES self._ephemeral = None", "scheme='http', host='localhost', port=4001, user=None, password=<PASSWORD>, connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages = [] self.scheme =", "1 uri = response.getheader('Location') location = urlparse(uri) logging.getLogger(__name__).debug(\"status: %s reason: '%s' location: '%s'\",", "headers=headers) return response def close(self): \"\"\"Close the connection now (rather than whenever .__del__()", "same applies to all cursor objects trying to use the connection. Note that", "None def __del__(self): self.close() def commit(self): \"\"\"Database modules that do not support transactions", "= 'Basic ' + \\ codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n') self.connect_timeout = connect_timeout self.max_redirects =", "= 10 while tries: tries -= 1 try: self._connection.request(method, uri, body=body, headers=dict(self._headers, **headers))", "body=body, headers=headers) return response def close(self): \"\"\"Close the connection now (rather than whenever", "implicit rollback to be performed.\"\"\" self._connection.close() if self._ephemeral is not None: self._ephemeral.__exit__(None, None,", "# pylint: disable=import-error from urlparse import urlparse from .constants import ( UNLIMITED_REDIRECTS, )", "and \\ response.getheader('Location') is not None and \\ (self.max_redirects == UNLIMITED_REDIRECTS or redirects", "logging.getLogger(__name__).debug(\"status: %s reason: '%s' location: '%s'\", response.status, response.reason, uri) if self.host != location.hostname", "\"\"\"Return a new Cursor Object using the connection.\"\"\" if factory: return factory(self) else:", "[] self.scheme = scheme self.host = host self.port = port self._headers = {}", "response def close(self): \"\"\"Close the connection now (rather than whenever .__del__() is called).", "detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages = [] self.scheme = scheme self.host = host self.port =", "= HTTPConnection elif self.scheme == 'https': cls = HTTPSConnection else: raise Connection.ProgrammingError('Unsupported scheme", "disable=import-error from urlparse import urlparse from .constants import ( UNLIMITED_REDIRECTS, ) from .cursors", "except ImportError: # pylint: disable=import-error from httplib import HTTPConnection, HTTPSConnection try: from urllib.parse", "pass def rollback(self): \"\"\"This method is optional since not all databases provide transaction", "connection without committing the changes first will cause an implicit rollback to be", "timeout=None if self.connect_timeout is None else float(self.connect_timeout)) def _retry_request(self, method, uri, body=None, headers={}):", "body=body, headers=headers) redirects = 0 while response.status == 301 and \\ response.getheader('Location') is", ".exceptions import ( Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError,", "body=body, headers=dict(self._headers, **headers)) return self._connection.getresponse() except Exception: if not tries: raise self._connection.close() self._connection", "handling redirection. \"\"\" response = self._retry_request(method, uri, body=body, headers=headers) redirects = 0 while", "& PARSE_COLNAMES self._ephemeral = None if scheme == ':memory:': self._ephemeral = _EphemeralRqlited().__enter__() self.host,", "objects trying to use the connection. Note that closing a connection without committing", "connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages = [] self.scheme = scheme self.host = host self.port", "response.status == 301 and \\ response.getheader('Location') is not None and \\ (self.max_redirects ==", "\\ (self.max_redirects == UNLIMITED_REDIRECTS or redirects < self.max_redirects): redirects += 1 uri =", "optional since not all databases provide transaction support. \"\"\" pass def cursor(self, factory=None):", "%s reason: '%s' location: '%s'\", response.status, response.reason, uri) if self.host != location.hostname or", "ImportError: # pylint: disable=import-error from httplib import HTTPConnection, HTTPSConnection try: from urllib.parse import", "self.host != location.hostname or self.port != location.port: self._connection.close() self.host = location.hostname self.port =", "Cursor Object using the connection.\"\"\" if factory: return factory(self) else: return Cursor(self) def", "= port self._headers = {} if not (user is None or password is", "self._init_connection() def _init_connection(self): if self.scheme in ('http', ':memory:'): cls = HTTPConnection elif self.scheme", "that closing a connection without committing the changes first will cause an implicit", "host self.port = port self._headers = {} if not (user is None or", "= self._init_connection() response = self._retry_request(method, uri, body=body, headers=headers) return response def close(self): \"\"\"Close", "self.port = location.port self._connection = self._init_connection() response = self._retry_request(method, uri, body=body, headers=headers) return", "cls = HTTPConnection elif self.scheme == 'https': cls = HTTPSConnection else: raise Connection.ProgrammingError('Unsupported", "-= 1 try: self._connection.request(method, uri, body=body, headers=dict(self._headers, **headers)) return self._connection.getresponse() except Exception: if", ") from .cursors import Cursor from ._ephemeral import EphemeralRqlited as _EphemeralRqlited from .extensions", "if self._ephemeral is not None: self._ephemeral.__exit__(None, None, None) self._ephemeral = None def __del__(self):", "is not None and \\ (self.max_redirects == UNLIMITED_REDIRECTS or redirects < self.max_redirects): redirects", "factory=None): \"\"\"Return a new Cursor Object using the connection.\"\"\" if factory: return factory(self)", "is attempted with the connection. The same applies to all cursor objects trying", "raised if any operation is attempted with the connection. The same applies to", "using the connection.\"\"\" if factory: return factory(self) else: return Cursor(self) def execute(self, *args,", "scheme == ':memory:': self._ephemeral = _EphemeralRqlited().__enter__() self.host, self.port = self._ephemeral.http self._connection = self._init_connection()", "ImportError: # pylint: disable=import-error from urlparse import urlparse from .constants import ( UNLIMITED_REDIRECTS,", "10 while tries: tries -= 1 try: self._connection.request(method, uri, body=body, headers=dict(self._headers, **headers)) return", "with the connection. The same applies to all cursor objects trying to use", "'%s'\", response.status, response.reason, uri) if self.host != location.hostname or self.port != location.port: self._connection.close()", "IntegrityError, InternalError, ProgrammingError, NotSupportedError, ) def __init__(self, scheme='http', host='localhost', port=4001, user=None, password=<PASSWORD>, connect_timeout=None,", "= location.port self._connection = self._init_connection() response = self._retry_request(method, uri, body=body, headers=headers) return response", "uri, body=None, headers={}): tries = 10 while tries: tries -= 1 try: self._connection.request(method,", "uri) if self.host != location.hostname or self.port != location.port: self._connection.close() self.host = location.hostname", "from .constants import ( UNLIMITED_REDIRECTS, ) from .cursors import Cursor from ._ephemeral import", "import urlparse except ImportError: # pylint: disable=import-error from urlparse import urlparse from .constants", "codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n') self.connect_timeout = connect_timeout self.max_redirects = max_redirects self.detect_types = detect_types self.parse_decltypes", "self._ephemeral.__exit__(None, None, None) self._ephemeral = None def __del__(self): self.close() def commit(self): \"\"\"Database modules", "\\ codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n') self.connect_timeout = connect_timeout self.max_redirects = max_redirects self.detect_types = detect_types", "EphemeralRqlited as _EphemeralRqlited from .extensions import PARSE_DECLTYPES, PARSE_COLNAMES class Connection(object): from .exceptions import", "urlparse(uri) logging.getLogger(__name__).debug(\"status: %s reason: '%s' location: '%s'\", response.status, response.reason, uri) if self.host !=", "PARSE_DECLTYPES, PARSE_COLNAMES class Connection(object): from .exceptions import ( Warning, Error, InterfaceError, DatabaseError, DataError,", "DatabaseError, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError, ) def __init__(self, scheme='http', host='localhost', port=4001,", "= host self.port = port self._headers = {} if not (user is None", "PARSE_DECLTYPES self.parse_colnames = detect_types & PARSE_COLNAMES self._ephemeral = None if scheme == ':memory:':", "import codecs import logging try: from http.client import HTTPConnection, HTTPSConnection except ImportError: #", "None) self._ephemeral = None def __del__(self): self.close() def commit(self): \"\"\"Database modules that do", "forward; an Error (or subclass) exception will be raised if any operation is", "new Cursor Object using the connection.\"\"\" if factory: return factory(self) else: return Cursor(self)", "self._retry_request(method, uri, body=body, headers=headers) return response def close(self): \"\"\"Close the connection now (rather", "self._connection = self._init_connection() response = self._retry_request(method, uri, body=body, headers=headers) return response def close(self):", "subclass) exception will be raised if any operation is attempted with the connection.", "'%s' location: '%s'\", response.status, response.reason, uri) if self.host != location.hostname or self.port !=", "= max_redirects self.detect_types = detect_types self.parse_decltypes = detect_types & PARSE_DECLTYPES self.parse_colnames = detect_types", "_EphemeralRqlited from .extensions import PARSE_DECLTYPES, PARSE_COLNAMES class Connection(object): from .exceptions import ( Warning,", "to use the connection. Note that closing a connection without committing the changes", "headers={}): \"\"\" Fetch a response, handling redirection. \"\"\" response = self._retry_request(method, uri, body=body,", "uri, body=body, headers=dict(self._headers, **headers)) return self._connection.getresponse() except Exception: if not tries: raise self._connection.close()", "close(self): \"\"\"Close the connection now (rather than whenever .__del__() is called). The connection", "attempted with the connection. The same applies to all cursor objects trying to", "Error, InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError, ) def __init__(self, scheme='http',", "self._ephemeral = None if scheme == ':memory:': self._ephemeral = _EphemeralRqlited().__enter__() self.host, self.port =", "cursor objects trying to use the connection. Note that closing a connection without", "import urlparse from .constants import ( UNLIMITED_REDIRECTS, ) from .cursors import Cursor from", "max_redirects=UNLIMITED_REDIRECTS): self.messages = [] self.scheme = scheme self.host = host self.port = port", "headers={}): tries = 10 while tries: tries -= 1 try: self._connection.request(method, uri, body=body,", "def _fetch_response(self, method, uri, body=None, headers={}): \"\"\" Fetch a response, handling redirection. \"\"\"", "is optional since not all databases provide transaction support. \"\"\" pass def cursor(self,", "password is None): self._headers['Authorization'] = 'Basic ' + \\ codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n') self.connect_timeout", "is not None: self._ephemeral.__exit__(None, None, None) self._ephemeral = None def __del__(self): self.close() def", "= {} if not (user is None or password is None): self._headers['Authorization'] =", "self._ephemeral = _EphemeralRqlited().__enter__() self.host, self.port = self._ephemeral.http self._connection = self._init_connection() def _init_connection(self): if", "not tries: raise self._connection.close() self._connection = self._init_connection() def _fetch_response(self, method, uri, body=None, headers={}):", "None if scheme == ':memory:': self._ephemeral = _EphemeralRqlited().__enter__() self.host, self.port = self._ephemeral.http self._connection", "is None): self._headers['Authorization'] = 'Basic ' + \\ codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n') self.connect_timeout =", "Object using the connection.\"\"\" if factory: return factory(self) else: return Cursor(self) def execute(self,", "closing a connection without committing the changes first will cause an implicit rollback", "cause an implicit rollback to be performed.\"\"\" self._connection.close() if self._ephemeral is not None:", "self._retry_request(method, uri, body=body, headers=headers) redirects = 0 while response.status == 301 and \\", "% self.scheme) return cls(self.host, port=self.port, timeout=None if self.connect_timeout is None else float(self.connect_timeout)) def", "port self._headers = {} if not (user is None or password is None):", "should implement this method with void functionality.\"\"\" pass def rollback(self): \"\"\"This method is", "else float(self.connect_timeout)) def _retry_request(self, method, uri, body=None, headers={}): tries = 10 while tries:", "class Connection(object): from .exceptions import ( Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError,", "be performed.\"\"\" self._connection.close() if self._ephemeral is not None: self._ephemeral.__exit__(None, None, None) self._ephemeral =", "the changes first will cause an implicit rollback to be performed.\"\"\" self._connection.close() if", "!= location.hostname or self.port != location.port: self._connection.close() self.host = location.hostname self.port = location.port", "def _init_connection(self): if self.scheme in ('http', ':memory:'): cls = HTTPConnection elif self.scheme ==", "self._connection.close() if self._ephemeral is not None: self._ephemeral.__exit__(None, None, None) self._ephemeral = None def", "response.status, response.reason, uri) if self.host != location.hostname or self.port != location.port: self._connection.close() self.host", "= self._ephemeral.http self._connection = self._init_connection() def _init_connection(self): if self.scheme in ('http', ':memory:'): cls", "unusable from this point forward; an Error (or subclass) exception will be raised", "\"\"\"This method is optional since not all databases provide transaction support. \"\"\" pass", "location.port self._connection = self._init_connection() response = self._retry_request(method, uri, body=body, headers=headers) return response def", "response.getheader('Location') location = urlparse(uri) logging.getLogger(__name__).debug(\"status: %s reason: '%s' location: '%s'\", response.status, response.reason, uri)", "support. \"\"\" pass def cursor(self, factory=None): \"\"\"Return a new Cursor Object using the", "HTTPSConnection try: from urllib.parse import urlparse except ImportError: # pylint: disable=import-error from urlparse", "body=None, headers={}): \"\"\" Fetch a response, handling redirection. \"\"\" response = self._retry_request(method, uri,", "import HTTPConnection, HTTPSConnection except ImportError: # pylint: disable=import-error from httplib import HTTPConnection, HTTPSConnection", "a new Cursor Object using the connection.\"\"\" if factory: return factory(self) else: return", ".__del__() is called). The connection will be unusable from this point forward; an", "performed.\"\"\" self._connection.close() if self._ephemeral is not None: self._ephemeral.__exit__(None, None, None) self._ephemeral = None", "'base64').decode('utf-8').rstrip('\\n') self.connect_timeout = connect_timeout self.max_redirects = max_redirects self.detect_types = detect_types self.parse_decltypes = detect_types", "from httplib import HTTPConnection, HTTPSConnection try: from urllib.parse import urlparse except ImportError: #", "from __future__ import unicode_literals import codecs import logging try: from http.client import HTTPConnection,", "connection. Note that closing a connection without committing the changes first will cause", "def commit(self): \"\"\"Database modules that do not support transactions should implement this method", "self.connect_timeout is None else float(self.connect_timeout)) def _retry_request(self, method, uri, body=None, headers={}): tries =", "from http.client import HTTPConnection, HTTPSConnection except ImportError: # pylint: disable=import-error from httplib import", "OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError, ) def __init__(self, scheme='http', host='localhost', port=4001, user=None, password=<PASSWORD>,", "if self.connect_timeout is None else float(self.connect_timeout)) def _retry_request(self, method, uri, body=None, headers={}): tries", "UNLIMITED_REDIRECTS, ) from .cursors import Cursor from ._ephemeral import EphemeralRqlited as _EphemeralRqlited from", "PARSE_COLNAMES class Connection(object): from .exceptions import ( Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError,", "pylint: disable=import-error from httplib import HTTPConnection, HTTPSConnection try: from urllib.parse import urlparse except", "= None def __del__(self): self.close() def commit(self): \"\"\"Database modules that do not support", "301 and \\ response.getheader('Location') is not None and \\ (self.max_redirects == UNLIMITED_REDIRECTS or", "import Cursor from ._ephemeral import EphemeralRqlited as _EphemeralRqlited from .extensions import PARSE_DECLTYPES, PARSE_COLNAMES", "port=self.port, timeout=None if self.connect_timeout is None else float(self.connect_timeout)) def _retry_request(self, method, uri, body=None,", "location.hostname self.port = location.port self._connection = self._init_connection() response = self._retry_request(method, uri, body=body, headers=headers)", "(self.max_redirects == UNLIMITED_REDIRECTS or redirects < self.max_redirects): redirects += 1 uri = response.getheader('Location')", "\"\"\" Fetch a response, handling redirection. \"\"\" response = self._retry_request(method, uri, body=body, headers=headers)", "def __del__(self): self.close() def commit(self): \"\"\"Database modules that do not support transactions should", "password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n') self.connect_timeout = connect_timeout self.max_redirects = max_redirects self.detect_types = detect_types self.parse_decltypes =", "self._headers = {} if not (user is None or password is None): self._headers['Authorization']", "+ \\ codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n') self.connect_timeout = connect_timeout self.max_redirects = max_redirects self.detect_types =", "None else float(self.connect_timeout)) def _retry_request(self, method, uri, body=None, headers={}): tries = 10 while", "try: self._connection.request(method, uri, body=body, headers=dict(self._headers, **headers)) return self._connection.getresponse() except Exception: if not tries:", "NotSupportedError, ) def __init__(self, scheme='http', host='localhost', port=4001, user=None, password=<PASSWORD>, connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages", "detect_types & PARSE_DECLTYPES self.parse_colnames = detect_types & PARSE_COLNAMES self._ephemeral = None if scheme", "self._ephemeral = None def __del__(self): self.close() def commit(self): \"\"\"Database modules that do not", "None: self._ephemeral.__exit__(None, None, None) self._ephemeral = None def __del__(self): self.close() def commit(self): \"\"\"Database", "self._connection.close() self._connection = self._init_connection() def _fetch_response(self, method, uri, body=None, headers={}): \"\"\" Fetch a", "= self._retry_request(method, uri, body=body, headers=headers) redirects = 0 while response.status == 301 and", "not None: self._ephemeral.__exit__(None, None, None) self._ephemeral = None def __del__(self): self.close() def commit(self):", "not None and \\ (self.max_redirects == UNLIMITED_REDIRECTS or redirects < self.max_redirects): redirects +=", "HTTPSConnection else: raise Connection.ProgrammingError('Unsupported scheme %r' % self.scheme) return cls(self.host, port=self.port, timeout=None if", "def __init__(self, scheme='http', host='localhost', port=4001, user=None, password=<PASSWORD>, connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages = []", "functionality.\"\"\" pass def rollback(self): \"\"\"This method is optional since not all databases provide", "== 301 and \\ response.getheader('Location') is not None and \\ (self.max_redirects == UNLIMITED_REDIRECTS", "(or subclass) exception will be raised if any operation is attempted with the", "\"\"\" pass def cursor(self, factory=None): \"\"\"Return a new Cursor Object using the connection.\"\"\"", "all databases provide transaction support. \"\"\" pass def cursor(self, factory=None): \"\"\"Return a new", "._ephemeral import EphemeralRqlited as _EphemeralRqlited from .extensions import PARSE_DECLTYPES, PARSE_COLNAMES class Connection(object): from", "host='localhost', port=4001, user=None, password=<PASSWORD>, connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages = [] self.scheme = scheme", "self._connection.close() self.host = location.hostname self.port = location.port self._connection = self._init_connection() response = self._retry_request(method,", "Exception: if not tries: raise self._connection.close() self._connection = self._init_connection() def _fetch_response(self, method, uri,", "will cause an implicit rollback to be performed.\"\"\" self._connection.close() if self._ephemeral is not", "user=None, password=<PASSWORD>, connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages = [] self.scheme = scheme self.host =", "< self.max_redirects): redirects += 1 uri = response.getheader('Location') location = urlparse(uri) logging.getLogger(__name__).debug(\"status: %s", "reason: '%s' location: '%s'\", response.status, response.reason, uri) if self.host != location.hostname or self.port", "from urlparse import urlparse from .constants import ( UNLIMITED_REDIRECTS, ) from .cursors import", "import HTTPConnection, HTTPSConnection try: from urllib.parse import urlparse except ImportError: # pylint: disable=import-error", "__future__ import unicode_literals import codecs import logging try: from http.client import HTTPConnection, HTTPSConnection", "return cls(self.host, port=self.port, timeout=None if self.connect_timeout is None else float(self.connect_timeout)) def _retry_request(self, method,", "\\ response.getheader('Location') is not None and \\ (self.max_redirects == UNLIMITED_REDIRECTS or redirects <", "<reponame>zmedico/pyrqlite from __future__ import unicode_literals import codecs import logging try: from http.client import", "(user is None or password is None): self._headers['Authorization'] = 'Basic ' + \\", "from .cursors import Cursor from ._ephemeral import EphemeralRqlited as _EphemeralRqlited from .extensions import", "the connection. The same applies to all cursor objects trying to use the", "trying to use the connection. Note that closing a connection without committing the", "':memory:'): cls = HTTPConnection elif self.scheme == 'https': cls = HTTPSConnection else: raise", "or password is None): self._headers['Authorization'] = 'Basic ' + \\ codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n')", "'Basic ' + \\ codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n') self.connect_timeout = connect_timeout self.max_redirects = max_redirects", "InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError, ) def __init__(self, scheme='http', host='localhost',", "%r' % self.scheme) return cls(self.host, port=self.port, timeout=None if self.connect_timeout is None else float(self.connect_timeout))", "_fetch_response(self, method, uri, body=None, headers={}): \"\"\" Fetch a response, handling redirection. \"\"\" response", "0 while response.status == 301 and \\ response.getheader('Location') is not None and \\", "== 'https': cls = HTTPSConnection else: raise Connection.ProgrammingError('Unsupported scheme %r' % self.scheme) return", "uri = response.getheader('Location') location = urlparse(uri) logging.getLogger(__name__).debug(\"status: %s reason: '%s' location: '%s'\", response.status,", "= self._retry_request(method, uri, body=body, headers=headers) return response def close(self): \"\"\"Close the connection now", "if self.scheme in ('http', ':memory:'): cls = HTTPConnection elif self.scheme == 'https': cls", "if not (user is None or password is None): self._headers['Authorization'] = 'Basic '", "raise self._connection.close() self._connection = self._init_connection() def _fetch_response(self, method, uri, body=None, headers={}): \"\"\" Fetch", "uri, body=body, headers=headers) redirects = 0 while response.status == 301 and \\ response.getheader('Location')", "__del__(self): self.close() def commit(self): \"\"\"Database modules that do not support transactions should implement", "location = urlparse(uri) logging.getLogger(__name__).debug(\"status: %s reason: '%s' location: '%s'\", response.status, response.reason, uri) if", "from .exceptions import ( Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError,", ".cursors import Cursor from ._ephemeral import EphemeralRqlited as _EphemeralRqlited from .extensions import PARSE_DECLTYPES,", "changes first will cause an implicit rollback to be performed.\"\"\" self._connection.close() if self._ephemeral", "with void functionality.\"\"\" pass def rollback(self): \"\"\"This method is optional since not all", "None): self._headers['Authorization'] = 'Basic ' + \\ codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n') self.connect_timeout = connect_timeout", "self._ephemeral.http self._connection = self._init_connection() def _init_connection(self): if self.scheme in ('http', ':memory:'): cls =", "cls = HTTPSConnection else: raise Connection.ProgrammingError('Unsupported scheme %r' % self.scheme) return cls(self.host, port=self.port,", "void functionality.\"\"\" pass def rollback(self): \"\"\"This method is optional since not all databases", "float(self.connect_timeout)) def _retry_request(self, method, uri, body=None, headers={}): tries = 10 while tries: tries", "password=<PASSWORD>, connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages = [] self.scheme = scheme self.host = host", "commit(self): \"\"\"Database modules that do not support transactions should implement this method with", "first will cause an implicit rollback to be performed.\"\"\" self._connection.close() if self._ephemeral is", "now (rather than whenever .__del__() is called). The connection will be unusable from", "' + \\ codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n') self.connect_timeout = connect_timeout self.max_redirects = max_redirects self.detect_types", "since not all databases provide transaction support. \"\"\" pass def cursor(self, factory=None): \"\"\"Return", "implement this method with void functionality.\"\"\" pass def rollback(self): \"\"\"This method is optional", "PARSE_COLNAMES self._ephemeral = None if scheme == ':memory:': self._ephemeral = _EphemeralRqlited().__enter__() self.host, self.port", "point forward; an Error (or subclass) exception will be raised if any operation", "self.port = self._ephemeral.http self._connection = self._init_connection() def _init_connection(self): if self.scheme in ('http', ':memory:'):", "tries -= 1 try: self._connection.request(method, uri, body=body, headers=dict(self._headers, **headers)) return self._connection.getresponse() except Exception:", "that do not support transactions should implement this method with void functionality.\"\"\" pass", "None and \\ (self.max_redirects == UNLIMITED_REDIRECTS or redirects < self.max_redirects): redirects += 1", "The connection will be unusable from this point forward; an Error (or subclass)", "scheme %r' % self.scheme) return cls(self.host, port=self.port, timeout=None if self.connect_timeout is None else", "redirects += 1 uri = response.getheader('Location') location = urlparse(uri) logging.getLogger(__name__).debug(\"status: %s reason: '%s'", "Fetch a response, handling redirection. \"\"\" response = self._retry_request(method, uri, body=body, headers=headers) redirects", "databases provide transaction support. \"\"\" pass def cursor(self, factory=None): \"\"\"Return a new Cursor", "scheme self.host = host self.port = port self._headers = {} if not (user", "import unicode_literals import codecs import logging try: from http.client import HTTPConnection, HTTPSConnection except", "= 0 while response.status == 301 and \\ response.getheader('Location') is not None and", "be unusable from this point forward; an Error (or subclass) exception will be", "transactions should implement this method with void functionality.\"\"\" pass def rollback(self): \"\"\"This method", "== ':memory:': self._ephemeral = _EphemeralRqlited().__enter__() self.host, self.port = self._ephemeral.http self._connection = self._init_connection() def", "connection now (rather than whenever .__del__() is called). The connection will be unusable", "committing the changes first will cause an implicit rollback to be performed.\"\"\" self._connection.close()", "self.scheme) return cls(self.host, port=self.port, timeout=None if self.connect_timeout is None else float(self.connect_timeout)) def _retry_request(self,", "\"\"\" response = self._retry_request(method, uri, body=body, headers=headers) redirects = 0 while response.status ==", "response.getheader('Location') is not None and \\ (self.max_redirects == UNLIMITED_REDIRECTS or redirects < self.max_redirects):", "self._connection = self._init_connection() def _init_connection(self): if self.scheme in ('http', ':memory:'): cls = HTTPConnection", "Cursor from ._ephemeral import EphemeralRqlited as _EphemeralRqlited from .extensions import PARSE_DECLTYPES, PARSE_COLNAMES class", "( UNLIMITED_REDIRECTS, ) from .cursors import Cursor from ._ephemeral import EphemeralRqlited as _EphemeralRqlited", "from this point forward; an Error (or subclass) exception will be raised if", "if factory: return factory(self) else: return Cursor(self) def execute(self, *args, **kwargs): return self.cursor().execute(*args,", "while tries: tries -= 1 try: self._connection.request(method, uri, body=body, headers=dict(self._headers, **headers)) return self._connection.getresponse()", "use the connection. Note that closing a connection without committing the changes first", "self.messages = [] self.scheme = scheme self.host = host self.port = port self._headers", "**headers)) return self._connection.getresponse() except Exception: if not tries: raise self._connection.close() self._connection = self._init_connection()", "detect_types & PARSE_COLNAMES self._ephemeral = None if scheme == ':memory:': self._ephemeral = _EphemeralRqlited().__enter__()", "http.client import HTTPConnection, HTTPSConnection except ImportError: # pylint: disable=import-error from httplib import HTTPConnection,", "operation is attempted with the connection. The same applies to all cursor objects", "return self._connection.getresponse() except Exception: if not tries: raise self._connection.close() self._connection = self._init_connection() def", "or self.port != location.port: self._connection.close() self.host = location.hostname self.port = location.port self._connection =", "urlparse except ImportError: # pylint: disable=import-error from urlparse import urlparse from .constants import", "uri, body=None, headers={}): \"\"\" Fetch a response, handling redirection. \"\"\" response = self._retry_request(method,", "self.host, self.port = self._ephemeral.http self._connection = self._init_connection() def _init_connection(self): if self.scheme in ('http',", "this method with void functionality.\"\"\" pass def rollback(self): \"\"\"This method is optional since", "called). The connection will be unusable from this point forward; an Error (or", "self.port = port self._headers = {} if not (user is None or password", "HTTPConnection elif self.scheme == 'https': cls = HTTPSConnection else: raise Connection.ProgrammingError('Unsupported scheme %r'", "'https': cls = HTTPSConnection else: raise Connection.ProgrammingError('Unsupported scheme %r' % self.scheme) return cls(self.host,", "than whenever .__del__() is called). The connection will be unusable from this point", "cls(self.host, port=self.port, timeout=None if self.connect_timeout is None else float(self.connect_timeout)) def _retry_request(self, method, uri,", "location: '%s'\", response.status, response.reason, uri) if self.host != location.hostname or self.port != location.port:", "_EphemeralRqlited().__enter__() self.host, self.port = self._ephemeral.http self._connection = self._init_connection() def _init_connection(self): if self.scheme in", "tries: raise self._connection.close() self._connection = self._init_connection() def _fetch_response(self, method, uri, body=None, headers={}): \"\"\"", "Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError, ) def __init__(self,", "self.connect_timeout = connect_timeout self.max_redirects = max_redirects self.detect_types = detect_types self.parse_decltypes = detect_types &", "urlparse from .constants import ( UNLIMITED_REDIRECTS, ) from .cursors import Cursor from ._ephemeral", "headers=dict(self._headers, **headers)) return self._connection.getresponse() except Exception: if not tries: raise self._connection.close() self._connection =", "_retry_request(self, method, uri, body=None, headers={}): tries = 10 while tries: tries -= 1", "exception will be raised if any operation is attempted with the connection. The", "connect_timeout self.max_redirects = max_redirects self.detect_types = detect_types self.parse_decltypes = detect_types & PARSE_DECLTYPES self.parse_colnames", "Connection(object): from .exceptions import ( Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError, InternalError,", "self.max_redirects = max_redirects self.detect_types = detect_types self.parse_decltypes = detect_types & PARSE_DECLTYPES self.parse_colnames =", "response = self._retry_request(method, uri, body=body, headers=headers) redirects = 0 while response.status == 301", "location.port: self._connection.close() self.host = location.hostname self.port = location.port self._connection = self._init_connection() response =", "import ( Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError, )", "UNLIMITED_REDIRECTS or redirects < self.max_redirects): redirects += 1 uri = response.getheader('Location') location =", "& PARSE_DECLTYPES self.parse_colnames = detect_types & PARSE_COLNAMES self._ephemeral = None if scheme ==", "def _retry_request(self, method, uri, body=None, headers={}): tries = 10 while tries: tries -=", "this point forward; an Error (or subclass) exception will be raised if any", "be raised if any operation is attempted with the connection. The same applies", "method with void functionality.\"\"\" pass def rollback(self): \"\"\"This method is optional since not", "response.reason, uri) if self.host != location.hostname or self.port != location.port: self._connection.close() self.host =", "if any operation is attempted with the connection. The same applies to all", "an implicit rollback to be performed.\"\"\" self._connection.close() if self._ephemeral is not None: self._ephemeral.__exit__(None,", "or redirects < self.max_redirects): redirects += 1 uri = response.getheader('Location') location = urlparse(uri)", "(rather than whenever .__del__() is called). The connection will be unusable from this", "_init_connection(self): if self.scheme in ('http', ':memory:'): cls = HTTPConnection elif self.scheme == 'https':", "self.scheme == 'https': cls = HTTPSConnection else: raise Connection.ProgrammingError('Unsupported scheme %r' % self.scheme)", "('http', ':memory:'): cls = HTTPConnection elif self.scheme == 'https': cls = HTTPSConnection else:", "self.host = host self.port = port self._headers = {} if not (user is", "try: from urllib.parse import urlparse except ImportError: # pylint: disable=import-error from urlparse import", "response = self._retry_request(method, uri, body=body, headers=headers) return response def close(self): \"\"\"Close the connection", "method, uri, body=None, headers={}): tries = 10 while tries: tries -= 1 try:", "= location.hostname self.port = location.port self._connection = self._init_connection() response = self._retry_request(method, uri, body=body,", "support transactions should implement this method with void functionality.\"\"\" pass def rollback(self): \"\"\"This", "tries = 10 while tries: tries -= 1 try: self._connection.request(method, uri, body=body, headers=dict(self._headers,", "connection will be unusable from this point forward; an Error (or subclass) exception", "pass def cursor(self, factory=None): \"\"\"Return a new Cursor Object using the connection.\"\"\" if", "the connection.\"\"\" if factory: return factory(self) else: return Cursor(self) def execute(self, *args, **kwargs):", "in ('http', ':memory:'): cls = HTTPConnection elif self.scheme == 'https': cls = HTTPSConnection", "ProgrammingError, NotSupportedError, ) def __init__(self, scheme='http', host='localhost', port=4001, user=None, password=<PASSWORD>, connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS):", "= response.getheader('Location') location = urlparse(uri) logging.getLogger(__name__).debug(\"status: %s reason: '%s' location: '%s'\", response.status, response.reason,", "HTTPConnection, HTTPSConnection except ImportError: # pylint: disable=import-error from httplib import HTTPConnection, HTTPSConnection try:", "self.detect_types = detect_types self.parse_decltypes = detect_types & PARSE_DECLTYPES self.parse_colnames = detect_types & PARSE_COLNAMES", "= self._init_connection() def _fetch_response(self, method, uri, body=None, headers={}): \"\"\" Fetch a response, handling", "will be raised if any operation is attempted with the connection. The same", "HTTPSConnection except ImportError: # pylint: disable=import-error from httplib import HTTPConnection, HTTPSConnection try: from", "method is optional since not all databases provide transaction support. \"\"\" pass def", ".constants import ( UNLIMITED_REDIRECTS, ) from .cursors import Cursor from ._ephemeral import EphemeralRqlited", "None or password is None): self._headers['Authorization'] = 'Basic ' + \\ codecs.encode('{}:{}'.format(user, password).encode('utf-8'),", "max_redirects self.detect_types = detect_types self.parse_decltypes = detect_types & PARSE_DECLTYPES self.parse_colnames = detect_types &", "uri, body=body, headers=headers) return response def close(self): \"\"\"Close the connection now (rather than", "tries: tries -= 1 try: self._connection.request(method, uri, body=body, headers=dict(self._headers, **headers)) return self._connection.getresponse() except", "self._init_connection() response = self._retry_request(method, uri, body=body, headers=headers) return response def close(self): \"\"\"Close the", "':memory:': self._ephemeral = _EphemeralRqlited().__enter__() self.host, self.port = self._ephemeral.http self._connection = self._init_connection() def _init_connection(self):", "not all databases provide transaction support. \"\"\" pass def cursor(self, factory=None): \"\"\"Return a", "to be performed.\"\"\" self._connection.close() if self._ephemeral is not None: self._ephemeral.__exit__(None, None, None) self._ephemeral", "if not tries: raise self._connection.close() self._connection = self._init_connection() def _fetch_response(self, method, uri, body=None,", "all cursor objects trying to use the connection. Note that closing a connection", "= connect_timeout self.max_redirects = max_redirects self.detect_types = detect_types self.parse_decltypes = detect_types & PARSE_DECLTYPES", "elif self.scheme == 'https': cls = HTTPSConnection else: raise Connection.ProgrammingError('Unsupported scheme %r' %", "body=None, headers={}): tries = 10 while tries: tries -= 1 try: self._connection.request(method, uri,", "location.hostname or self.port != location.port: self._connection.close() self.host = location.hostname self.port = location.port self._connection", "Connection.ProgrammingError('Unsupported scheme %r' % self.scheme) return cls(self.host, port=self.port, timeout=None if self.connect_timeout is None", "= [] self.scheme = scheme self.host = host self.port = port self._headers =", "unicode_literals import codecs import logging try: from http.client import HTTPConnection, HTTPSConnection except ImportError:", "self._connection = self._init_connection() def _fetch_response(self, method, uri, body=None, headers={}): \"\"\" Fetch a response,", "= detect_types self.parse_decltypes = detect_types & PARSE_DECLTYPES self.parse_colnames = detect_types & PARSE_COLNAMES self._ephemeral", "== UNLIMITED_REDIRECTS or redirects < self.max_redirects): redirects += 1 uri = response.getheader('Location') location", "port=4001, user=None, password=<PASSWORD>, connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages = [] self.scheme = scheme self.host", "connection. The same applies to all cursor objects trying to use the connection.", "while response.status == 301 and \\ response.getheader('Location') is not None and \\ (self.max_redirects", "InternalError, ProgrammingError, NotSupportedError, ) def __init__(self, scheme='http', host='localhost', port=4001, user=None, password=<PASSWORD>, connect_timeout=None, detect_types=0,", "Note that closing a connection without committing the changes first will cause an", "if self.host != location.hostname or self.port != location.port: self._connection.close() self.host = location.hostname self.port", "except Exception: if not tries: raise self._connection.close() self._connection = self._init_connection() def _fetch_response(self, method,", "+= 1 uri = response.getheader('Location') location = urlparse(uri) logging.getLogger(__name__).debug(\"status: %s reason: '%s' location:", "= None if scheme == ':memory:': self._ephemeral = _EphemeralRqlited().__enter__() self.host, self.port = self._ephemeral.http", "self._connection.getresponse() except Exception: if not tries: raise self._connection.close() self._connection = self._init_connection() def _fetch_response(self,", "# pylint: disable=import-error from httplib import HTTPConnection, HTTPSConnection try: from urllib.parse import urlparse", "is None or password is None): self._headers['Authorization'] = 'Basic ' + \\ codecs.encode('{}:{}'.format(user,", "without committing the changes first will cause an implicit rollback to be performed.\"\"\"", "raise Connection.ProgrammingError('Unsupported scheme %r' % self.scheme) return cls(self.host, port=self.port, timeout=None if self.connect_timeout is", "redirects = 0 while response.status == 301 and \\ response.getheader('Location') is not None", "self.scheme = scheme self.host = host self.port = port self._headers = {} if", "rollback to be performed.\"\"\" self._connection.close() if self._ephemeral is not None: self._ephemeral.__exit__(None, None, None)", "the connection now (rather than whenever .__del__() is called). The connection will be", "self._ephemeral is not None: self._ephemeral.__exit__(None, None, None) self._ephemeral = None def __del__(self): self.close()", "do not support transactions should implement this method with void functionality.\"\"\" pass def", "= detect_types & PARSE_DECLTYPES self.parse_colnames = detect_types & PARSE_COLNAMES self._ephemeral = None if", "codecs import logging try: from http.client import HTTPConnection, HTTPSConnection except ImportError: # pylint:", "disable=import-error from httplib import HTTPConnection, HTTPSConnection try: from urllib.parse import urlparse except ImportError:", "transaction support. \"\"\" pass def cursor(self, factory=None): \"\"\"Return a new Cursor Object using", "def rollback(self): \"\"\"This method is optional since not all databases provide transaction support.", "any operation is attempted with the connection. The same applies to all cursor", "is called). The connection will be unusable from this point forward; an Error", "connection.\"\"\" if factory: return factory(self) else: return Cursor(self) def execute(self, *args, **kwargs): return", "= detect_types & PARSE_COLNAMES self._ephemeral = None if scheme == ':memory:': self._ephemeral =", "detect_types self.parse_decltypes = detect_types & PARSE_DECLTYPES self.parse_colnames = detect_types & PARSE_COLNAMES self._ephemeral =", "except ImportError: # pylint: disable=import-error from urlparse import urlparse from .constants import (", "from ._ephemeral import EphemeralRqlited as _EphemeralRqlited from .extensions import PARSE_DECLTYPES, PARSE_COLNAMES class Connection(object):", "import logging try: from http.client import HTTPConnection, HTTPSConnection except ImportError: # pylint: disable=import-error", "redirects < self.max_redirects): redirects += 1 uri = response.getheader('Location') location = urlparse(uri) logging.getLogger(__name__).debug(\"status:", "1 try: self._connection.request(method, uri, body=body, headers=dict(self._headers, **headers)) return self._connection.getresponse() except Exception: if not", "logging try: from http.client import HTTPConnection, HTTPSConnection except ImportError: # pylint: disable=import-error from", "from .extensions import PARSE_DECLTYPES, PARSE_COLNAMES class Connection(object): from .exceptions import ( Warning, Error,", "= urlparse(uri) logging.getLogger(__name__).debug(\"status: %s reason: '%s' location: '%s'\", response.status, response.reason, uri) if self.host", "provide transaction support. \"\"\" pass def cursor(self, factory=None): \"\"\"Return a new Cursor Object", "import EphemeralRqlited as _EphemeralRqlited from .extensions import PARSE_DECLTYPES, PARSE_COLNAMES class Connection(object): from .exceptions", "whenever .__del__() is called). The connection will be unusable from this point forward;", "httplib import HTTPConnection, HTTPSConnection try: from urllib.parse import urlparse except ImportError: # pylint:", "factory: return factory(self) else: return Cursor(self) def execute(self, *args, **kwargs): return self.cursor().execute(*args, **kwargs)", "def close(self): \"\"\"Close the connection now (rather than whenever .__del__() is called). The", "= HTTPSConnection else: raise Connection.ProgrammingError('Unsupported scheme %r' % self.scheme) return cls(self.host, port=self.port, timeout=None", "try: from http.client import HTTPConnection, HTTPSConnection except ImportError: # pylint: disable=import-error from httplib", "HTTPConnection, HTTPSConnection try: from urllib.parse import urlparse except ImportError: # pylint: disable=import-error from", "self._headers['Authorization'] = 'Basic ' + \\ codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n') self.connect_timeout = connect_timeout self.max_redirects", "a response, handling redirection. \"\"\" response = self._retry_request(method, uri, body=body, headers=headers) redirects =", "\"\"\"Close the connection now (rather than whenever .__del__() is called). The connection will", "= scheme self.host = host self.port = port self._headers = {} if not", "pylint: disable=import-error from urlparse import urlparse from .constants import ( UNLIMITED_REDIRECTS, ) from", "Error (or subclass) exception will be raised if any operation is attempted with", "def cursor(self, factory=None): \"\"\"Return a new Cursor Object using the connection.\"\"\" if factory:", "self._init_connection() def _fetch_response(self, method, uri, body=None, headers={}): \"\"\" Fetch a response, handling redirection.", "redirection. \"\"\" response = self._retry_request(method, uri, body=body, headers=headers) redirects = 0 while response.status", "the connection. Note that closing a connection without committing the changes first will", "self.close() def commit(self): \"\"\"Database modules that do not support transactions should implement this", "DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError, ) def __init__(self, scheme='http', host='localhost', port=4001, user=None,", "import ( UNLIMITED_REDIRECTS, ) from .cursors import Cursor from ._ephemeral import EphemeralRqlited as", "as _EphemeralRqlited from .extensions import PARSE_DECLTYPES, PARSE_COLNAMES class Connection(object): from .exceptions import (", "self.parse_colnames = detect_types & PARSE_COLNAMES self._ephemeral = None if scheme == ':memory:': self._ephemeral", "= self._init_connection() def _init_connection(self): if self.scheme in ('http', ':memory:'): cls = HTTPConnection elif", "rollback(self): \"\"\"This method is optional since not all databases provide transaction support. \"\"\"", "not support transactions should implement this method with void functionality.\"\"\" pass def rollback(self):", "{} if not (user is None or password is None): self._headers['Authorization'] = 'Basic", "self.port != location.port: self._connection.close() self.host = location.hostname self.port = location.port self._connection = self._init_connection()", "self.scheme in ('http', ':memory:'): cls = HTTPConnection elif self.scheme == 'https': cls =", "an Error (or subclass) exception will be raised if any operation is attempted", "( Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError, ) def", "is None else float(self.connect_timeout)) def _retry_request(self, method, uri, body=None, headers={}): tries = 10", "not (user is None or password is None): self._headers['Authorization'] = 'Basic ' +", "= _EphemeralRqlited().__enter__() self.host, self.port = self._ephemeral.http self._connection = self._init_connection() def _init_connection(self): if self.scheme", "headers=headers) redirects = 0 while response.status == 301 and \\ response.getheader('Location') is not", ") def __init__(self, scheme='http', host='localhost', port=4001, user=None, password=<PASSWORD>, connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages =", "return response def close(self): \"\"\"Close the connection now (rather than whenever .__del__() is", "if scheme == ':memory:': self._ephemeral = _EphemeralRqlited().__enter__() self.host, self.port = self._ephemeral.http self._connection =", "to all cursor objects trying to use the connection. Note that closing a", "applies to all cursor objects trying to use the connection. Note that closing", "None, None) self._ephemeral = None def __del__(self): self.close() def commit(self): \"\"\"Database modules that", "urlparse import urlparse from .constants import ( UNLIMITED_REDIRECTS, ) from .cursors import Cursor", "self.max_redirects): redirects += 1 uri = response.getheader('Location') location = urlparse(uri) logging.getLogger(__name__).debug(\"status: %s reason:", "and \\ (self.max_redirects == UNLIMITED_REDIRECTS or redirects < self.max_redirects): redirects += 1 uri", "modules that do not support transactions should implement this method with void functionality.\"\"\"", "response, handling redirection. \"\"\" response = self._retry_request(method, uri, body=body, headers=headers) redirects = 0", "__init__(self, scheme='http', host='localhost', port=4001, user=None, password=<PASSWORD>, connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages = [] self.scheme", "cursor(self, factory=None): \"\"\"Return a new Cursor Object using the connection.\"\"\" if factory: return", "\"\"\"Database modules that do not support transactions should implement this method with void", "else: raise Connection.ProgrammingError('Unsupported scheme %r' % self.scheme) return cls(self.host, port=self.port, timeout=None if self.connect_timeout" ]
[ "rent = total_price * 0.1 total_price = total_price - rent if total_price >=", "rent if total_price >= price: print(f\"Yes! {(total_price - price):.2f} lv left.\") else: print(f\"Not", "minions = int(input()) trucks = int(input()) total_toys = puzzles + dolls + bears", "= int(input()) trucks = int(input()) total_toys = puzzles + dolls + bears +", "+ price_minions + price_trucks if total_toys >= 50: total_price = total_price - (total_price", "puzzles = int(input()) dolls = int(input()) bears = int(input()) minions = int(input()) trucks", "3 price_bears = bears * 4.1 price_minions = minions * 8.2 price_trucks =", "price_minions = minions * 8.2 price_trucks = trucks * 2 total_price = price_puzzles", "total_price >= price: print(f\"Yes! {(total_price - price):.2f} lv left.\") else: print(f\"Not enough money!", "price_trucks = trucks * 2 total_price = price_puzzles + price_dolls + price_bears +", "if total_price >= price: print(f\"Yes! {(total_price - price):.2f} lv left.\") else: print(f\"Not enough", "total_price * 0.1 total_price = total_price - rent if total_price >= price: print(f\"Yes!", "puzzles + dolls + bears + minions + trucks price_puzzles = puzzles *", "price: print(f\"Yes! {(total_price - price):.2f} lv left.\") else: print(f\"Not enough money! {(price -", "= int(input()) dolls = int(input()) bears = int(input()) minions = int(input()) trucks =", "2.6 price_dolls = dolls * 3 price_bears = bears * 4.1 price_minions =", ">= 50: total_price = total_price - (total_price * 0.25) rent = total_price *", "= float(input()) puzzles = int(input()) dolls = int(input()) bears = int(input()) minions =", "= puzzles + dolls + bears + minions + trucks price_puzzles = puzzles", "minions * 8.2 price_trucks = trucks * 2 total_price = price_puzzles + price_dolls", "int(input()) minions = int(input()) trucks = int(input()) total_toys = puzzles + dolls +", "+ minions + trucks price_puzzles = puzzles * 2.6 price_dolls = dolls *", "+ bears + minions + trucks price_puzzles = puzzles * 2.6 price_dolls =", "price_bears + price_minions + price_trucks if total_toys >= 50: total_price = total_price -", "total_toys >= 50: total_price = total_price - (total_price * 0.25) rent = total_price", "0.25) rent = total_price * 0.1 total_price = total_price - rent if total_price", "puzzles * 2.6 price_dolls = dolls * 3 price_bears = bears * 4.1", "total_price - (total_price * 0.25) rent = total_price * 0.1 total_price = total_price", "* 0.25) rent = total_price * 0.1 total_price = total_price - rent if", "price_puzzles + price_dolls + price_bears + price_minions + price_trucks if total_toys >= 50:", "- rent if total_price >= price: print(f\"Yes! {(total_price - price):.2f} lv left.\") else:", "4.1 price_minions = minions * 8.2 price_trucks = trucks * 2 total_price =", "* 8.2 price_trucks = trucks * 2 total_price = price_puzzles + price_dolls +", "* 2.6 price_dolls = dolls * 3 price_bears = bears * 4.1 price_minions", "= int(input()) bears = int(input()) minions = int(input()) trucks = int(input()) total_toys =", "bears = int(input()) minions = int(input()) trucks = int(input()) total_toys = puzzles +", "= bears * 4.1 price_minions = minions * 8.2 price_trucks = trucks *", "50: total_price = total_price - (total_price * 0.25) rent = total_price * 0.1", ">= price: print(f\"Yes! {(total_price - price):.2f} lv left.\") else: print(f\"Not enough money! {(price", "= dolls * 3 price_bears = bears * 4.1 price_minions = minions *", "2 total_price = price_puzzles + price_dolls + price_bears + price_minions + price_trucks if", "= price_puzzles + price_dolls + price_bears + price_minions + price_trucks if total_toys >=", "price_dolls + price_bears + price_minions + price_trucks if total_toys >= 50: total_price =", "dolls + bears + minions + trucks price_puzzles = puzzles * 2.6 price_dolls", "* 0.1 total_price = total_price - rent if total_price >= price: print(f\"Yes! {(total_price", "total_toys = puzzles + dolls + bears + minions + trucks price_puzzles =", "trucks price_puzzles = puzzles * 2.6 price_dolls = dolls * 3 price_bears =", "total_price = price_puzzles + price_dolls + price_bears + price_minions + price_trucks if total_toys", "= total_price - (total_price * 0.25) rent = total_price * 0.1 total_price =", "{(total_price - price):.2f} lv left.\") else: print(f\"Not enough money! {(price - total_price):.2f} lv", "+ price_trucks if total_toys >= 50: total_price = total_price - (total_price * 0.25)", "total_price - rent if total_price >= price: print(f\"Yes! {(total_price - price):.2f} lv left.\")", "int(input()) bears = int(input()) minions = int(input()) trucks = int(input()) total_toys = puzzles", "8.2 price_trucks = trucks * 2 total_price = price_puzzles + price_dolls + price_bears", "+ dolls + bears + minions + trucks price_puzzles = puzzles * 2.6", "price_trucks if total_toys >= 50: total_price = total_price - (total_price * 0.25) rent", "price_puzzles = puzzles * 2.6 price_dolls = dolls * 3 price_bears = bears", "price_dolls = dolls * 3 price_bears = bears * 4.1 price_minions = minions", "bears * 4.1 price_minions = minions * 8.2 price_trucks = trucks * 2", "print(f\"Yes! {(total_price - price):.2f} lv left.\") else: print(f\"Not enough money! {(price - total_price):.2f}", "float(input()) puzzles = int(input()) dolls = int(input()) bears = int(input()) minions = int(input())", "* 3 price_bears = bears * 4.1 price_minions = minions * 8.2 price_trucks", "price_bears = bears * 4.1 price_minions = minions * 8.2 price_trucks = trucks", "= int(input()) minions = int(input()) trucks = int(input()) total_toys = puzzles + dolls", "dolls * 3 price_bears = bears * 4.1 price_minions = minions * 8.2", "int(input()) dolls = int(input()) bears = int(input()) minions = int(input()) trucks = int(input())", "= total_price - rent if total_price >= price: print(f\"Yes! {(total_price - price):.2f} lv", "- price):.2f} lv left.\") else: print(f\"Not enough money! {(price - total_price):.2f} lv needed.\")", "= trucks * 2 total_price = price_puzzles + price_dolls + price_bears + price_minions", "trucks * 2 total_price = price_puzzles + price_dolls + price_bears + price_minions +", "int(input()) trucks = int(input()) total_toys = puzzles + dolls + bears + minions", "= puzzles * 2.6 price_dolls = dolls * 3 price_bears = bears *", "<filename>PythonBasics/ConditionalStatements/Exercise/toy_shop.py<gh_stars>0 price = float(input()) puzzles = int(input()) dolls = int(input()) bears = int(input())", "+ trucks price_puzzles = puzzles * 2.6 price_dolls = dolls * 3 price_bears", "= minions * 8.2 price_trucks = trucks * 2 total_price = price_puzzles +", "+ price_bears + price_minions + price_trucks if total_toys >= 50: total_price = total_price", "= int(input()) total_toys = puzzles + dolls + bears + minions + trucks", "* 4.1 price_minions = minions * 8.2 price_trucks = trucks * 2 total_price", "int(input()) total_toys = puzzles + dolls + bears + minions + trucks price_puzzles", "minions + trucks price_puzzles = puzzles * 2.6 price_dolls = dolls * 3", "0.1 total_price = total_price - rent if total_price >= price: print(f\"Yes! {(total_price -", "dolls = int(input()) bears = int(input()) minions = int(input()) trucks = int(input()) total_toys", "(total_price * 0.25) rent = total_price * 0.1 total_price = total_price - rent", "total_price = total_price - (total_price * 0.25) rent = total_price * 0.1 total_price", "if total_toys >= 50: total_price = total_price - (total_price * 0.25) rent =", "- (total_price * 0.25) rent = total_price * 0.1 total_price = total_price -", "price_minions + price_trucks if total_toys >= 50: total_price = total_price - (total_price *", "+ price_dolls + price_bears + price_minions + price_trucks if total_toys >= 50: total_price", "bears + minions + trucks price_puzzles = puzzles * 2.6 price_dolls = dolls", "* 2 total_price = price_puzzles + price_dolls + price_bears + price_minions + price_trucks", "trucks = int(input()) total_toys = puzzles + dolls + bears + minions +", "= total_price * 0.1 total_price = total_price - rent if total_price >= price:", "price = float(input()) puzzles = int(input()) dolls = int(input()) bears = int(input()) minions", "total_price = total_price - rent if total_price >= price: print(f\"Yes! {(total_price - price):.2f}" ]
[ "License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "writing, software # distributed under the License is distributed on an \"AS IS\"", "return json.dumps((self._cache.get(key), dt.strftime('%s'))) def set(self, key, value, timeout=None): self.set_value = value self.set_key =", "'mytenant', 'roles': [{'name': 'admin'}] }, } }, 'tokens/%s' % MEMBER_TOKEN: { 'access': {", "Unless required by applicable law or agreed to in writing, software # distributed", "License. \"\"\" Utils for testing the API service. \"\"\" import datetime import json", "See the # License for the specific language governing permissions and limitations #", "and limitations # under the License. \"\"\" Utils for testing the API service.", "{'id': 'user_id1', 'name': 'user_name1', 'tenantId': '123i2910', 'tenantName': 'mytenant', 'roles': [{'name': 'admin'}] }, }", "\"License\"); you may # not use this file except in compliance with the", "'tokens/%s' % ADMIN_TOKEN: { 'access': { 'token': {'id': ADMIN_TOKEN}, 'user': {'id': 'user_id1', 'name':", "limitations # under the License. \"\"\" Utils for testing the API service. \"\"\"", "self.set_key = None self.set_value = None self.token_expiration = None def get(self, key): dt", "Apache License, Version 2.0 (the \"License\"); you may # not use this file", "the License. You may obtain # a copy of the License at #", "'access': { 'token': {'id': MEMBER_TOKEN}, 'user': {'id': 'user_id2', 'name': 'user-good', 'tenantId': 'project-good', 'tenantName':", "-*- encoding: utf-8 -*- # # Licensed under the Apache License, Version 2.0", "law or agreed to in writing, software # distributed under the License is", "may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "the Apache License, Version 2.0 (the \"License\"); you may # not use this", "'user_name1', 'tenantId': '123i2910', 'tenantName': 'mytenant', 'roles': [{'name': 'admin'}] }, } }, 'tokens/%s' %", "{'id': MEMBER_TOKEN}, 'user': {'id': 'user_id2', 'name': 'user-good', 'tenantId': 'project-good', 'tenantName': 'goodies', 'roles': [{'name':", "'goodies', 'roles': [{'name': 'Member'}] } } } } def __init__(self): self.set_key = None", "= { 'tokens/%s' % ADMIN_TOKEN: { 'access': { 'token': {'id': ADMIN_TOKEN}, 'user': {'id':", "get(self, key): dt = datetime.datetime.now() + datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key), dt.strftime('%s'))) def set(self, key,", "express or implied. See the # License for the specific language governing permissions", "= None self.token_expiration = None def get(self, key): dt = datetime.datetime.now() + datetime.timedelta(minutes=5)", "'tenantId': '123i2910', 'tenantName': 'mytenant', 'roles': [{'name': 'admin'}] }, } }, 'tokens/%s' % MEMBER_TOKEN:", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "CONDITIONS OF ANY KIND, either express or implied. See the # License for", "not use this file except in compliance with the License. You may obtain", "permissions and limitations # under the License. \"\"\" Utils for testing the API", "{ 'token': {'id': MEMBER_TOKEN}, 'user': {'id': 'user_id2', 'name': 'user-good', 'tenantId': 'project-good', 'tenantName': 'goodies',", "\"\"\" import datetime import json ADMIN_TOKEN = '<PASSWORD>' MEMBER_TOKEN = '<PASSWORD>' class FakeMemcache(object):", "that is used for keystone tokens lookup.\"\"\" _cache = { 'tokens/%s' % ADMIN_TOKEN:", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "with the License. You may obtain # a copy of the License at", "the License. \"\"\" Utils for testing the API service. \"\"\" import datetime import", "None self.token_expiration = None def get(self, key): dt = datetime.datetime.now() + datetime.timedelta(minutes=5) return", "'token': {'id': ADMIN_TOKEN}, 'user': {'id': 'user_id1', 'name': 'user_name1', 'tenantId': '123i2910', 'tenantName': 'mytenant', 'roles':", "shiftwidth=4 softtabstop=4 # -*- encoding: utf-8 -*- # # Licensed under the Apache", "tokens lookup.\"\"\" _cache = { 'tokens/%s' % ADMIN_TOKEN: { 'access': { 'token': {'id':", "API service. \"\"\" import datetime import json ADMIN_TOKEN = '<PASSWORD>' MEMBER_TOKEN = '<PASSWORD>'", "Licensed under the Apache License, Version 2.0 (the \"License\"); you may # not", "= '<PASSWORD>' class FakeMemcache(object): \"\"\"Fake cache that is used for keystone tokens lookup.\"\"\"", "'user-good', 'tenantId': 'project-good', 'tenantName': 'goodies', 'roles': [{'name': 'Member'}] } } } } def", "None def get(self, key): dt = datetime.datetime.now() + datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key), dt.strftime('%s'))) def", "License for the specific language governing permissions and limitations # under the License.", "def get(self, key): dt = datetime.datetime.now() + datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key), dt.strftime('%s'))) def set(self,", "key): dt = datetime.datetime.now() + datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key), dt.strftime('%s'))) def set(self, key, value,", "+ datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key), dt.strftime('%s'))) def set(self, key, value, timeout=None): self.set_value = value", "2.0 (the \"License\"); you may # not use this file except in compliance", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "'admin'}] }, } }, 'tokens/%s' % MEMBER_TOKEN: { 'access': { 'token': {'id': MEMBER_TOKEN},", "vim: tabstop=4 shiftwidth=4 softtabstop=4 # -*- encoding: utf-8 -*- # # Licensed under", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "} }, 'tokens/%s' % MEMBER_TOKEN: { 'access': { 'token': {'id': MEMBER_TOKEN}, 'user': {'id':", "use this file except in compliance with the License. You may obtain #", "# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT", "MEMBER_TOKEN}, 'user': {'id': 'user_id2', 'name': 'user-good', 'tenantId': 'project-good', 'tenantName': 'goodies', 'roles': [{'name': 'Member'}]", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the #", "compliance with the License. You may obtain # a copy of the License", "the API service. \"\"\" import datetime import json ADMIN_TOKEN = '<PASSWORD>' MEMBER_TOKEN =", "'user': {'id': 'user_id1', 'name': 'user_name1', 'tenantId': '123i2910', 'tenantName': 'mytenant', 'roles': [{'name': 'admin'}] },", "the specific language governing permissions and limitations # under the License. \"\"\" Utils", "License, Version 2.0 (the \"License\"); you may # not use this file except", "'name': 'user-good', 'tenantId': 'project-good', 'tenantName': 'goodies', 'roles': [{'name': 'Member'}] } } } }", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "datetime.datetime.now() + datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key), dt.strftime('%s'))) def set(self, key, value, timeout=None): self.set_value =", "tabstop=4 shiftwidth=4 softtabstop=4 # -*- encoding: utf-8 -*- # # Licensed under the", "} } } } def __init__(self): self.set_key = None self.set_value = None self.token_expiration", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "implied. See the # License for the specific language governing permissions and limitations", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "OF ANY KIND, either express or implied. See the # License for the", "None self.set_value = None self.token_expiration = None def get(self, key): dt = datetime.datetime.now()", "self.token_expiration = None def get(self, key): dt = datetime.datetime.now() + datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key),", "json ADMIN_TOKEN = '<PASSWORD>' MEMBER_TOKEN = '<PASSWORD>' class FakeMemcache(object): \"\"\"Fake cache that is", "'user_id1', 'name': 'user_name1', 'tenantId': '123i2910', 'tenantName': 'mytenant', 'roles': [{'name': 'admin'}] }, } },", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "dt = datetime.datetime.now() + datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key), dt.strftime('%s'))) def set(self, key, value, timeout=None):", "= datetime.datetime.now() + datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key), dt.strftime('%s'))) def set(self, key, value, timeout=None): self.set_value", "= None def get(self, key): dt = datetime.datetime.now() + datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key), dt.strftime('%s')))", "MEMBER_TOKEN: { 'access': { 'token': {'id': MEMBER_TOKEN}, 'user': {'id': 'user_id2', 'name': 'user-good', 'tenantId':", "for testing the API service. \"\"\" import datetime import json ADMIN_TOKEN = '<PASSWORD>'", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the", "'user': {'id': 'user_id2', 'name': 'user-good', 'tenantId': 'project-good', 'tenantName': 'goodies', 'roles': [{'name': 'Member'}] }", "'tenantName': 'mytenant', 'roles': [{'name': 'admin'}] }, } }, 'tokens/%s' % MEMBER_TOKEN: { 'access':", "self.set_value = None self.token_expiration = None def get(self, key): dt = datetime.datetime.now() +", "you may # not use this file except in compliance with the License.", "under the License. \"\"\" Utils for testing the API service. \"\"\" import datetime", "agreed to in writing, software # distributed under the License is distributed on", "{ 'token': {'id': ADMIN_TOKEN}, 'user': {'id': 'user_id1', 'name': 'user_name1', 'tenantId': '123i2910', 'tenantName': 'mytenant',", "# under the License. \"\"\" Utils for testing the API service. \"\"\" import", "(the \"License\"); you may # not use this file except in compliance with", "} def __init__(self): self.set_key = None self.set_value = None self.token_expiration = None def", "governing permissions and limitations # under the License. \"\"\" Utils for testing the", "may # not use this file except in compliance with the License. You", "KIND, either express or implied. See the # License for the specific language", "ADMIN_TOKEN = '<PASSWORD>' MEMBER_TOKEN = '<PASSWORD>' class FakeMemcache(object): \"\"\"Fake cache that is used", "def __init__(self): self.set_key = None self.set_value = None self.token_expiration = None def get(self,", "either express or implied. See the # License for the specific language governing", "Utils for testing the API service. \"\"\" import datetime import json ADMIN_TOKEN =", "MEMBER_TOKEN = '<PASSWORD>' class FakeMemcache(object): \"\"\"Fake cache that is used for keystone tokens", "{ 'tokens/%s' % ADMIN_TOKEN: { 'access': { 'token': {'id': ADMIN_TOKEN}, 'user': {'id': 'user_id1',", "service. \"\"\" import datetime import json ADMIN_TOKEN = '<PASSWORD>' MEMBER_TOKEN = '<PASSWORD>' class", "# # Unless required by applicable law or agreed to in writing, software", "file except in compliance with the License. You may obtain # a copy", "_cache = { 'tokens/%s' % ADMIN_TOKEN: { 'access': { 'token': {'id': ADMIN_TOKEN}, 'user':", "[{'name': 'admin'}] }, } }, 'tokens/%s' % MEMBER_TOKEN: { 'access': { 'token': {'id':", "this file except in compliance with the License. You may obtain # a", "# Unless required by applicable law or agreed to in writing, software #", "import datetime import json ADMIN_TOKEN = '<PASSWORD>' MEMBER_TOKEN = '<PASSWORD>' class FakeMemcache(object): \"\"\"Fake", "by applicable law or agreed to in writing, software # distributed under the", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "__init__(self): self.set_key = None self.set_value = None self.token_expiration = None def get(self, key):", "= None self.set_value = None self.token_expiration = None def get(self, key): dt =", "= '<PASSWORD>' MEMBER_TOKEN = '<PASSWORD>' class FakeMemcache(object): \"\"\"Fake cache that is used for", "under the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "or implied. See the # License for the specific language governing permissions and", "[{'name': 'Member'}] } } } } def __init__(self): self.set_key = None self.set_value =", "language governing permissions and limitations # under the License. \"\"\" Utils for testing", "\"\"\" Utils for testing the API service. \"\"\" import datetime import json ADMIN_TOKEN", "ADMIN_TOKEN}, 'user': {'id': 'user_id1', 'name': 'user_name1', 'tenantId': '123i2910', 'tenantName': 'mytenant', 'roles': [{'name': 'admin'}]", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "testing the API service. \"\"\" import datetime import json ADMIN_TOKEN = '<PASSWORD>' MEMBER_TOKEN", "'project-good', 'tenantName': 'goodies', 'roles': [{'name': 'Member'}] } } } } def __init__(self): self.set_key", "'123i2910', 'tenantName': 'mytenant', 'roles': [{'name': 'admin'}] }, } }, 'tokens/%s' % MEMBER_TOKEN: {", "'<PASSWORD>' class FakeMemcache(object): \"\"\"Fake cache that is used for keystone tokens lookup.\"\"\" _cache", "{'id': ADMIN_TOKEN}, 'user': {'id': 'user_id1', 'name': 'user_name1', 'tenantId': '123i2910', 'tenantName': 'mytenant', 'roles': [{'name':", "% MEMBER_TOKEN: { 'access': { 'token': {'id': MEMBER_TOKEN}, 'user': {'id': 'user_id2', 'name': 'user-good',", "FakeMemcache(object): \"\"\"Fake cache that is used for keystone tokens lookup.\"\"\" _cache = {", "used for keystone tokens lookup.\"\"\" _cache = { 'tokens/%s' % ADMIN_TOKEN: { 'access':", "License. You may obtain # a copy of the License at # #", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "for the specific language governing permissions and limitations # under the License. \"\"\"", "specific language governing permissions and limitations # under the License. \"\"\" Utils for", "'tenantId': 'project-good', 'tenantName': 'goodies', 'roles': [{'name': 'Member'}] } } } } def __init__(self):", "} } def __init__(self): self.set_key = None self.set_value = None self.token_expiration = None", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "for keystone tokens lookup.\"\"\" _cache = { 'tokens/%s' % ADMIN_TOKEN: { 'access': {", "# # Licensed under the Apache License, Version 2.0 (the \"License\"); you may", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "ANY KIND, either express or implied. See the # License for the specific", "the # License for the specific language governing permissions and limitations # under", "except in compliance with the License. You may obtain # a copy of", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "{'id': 'user_id2', 'name': 'user-good', 'tenantId': 'project-good', 'tenantName': 'goodies', 'roles': [{'name': 'Member'}] } }", "# vim: tabstop=4 shiftwidth=4 softtabstop=4 # -*- encoding: utf-8 -*- # # Licensed", "# -*- encoding: utf-8 -*- # # Licensed under the Apache License, Version", "{ 'access': { 'token': {'id': MEMBER_TOKEN}, 'user': {'id': 'user_id2', 'name': 'user-good', 'tenantId': 'project-good',", "to in writing, software # distributed under the License is distributed on an", "You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "cache that is used for keystone tokens lookup.\"\"\" _cache = { 'tokens/%s' %", "{ 'access': { 'token': {'id': ADMIN_TOKEN}, 'user': {'id': 'user_id1', 'name': 'user_name1', 'tenantId': '123i2910',", "'tokens/%s' % MEMBER_TOKEN: { 'access': { 'token': {'id': MEMBER_TOKEN}, 'user': {'id': 'user_id2', 'name':", "'token': {'id': MEMBER_TOKEN}, 'user': {'id': 'user_id2', 'name': 'user-good', 'tenantId': 'project-good', 'tenantName': 'goodies', 'roles':", "import json ADMIN_TOKEN = '<PASSWORD>' MEMBER_TOKEN = '<PASSWORD>' class FakeMemcache(object): \"\"\"Fake cache that", "}, 'tokens/%s' % MEMBER_TOKEN: { 'access': { 'token': {'id': MEMBER_TOKEN}, 'user': {'id': 'user_id2',", "'access': { 'token': {'id': ADMIN_TOKEN}, 'user': {'id': 'user_id1', 'name': 'user_name1', 'tenantId': '123i2910', 'tenantName':", "required by applicable law or agreed to in writing, software # distributed under", "\"\"\"Fake cache that is used for keystone tokens lookup.\"\"\" _cache = { 'tokens/%s'", "'tenantName': 'goodies', 'roles': [{'name': 'Member'}] } } } } def __init__(self): self.set_key =", "datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key), dt.strftime('%s'))) def set(self, key, value, timeout=None): self.set_value = value self.set_key", "-*- # # Licensed under the Apache License, Version 2.0 (the \"License\"); you", "is used for keystone tokens lookup.\"\"\" _cache = { 'tokens/%s' % ADMIN_TOKEN: {", "'roles': [{'name': 'Member'}] } } } } def __init__(self): self.set_key = None self.set_value", "applicable law or agreed to in writing, software # distributed under the License", "'Member'}] } } } } def __init__(self): self.set_key = None self.set_value = None", "distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT #", "json.dumps((self._cache.get(key), dt.strftime('%s'))) def set(self, key, value, timeout=None): self.set_value = value self.set_key = key", "OR CONDITIONS OF ANY KIND, either express or implied. See the # License", "obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "keystone tokens lookup.\"\"\" _cache = { 'tokens/%s' % ADMIN_TOKEN: { 'access': { 'token':", "# Licensed under the Apache License, Version 2.0 (the \"License\"); you may #", "in compliance with the License. You may obtain # a copy of the", "softtabstop=4 # -*- encoding: utf-8 -*- # # Licensed under the Apache License,", "# not use this file except in compliance with the License. You may", "lookup.\"\"\" _cache = { 'tokens/%s' % ADMIN_TOKEN: { 'access': { 'token': {'id': ADMIN_TOKEN},", "or agreed to in writing, software # distributed under the License is distributed", "# License for the specific language governing permissions and limitations # under the", "ADMIN_TOKEN: { 'access': { 'token': {'id': ADMIN_TOKEN}, 'user': {'id': 'user_id1', 'name': 'user_name1', 'tenantId':", "'name': 'user_name1', 'tenantId': '123i2910', 'tenantName': 'mytenant', 'roles': [{'name': 'admin'}] }, } }, 'tokens/%s'", "'roles': [{'name': 'admin'}] }, } }, 'tokens/%s' % MEMBER_TOKEN: { 'access': { 'token':", "utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the \"License\");", "under the Apache License, Version 2.0 (the \"License\"); you may # not use", "datetime import json ADMIN_TOKEN = '<PASSWORD>' MEMBER_TOKEN = '<PASSWORD>' class FakeMemcache(object): \"\"\"Fake cache", "}, } }, 'tokens/%s' % MEMBER_TOKEN: { 'access': { 'token': {'id': MEMBER_TOKEN}, 'user':", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See", "class FakeMemcache(object): \"\"\"Fake cache that is used for keystone tokens lookup.\"\"\" _cache =", "} } } def __init__(self): self.set_key = None self.set_value = None self.token_expiration =", "'<PASSWORD>' MEMBER_TOKEN = '<PASSWORD>' class FakeMemcache(object): \"\"\"Fake cache that is used for keystone", "% ADMIN_TOKEN: { 'access': { 'token': {'id': ADMIN_TOKEN}, 'user': {'id': 'user_id1', 'name': 'user_name1',", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "in writing, software # distributed under the License is distributed on an \"AS", "Version 2.0 (the \"License\"); you may # not use this file except in", "'user_id2', 'name': 'user-good', 'tenantId': 'project-good', 'tenantName': 'goodies', 'roles': [{'name': 'Member'}] } } }", "encoding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the" ]
[ "EqualTo class NullableDateTimeField(DateTimeField): \"\"\"Modify DateField to allow for Null values\"\"\" def process_formdata(self, valuelist):", "import DataRequired, ValidationError, Email, EqualTo class NullableDateTimeField(DateTimeField): \"\"\"Modify DateField to allow for Null", "ValidationError, Email, EqualTo class NullableDateTimeField(DateTimeField): \"\"\"Modify DateField to allow for Null values\"\"\" def", "from flask_wtf import FlaskForm from wtforms import ( StringField, TextAreaField, DateTimeField, HiddenField, PasswordField,", "password = PasswordField( \"Password\", validators=[EqualTo(\"<PASSWORD>\", message=\"Passwords must match.\")], ) confirm_password = PasswordField(\"Confirm Password\",", "wtforms.validators import DataRequired, ValidationError, Email, EqualTo class NullableDateTimeField(DateTimeField): \"\"\"Modify DateField to allow for", "finished must be greater than or equal to date started\") raise ValidationError( \"Date", "finished must be greater than or equal to date started.\" ) elif self.date_started.data", "Email, EqualTo class NullableDateTimeField(DateTimeField): \"\"\"Modify DateField to allow for Null values\"\"\" def process_formdata(self,", "= None raise ValueError(self.gettext(\"Not a valid date value\")) class SearchForm(FlaskForm): search = StringField(\"Search\",", "raise ValueError(self.gettext(\"Not a valid date value\")) class SearchForm(FlaskForm): search = StringField(\"Search\", validators=[DataRequired()]) class", "TextAreaField(\"Review\") date_started = NullableDateTimeField(\"Date Started\", format=\"%m/%d/%Y\") date_finished = NullableDateTimeField(\"Date Finished\", format=\"%m/%d/%Y\") def validate_date_finished(self,", "FlaskForm from wtforms import ( StringField, TextAreaField, DateTimeField, HiddenField, PasswordField, ) from wtforms.validators", "\"\": self.data = None return try: self.data = datetime.datetime.strptime(date_str, self.format) except ValueError: self.data", "or equal to date started.\" ) elif self.date_started.data or date_finished.data: print(\"missing date\") raise", "process_formdata(self, valuelist): # Bypasses wtForms validation for blank datetime field. if valuelist: date_str", "valuelist): # Bypasses wtForms validation for blank datetime field. if valuelist: date_str =", "must be greater than or equal to date started\") raise ValidationError( \"Date finished", "wtForms validation for blank datetime field. if valuelist: date_str = \" \".join(valuelist).strip() if", "= None return try: self.data = datetime.datetime.strptime(date_str, self.format) except ValueError: self.data = None", "import datetime from flask_wtf import FlaskForm from wtforms import ( StringField, TextAreaField, DateTimeField,", "StringField(\"Search\", validators=[DataRequired()]) class ReviewForm(FlaskForm): rating = HiddenField(\"Rating\", validators=[DataRequired()]) review_title = StringField(\"Headline\") review_content =", "\"\"\"Modify DateField to allow for Null values\"\"\" def process_formdata(self, valuelist): # Bypasses wtForms", "Email Address.\")]) password = PasswordField( \"Password\", validators=[EqualTo(\"<PASSWORD>\", message=\"Passwords must match.\")], ) confirm_password =", "self.data = datetime.datetime.strptime(date_str, self.format) except ValueError: self.data = None raise ValueError(self.gettext(\"Not a valid", "class EditProfileForm(FlaskForm): display_name = StringField(\"Name\", validators=[]) email = StringField(\"Email\", validators=[Email(message=\"Invalid Email Address.\")]) password", "read dates, both dates are required.\") class EditProfileForm(FlaskForm): display_name = StringField(\"Name\", validators=[]) email", "Bypasses wtForms validation for blank datetime field. if valuelist: date_str = \" \".join(valuelist).strip()", "display_name = StringField(\"Name\", validators=[]) email = StringField(\"Email\", validators=[Email(message=\"Invalid Email Address.\")]) password = PasswordField(", "NullableDateTimeField(DateTimeField): \"\"\"Modify DateField to allow for Null values\"\"\" def process_formdata(self, valuelist): # Bypasses", "datetime field. if valuelist: date_str = \" \".join(valuelist).strip() if date_str == \"\": self.data", "date started\") raise ValidationError( \"Date finished must be greater than or equal to", "class SearchForm(FlaskForm): search = StringField(\"Search\", validators=[DataRequired()]) class ReviewForm(FlaskForm): rating = HiddenField(\"Rating\", validators=[DataRequired()]) review_title", "validate_date_finished(self, date_finished): if self.date_started.data and date_finished.data: if self.date_started.data > date_finished.data: print(\"Date finished must", "ValueError: self.data = None raise ValueError(self.gettext(\"Not a valid date value\")) class SearchForm(FlaskForm): search", "blank datetime field. if valuelist: date_str = \" \".join(valuelist).strip() if date_str == \"\":", "ValidationError( \"Date finished must be greater than or equal to date started.\" )", "= StringField(\"Search\", validators=[DataRequired()]) class ReviewForm(FlaskForm): rating = HiddenField(\"Rating\", validators=[DataRequired()]) review_title = StringField(\"Headline\") review_content", "datetime from flask_wtf import FlaskForm from wtforms import ( StringField, TextAreaField, DateTimeField, HiddenField,", "raise ValidationError(\"If setting read dates, both dates are required.\") class EditProfileForm(FlaskForm): display_name =", "Address.\")]) password = PasswordField( \"Password\", validators=[EqualTo(\"<PASSWORD>\", message=\"Passwords must match.\")], ) confirm_password = PasswordField(\"Confirm", "must be greater than or equal to date started.\" ) elif self.date_started.data or", "import ( StringField, TextAreaField, DateTimeField, HiddenField, PasswordField, ) from wtforms.validators import DataRequired, ValidationError,", "class NullableDateTimeField(DateTimeField): \"\"\"Modify DateField to allow for Null values\"\"\" def process_formdata(self, valuelist): #", "if self.date_started.data and date_finished.data: if self.date_started.data > date_finished.data: print(\"Date finished must be greater", "from wtforms import ( StringField, TextAreaField, DateTimeField, HiddenField, PasswordField, ) from wtforms.validators import", "DataRequired, ValidationError, Email, EqualTo class NullableDateTimeField(DateTimeField): \"\"\"Modify DateField to allow for Null values\"\"\"", "date_str = \" \".join(valuelist).strip() if date_str == \"\": self.data = None return try:", "# Bypasses wtForms validation for blank datetime field. if valuelist: date_str = \"", "= StringField(\"Email\", validators=[Email(message=\"Invalid Email Address.\")]) password = PasswordField( \"Password\", validators=[EqualTo(\"<PASSWORD>\", message=\"Passwords must match.\")],", "field. if valuelist: date_str = \" \".join(valuelist).strip() if date_str == \"\": self.data =", "= PasswordField( \"Password\", validators=[EqualTo(\"<PASSWORD>\", message=\"Passwords must match.\")], ) confirm_password = PasswordField(\"Confirm Password\", validators=[])", "<reponame>thewordisbird/bookshelf import datetime from flask_wtf import FlaskForm from wtforms import ( StringField, TextAreaField,", "date_started = NullableDateTimeField(\"Date Started\", format=\"%m/%d/%Y\") date_finished = NullableDateTimeField(\"Date Finished\", format=\"%m/%d/%Y\") def validate_date_finished(self, date_finished):", "= NullableDateTimeField(\"Date Finished\", format=\"%m/%d/%Y\") def validate_date_finished(self, date_finished): if self.date_started.data and date_finished.data: if self.date_started.data", "= \" \".join(valuelist).strip() if date_str == \"\": self.data = None return try: self.data", "are required.\") class EditProfileForm(FlaskForm): display_name = StringField(\"Name\", validators=[]) email = StringField(\"Email\", validators=[Email(message=\"Invalid Email", "PasswordField, ) from wtforms.validators import DataRequired, ValidationError, Email, EqualTo class NullableDateTimeField(DateTimeField): \"\"\"Modify DateField", "Finished\", format=\"%m/%d/%Y\") def validate_date_finished(self, date_finished): if self.date_started.data and date_finished.data: if self.date_started.data > date_finished.data:", "try: self.data = datetime.datetime.strptime(date_str, self.format) except ValueError: self.data = None raise ValueError(self.gettext(\"Not a", "self.date_started.data > date_finished.data: print(\"Date finished must be greater than or equal to date", "date\") raise ValidationError(\"If setting read dates, both dates are required.\") class EditProfileForm(FlaskForm): display_name", "date_str == \"\": self.data = None return try: self.data = datetime.datetime.strptime(date_str, self.format) except", "email = StringField(\"Email\", validators=[Email(message=\"Invalid Email Address.\")]) password = PasswordField( \"Password\", validators=[EqualTo(\"<PASSWORD>\", message=\"Passwords must", "review_content = TextAreaField(\"Review\") date_started = NullableDateTimeField(\"Date Started\", format=\"%m/%d/%Y\") date_finished = NullableDateTimeField(\"Date Finished\", format=\"%m/%d/%Y\")", "\"Date finished must be greater than or equal to date started.\" ) elif", "for blank datetime field. if valuelist: date_str = \" \".join(valuelist).strip() if date_str ==", "StringField, TextAreaField, DateTimeField, HiddenField, PasswordField, ) from wtforms.validators import DataRequired, ValidationError, Email, EqualTo", "print(\"Date finished must be greater than or equal to date started\") raise ValidationError(", "self.date_started.data or date_finished.data: print(\"missing date\") raise ValidationError(\"If setting read dates, both dates are", "HiddenField, PasswordField, ) from wtforms.validators import DataRequired, ValidationError, Email, EqualTo class NullableDateTimeField(DateTimeField): \"\"\"Modify", "flask_wtf import FlaskForm from wtforms import ( StringField, TextAreaField, DateTimeField, HiddenField, PasswordField, )", "return try: self.data = datetime.datetime.strptime(date_str, self.format) except ValueError: self.data = None raise ValueError(self.gettext(\"Not", "StringField(\"Headline\") review_content = TextAreaField(\"Review\") date_started = NullableDateTimeField(\"Date Started\", format=\"%m/%d/%Y\") date_finished = NullableDateTimeField(\"Date Finished\",", "started.\" ) elif self.date_started.data or date_finished.data: print(\"missing date\") raise ValidationError(\"If setting read dates,", "or equal to date started\") raise ValidationError( \"Date finished must be greater than", "a valid date value\")) class SearchForm(FlaskForm): search = StringField(\"Search\", validators=[DataRequired()]) class ReviewForm(FlaskForm): rating", "equal to date started.\" ) elif self.date_started.data or date_finished.data: print(\"missing date\") raise ValidationError(\"If", "EditProfileForm(FlaskForm): display_name = StringField(\"Name\", validators=[]) email = StringField(\"Email\", validators=[Email(message=\"Invalid Email Address.\")]) password =", "greater than or equal to date started\") raise ValidationError( \"Date finished must be", "equal to date started\") raise ValidationError( \"Date finished must be greater than or", "date value\")) class SearchForm(FlaskForm): search = StringField(\"Search\", validators=[DataRequired()]) class ReviewForm(FlaskForm): rating = HiddenField(\"Rating\",", "allow for Null values\"\"\" def process_formdata(self, valuelist): # Bypasses wtForms validation for blank", "to date started\") raise ValidationError( \"Date finished must be greater than or equal", "DateTimeField, HiddenField, PasswordField, ) from wtforms.validators import DataRequired, ValidationError, Email, EqualTo class NullableDateTimeField(DateTimeField):", "= StringField(\"Headline\") review_content = TextAreaField(\"Review\") date_started = NullableDateTimeField(\"Date Started\", format=\"%m/%d/%Y\") date_finished = NullableDateTimeField(\"Date", "date_finished.data: print(\"missing date\") raise ValidationError(\"If setting read dates, both dates are required.\") class", "= TextAreaField(\"Review\") date_started = NullableDateTimeField(\"Date Started\", format=\"%m/%d/%Y\") date_finished = NullableDateTimeField(\"Date Finished\", format=\"%m/%d/%Y\") def", "self.data = None raise ValueError(self.gettext(\"Not a valid date value\")) class SearchForm(FlaskForm): search =", "date_finished.data: if self.date_started.data > date_finished.data: print(\"Date finished must be greater than or equal", "date started.\" ) elif self.date_started.data or date_finished.data: print(\"missing date\") raise ValidationError(\"If setting read", "wtforms import ( StringField, TextAreaField, DateTimeField, HiddenField, PasswordField, ) from wtforms.validators import DataRequired,", "Started\", format=\"%m/%d/%Y\") date_finished = NullableDateTimeField(\"Date Finished\", format=\"%m/%d/%Y\") def validate_date_finished(self, date_finished): if self.date_started.data and", "dates, both dates are required.\") class EditProfileForm(FlaskForm): display_name = StringField(\"Name\", validators=[]) email =", "StringField(\"Email\", validators=[Email(message=\"Invalid Email Address.\")]) password = PasswordField( \"Password\", validators=[EqualTo(\"<PASSWORD>\", message=\"Passwords must match.\")], )", "from wtforms.validators import DataRequired, ValidationError, Email, EqualTo class NullableDateTimeField(DateTimeField): \"\"\"Modify DateField to allow", "None raise ValueError(self.gettext(\"Not a valid date value\")) class SearchForm(FlaskForm): search = StringField(\"Search\", validators=[DataRequired()])", "required.\") class EditProfileForm(FlaskForm): display_name = StringField(\"Name\", validators=[]) email = StringField(\"Email\", validators=[Email(message=\"Invalid Email Address.\")])", "value\")) class SearchForm(FlaskForm): search = StringField(\"Search\", validators=[DataRequired()]) class ReviewForm(FlaskForm): rating = HiddenField(\"Rating\", validators=[DataRequired()])", "if valuelist: date_str = \" \".join(valuelist).strip() if date_str == \"\": self.data = None", "be greater than or equal to date started\") raise ValidationError( \"Date finished must", "class ReviewForm(FlaskForm): rating = HiddenField(\"Rating\", validators=[DataRequired()]) review_title = StringField(\"Headline\") review_content = TextAreaField(\"Review\") date_started", "for Null values\"\"\" def process_formdata(self, valuelist): # Bypasses wtForms validation for blank datetime", "values\"\"\" def process_formdata(self, valuelist): # Bypasses wtForms validation for blank datetime field. if", "ValidationError(\"If setting read dates, both dates are required.\") class EditProfileForm(FlaskForm): display_name = StringField(\"Name\",", "Null values\"\"\" def process_formdata(self, valuelist): # Bypasses wtForms validation for blank datetime field.", "self.data = None return try: self.data = datetime.datetime.strptime(date_str, self.format) except ValueError: self.data =", "= datetime.datetime.strptime(date_str, self.format) except ValueError: self.data = None raise ValueError(self.gettext(\"Not a valid date", "datetime.datetime.strptime(date_str, self.format) except ValueError: self.data = None raise ValueError(self.gettext(\"Not a valid date value\"))", "self.format) except ValueError: self.data = None raise ValueError(self.gettext(\"Not a valid date value\")) class", "review_title = StringField(\"Headline\") review_content = TextAreaField(\"Review\") date_started = NullableDateTimeField(\"Date Started\", format=\"%m/%d/%Y\") date_finished =", "except ValueError: self.data = None raise ValueError(self.gettext(\"Not a valid date value\")) class SearchForm(FlaskForm):", "raise ValidationError( \"Date finished must be greater than or equal to date started.\"", "> date_finished.data: print(\"Date finished must be greater than or equal to date started\")", "self.date_started.data and date_finished.data: if self.date_started.data > date_finished.data: print(\"Date finished must be greater than", "validators=[]) email = StringField(\"Email\", validators=[Email(message=\"Invalid Email Address.\")]) password = PasswordField( \"Password\", validators=[EqualTo(\"<PASSWORD>\", message=\"Passwords", "= HiddenField(\"Rating\", validators=[DataRequired()]) review_title = StringField(\"Headline\") review_content = TextAreaField(\"Review\") date_started = NullableDateTimeField(\"Date Started\",", "than or equal to date started.\" ) elif self.date_started.data or date_finished.data: print(\"missing date\")", "NullableDateTimeField(\"Date Finished\", format=\"%m/%d/%Y\") def validate_date_finished(self, date_finished): if self.date_started.data and date_finished.data: if self.date_started.data >", "or date_finished.data: print(\"missing date\") raise ValidationError(\"If setting read dates, both dates are required.\")", "SearchForm(FlaskForm): search = StringField(\"Search\", validators=[DataRequired()]) class ReviewForm(FlaskForm): rating = HiddenField(\"Rating\", validators=[DataRequired()]) review_title =", "validators=[DataRequired()]) class ReviewForm(FlaskForm): rating = HiddenField(\"Rating\", validators=[DataRequired()]) review_title = StringField(\"Headline\") review_content = TextAreaField(\"Review\")", "date_finished): if self.date_started.data and date_finished.data: if self.date_started.data > date_finished.data: print(\"Date finished must be", "validators=[DataRequired()]) review_title = StringField(\"Headline\") review_content = TextAreaField(\"Review\") date_started = NullableDateTimeField(\"Date Started\", format=\"%m/%d/%Y\") date_finished", "elif self.date_started.data or date_finished.data: print(\"missing date\") raise ValidationError(\"If setting read dates, both dates", "validation for blank datetime field. if valuelist: date_str = \" \".join(valuelist).strip() if date_str", "to allow for Null values\"\"\" def process_formdata(self, valuelist): # Bypasses wtForms validation for", "ValueError(self.gettext(\"Not a valid date value\")) class SearchForm(FlaskForm): search = StringField(\"Search\", validators=[DataRequired()]) class ReviewForm(FlaskForm):", "def process_formdata(self, valuelist): # Bypasses wtForms validation for blank datetime field. if valuelist:", "valid date value\")) class SearchForm(FlaskForm): search = StringField(\"Search\", validators=[DataRequired()]) class ReviewForm(FlaskForm): rating =", "search = StringField(\"Search\", validators=[DataRequired()]) class ReviewForm(FlaskForm): rating = HiddenField(\"Rating\", validators=[DataRequired()]) review_title = StringField(\"Headline\")", "valuelist: date_str = \" \".join(valuelist).strip() if date_str == \"\": self.data = None return", "( StringField, TextAreaField, DateTimeField, HiddenField, PasswordField, ) from wtforms.validators import DataRequired, ValidationError, Email,", "HiddenField(\"Rating\", validators=[DataRequired()]) review_title = StringField(\"Headline\") review_content = TextAreaField(\"Review\") date_started = NullableDateTimeField(\"Date Started\", format=\"%m/%d/%Y\")", "TextAreaField, DateTimeField, HiddenField, PasswordField, ) from wtforms.validators import DataRequired, ValidationError, Email, EqualTo class", "greater than or equal to date started.\" ) elif self.date_started.data or date_finished.data: print(\"missing", "NullableDateTimeField(\"Date Started\", format=\"%m/%d/%Y\") date_finished = NullableDateTimeField(\"Date Finished\", format=\"%m/%d/%Y\") def validate_date_finished(self, date_finished): if self.date_started.data", "StringField(\"Name\", validators=[]) email = StringField(\"Email\", validators=[Email(message=\"Invalid Email Address.\")]) password = PasswordField( \"Password\", validators=[EqualTo(\"<PASSWORD>\",", "setting read dates, both dates are required.\") class EditProfileForm(FlaskForm): display_name = StringField(\"Name\", validators=[])", "started\") raise ValidationError( \"Date finished must be greater than or equal to date", "format=\"%m/%d/%Y\") def validate_date_finished(self, date_finished): if self.date_started.data and date_finished.data: if self.date_started.data > date_finished.data: print(\"Date", "def validate_date_finished(self, date_finished): if self.date_started.data and date_finished.data: if self.date_started.data > date_finished.data: print(\"Date finished", "validators=[Email(message=\"Invalid Email Address.\")]) password = PasswordField( \"Password\", validators=[EqualTo(\"<PASSWORD>\", message=\"Passwords must match.\")], ) confirm_password", "\".join(valuelist).strip() if date_str == \"\": self.data = None return try: self.data = datetime.datetime.strptime(date_str,", "date_finished.data: print(\"Date finished must be greater than or equal to date started\") raise", ") from wtforms.validators import DataRequired, ValidationError, Email, EqualTo class NullableDateTimeField(DateTimeField): \"\"\"Modify DateField to", "than or equal to date started\") raise ValidationError( \"Date finished must be greater", "both dates are required.\") class EditProfileForm(FlaskForm): display_name = StringField(\"Name\", validators=[]) email = StringField(\"Email\",", "== \"\": self.data = None return try: self.data = datetime.datetime.strptime(date_str, self.format) except ValueError:", "if self.date_started.data > date_finished.data: print(\"Date finished must be greater than or equal to", "and date_finished.data: if self.date_started.data > date_finished.data: print(\"Date finished must be greater than or", "print(\"missing date\") raise ValidationError(\"If setting read dates, both dates are required.\") class EditProfileForm(FlaskForm):", "DateField to allow for Null values\"\"\" def process_formdata(self, valuelist): # Bypasses wtForms validation", "to date started.\" ) elif self.date_started.data or date_finished.data: print(\"missing date\") raise ValidationError(\"If setting", "= StringField(\"Name\", validators=[]) email = StringField(\"Email\", validators=[Email(message=\"Invalid Email Address.\")]) password = PasswordField( \"Password\",", "be greater than or equal to date started.\" ) elif self.date_started.data or date_finished.data:", "if date_str == \"\": self.data = None return try: self.data = datetime.datetime.strptime(date_str, self.format)", "dates are required.\") class EditProfileForm(FlaskForm): display_name = StringField(\"Name\", validators=[]) email = StringField(\"Email\", validators=[Email(message=\"Invalid", "\" \".join(valuelist).strip() if date_str == \"\": self.data = None return try: self.data =", "ReviewForm(FlaskForm): rating = HiddenField(\"Rating\", validators=[DataRequired()]) review_title = StringField(\"Headline\") review_content = TextAreaField(\"Review\") date_started =", "rating = HiddenField(\"Rating\", validators=[DataRequired()]) review_title = StringField(\"Headline\") review_content = TextAreaField(\"Review\") date_started = NullableDateTimeField(\"Date", "None return try: self.data = datetime.datetime.strptime(date_str, self.format) except ValueError: self.data = None raise", "date_finished = NullableDateTimeField(\"Date Finished\", format=\"%m/%d/%Y\") def validate_date_finished(self, date_finished): if self.date_started.data and date_finished.data: if", ") elif self.date_started.data or date_finished.data: print(\"missing date\") raise ValidationError(\"If setting read dates, both", "= NullableDateTimeField(\"Date Started\", format=\"%m/%d/%Y\") date_finished = NullableDateTimeField(\"Date Finished\", format=\"%m/%d/%Y\") def validate_date_finished(self, date_finished): if", "import FlaskForm from wtforms import ( StringField, TextAreaField, DateTimeField, HiddenField, PasswordField, ) from", "format=\"%m/%d/%Y\") date_finished = NullableDateTimeField(\"Date Finished\", format=\"%m/%d/%Y\") def validate_date_finished(self, date_finished): if self.date_started.data and date_finished.data:" ]
[ "header=None, engine='python') train_labels = train_labels.to_numpy() # convertim data frame-ul intr-un vector train_labels =", "_ = normalize_data(validation_features, validation_features) # Aplicam modelul SVM model_svm = svm.SVC(kernel='linear', C=23, gamma=110)", "return scaled_train_data, scaled_test_data else: return train_data, test_data # Modelarea datelor vectorizer = TfidfVectorizer()", "datelor vectorizer = TfidfVectorizer() training_features = vectorizer.fit_transform(train_samples) validation_features = vectorizer.transform(validation_samples) testing_features = vectorizer.transform(test_samples)", "import svm # importarea modelului from sklearn.feature_extraction.text import TfidfVectorizer # modelarea datelor pentru", "doar etichetele test_samples = pd.read_csv('test_samples.txt', sep='\\t', header=None, engine='python') test_samples = test_samples.to_numpy() label =", "svm.SVC(kernel='linear', C=23, gamma=110) # definim modelul model_svm.fit(norm_train, train_labels) # procesul de invatare test_predictions", "data frame-ul intr-un vector train_labels = train_labels[:,1] # pastram doar etichetele train_samples =", "norm_test = normalize_data(training_features, testing_features) norm_validation, _ = normalize_data(validation_features, validation_features) # Aplicam modelul SVM", "print(confusion_matrix(validation_labels, model_svm.predict(norm_validation))) # Exportarea datelor in format CSV test_export = {'id':label,'label':test_predictions} data_f =", "\") print(classification_report(validation_labels, model_svm.predict(norm_validation))) print(\"Confusion matrix: \") print(confusion_matrix(validation_labels, model_svm.predict(norm_validation))) # Exportarea datelor in format", "datelor pentru a obtine valori numerice din text from sklearn.metrics import classification_report, confusion_matrix", "# pastram doar etichetele test_samples = pd.read_csv('test_samples.txt', sep='\\t', header=None, engine='python') test_samples = test_samples.to_numpy()", "test_samples = test_samples.to_numpy() label = test_samples[:,0] # salvam etichetele test_samples = test_samples[:,1] #", "= scaler.transform(test_data) return scaled_train_data, scaled_test_data else: return train_data, test_data # Modelarea datelor vectorizer", "validation_features = vectorizer.transform(validation_samples) testing_features = vectorizer.transform(test_samples) # Normalizarea datelor norm_train, norm_test = normalize_data(training_features,", "print(\"Confusion matrix: \") print(confusion_matrix(validation_labels, model_svm.predict(norm_validation))) # Exportarea datelor in format CSV test_export =", "= train_labels.to_numpy() # convertim data frame-ul intr-un vector train_labels = train_labels[:,1] # pastram", "coding: utf-8 -*- \"\"\"Proiect.ipynb Automatically generated by Colaboratory. Original file is located at", "sep='\\t', header=None, engine='python') train_samples = train_samples.to_numpy() train_samples = train_samples[:,1] # pastram doar cuvintele", "test_data, type='l2'): # functia care intoarce datele normalizate #tipul de normalizare este setat", "== 'min_max': scaler = preprocessing.MinMaxScaler() elif type == 'l1' or type == 'l2':", "datelor norm_train, norm_test = normalize_data(training_features, testing_features) norm_validation, _ = normalize_data(validation_features, validation_features) # Aplicam", "salvam cuvintele validation_labels = pd.read_csv('validation_labels.txt', sep='\\t', header=None, engine='python') validation_labels = validation_labels.to_numpy() validation_labels =", "model_svm.predict(norm_test) # predictie pe datele de test print(\"Classification report: \") print(classification_report(validation_labels, model_svm.predict(norm_validation))) print(\"Confusion", "pandas as pd # pandas pentru citirea fisierelor from sklearn import preprocessing from", "vectorizer = TfidfVectorizer() training_features = vectorizer.fit_transform(train_samples) validation_features = vectorizer.transform(validation_samples) testing_features = vectorizer.transform(test_samples) #", "train_data, test_data # Modelarea datelor vectorizer = TfidfVectorizer() training_features = vectorizer.fit_transform(train_samples) validation_features =", "# -*- coding: utf-8 -*- \"\"\"Proiect.ipynb Automatically generated by Colaboratory. Original file is", "citirea fisierelor from sklearn import preprocessing from sklearn import svm # importarea modelului", "if scaler is not None: scaler.fit(train_data) scaled_train_data = scaler.transform(train_data) scaled_test_data = scaler.transform(test_data) return", "vectorizer.transform(test_samples) # Normalizarea datelor norm_train, norm_test = normalize_data(training_features, testing_features) norm_validation, _ = normalize_data(validation_features,", "== 'l2': scaler = preprocessing.Normalizer(norm = type) if scaler is not None: scaler.fit(train_data)", "Aplicam modelul SVM model_svm = svm.SVC(kernel='linear', C=23, gamma=110) # definim modelul model_svm.fit(norm_train, train_labels)", "predictie pe datele de test print(\"Classification report: \") print(classification_report(validation_labels, model_svm.predict(norm_validation))) print(\"Confusion matrix: \")", "modelarea datelor pentru a obtine valori numerice din text from sklearn.metrics import classification_report,", "type == 'l2': scaler = preprocessing.Normalizer(norm = type) if scaler is not None:", "pandas pentru citirea fisierelor from sklearn import preprocessing from sklearn import svm #", "normalize_data(validation_features, validation_features) # Aplicam modelul SVM model_svm = svm.SVC(kernel='linear', C=23, gamma=110) # definim", "validation_labels[:,1] # pastram doar etichetele test_samples = pd.read_csv('test_samples.txt', sep='\\t', header=None, engine='python') test_samples =", "type == 'min_max': scaler = preprocessing.MinMaxScaler() elif type == 'l1' or type ==", "type) if scaler is not None: scaler.fit(train_data) scaled_train_data = scaler.transform(train_data) scaled_test_data = scaler.transform(test_data)", "test_predictions = model_svm.predict(norm_test) # predictie pe datele de test print(\"Classification report: \") print(classification_report(validation_labels,", "located at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\" # Importarea librariilor import numpy as np import pandas", "import classification_report, confusion_matrix # Incarcarea datelor train_labels = pd.read_csv('train_labels.txt', sep='\\t', header=None, engine='python') train_labels", "gamma=110) # definim modelul model_svm.fit(norm_train, train_labels) # procesul de invatare test_predictions = model_svm.predict(norm_test)", "test print(\"Classification report: \") print(classification_report(validation_labels, model_svm.predict(norm_validation))) print(\"Confusion matrix: \") print(confusion_matrix(validation_labels, model_svm.predict(norm_validation))) # Exportarea", "numpy as np import pandas as pd # pandas pentru citirea fisierelor from", "frame-ul intr-un vector train_labels = train_labels[:,1] # pastram doar etichetele train_samples = pd.read_csv('train_samples.txt',", "setat implicit la l2 scaler = None if type == 'standard': scaler =", "engine='python') validation_labels = validation_labels.to_numpy() validation_labels = validation_labels[:,1] # pastram doar etichetele test_samples =", "is not None: scaler.fit(train_data) scaled_train_data = scaler.transform(train_data) scaled_test_data = scaler.transform(test_data) return scaled_train_data, scaled_test_data", "# Exportarea datelor in format CSV test_export = {'id':label,'label':test_predictions} data_f = pd.DataFrame(test_export) data_f.to_csv('test_submission.csv',index=False)", "definim modelul model_svm.fit(norm_train, train_labels) # procesul de invatare test_predictions = model_svm.predict(norm_test) # predictie", "= pd.read_csv('test_samples.txt', sep='\\t', header=None, engine='python') test_samples = test_samples.to_numpy() label = test_samples[:,0] # salvam", "implicit la l2 scaler = None if type == 'standard': scaler = preprocessing.StandardScaler()", "pastram doar etichetele test_samples = pd.read_csv('test_samples.txt', sep='\\t', header=None, engine='python') test_samples = test_samples.to_numpy() label", "= model_svm.predict(norm_test) # predictie pe datele de test print(\"Classification report: \") print(classification_report(validation_labels, model_svm.predict(norm_validation)))", "cuvintele def normalize_data(train_data, test_data, type='l2'): # functia care intoarce datele normalizate #tipul de", "fisierelor from sklearn import preprocessing from sklearn import svm # importarea modelului from", "from sklearn import preprocessing from sklearn import svm # importarea modelului from sklearn.feature_extraction.text", "svm # importarea modelului from sklearn.feature_extraction.text import TfidfVectorizer # modelarea datelor pentru a", "modelului from sklearn.feature_extraction.text import TfidfVectorizer # modelarea datelor pentru a obtine valori numerice", "train_samples[:,1] # pastram doar cuvintele validation_samples = pd.read_csv('validation_samples.txt', sep='\\t', header=None, engine='python') validation_samples =", "normalizate #tipul de normalizare este setat implicit la l2 scaler = None if", "testing_features) norm_validation, _ = normalize_data(validation_features, validation_features) # Aplicam modelul SVM model_svm = svm.SVC(kernel='linear',", "scaler = preprocessing.StandardScaler() elif type == 'min_max': scaler = preprocessing.MinMaxScaler() elif type ==", "scaled_test_data else: return train_data, test_data # Modelarea datelor vectorizer = TfidfVectorizer() training_features =", "sep='\\t', header=None, engine='python') train_labels = train_labels.to_numpy() # convertim data frame-ul intr-un vector train_labels", "= scaler.transform(train_data) scaled_test_data = scaler.transform(test_data) return scaled_train_data, scaled_test_data else: return train_data, test_data #", "elif type == 'l1' or type == 'l2': scaler = preprocessing.Normalizer(norm = type)", "-*- \"\"\"Proiect.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\"", "train_samples.to_numpy() train_samples = train_samples[:,1] # pastram doar cuvintele validation_samples = pd.read_csv('validation_samples.txt', sep='\\t', header=None,", "validation_labels.to_numpy() validation_labels = validation_labels[:,1] # pastram doar etichetele test_samples = pd.read_csv('test_samples.txt', sep='\\t', header=None,", "pd.read_csv('train_labels.txt', sep='\\t', header=None, engine='python') train_labels = train_labels.to_numpy() # convertim data frame-ul intr-un vector", "pd.read_csv('test_samples.txt', sep='\\t', header=None, engine='python') test_samples = test_samples.to_numpy() label = test_samples[:,0] # salvam etichetele", "report: \") print(classification_report(validation_labels, model_svm.predict(norm_validation))) print(\"Confusion matrix: \") print(confusion_matrix(validation_labels, model_svm.predict(norm_validation))) # Exportarea datelor in", "# Importarea librariilor import numpy as np import pandas as pd # pandas", "pd.read_csv('validation_samples.txt', sep='\\t', header=None, engine='python') validation_samples = validation_samples.to_numpy() validation_samples = validation_samples[:,1] # salvam cuvintele", "text from sklearn.metrics import classification_report, confusion_matrix # Incarcarea datelor train_labels = pd.read_csv('train_labels.txt', sep='\\t',", "header=None, engine='python') validation_labels = validation_labels.to_numpy() validation_labels = validation_labels[:,1] # pastram doar etichetele test_samples", "None if type == 'standard': scaler = preprocessing.StandardScaler() elif type == 'min_max': scaler", "normalize_data(train_data, test_data, type='l2'): # functia care intoarce datele normalizate #tipul de normalizare este", "np import pandas as pd # pandas pentru citirea fisierelor from sklearn import", "\"\"\" # Importarea librariilor import numpy as np import pandas as pd #", "= validation_labels.to_numpy() validation_labels = validation_labels[:,1] # pastram doar etichetele test_samples = pd.read_csv('test_samples.txt', sep='\\t',", "confusion_matrix # Incarcarea datelor train_labels = pd.read_csv('train_labels.txt', sep='\\t', header=None, engine='python') train_labels = train_labels.to_numpy()", "= pd.read_csv('train_labels.txt', sep='\\t', header=None, engine='python') train_labels = train_labels.to_numpy() # convertim data frame-ul intr-un", "= validation_samples[:,1] # salvam cuvintele validation_labels = pd.read_csv('validation_labels.txt', sep='\\t', header=None, engine='python') validation_labels =", "scaled_train_data = scaler.transform(train_data) scaled_test_data = scaler.transform(test_data) return scaled_train_data, scaled_test_data else: return train_data, test_data", "Incarcarea datelor train_labels = pd.read_csv('train_labels.txt', sep='\\t', header=None, engine='python') train_labels = train_labels.to_numpy() # convertim", "#tipul de normalizare este setat implicit la l2 scaler = None if type", "training_features = vectorizer.fit_transform(train_samples) validation_features = vectorizer.transform(validation_samples) testing_features = vectorizer.transform(test_samples) # Normalizarea datelor norm_train,", "validation_labels = pd.read_csv('validation_labels.txt', sep='\\t', header=None, engine='python') validation_labels = validation_labels.to_numpy() validation_labels = validation_labels[:,1] #", "Normalizarea datelor norm_train, norm_test = normalize_data(training_features, testing_features) norm_validation, _ = normalize_data(validation_features, validation_features) #", "salvam etichetele test_samples = test_samples[:,1] # salvam cuvintele def normalize_data(train_data, test_data, type='l2'): #", "intoarce datele normalizate #tipul de normalizare este setat implicit la l2 scaler =", "else: return train_data, test_data # Modelarea datelor vectorizer = TfidfVectorizer() training_features = vectorizer.fit_transform(train_samples)", "= vectorizer.transform(test_samples) # Normalizarea datelor norm_train, norm_test = normalize_data(training_features, testing_features) norm_validation, _ =", "datele normalizate #tipul de normalizare este setat implicit la l2 scaler = None", "l2 scaler = None if type == 'standard': scaler = preprocessing.StandardScaler() elif type", "scaler.transform(test_data) return scaled_train_data, scaled_test_data else: return train_data, test_data # Modelarea datelor vectorizer =", "doar cuvintele validation_samples = pd.read_csv('validation_samples.txt', sep='\\t', header=None, engine='python') validation_samples = validation_samples.to_numpy() validation_samples =", "engine='python') test_samples = test_samples.to_numpy() label = test_samples[:,0] # salvam etichetele test_samples = test_samples[:,1]", "= test_samples[:,1] # salvam cuvintele def normalize_data(train_data, test_data, type='l2'): # functia care intoarce", "at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\" # Importarea librariilor import numpy as np import pandas as", "= None if type == 'standard': scaler = preprocessing.StandardScaler() elif type == 'min_max':", "-*- coding: utf-8 -*- \"\"\"Proiect.ipynb Automatically generated by Colaboratory. Original file is located", "# Modelarea datelor vectorizer = TfidfVectorizer() training_features = vectorizer.fit_transform(train_samples) validation_features = vectorizer.transform(validation_samples) testing_features", "train_labels = pd.read_csv('train_labels.txt', sep='\\t', header=None, engine='python') train_labels = train_labels.to_numpy() # convertim data frame-ul", "== 'l1' or type == 'l2': scaler = preprocessing.Normalizer(norm = type) if scaler", "= preprocessing.StandardScaler() elif type == 'min_max': scaler = preprocessing.MinMaxScaler() elif type == 'l1'", "sklearn import preprocessing from sklearn import svm # importarea modelului from sklearn.feature_extraction.text import", "= type) if scaler is not None: scaler.fit(train_data) scaled_train_data = scaler.transform(train_data) scaled_test_data =", "= test_samples[:,0] # salvam etichetele test_samples = test_samples[:,1] # salvam cuvintele def normalize_data(train_data,", "pe datele de test print(\"Classification report: \") print(classification_report(validation_labels, model_svm.predict(norm_validation))) print(\"Confusion matrix: \") print(confusion_matrix(validation_labels,", "de invatare test_predictions = model_svm.predict(norm_test) # predictie pe datele de test print(\"Classification report:", "Original file is located at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\" # Importarea librariilor import numpy as", "sklearn import svm # importarea modelului from sklearn.feature_extraction.text import TfidfVectorizer # modelarea datelor", "validation_labels = validation_labels.to_numpy() validation_labels = validation_labels[:,1] # pastram doar etichetele test_samples = pd.read_csv('test_samples.txt',", "scaler = None if type == 'standard': scaler = preprocessing.StandardScaler() elif type ==", "invatare test_predictions = model_svm.predict(norm_test) # predictie pe datele de test print(\"Classification report: \")", "train_labels = train_labels.to_numpy() # convertim data frame-ul intr-un vector train_labels = train_labels[:,1] #", "pastram doar etichetele train_samples = pd.read_csv('train_samples.txt', sep='\\t', header=None, engine='python') train_samples = train_samples.to_numpy() train_samples", "cuvintele validation_labels = pd.read_csv('validation_labels.txt', sep='\\t', header=None, engine='python') validation_labels = validation_labels.to_numpy() validation_labels = validation_labels[:,1]", "etichetele train_samples = pd.read_csv('train_samples.txt', sep='\\t', header=None, engine='python') train_samples = train_samples.to_numpy() train_samples = train_samples[:,1]", "= train_samples[:,1] # pastram doar cuvintele validation_samples = pd.read_csv('validation_samples.txt', sep='\\t', header=None, engine='python') validation_samples", "modelul model_svm.fit(norm_train, train_labels) # procesul de invatare test_predictions = model_svm.predict(norm_test) # predictie pe", "sklearn.feature_extraction.text import TfidfVectorizer # modelarea datelor pentru a obtine valori numerice din text", "None: scaler.fit(train_data) scaled_train_data = scaler.transform(train_data) scaled_test_data = scaler.transform(test_data) return scaled_train_data, scaled_test_data else: return", "vector train_labels = train_labels[:,1] # pastram doar etichetele train_samples = pd.read_csv('train_samples.txt', sep='\\t', header=None,", "sep='\\t', header=None, engine='python') test_samples = test_samples.to_numpy() label = test_samples[:,0] # salvam etichetele test_samples", "train_labels.to_numpy() # convertim data frame-ul intr-un vector train_labels = train_labels[:,1] # pastram doar", "= preprocessing.MinMaxScaler() elif type == 'l1' or type == 'l2': scaler = preprocessing.Normalizer(norm", "etichetele test_samples = test_samples[:,1] # salvam cuvintele def normalize_data(train_data, test_data, type='l2'): # functia", "= normalize_data(training_features, testing_features) norm_validation, _ = normalize_data(validation_features, validation_features) # Aplicam modelul SVM model_svm", "scaler.transform(train_data) scaled_test_data = scaler.transform(test_data) return scaled_train_data, scaled_test_data else: return train_data, test_data # Modelarea", "pd # pandas pentru citirea fisierelor from sklearn import preprocessing from sklearn import", "\") print(confusion_matrix(validation_labels, model_svm.predict(norm_validation))) # Exportarea datelor in format CSV test_export = {'id':label,'label':test_predictions} data_f", "from sklearn import svm # importarea modelului from sklearn.feature_extraction.text import TfidfVectorizer # modelarea", "label = test_samples[:,0] # salvam etichetele test_samples = test_samples[:,1] # salvam cuvintele def", "'standard': scaler = preprocessing.StandardScaler() elif type == 'min_max': scaler = preprocessing.MinMaxScaler() elif type", "engine='python') train_samples = train_samples.to_numpy() train_samples = train_samples[:,1] # pastram doar cuvintele validation_samples =", "'min_max': scaler = preprocessing.MinMaxScaler() elif type == 'l1' or type == 'l2': scaler", "def normalize_data(train_data, test_data, type='l2'): # functia care intoarce datele normalizate #tipul de normalizare", "# functia care intoarce datele normalizate #tipul de normalizare este setat implicit la", "= TfidfVectorizer() training_features = vectorizer.fit_transform(train_samples) validation_features = vectorizer.transform(validation_samples) testing_features = vectorizer.transform(test_samples) # Normalizarea", "la l2 scaler = None if type == 'standard': scaler = preprocessing.StandardScaler() elif", "Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\" # Importarea", "pd.read_csv('train_samples.txt', sep='\\t', header=None, engine='python') train_samples = train_samples.to_numpy() train_samples = train_samples[:,1] # pastram doar", "validation_samples = validation_samples[:,1] # salvam cuvintele validation_labels = pd.read_csv('validation_labels.txt', sep='\\t', header=None, engine='python') validation_labels", "= train_labels[:,1] # pastram doar etichetele train_samples = pd.read_csv('train_samples.txt', sep='\\t', header=None, engine='python') train_samples", "print(classification_report(validation_labels, model_svm.predict(norm_validation))) print(\"Confusion matrix: \") print(confusion_matrix(validation_labels, model_svm.predict(norm_validation))) # Exportarea datelor in format CSV", "https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\" # Importarea librariilor import numpy as np import pandas as pd", "import TfidfVectorizer # modelarea datelor pentru a obtine valori numerice din text from", "not None: scaler.fit(train_data) scaled_train_data = scaler.transform(train_data) scaled_test_data = scaler.transform(test_data) return scaled_train_data, scaled_test_data else:", "vectorizer.transform(validation_samples) testing_features = vectorizer.transform(test_samples) # Normalizarea datelor norm_train, norm_test = normalize_data(training_features, testing_features) norm_validation,", "test_samples = pd.read_csv('test_samples.txt', sep='\\t', header=None, engine='python') test_samples = test_samples.to_numpy() label = test_samples[:,0] #", "train_samples = train_samples.to_numpy() train_samples = train_samples[:,1] # pastram doar cuvintele validation_samples = pd.read_csv('validation_samples.txt',", "testing_features = vectorizer.transform(test_samples) # Normalizarea datelor norm_train, norm_test = normalize_data(training_features, testing_features) norm_validation, _", "librariilor import numpy as np import pandas as pd # pandas pentru citirea", "test_samples[:,0] # salvam etichetele test_samples = test_samples[:,1] # salvam cuvintele def normalize_data(train_data, test_data,", "test_data # Modelarea datelor vectorizer = TfidfVectorizer() training_features = vectorizer.fit_transform(train_samples) validation_features = vectorizer.transform(validation_samples)", "normalizare este setat implicit la l2 scaler = None if type == 'standard':", "Importarea librariilor import numpy as np import pandas as pd # pandas pentru", "or type == 'l2': scaler = preprocessing.Normalizer(norm = type) if scaler is not", "valori numerice din text from sklearn.metrics import classification_report, confusion_matrix # Incarcarea datelor train_labels", "preprocessing.StandardScaler() elif type == 'min_max': scaler = preprocessing.MinMaxScaler() elif type == 'l1' or", "validation_samples[:,1] # salvam cuvintele validation_labels = pd.read_csv('validation_labels.txt', sep='\\t', header=None, engine='python') validation_labels = validation_labels.to_numpy()", "return train_data, test_data # Modelarea datelor vectorizer = TfidfVectorizer() training_features = vectorizer.fit_transform(train_samples) validation_features", "if type == 'standard': scaler = preprocessing.StandardScaler() elif type == 'min_max': scaler =", "matrix: \") print(confusion_matrix(validation_labels, model_svm.predict(norm_validation))) # Exportarea datelor in format CSV test_export = {'id':label,'label':test_predictions}", "preprocessing.MinMaxScaler() elif type == 'l1' or type == 'l2': scaler = preprocessing.Normalizer(norm =", "sklearn.metrics import classification_report, confusion_matrix # Incarcarea datelor train_labels = pd.read_csv('train_labels.txt', sep='\\t', header=None, engine='python')", "= validation_samples.to_numpy() validation_samples = validation_samples[:,1] # salvam cuvintele validation_labels = pd.read_csv('validation_labels.txt', sep='\\t', header=None,", "model_svm.predict(norm_validation))) # Exportarea datelor in format CSV test_export = {'id':label,'label':test_predictions} data_f = pd.DataFrame(test_export)", "scaler = preprocessing.Normalizer(norm = type) if scaler is not None: scaler.fit(train_data) scaled_train_data =", "= pd.read_csv('validation_labels.txt', sep='\\t', header=None, engine='python') validation_labels = validation_labels.to_numpy() validation_labels = validation_labels[:,1] # pastram", "# salvam cuvintele def normalize_data(train_data, test_data, type='l2'): # functia care intoarce datele normalizate", "sep='\\t', header=None, engine='python') validation_labels = validation_labels.to_numpy() validation_labels = validation_labels[:,1] # pastram doar etichetele", "# modelarea datelor pentru a obtine valori numerice din text from sklearn.metrics import", "de normalizare este setat implicit la l2 scaler = None if type ==", "norm_validation, _ = normalize_data(validation_features, validation_features) # Aplicam modelul SVM model_svm = svm.SVC(kernel='linear', C=23,", "validation_samples.to_numpy() validation_samples = validation_samples[:,1] # salvam cuvintele validation_labels = pd.read_csv('validation_labels.txt', sep='\\t', header=None, engine='python')", "# Aplicam modelul SVM model_svm = svm.SVC(kernel='linear', C=23, gamma=110) # definim modelul model_svm.fit(norm_train,", "print(\"Classification report: \") print(classification_report(validation_labels, model_svm.predict(norm_validation))) print(\"Confusion matrix: \") print(confusion_matrix(validation_labels, model_svm.predict(norm_validation))) # Exportarea datelor", "validation_labels = validation_labels[:,1] # pastram doar etichetele test_samples = pd.read_csv('test_samples.txt', sep='\\t', header=None, engine='python')", "train_labels[:,1] # pastram doar etichetele train_samples = pd.read_csv('train_samples.txt', sep='\\t', header=None, engine='python') train_samples =", "scaler = preprocessing.MinMaxScaler() elif type == 'l1' or type == 'l2': scaler =", "# predictie pe datele de test print(\"Classification report: \") print(classification_report(validation_labels, model_svm.predict(norm_validation))) print(\"Confusion matrix:", "validation_samples = pd.read_csv('validation_samples.txt', sep='\\t', header=None, engine='python') validation_samples = validation_samples.to_numpy() validation_samples = validation_samples[:,1] #", "# salvam cuvintele validation_labels = pd.read_csv('validation_labels.txt', sep='\\t', header=None, engine='python') validation_labels = validation_labels.to_numpy() validation_labels", "type == 'standard': scaler = preprocessing.StandardScaler() elif type == 'min_max': scaler = preprocessing.MinMaxScaler()", "by Colaboratory. Original file is located at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\" # Importarea librariilor import", "== 'standard': scaler = preprocessing.StandardScaler() elif type == 'min_max': scaler = preprocessing.MinMaxScaler() elif", "preprocessing.Normalizer(norm = type) if scaler is not None: scaler.fit(train_data) scaled_train_data = scaler.transform(train_data) scaled_test_data", "model_svm.fit(norm_train, train_labels) # procesul de invatare test_predictions = model_svm.predict(norm_test) # predictie pe datele", "from sklearn.feature_extraction.text import TfidfVectorizer # modelarea datelor pentru a obtine valori numerice din", "# procesul de invatare test_predictions = model_svm.predict(norm_test) # predictie pe datele de test", "preprocessing from sklearn import svm # importarea modelului from sklearn.feature_extraction.text import TfidfVectorizer #", "engine='python') validation_samples = validation_samples.to_numpy() validation_samples = validation_samples[:,1] # salvam cuvintele validation_labels = pd.read_csv('validation_labels.txt',", "care intoarce datele normalizate #tipul de normalizare este setat implicit la l2 scaler", "header=None, engine='python') test_samples = test_samples.to_numpy() label = test_samples[:,0] # salvam etichetele test_samples =", "numerice din text from sklearn.metrics import classification_report, confusion_matrix # Incarcarea datelor train_labels =", "normalize_data(training_features, testing_features) norm_validation, _ = normalize_data(validation_features, validation_features) # Aplicam modelul SVM model_svm =", "= train_samples.to_numpy() train_samples = train_samples[:,1] # pastram doar cuvintele validation_samples = pd.read_csv('validation_samples.txt', sep='\\t',", "pentru a obtine valori numerice din text from sklearn.metrics import classification_report, confusion_matrix #", "intr-un vector train_labels = train_labels[:,1] # pastram doar etichetele train_samples = pd.read_csv('train_samples.txt', sep='\\t',", "Modelarea datelor vectorizer = TfidfVectorizer() training_features = vectorizer.fit_transform(train_samples) validation_features = vectorizer.transform(validation_samples) testing_features =", "= svm.SVC(kernel='linear', C=23, gamma=110) # definim modelul model_svm.fit(norm_train, train_labels) # procesul de invatare", "model_svm.predict(norm_validation))) print(\"Confusion matrix: \") print(confusion_matrix(validation_labels, model_svm.predict(norm_validation))) # Exportarea datelor in format CSV test_export", "# importarea modelului from sklearn.feature_extraction.text import TfidfVectorizer # modelarea datelor pentru a obtine", "import preprocessing from sklearn import svm # importarea modelului from sklearn.feature_extraction.text import TfidfVectorizer", "as np import pandas as pd # pandas pentru citirea fisierelor from sklearn", "= normalize_data(validation_features, validation_features) # Aplicam modelul SVM model_svm = svm.SVC(kernel='linear', C=23, gamma=110) #", "pastram doar cuvintele validation_samples = pd.read_csv('validation_samples.txt', sep='\\t', header=None, engine='python') validation_samples = validation_samples.to_numpy() validation_samples", "import pandas as pd # pandas pentru citirea fisierelor from sklearn import preprocessing", "Colaboratory. Original file is located at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\" # Importarea librariilor import numpy", "= pd.read_csv('validation_samples.txt', sep='\\t', header=None, engine='python') validation_samples = validation_samples.to_numpy() validation_samples = validation_samples[:,1] # salvam", "validation_features) # Aplicam modelul SVM model_svm = svm.SVC(kernel='linear', C=23, gamma=110) # definim modelul", "# pastram doar cuvintele validation_samples = pd.read_csv('validation_samples.txt', sep='\\t', header=None, engine='python') validation_samples = validation_samples.to_numpy()", "scaled_test_data = scaler.transform(test_data) return scaled_train_data, scaled_test_data else: return train_data, test_data # Modelarea datelor", "scaled_train_data, scaled_test_data else: return train_data, test_data # Modelarea datelor vectorizer = TfidfVectorizer() training_features", "datele de test print(\"Classification report: \") print(classification_report(validation_labels, model_svm.predict(norm_validation))) print(\"Confusion matrix: \") print(confusion_matrix(validation_labels, model_svm.predict(norm_validation)))", "import numpy as np import pandas as pd # pandas pentru citirea fisierelor", "type == 'l1' or type == 'l2': scaler = preprocessing.Normalizer(norm = type) if", "# definim modelul model_svm.fit(norm_train, train_labels) # procesul de invatare test_predictions = model_svm.predict(norm_test) #", "is located at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\" # Importarea librariilor import numpy as np import", "TfidfVectorizer # modelarea datelor pentru a obtine valori numerice din text from sklearn.metrics", "norm_train, norm_test = normalize_data(training_features, testing_features) norm_validation, _ = normalize_data(validation_features, validation_features) # Aplicam modelul", "train_labels) # procesul de invatare test_predictions = model_svm.predict(norm_test) # predictie pe datele de", "SVM model_svm = svm.SVC(kernel='linear', C=23, gamma=110) # definim modelul model_svm.fit(norm_train, train_labels) # procesul", "header=None, engine='python') train_samples = train_samples.to_numpy() train_samples = train_samples[:,1] # pastram doar cuvintele validation_samples", "este setat implicit la l2 scaler = None if type == 'standard': scaler", "TfidfVectorizer() training_features = vectorizer.fit_transform(train_samples) validation_features = vectorizer.transform(validation_samples) testing_features = vectorizer.transform(test_samples) # Normalizarea datelor", "'l1' or type == 'l2': scaler = preprocessing.Normalizer(norm = type) if scaler is", "utf-8 -*- \"\"\"Proiect.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw", "file is located at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\" # Importarea librariilor import numpy as np", "functia care intoarce datele normalizate #tipul de normalizare este setat implicit la l2", "convertim data frame-ul intr-un vector train_labels = train_labels[:,1] # pastram doar etichetele train_samples", "# pandas pentru citirea fisierelor from sklearn import preprocessing from sklearn import svm", "= test_samples.to_numpy() label = test_samples[:,0] # salvam etichetele test_samples = test_samples[:,1] # salvam", "pentru citirea fisierelor from sklearn import preprocessing from sklearn import svm # importarea", "elif type == 'min_max': scaler = preprocessing.MinMaxScaler() elif type == 'l1' or type", "procesul de invatare test_predictions = model_svm.predict(norm_test) # predictie pe datele de test print(\"Classification", "test_samples = test_samples[:,1] # salvam cuvintele def normalize_data(train_data, test_data, type='l2'): # functia care", "# Normalizarea datelor norm_train, norm_test = normalize_data(training_features, testing_features) norm_validation, _ = normalize_data(validation_features, validation_features)", "pd.read_csv('validation_labels.txt', sep='\\t', header=None, engine='python') validation_labels = validation_labels.to_numpy() validation_labels = validation_labels[:,1] # pastram doar", "scaler is not None: scaler.fit(train_data) scaled_train_data = scaler.transform(train_data) scaled_test_data = scaler.transform(test_data) return scaled_train_data,", "'l2': scaler = preprocessing.Normalizer(norm = type) if scaler is not None: scaler.fit(train_data) scaled_train_data", "scaler.fit(train_data) scaled_train_data = scaler.transform(train_data) scaled_test_data = scaler.transform(test_data) return scaled_train_data, scaled_test_data else: return train_data,", "modelul SVM model_svm = svm.SVC(kernel='linear', C=23, gamma=110) # definim modelul model_svm.fit(norm_train, train_labels) #", "a obtine valori numerice din text from sklearn.metrics import classification_report, confusion_matrix # Incarcarea", "= pd.read_csv('train_samples.txt', sep='\\t', header=None, engine='python') train_samples = train_samples.to_numpy() train_samples = train_samples[:,1] # pastram", "importarea modelului from sklearn.feature_extraction.text import TfidfVectorizer # modelarea datelor pentru a obtine valori", "= vectorizer.transform(validation_samples) testing_features = vectorizer.transform(test_samples) # Normalizarea datelor norm_train, norm_test = normalize_data(training_features, testing_features)", "train_samples = train_samples[:,1] # pastram doar cuvintele validation_samples = pd.read_csv('validation_samples.txt', sep='\\t', header=None, engine='python')", "obtine valori numerice din text from sklearn.metrics import classification_report, confusion_matrix # Incarcarea datelor", "as pd # pandas pentru citirea fisierelor from sklearn import preprocessing from sklearn", "din text from sklearn.metrics import classification_report, confusion_matrix # Incarcarea datelor train_labels = pd.read_csv('train_labels.txt',", "= validation_labels[:,1] # pastram doar etichetele test_samples = pd.read_csv('test_samples.txt', sep='\\t', header=None, engine='python') test_samples", "test_samples.to_numpy() label = test_samples[:,0] # salvam etichetele test_samples = test_samples[:,1] # salvam cuvintele", "# convertim data frame-ul intr-un vector train_labels = train_labels[:,1] # pastram doar etichetele", "vectorizer.fit_transform(train_samples) validation_features = vectorizer.transform(validation_samples) testing_features = vectorizer.transform(test_samples) # Normalizarea datelor norm_train, norm_test =", "from sklearn.metrics import classification_report, confusion_matrix # Incarcarea datelor train_labels = pd.read_csv('train_labels.txt', sep='\\t', header=None,", "doar etichetele train_samples = pd.read_csv('train_samples.txt', sep='\\t', header=None, engine='python') train_samples = train_samples.to_numpy() train_samples =", "C=23, gamma=110) # definim modelul model_svm.fit(norm_train, train_labels) # procesul de invatare test_predictions =", "engine='python') train_labels = train_labels.to_numpy() # convertim data frame-ul intr-un vector train_labels = train_labels[:,1]", "de test print(\"Classification report: \") print(classification_report(validation_labels, model_svm.predict(norm_validation))) print(\"Confusion matrix: \") print(confusion_matrix(validation_labels, model_svm.predict(norm_validation))) #", "# pastram doar etichetele train_samples = pd.read_csv('train_samples.txt', sep='\\t', header=None, engine='python') train_samples = train_samples.to_numpy()", "salvam cuvintele def normalize_data(train_data, test_data, type='l2'): # functia care intoarce datele normalizate #tipul", "classification_report, confusion_matrix # Incarcarea datelor train_labels = pd.read_csv('train_labels.txt', sep='\\t', header=None, engine='python') train_labels =", "validation_samples = validation_samples.to_numpy() validation_samples = validation_samples[:,1] # salvam cuvintele validation_labels = pd.read_csv('validation_labels.txt', sep='\\t',", "etichetele test_samples = pd.read_csv('test_samples.txt', sep='\\t', header=None, engine='python') test_samples = test_samples.to_numpy() label = test_samples[:,0]", "sep='\\t', header=None, engine='python') validation_samples = validation_samples.to_numpy() validation_samples = validation_samples[:,1] # salvam cuvintele validation_labels", "# salvam etichetele test_samples = test_samples[:,1] # salvam cuvintele def normalize_data(train_data, test_data, type='l2'):", "header=None, engine='python') validation_samples = validation_samples.to_numpy() validation_samples = validation_samples[:,1] # salvam cuvintele validation_labels =", "= preprocessing.Normalizer(norm = type) if scaler is not None: scaler.fit(train_data) scaled_train_data = scaler.transform(train_data)", "cuvintele validation_samples = pd.read_csv('validation_samples.txt', sep='\\t', header=None, engine='python') validation_samples = validation_samples.to_numpy() validation_samples = validation_samples[:,1]", "\"\"\"Proiect.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\" #", "# Incarcarea datelor train_labels = pd.read_csv('train_labels.txt', sep='\\t', header=None, engine='python') train_labels = train_labels.to_numpy() #", "test_samples[:,1] # salvam cuvintele def normalize_data(train_data, test_data, type='l2'): # functia care intoarce datele", "train_labels = train_labels[:,1] # pastram doar etichetele train_samples = pd.read_csv('train_samples.txt', sep='\\t', header=None, engine='python')", "train_samples = pd.read_csv('train_samples.txt', sep='\\t', header=None, engine='python') train_samples = train_samples.to_numpy() train_samples = train_samples[:,1] #", "datelor train_labels = pd.read_csv('train_labels.txt', sep='\\t', header=None, engine='python') train_labels = train_labels.to_numpy() # convertim data", "= vectorizer.fit_transform(train_samples) validation_features = vectorizer.transform(validation_samples) testing_features = vectorizer.transform(test_samples) # Normalizarea datelor norm_train, norm_test", "model_svm = svm.SVC(kernel='linear', C=23, gamma=110) # definim modelul model_svm.fit(norm_train, train_labels) # procesul de", "type='l2'): # functia care intoarce datele normalizate #tipul de normalizare este setat implicit", "generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\" # Importarea librariilor" ]
[]
[ "from flytekit.core.promise import ( NodeOutput, Promise, VoidPromise, binding_from_python_std, create_and_link_node, create_native_named_tuple, create_task_output, translate_inputs_to_literals, )", "a Python native value. for k, v in kwargs.items(): if not isinstance(v, Promise):", "need to run through the function itself because the body of the function", "return self._name @property def short_name(self) -> str: return self._name.split(\".\")[-1] @property def workflow_metadata(self) ->", "added using the add_entity function, all inputs to that entity should've been already", "the IDL for more information but essentially, this WorkflowMetadataDefaults class represents the defaults", "in self.python_interface.outputs.keys()] return output_tuple(*nones) else: return None # We are already in a", "the same way as any other previous node. \"\"\" if not self.ready(): raise", "_workflow_function: return wrapper(_workflow_function) else: return wrapper class ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow): \"\"\" A reference workflow", "type (e.g. List[int]\" ) python_type = p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring python type for wf output", "(result is not None and expected_outputs == 1): return create_native_named_tuple(ctx, result, self.python_interface) raise", "upstream_nodes=[], flyte_entity=None, ) class WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY = _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE = ( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE )", "VoidPromise]: # This is done to support the invariant that Workflow local executions", "{} # Retrieve the entity from the node, and call it by looking", "# object itself. for n in comp_ctx.compilation_state.nodes: if isinstance(n.flyte_entity, PythonAutoContainerTask) and n.flyte_entity.task_resolver ==", "flytekit.models import literals as _literal_models from flytekit.models.core import workflow as _workflow_model GLOBAL_START_NODE =", "def python_interface(self) -> Interface: return self._python_interface @property def interface(self) -> _interface_models.TypedInterface: return self._interface", "way as any other previous node. \"\"\" if not self.ready(): raise FlyteValidationException(f\"Workflow not", "that we're dealing with a one-element # named tuple if self.python_interface.output_tuple_name: return (get_promise(self.output_bindings[0].binding,", "workflow itself. \"\"\" interruptible: bool def __post_init__(self): if self.interruptible is not True and", "pulling in outputs from previously completed nodes and filling in the necessary inputs.", "resolver change. The task resolver interface itself is # more or less stateless", "expected_output_names = list(self.python_interface.outputs.keys()) if len(expected_output_names) == 1: # Here we have to handle", "# length one. That convention is used for naming outputs - and single-length-NamedTuples", "result is None or isinstance(result, VoidPromise): return None else: raise Exception(f\"Workflow local execution", "( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ) @dataclass class WorkflowMetadata(object): on_failure: WorkflowFailurePolicy def __post_init__(self): if ( self.on_failure", "this workflow class has to keep track of its own compilation state. \"\"\"", "entire structure of a task by looking at the function's signature, workflows need", "serialization-time (aka compile-time). This is because while we can determine the entire structure", "when expecting a native value for {k}\") with FlyteContextManager.with_context( ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) ) )", "through the nodes in order and we shouldn't run into any dependency issues.", "p: Union[Promise, List[Promise], Dict[str, Promise]], python_type: Optional[Type] = None ): \"\"\" Add an", "= PythonFunctionWorkflow( fn, metadata=workflow_metadata, default_metadata=workflow_metadata_defaults ) workflow_instance.compile() return workflow_instance if _workflow_function: return wrapper(_workflow_function)", "here only to try to streamline the pattern between workflows and tasks. Since", "import logger from flytekit.models import interface as _interface_models from flytekit.models import literals as", "fill in the node's entity's input arguments, which are specified using the bindings", "results is None: continue # pragma: no cover # Move along, nothing to", "function and decorated with the :py:func:`@workflow <flytekit.workflow>` decorator. Please see notes on that", "n def add_workflow_input(self, input_name: str, python_type: Type) -> Interface: \"\"\" Adds an input", "unexpected keyword argument {k}\") if isinstance(v, Promise): raise ValueError(f\"Received a promise for a", "given node output. \"\"\" if output_name in self._python_interface.outputs: raise FlyteValidationException(f\"Output {output_name} already exists", "VoidPromise) or function_outputs is None: if len(self.python_interface.outputs) != 0: raise FlyteValueException( function_outputs, f\"{function_outputs}", "just raise an error here. if len(self.python_interface.outputs) == 0: raise FlyteValueException( function_outputs, f\"{function_outputs}", "self.interface.inputs.keys()]) input_kwargs.update(kwargs) workflow_outputs = self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes) # This little loop was added as", "f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function = workflow_function native_interface = transform_signature_to_interface(inspect.signature(workflow_function)) # TODO do we need this", "n in comp_ctx.compilation_state.nodes: if isinstance(n.flyte_entity, PythonAutoContainerTask) and n.flyte_entity.task_resolver == self: logger.debug(f\"WF {self.name} saving", "local runs notwithstanding). Please see the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for more usage examples. :param _workflow_function:", "{self}\") # Create a map that holds the outputs of each node. intermediate_node_outputs", "declared with a typing.NamedTuple of # length one. That convention is used for", "\"\"\" This decorator declares a function to be a Flyte workflow. Workflows are", "workflows are in Flyte. This Python object represents a workflow defined by a", "wrapper(fn): workflow_metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) workflow_instance = PythonFunctionWorkflow( fn,", "to a workflow's tasks, whereas WorkflowMetadata represents metadata about the workflow itself. \"\"\"", "Anytime you add an entity, all the inputs to the entity must be", "when the workflow runs on Flyte. That is, workflows should not call non-Flyte", "in kwargs are Promise objects for k, v in kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k] = v", "former case we get the task's VoidPromise, in the latter we get None", "len(results) != len(expected_output_names): raise FlyteValueException(results, f\"Different lengths {results} {expected_output_names}\") for idx, r in", "inputs: Dict[str, Type], outputs: Dict[str, Type] ): super().__init__(WorkflowReference(project, domain, name, version), inputs, outputs)", "super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=default_metadata, python_interface=native_interface, ) @property def function(self): return self._workflow_function def task_name(self,", "Optional[List[_literal_models.Binding]] = [] FlyteEntities.entities.append(self) super().__init__(**kwargs) @property def name(self) -> str: return self._name @property", "to start things off, filled in only with the workflow inputs (if any).", "binding into a Promise object, using a lookup map. Please see get_promise_map for", "Promise object, using a lookup map. Please see get_promise_map for the rest of", "{len(workflow_outputs)}\" ) if self.python_interface.output_tuple_name is None: raise AssertionError( \"Outputs specification for Workflow does", "dealing with a one-element # named tuple if self.python_interface.output_tuple_name: return (get_promise(self.output_bindings[0].binding, intermediate_node_outputs),) #", "tuple(bindings) def execute(self, **kwargs): \"\"\" This function is here only to try to", "if ctx.execution_state.branch_eval_mode == BranchEvalMode.BRANCH_SKIPPED: if self.python_interface and self.python_interface.output_tuple_name: variables = [k for k", "by default interruptible \"\"\" def wrapper(fn): workflow_metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults =", "1 case is separate is because the one output might be a list.", "is a tuple\" ) workflow_outputs = workflow_outputs[0] t = self.python_interface.outputs[output_names[0]] b = binding_from_python_std(", "intermediate_node_outputs) # Handle the calling and outputs of each node's entity results =", "def add_entity(self, entity: Union[PythonTask, LaunchPlan, WorkflowBase], **kwargs) -> Node: \"\"\" Anytime you add", "sanity checks # Even though the _local_execute call generally expects inputs to be", "f\"Nodes ({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\" def execute(self, **kwargs): \"\"\" Called by _local_execute. This function is", "the compilation. This mimics a 'closure' in the traditional sense of the word.", "Unlike a task, the function body of a workflow is evaluated at serialization-time", "above, which do additional checking. \"\"\" if len(self.compilation_state.nodes) == 0: return False if", "with the functions above, which do additional checking. \"\"\" if len(self.compilation_state.nodes) == 0:", "call to Admin, which is why the user is asked to provide the", "WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) workflow_instance = PythonFunctionWorkflow( fn, metadata=workflow_metadata, default_metadata=workflow_metadata_defaults )", "{} for k, bd in binding_data.map.bindings.items(): p = get_promise(bd, outputs_cache) literals[k] = p.val", "local execution notwithstanding, it is not evaluated again when the workflow runs on", "for k, v in kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k] = v # Next iterate through the", "Promise]], python_type: Optional[Type] = None ): \"\"\" Add an output with the given", "a workflow is evaluated at serialization-time (aka compile-time). This is because while we", "Retrieve the entity from the node, and call it by looking up the", "'closure' in the traditional sense of the word. \"\"\" ctx = FlyteContextManager.current_context() self._input_parameters", "upstream node's output we want return outputs_cache[binding_data.promise.node][binding_data.promise.var] elif binding_data.scalar is not None: return", "import ClassStorageTaskResolver from flytekit.core.condition import ConditionalSection from flytekit.core.context_manager import ( BranchEvalMode, CompilationState, ExecutionState,", "= node.flyte_entity entity_kwargs = get_promise_map(node.bindings, intermediate_node_outputs) # Handle the calling and outputs of", "call pattern for Workflows is close to, but not exactly, the call pattern", "python_interface self._interface = transform_interface_to_typed_interface(python_interface) self._inputs = {} self._unbound_inputs = set() self._nodes = []", "in workflow {self.name}\") if python_type is None: if type(p) == list or type(p)", "the functions above, which do additional checking. \"\"\" if len(self.compilation_state.nodes) == 0: return", "not None: return Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar)) elif binding_data.collection is not None: literals = []", "= workflow_metadata_defaults self._python_interface = python_interface self._interface = transform_interface_to_typed_interface(python_interface) self._inputs = {} self._unbound_inputs =", "were done with the functions above, which do additional checking. \"\"\" if len(self.compilation_state.nodes)", "n = create_node(entity=entity, **kwargs) def get_input_values(input_value): if isinstance(input_value, list): input_promises = [] for", "with a typing.NamedTuple of # length one. That convention is used for naming", "literals.append(p.val) return Promise( var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), ) elif binding_data.map is not None: literals =", "output_tuple_name as a proxy. if self.python_interface.output_tuple_name and isinstance(function_outputs, tuple): wf_outputs_as_map = {expected_output_names[0]: function_outputs[0]}", "- and single-length-NamedTuples are # particularly troublesome but elegant handling of them is", "Optional[bool] = False, ): metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) self._compilation_state", "Dict[str, Promise]: \"\"\" Local execution of imperatively defined workflows is done node by", "an error will be returned. \"\"\" def wrapper(fn) -> ReferenceWorkflow: interface = transform_signature_to_interface(inspect.signature(fn))", "# interface. We do that by extracting out the literals, and creating new", "of imperatively defined workflows is done node by node. This function will fill", "the traditional sense of the word. \"\"\" ctx = FlyteContextManager.current_context() self._input_parameters = transform_inputs_to_parameters(ctx,", "with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: b = binding_from_python_std( ctx, output_name, expected_literal_type=flyte_type, t_value=p, t_value_type=python_type )", "= {} for k, bd in binding_data.map.bindings.items(): p = get_promise(bd, outputs_cache) literals[k] =", "# Run some sanity checks # Even though the _local_execute call generally expects", "issues a bit earlier. It just # keeps track of workflow inputs that", "r in enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]] = r # The rest of this function looks", "lengths {results} {expected_output_names}\") for idx, r in enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]] = r # The", "sense of the word. \"\"\" ctx = FlyteContextManager.current_context() self._input_parameters = transform_inputs_to_parameters(ctx, self.python_interface) all_nodes", "the list here, instead we should let the binding creation unwrap it and", "return { input_name: Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) for input_name in inputs } def get_promise(binding_data:", "_ in self.python_interface.outputs.keys()] return output_tuple(*nones) else: return None # We are already in", "not match\") def execute(self, **kwargs): raise Exception(\"Should not be called\") def _local_execute(self, ctx:", "using the node output tracker map we have. entity = node.flyte_entity entity_kwargs =", "fn, metadata=workflow_metadata, default_metadata=workflow_metadata_defaults ) workflow_instance.compile() return workflow_instance if _workflow_function: return wrapper(_workflow_function) else: return", "Next iterate through the nodes in order. for node in self.compilation_state.nodes: if node", "are in Flyte. This Python object represents a workflow defined by a function", "a user would return in mock function. That is, if it's a tuple,", "a tuple, but return value is a tuple\" ) workflow_outputs = workflow_outputs[0] t", "Last is starting a local workflow execution else: # Run some sanity checks", "# Basically we need to repackage the promises coming from the tasks into", ":std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for more usage examples. :param _workflow_function: This argument is implicitly passed and", "if isinstance(n.flyte_entity, PythonAutoContainerTask) and n.flyte_entity.task_resolver == self: logger.debug(f\"WF {self.name} saving task {n.flyte_entity.name}\") self.add(n.flyte_entity)", "ctx, output_names[0], self.interface.outputs[output_names[0]].type, workflow_outputs, t, ) bindings.append(b) elif len(output_names) > 1: if not", "return self._workflow_function(**kwargs) def workflow( _workflow_function=None, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False,", "The nodes in these Promise objects should always point to the global start", "one at a time. \"\"\" if len(args) > 0: raise AssertionError(\"Only Keyword Arguments", "we create a map to start things off, filled in only with the", "expresses the workflow structure. It's also important to note that, local execution notwithstanding,", "A workflow function may return a task that doesn't return anything # def", "= WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) self._compilation_state = CompilationState(prefix=\"\") self._inputs = {}", "= [] for x in input_value: input_promises.extend(get_input_values(x)) return input_promises if isinstance(input_value, dict): input_promises", "and self.python_interface.output_tuple_name: variables = [k for k in self.python_interface.outputs.keys()] output_tuple = collections.namedtuple(self.python_interface.output_tuple_name, variables)", "by looking at the function's signature, workflows need to run through the function", "VoidPromise) or results is None: continue # pragma: no cover # Move along,", "then we do a one-element non-named tuple, # if it's a single element", "= None super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=default_metadata, python_interface=native_interface, ) @property def function(self): return self._workflow_function", "by fulfilling all of the # workflow's output bindings. # The return style", "input promise bindings, but then override with the provided inputs, if any input_kwargs", "return VoidPromise(self.name) # The values that we return below from the output have", "interface itself is # more or less stateless (the future-proofing get_all_tasks function notwithstanding).", "combination of Python native values and Promises containing Flyte # Literals. function_outputs =", "AssertionError( \"Outputs specification for Workflow does not define a tuple, but return value", "outputs of each node's entity results = entity(**entity_kwargs) expected_output_names = list(entity.python_interface.outputs.keys()) if isinstance(results,", "_local_execute -> execute From execute, different things happen for the two Workflow styles.", "not None and expected_outputs == 1): return create_native_named_tuple(ctx, result, self.python_interface) raise ValueError(\"expected outputs", "v in input_value.items(): input_promises.extend(get_input_values(v)) return input_promises else: return [input_value] # Every time an", "self._unbound_inputs = set() self._nodes = [] self._output_bindings: Optional[List[_literal_models.Binding]] = [] FlyteEntities.entities.append(self) super().__init__(**kwargs) @property", "all # def wf(): # t1() # In the former case we get", "native_interface = transform_signature_to_interface(inspect.signature(workflow_function)) # TODO do we need this - can this not", "from flytekit.models import literals as _literal_models from flytekit.models.core import workflow as _workflow_model GLOBAL_START_NODE", "is not None: raise Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: b", "gather all the input # values but we're only interested in the ones", "and override with kwargs passed in input_kwargs = self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs) # The first", "self.interface.outputs[output_names[0]].type, workflow_outputs, t, ) bindings.append(b) elif len(output_names) > 1: if not isinstance(workflow_outputs, tuple):", "continue the execution context return self._local_execute(ctx, **input_kwargs) # Last is starting a local", "looking up the promises the node's bindings require, # and then fill them", "dispatch_execute which is in _local_execute, workflows should also call an execute inside _local_execute.", "Callable, Dict, List, Optional, Tuple, Type, Union from flytekit.common import constants as _common_constants", "intermediate_node_outputs) return tuple([get_promise(b.binding, intermediate_node_outputs) for b in self.output_bindings]) def add_entity(self, entity: Union[PythonTask, LaunchPlan,", "to the workflow. \"\"\" if input_name in self._inputs: raise FlyteValidationException(f\"Input {input_name} has already", "an SdkWorkflow, except for the missing project and domain self._nodes = all_nodes self._output_bindings", "= translate_inputs_to_literals( ctx, wf_outputs_as_map, flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs, ) # Recreate new promises that use", "the output_tuple_name as a proxy. if self.python_interface.output_tuple_name and isinstance(function_outputs, tuple): wf_outputs_as_map = {expected_output_names[0]:", "by node. This function will fill in the node's entity's input arguments, which", "results = entity(**entity_kwargs) expected_output_names = list(entity.python_interface.outputs.keys()) if isinstance(results, VoidPromise) or results is None:", "intermediate_node_outputs),) # Just a normal single element return get_promise(self.output_bindings[0].binding, intermediate_node_outputs) return tuple([get_promise(b.binding, intermediate_node_outputs)", "in the traditional sense of the word. \"\"\" ctx = FlyteContextManager.current_context() self._input_parameters =", "comp_ctx: # Construct the default input promise bindings, but then override with the", "not in self.interface.inputs: raise ValueError(f\"Received unexpected keyword argument {k}\") if isinstance(v, Promise): raise", "{output_name} already exists in workflow {self.name}\") if python_type is None: if type(p) ==", "__init__( self, name: str, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False, ):", "holds the outputs of each node. intermediate_node_outputs = {GLOBAL_START_NODE: {}} # type: Dict[Node,", "to understand that we're dealing with a one-element # named tuple if self.python_interface.output_tuple_name:", "this function looks like the above but now we're doing it for the", "# Even though the _local_execute call generally expects inputs to be Promises, we", "override with the provided inputs, if any input_kwargs = construct_input_promises([k for k in", "tuple): raise AssertionError(\"The Workflow specification indicates multiple return values, received only one\") if", "task_name(self, t: PythonAutoContainerTask) -> str: return f\"{self.name}.{t.__module__}.{t.name}\" def compile(self, **kwargs): \"\"\" Supply static", "if ( self.on_failure != WorkflowFailurePolicy.FAIL_IMMEDIATELY and self.on_failure != WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ): raise FlyteValidationException(f\"Failure policy", "in workflow level outputs the same way as any other previous node. \"\"\"", "input_promises = [] for x in input_value: input_promises.extend(get_input_values(x)) return input_promises if isinstance(input_value, dict):", "{self.name}.\") self._python_interface = self._python_interface.with_inputs(extra_inputs={input_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name] = Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name))", "def wf(): # t1() # In the former case we get the task's", "Callable, metadata: Optional[WorkflowMetadata], default_metadata: Optional[WorkflowMetadataDefaults], ): name = f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function = workflow_function native_interface", "raise FlyteValidationException(\"Binding type unrecognized.\") def get_promise_map( bindings: List[_literal_models.Binding], outputs_cache: Dict[Node, Dict[str, Promise]] )", "as a proxy. if self.python_interface.output_tuple_name and isinstance(function_outputs, tuple): wf_outputs_as_map = {expected_output_names[0]: function_outputs[0]} else:", "state, which means * Has at least one node * All workflow inputs", "pointer to a workflow that already exists on your Flyte installation. This object", "an output with the given name from the given node output. \"\"\" if", "nodes and workflow i/o changes were done with the functions above, which do", "itself because the body of the function is what expresses the workflow structure.", "t_value_type=python_type ) self._output_bindings.append(b) self._python_interface = self._python_interface.with_outputs(extra_outputs={output_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) def add_task(self, task:", "is starting a local workflow execution else: # Run some sanity checks #", "For PythonFunctionWorkflows, the Python function is run, for the ImperativeWorkflow, each node is", "name instead of value? all_input_values = get_input_values(kwargs) for input_value in filter(lambda x: isinstance(x,", "== ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ): if ctx.execution_state.branch_eval_mode == BranchEvalMode.BRANCH_SKIPPED: if self.python_interface and self.python_interface.output_tuple_name: variables =", "from flytekit.core.interface import ( Interface, transform_inputs_to_parameters, transform_interface_to_typed_interface, transform_signature_to_interface, ) from flytekit.core.launch_plan import LaunchPlan", "bound. \"\"\" # circular import from flytekit.core.node_creation import create_node ctx = FlyteContext.current_context() if", "domain: str, name: str, version: str, inputs: Dict[str, Type], outputs: Dict[str, Type] ):", "for idx, r in enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]] = r # The rest of this", "# than just one node at a time. if len(self.python_interface.outputs) == 0: return", "expected interface. If at registration time the interface provided causes an issue with", "ready, wf is currently {self}\") # Create a map that holds the outputs", "workflows should also call an execute inside _local_execute. This makes mocking cleaner. \"\"\"", "interruptible: Optional[bool] = False, ): metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible)", "down to a workflow's tasks, whereas WorkflowMetadata represents metadata about the workflow itself.", "{k}\") if isinstance(v, Promise): raise ValueError(f\"Received a promise for a workflow call, when", "of the global input node, i.e. the inputs to the workflow. # _local_execute", "@property def function(self): return self._workflow_function def task_name(self, t: PythonAutoContainerTask) -> str: return f\"{self.name}.{t.__module__}.{t.name}\"", "__post_init__(self): if self.interruptible is not True and self.interruptible is not False: raise FlyteValidationException(f\"Interruptible", "also call an execute inside _local_execute. This makes mocking cleaner. \"\"\" return self._workflow_function(**kwargs)", "self, output_name: str, p: Union[Promise, List[Promise], Dict[str, Promise]], python_type: Optional[Type] = None ):", "then override with the provided inputs, if any input_kwargs = construct_input_promises([k for k", "val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) for input_name in inputs } def get_promise(binding_data: _literal_models.BindingData, outputs_cache: Dict[Node, Dict[str,", "\"\"\" A reference workflow is a pointer to a workflow that already exists", "FlyteValidationException(f\"Failure policy {self.on_failure} not acceptable\") def to_flyte_model(self): if self.on_failure == WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure =", "{expected_output_names[0]: function_outputs} else: wf_outputs_as_map = {expected_output_names[i]: function_outputs[i] for i, _ in enumerate(function_outputs)} #", "tuple if self.python_interface.output_tuple_name: return (get_promise(self.output_bindings[0].binding, intermediate_node_outputs),) # Just a normal single element return", "but then override with the provided inputs, if any input_kwargs = construct_input_promises([k for", "First handle the empty return case. # A workflow function may return a", "for k in self.interface.inputs.keys()]) input_kwargs.update(kwargs) workflow_outputs = self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes) # This little loop", "provided inputs, if any input_kwargs = construct_input_promises([k for k in self.interface.inputs.keys()]) input_kwargs.update(kwargs) workflow_outputs", "node is run one at a time. \"\"\" if len(args) > 0: raise", "in kwargs.items(): if not isinstance(v, Promise): t = self.python_interface.inputs[k] kwargs[k] = Promise(var=k, val=TypeEngine.to_literal(ctx,", "({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\" def execute(self, **kwargs): \"\"\" Called by _local_execute. This function is how", "outputs are stored in this map. After all nodes are run, we fill", "are only run once (again, this is with respect to the platform, local", "add_entity function, all inputs to that entity should've been already declared, we can", "wrapper class ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow): \"\"\" A reference workflow is a pointer to a", "interface. We do that by extracting out the literals, and creating new Promises", "of the upstream node's output we want return outputs_cache[binding_data.promise.node][binding_data.promise.var] elif binding_data.scalar is not", "Because when an entity is added using the add_entity function, all inputs to", "\"\"\" if input_name in self._inputs: raise FlyteValidationException(f\"Input {input_name} has already been specified for", "The output of this will always be a combination of Python native values", "output_tuple = collections.namedtuple(self.python_interface.output_tuple_name, variables) nones = [None for _ in self.python_interface.outputs.keys()] return output_tuple(*nones)", "execution of imperatively defined workflows is done node by node. This function will", "= CompilationState(prefix=\"\") self._inputs = {} # This unbound inputs construct is just here", "outputs_cache: Dict[Node, Dict[str, Promise]] ) -> Dict[str, Promise]: \"\"\" Local execution of imperatively", "of tasks using the data flow between tasks. Unlike a task, the function", "len(args) > 0: raise AssertionError(\"Only Keyword Arguments are supported for Workflow executions\") ctx", "workflow are by default interruptible \"\"\" def wrapper(fn): workflow_metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY)", "raise FlyteValidationException(f\"Workflow not ready, wf is currently {self}\") # Create a map that", "isinstance(n.flyte_entity, PythonAutoContainerTask) and n.flyte_entity.task_resolver == self: logger.debug(f\"WF {self.name} saving task {n.flyte_entity.name}\") self.add(n.flyte_entity) #", "if it's a single element then we return a single element if len(self.output_bindings)", ") workflow_outputs = workflow_outputs[0] t = self.python_interface.outputs[output_names[0]] b = binding_from_python_std( ctx, output_names[0], self.interface.outputs[output_names[0]].type,", "raise FlyteValidationException(f\"Input {input_name} has already been specified for wf {self.name}.\") self._python_interface = self._python_interface.with_inputs(extra_inputs={input_name:", "from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union from flytekit.common", "workflows need to run through the function itself because the body of the", "always be a combination of Python native values and Promises containing Flyte #", "def inputs(self) -> Dict[str, Promise]: \"\"\" This holds the input promises to the", "else: # Run some sanity checks # Even though the _local_execute call generally", "outputs and actual outputs do not match\") def execute(self, **kwargs): raise Exception(\"Should not", "# particularly troublesome but elegant handling of them is not a high priority", "define a tuple, but return value is a tuple\" ) workflow_outputs = workflow_outputs[0]", "= False, ): \"\"\" This decorator declares a function to be a Flyte", "is being called as part of a parent's workflow local run. # The", "haven't yet consumed. This # is an error that Admin would return at", "a lookup map. Please see get_promise_map for the rest of the details. \"\"\"", "returns whether or not the workflow is in a ready state, which means", "object represents a workflow defined by a function and decorated with the :py:func:`@workflow", "are specified using the bindings list, and a map of nodes to its", "== 1): return create_native_named_tuple(ctx, result, self.python_interface) raise ValueError(\"expected outputs and actual outputs do", "native value for {k}\") with FlyteContextManager.with_context( ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) ) ) as child_ctx: result", "ctx.execution_state is not None and ctx.execution_state.mode == ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ): if ctx.execution_state.branch_eval_mode == BranchEvalMode.BRANCH_SKIPPED:", "latter we get None if isinstance(function_outputs, VoidPromise) or function_outputs is None: if len(self.python_interface.outputs)", "does not define a tuple, but return value is a tuple\" ) workflow_outputs", "always end with an `else_()` clause\") t = self.python_interface.outputs[out] b = binding_from_python_std( ctx,", "call non-Flyte entities since they are only run once (again, this is with", "make a binding # collection/map out of it. if len(output_names) == 1: if", "nodes to its outputs. Basically this takes the place of propeller in resolving", "self._unbound_inputs.add(self._inputs[input_name]) return self._inputs[input_name] def add_workflow_output( self, output_name: str, p: Union[Promise, List[Promise], Dict[str, Promise]],", "flytekit.core.base_task import PythonTask from flytekit.core.class_based_resolver import ClassStorageTaskResolver from flytekit.core.condition import ConditionalSection from flytekit.core.context_manager", "the bindings list, and a map of nodes to its outputs. Basically this", "PythonFunctionWorkflow( fn, metadata=workflow_metadata, default_metadata=workflow_metadata_defaults ) workflow_instance.compile() return workflow_instance if _workflow_function: return wrapper(_workflow_function) else:", "represents the defaults that are handed down to a workflow's tasks, whereas WorkflowMetadata", "the input to the task # binding_data.promise.var is the name of the upstream", "**input_kwargs) expected_outputs = len(self.python_interface.outputs) if expected_outputs == 0: if result is None or", "(if-else) should always end with an `else_()` clause\") t = self.python_interface.outputs[out] b =", "1: # Again use presence of output_tuple_name to understand that we're dealing with", "import from flytekit.core.node_creation import create_node ctx = FlyteContext.current_context() if ctx.compilation_state is not None:", "only? # This can be in launch plan only, but is here only", "one return value, received {len(workflow_outputs)}\" ) if self.python_interface.output_tuple_name is None: raise AssertionError( \"Outputs", "exists in workflow {self.name}\") if python_type is None: if type(p) == list or", "list. We don't want to # iterate through the list here, instead we", "a time. \"\"\" if len(args) > 0: raise AssertionError(\"Only Keyword Arguments are supported", "{GLOBAL_START_NODE: {}} # type: Dict[Node, Dict[str, Promise]] # Start things off with the", "binding_data.map is not None: literals = {} for k, bd in binding_data.map.bindings.items(): p", "declares a function to be a Flyte workflow. Workflows are declarative entities that", "from flytekit.loggers import logger from flytekit.models import interface as _interface_models from flytekit.models import", "launchplan only? # This can be in launch plan only, but is here", "same way as any other previous node. \"\"\" if not self.ready(): raise FlyteValidationException(f\"Workflow", "runs notwithstanding). Please see the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for more usage examples. :param _workflow_function: This", "function notwithstanding). However the # implementation of the TaskResolverMixin that this workflow class", "be boolean, {self.interruptible} invalid\") def to_flyte_model(self): return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def construct_input_promises(inputs: List[str]): return {", "@property def output_bindings(self) -> List[_literal_models.Binding]: return self._output_bindings @property def nodes(self) -> List[Node]: return", "raise Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: n = create_node(entity=entity, **kwargs)", "# def wf(): # t1() # In the former case we get the", "for node in self.compilation_state.nodes: if node not in intermediate_node_outputs.keys(): intermediate_node_outputs[node] = {} #", "= binding_from_python_std( ctx, out, self.interface.outputs[out].type, workflow_outputs[i], t, ) bindings.append(b) # Save all the", "_, v in input_value.items(): input_promises.extend(get_input_values(v)) return input_promises else: return [input_value] # Every time", "static Python native values in the kwargs if you want them to be", "str, ) -> Callable[[Callable[..., Any]], ReferenceWorkflow]: \"\"\" A reference workflow is a pointer", "a tuple, then it # should be a tuple here, if it's a", "output, if len(expected_output_names) == 1: if entity.python_interface.output_tuple_name and isinstance(results, tuple): intermediate_node_outputs[node][expected_output_names[0]] = results[0]", "Keyword Arguments are supported for Workflow executions\") ctx = FlyteContextManager.current_context() # Get default", "a workflow defined by a function and decorated with the :py:func:`@workflow <flytekit.workflow>` decorator.", "way to clean this up, maybe key off of the name instead of", "bindings if not output_names: return None if len(output_names) == 1: return bindings[0] return", "execute from dispatch_execute which is in _local_execute, workflows should also call an execute", "return a task that doesn't return anything # def wf(): # return t1()", "if input_value in self._unbound_inputs: self._unbound_inputs.remove(input_value) return n def add_workflow_input(self, input_name: str, python_type: Type)", "is currently {self}\") # Create a map that holds the outputs of each", "WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure = 0 else: on_failure = 1 return _workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass class WorkflowMetadataDefaults(object):", "called as part of a parent's workflow local run. # The context specifying", "\"\"\" ctx = FlyteContextManager.current_context() self._input_parameters = transform_inputs_to_parameters(ctx, self.python_interface) all_nodes = [] prefix =", "DAG of tasks using the data flow between tasks. Unlike a task, the", "0 outputs but something received {result}\") if (1 < expected_outputs == len(result)) or", "checking. \"\"\" if len(self.compilation_state.nodes) == 0: return False if len(self._unbound_inputs) > 0: return", "for b in bindings: entity_kwargs[b.var] = get_promise(b.binding, outputs_cache) return entity_kwargs class WorkflowBase(object): def", "VoidPromise(self.name) # Because we should've already returned in the above check, we just", "workflow class has to keep track of its own compilation state. \"\"\" return", "handling of them is not a high priority # Again, we're using the", "def reference_workflow( project: str, domain: str, name: str, version: str, ) -> Callable[[Callable[...,", "workflow. # _local_execute should've already ensured that all the values in kwargs are", "the platform, local runs notwithstanding). Please see the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for more usage examples.", "wf(): # return t1() # or it may not return at all #", "wrapper(fn) -> ReferenceWorkflow: interface = transform_signature_to_interface(inspect.signature(fn)) return ReferenceWorkflow(project, domain, name, version, interface.inputs, interface.outputs)", "containing Flyte # Literals. function_outputs = self.execute(**kwargs) # First handle the empty return", "above check, we just raise an Exception here. if len(entity.python_interface.outputs) == 0: raise", "than just one node at a time. if len(self.python_interface.outputs) == 0: return VoidPromise(self.name)", "whether or not the workflow is in a ready state, which means *", "declared, we can just iterate through the nodes in order and we shouldn't", "mimics a 'closure' in the traditional sense of the word. \"\"\" ctx =", "that all the values in kwargs are Promise objects for k, v in", "bindings=[], upstream_nodes=[], flyte_entity=None, ) class WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY = _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE = ( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE", "Local execution of imperatively defined workflows is done node by node. This function", "k, v in input_kwargs.items(): if k not in self.interface.inputs: raise ValueError(f\"Received unexpected keyword", "as ctx: b = binding_from_python_std( ctx, output_name, expected_literal_type=flyte_type, t_value=p, t_value_type=python_type ) self._output_bindings.append(b) self._python_interface", "Node: return self.add_entity(task, **kwargs) def add_launch_plan(self, launch_plan: LaunchPlan, **kwargs) -> Node: return self.add_entity(launch_plan,", "interface(self) -> _interface_models.TypedInterface: return self._interface @property def output_bindings(self) -> List[_literal_models.Binding]: return self._output_bindings @property", "the function body of a workflow is evaluated at serialization-time (aka compile-time). This", "nones = [None for _ in self.python_interface.outputs.keys()] return output_tuple(*nones) else: return None #", "list(self.interface.outputs.keys()) # The reason the length 1 case is separate is because the", "-> Callable[[Callable[..., Any]], ReferenceWorkflow]: \"\"\" A reference workflow is a pointer to a", "is not a high priority # Again, we're using the output_tuple_name as a", "to handle the fact that the wf could've been declared with a typing.NamedTuple", "flow between tasks. Unlike a task, the function body of a workflow is", "is added using the add_entity function, all inputs to that entity should've been", "**kwargs) -> Node: return self.add_entity(launch_plan, **kwargs) def add_subwf(self, sub_wf: WorkflowBase, **kwargs) -> Node:", ") class WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY = _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE = ( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ) @dataclass class", "workflow's # interface. We do that by extracting out the literals, and creating", "the above check, we just raise an Exception here. if len(entity.python_interface.outputs) == 0:", "or type(p) == dict: raise FlyteValidationException( f\"If specifying a list or dict of", "we want return outputs_cache[binding_data.promise.node][binding_data.promise.var] elif binding_data.scalar is not None: return Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar)) elif", "= WorkflowMetadataDefaults(interruptible) self._compilation_state = CompilationState(prefix=\"\") self._inputs = {} # This unbound inputs construct", "None ): \"\"\" Add an output with the given name from the given", "Save all the things necessary to create an SdkWorkflow, except for the missing", "you must specify the python_type type for {output_name}\" f\" starting with the container", "to, but not exactly, the call pattern for Tasks. For local execution, it", "dict of Promises, you must specify the python_type type for {output_name}\" f\" starting", "function(self): return self._workflow_function def task_name(self, t: PythonAutoContainerTask) -> str: return f\"{self.name}.{t.__module__}.{t.name}\" def compile(self,", "1: if not isinstance(workflow_outputs, tuple): raise AssertionError(\"The Workflow specification indicates multiple return values,", "type for wf output {output_name} from Promise provided {python_type}\") flyte_type = TypeEngine.to_literal_type(python_type=python_type) ctx", "def to_flyte_model(self): if self.on_failure == WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure = 0 else: on_failure = 1", "should also call an execute inside _local_execute. This makes mocking cleaner. \"\"\" return", "invariant that Workflow local executions always work with Promise objects # holding Flyte", "starting a local workflow execution else: # Run some sanity checks # Even", "> 0: return False return True class PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver): \"\"\" Please read :std:ref:`flyte:divedeep-workflows`", "to the entity must be bound. \"\"\" # circular import from flytekit.core.node_creation import", "self._inputs = {} # This unbound inputs construct is just here to help", "objects for k, v in kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k] = v # Next iterate through", "a proxy. if self.python_interface.output_tuple_name and isinstance(function_outputs, tuple): wf_outputs_as_map = {expected_output_names[0]: function_outputs[0]} else: wf_outputs_as_map", "always work with Promise objects # holding Flyte literal values. Even in a", "bindings: {self._output_bindings} && \" ) def __call__(self, *args, **kwargs): \"\"\" The call pattern", "not self.ready(): raise FlyteValidationException(f\"Workflow not ready, wf is currently {self}\") # Create a", "a list or dict of Promises, you must specify the python_type type for", "should've been VoidPromise or None.\" ) expected_output_names = list(self.python_interface.outputs.keys()) if len(expected_output_names) == 1:", "list): input_promises = [] for x in input_value: input_promises.extend(get_input_values(x)) return input_promises if isinstance(input_value,", "bindings: entity_kwargs[b.var] = get_promise(b.binding, outputs_cache) return entity_kwargs class WorkflowBase(object): def __init__( self, name:", "bindings.append(b) elif len(output_names) > 1: if not isinstance(workflow_outputs, tuple): raise AssertionError(\"The Workflow specification", "into any dependency issues. That is, we force the user to declare entities", "workflows and tasks. Since tasks call execute from dispatch_execute which is in _local_execute,", "enumerate(output_names): if isinstance(workflow_outputs[i], ConditionalSection): raise AssertionError(\"A Conditional block (if-else) should always end with", ") from flytekit.core.interface import ( Interface, transform_inputs_to_parameters, transform_interface_to_typed_interface, transform_signature_to_interface, ) from flytekit.core.launch_plan import", "workflow call, when expecting a native value for {k}\") with FlyteContextManager.with_context( ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION)", "import interface as _interface_models from flytekit.models import literals as _literal_models from flytekit.models.core import", "at the function's signature, workflows need to run through the function itself because", "Promise provided {python_type}\") flyte_type = TypeEngine.to_literal_type(python_type=python_type) ctx = FlyteContext.current_context() if ctx.compilation_state is not", "if result is None or isinstance(result, VoidPromise): return None else: raise Exception(f\"Workflow local", "with add_workflow_input but haven't yet consumed. This # is an error that Admin", "things necessary to create an SdkWorkflow, except for the missing project and domain", "had it been declared # functionally, and 2) what a user would return", "normal single element return get_promise(self.output_bindings[0].binding, intermediate_node_outputs) return tuple([get_promise(b.binding, intermediate_node_outputs) for b in self.output_bindings])", "0: raise AssertionError(\"Only Keyword Arguments are supported for Workflow executions\") ctx = FlyteContextManager.current_context()", "inputs to the entity must be bound. \"\"\" # circular import from flytekit.core.node_creation", "but this allows flytekit to raise # the error earlier. self._unbound_inputs = set()", "To keep track of outputs, we create a map to start things off,", "there's another Promise-generating loop inside _local_execute too for k, v in input_kwargs.items(): if", "[] for _, v in input_value.items(): input_promises.extend(get_input_values(v)) return input_promises else: return [input_value] #", "FlyteValidationException( f\"If specifying a list or dict of Promises, you must specify the", "in flytekit.WorkflowFailurePolicy :param interruptible: Whether or not tasks launched from this workflow are", "or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) self._compilation_state = CompilationState(prefix=\"\") self._inputs = {} # This", "in the necessary inputs. \"\"\" entity_kwargs = {} for b in bindings: entity_kwargs[b.var]", "input_promises.extend(get_input_values(x)) return input_promises if isinstance(input_value, dict): input_promises = [] for _, v in", "workflow i/o changes were done with the functions above, which do additional checking.", "outputs_cache) return entity_kwargs class WorkflowBase(object): def __init__( self, name: str, workflow_metadata: WorkflowMetadata, workflow_metadata_defaults:", "is why this workflow class has to keep track of its own compilation", "consumed. This # is an error that Admin would return at compile time", "val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) ) raise FlyteValidationException(\"Binding type unrecognized.\") def get_promise_map( bindings: List[_literal_models.Binding], outputs_cache: Dict[Node, Dict[str,", "starting with the container type (e.g. List[int]\" ) python_type = p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring python", "Basically we need to repackage the promises coming from the tasks into Promises", "Construct the default input promise bindings, but then override with the provided inputs,", "the wf could've been declared with a typing.NamedTuple of # length one. That", "tasks call execute from dispatch_execute which is in _local_execute, workflows should also call", "users from specifying inputs # as direct scalars, which means there's another Promise-generating", "isinstance(v, Promise): t = self.python_interface.inputs[k] kwargs[k] = Promise(var=k, val=TypeEngine.to_literal(ctx, v, t, self.interface.inputs[k].type)) #", "{results} {expected_output_names}\") for idx, r in enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]] = r # The rest", "a promise for a workflow call, when expecting a native value for {k}\")", "outputs_cache) literals[k] = p.val return Promise( var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) ) raise FlyteValidationException(\"Binding type unrecognized.\")", "here has to match what 1) what the workflow would've returned had it", "self._python_interface @property def interface(self) -> _interface_models.TypedInterface: return self._interface @property def output_bindings(self) -> List[_literal_models.Binding]:", "is done a bit at a time, one task or other entity call", "it's a one element named tuple, then we do a one-element non-named tuple,", "**kwargs): raise Exception(\"Should not be called\") def _local_execute(self, ctx: FlyteContext, **kwargs) -> Union[Tuple[Promise],", "The return style here has to match what 1) what the workflow would've", "workflow_metadata_defaults: WorkflowMetadataDefaults, python_interface: Interface, **kwargs, ): self._name = name self._workflow_metadata = workflow_metadata self._workflow_metadata_defaults", "if len(self.output_bindings) == 1: # Again use presence of output_tuple_name to understand that", "are already in a local execution, just continue the execution context return self._local_execute(ctx,", "compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: n = create_node(entity=entity, **kwargs) def get_input_values(input_value): if isinstance(input_value,", "in binding_data.map.bindings.items(): p = get_promise(bd, outputs_cache) literals[k] = p.val return Promise( var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals))", "Union from flytekit.common import constants as _common_constants from flytekit.common.exceptions.user import FlyteValidationException, FlyteValueException from", "= workflow_function native_interface = transform_signature_to_interface(inspect.signature(workflow_function)) # TODO do we need this - can", "WorkflowBase(object): def __init__( self, name: str, workflow_metadata: WorkflowMetadata, workflow_metadata_defaults: WorkflowMetadataDefaults, python_interface: Interface, **kwargs,", "\"\"\" def wrapper(fn) -> ReferenceWorkflow: interface = transform_signature_to_interface(inspect.signature(fn)) return ReferenceWorkflow(project, domain, name, version,", "looks like the above but now we're doing it for the workflow as", "self._output_bindings = bindings if not output_names: return None if len(output_names) == 1: return", "not None: literals = [] for bd in binding_data.collection.bindings: p = get_promise(bd, outputs_cache)", "time. \"\"\" if len(args) > 0: raise AssertionError(\"Only Keyword Arguments are supported for", "then fill them in using the node output tracker map we have. entity", "self.python_interface.outputs[output_names[0]] b = binding_from_python_std( ctx, output_names[0], self.interface.outputs[output_names[0]].type, workflow_outputs, t, ) bindings.append(b) elif len(output_names)", "cover # Move along, nothing to assign # Because we should've already returned", "from enum import Enum from typing import Any, Callable, Dict, List, Optional, Tuple,", "len(output_names) == 1: if isinstance(workflow_outputs, tuple): if len(workflow_outputs) != 1: raise AssertionError( f\"The", "with the workflow inputs (if any). As things are run, their outputs are", "{k}\") with FlyteContextManager.with_context( ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) ) ) as child_ctx: result = self._local_execute(child_ctx, **input_kwargs)", "arguments, which are specified using the bindings list, and a map of nodes", "or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) workflow_instance = PythonFunctionWorkflow( fn, metadata=workflow_metadata, default_metadata=workflow_metadata_defaults ) workflow_instance.compile()", "# Every time an entity is added, mark it as used. The above", "only interested in the ones that are Promises so let's filter for those.", "not acceptable\") def to_flyte_model(self): if self.on_failure == WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure = 0 else: on_failure", "= self._python_interface.with_inputs(extra_inputs={input_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name] = Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) self._unbound_inputs.add(self._inputs[input_name]) return", "str, p: Union[Promise, List[Promise], Dict[str, Promise]], python_type: Optional[Type] = None ): \"\"\" Add", "calling and outputs of each node's entity results = entity(**entity_kwargs) expected_output_names = list(entity.python_interface.outputs.keys())", "workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(), ) @property def compilation_state(self) -> CompilationState: \"\"\" Compilation is done", "the nodes in order and we shouldn't run into any dependency issues. That", "probably a way to clean this up, maybe key off of the name", "self._interface = transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name] = Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) self._unbound_inputs.add(self._inputs[input_name]) return self._inputs[input_name] def add_workflow_output(", "# the error earlier. self._unbound_inputs = set() super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(), )", "b = binding_from_python_std( ctx, out, self.interface.outputs[out].type, workflow_outputs[i], t, ) bindings.append(b) # Save all", "= WorkflowMetadataDefaults(interruptible) workflow_instance = PythonFunctionWorkflow( fn, metadata=workflow_metadata, default_metadata=workflow_metadata_defaults ) workflow_instance.compile() return workflow_instance if", "return self._compilation_state.nodes @property def inputs(self) -> Dict[str, Promise]: \"\"\" This holds the input", "self.python_interface.outputs[out] b = binding_from_python_std( ctx, out, self.interface.outputs[out].type, workflow_outputs[i], t, ) bindings.append(b) # Save", "node. This function will fill in the node's entity's input arguments, which are", "means * Has at least one node * All workflow inputs are bound", "domain: str, name: str, version: str, ) -> Callable[[Callable[..., Any]], ReferenceWorkflow]: \"\"\" A", "( BranchEvalMode, CompilationState, ExecutionState, FlyteContext, FlyteContextManager, FlyteEntities, ) from flytekit.core.interface import ( Interface,", "= v # Next iterate through the nodes in order. for node in", "but now we're doing it for the workflow as a whole rather #", "should've already returned in the above check, we just raise an error here.", "already in a topological sort. To keep track of outputs, we create a", "one element named tuple, then we do a one-element non-named tuple, # if", "!= WorkflowFailurePolicy.FAIL_IMMEDIATELY and self.on_failure != WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ): raise FlyteValidationException(f\"Failure policy {self.on_failure} not acceptable\")", "List[int]\" ) python_type = p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring python type for wf output {output_name} from", "workflow_outputs = self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes) # This little loop was added as part of", "a list. We don't want to # iterate through the list here, instead", "function is here only to try to streamline the pattern between workflows and", "# Here we have to handle the fact that the wf could've been", "nodes are run, we fill in workflow level outputs the same way as", "# functionally, and 2) what a user would return in mock function. That", "nothing to assign # Because we should've already returned in the above check,", "= workflow_metadata self._workflow_metadata_defaults = workflow_metadata_defaults self._python_interface = python_interface self._interface = transform_interface_to_typed_interface(python_interface) self._inputs =", "that doesn't return anything # def wf(): # return t1() # or it", "raise AssertionError( f\"The Workflow specification indicates only one return value, received {len(workflow_outputs)}\" )", "kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k] = v # Next iterate through the nodes in order. for", "already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: b = binding_from_python_std( ctx, output_name, expected_literal_type=flyte_type,", "raise ValueError(f\"Received a promise for a workflow call, when expecting a native value", "output_name in self._python_interface.outputs: raise FlyteValidationException(f\"Output {output_name} already exists in workflow {self.name}\") if python_type", "construct_input_promises([k for k in self.interface.inputs.keys()]) input_kwargs.update(kwargs) workflow_outputs = self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes) # This little", "== list or type(p) == dict: raise FlyteValidationException( f\"If specifying a list or", "doesn't return anything # def wf(): # return t1() # or it may", "= {GLOBAL_START_NODE: {}} # type: Dict[Node, Dict[str, Promise]] # Start things off with", "values in kwargs are Promise objects for k, v in kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k] =", "FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self)) ) as comp_ctx: # Construct the default input promise bindings,", "{self.on_failure} not acceptable\") def to_flyte_model(self): if self.on_failure == WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure = 0 else:", "Exception here. if len(entity.python_interface.outputs) == 0: raise FlyteValueException(results, f\"{results} received but should've been", "store state. This loop adds Tasks that are defined within the body of", "-> str: return self._name @property def short_name(self) -> str: return self._name.split(\".\")[-1] @property def", "# Next iterate through the nodes in order. for node in self.compilation_state.nodes: if", "decorator declares a function to be a Flyte workflow. Workflows are declarative entities", "Optional[WorkflowMetadata], default_metadata: Optional[WorkflowMetadataDefaults], ): name = f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function = workflow_function native_interface = transform_signature_to_interface(inspect.signature(workflow_function))", "def workflow( _workflow_function=None, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False, ): \"\"\"", "# The values that we return below from the output have to be", "values but we're only interested in the ones that are Promises so let's", "= get_promise(bd, outputs_cache) literals.append(p.val) return Promise( var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), ) elif binding_data.map is not", "intermediate_node_outputs[GLOBAL_START_NODE][k] = v # Next iterate through the nodes in order. for node", "filter for those. # There's probably a way to clean this up, maybe", "input_promises.extend(get_input_values(v)) return input_promises else: return [input_value] # Every time an entity is added,", "AssertionError(\"Only Keyword Arguments are supported for Workflow executions\") ctx = FlyteContextManager.current_context() # Get", "task_resolver=self)) ) as comp_ctx: # Construct the default input promise bindings, but then", "only with the workflow inputs (if any). As things are run, their outputs", "List[_literal_models.Binding]: return self._output_bindings @property def nodes(self) -> List[Node]: return self._nodes def __repr__(self): return", "_local_execute, workflows should also call an execute inside _local_execute. This makes mocking cleaner.", "with FlyteContextManager.with_context( ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) ) ) as child_ctx: result = self._local_execute(child_ctx, **input_kwargs) expected_outputs", "it goes __call__ -> _local_execute -> execute From execute, different things happen for", "to be of the NodeOutput type {type(binding_data.promise)} found\" ) # b.var is the", "1 return _workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass class WorkflowMetadataDefaults(object): \"\"\" This class is similarly named to", "determine the entire structure of a task by looking at the function's signature,", "ones that are Promises so let's filter for those. # There's probably a", "-> Node: return self.add_entity(launch_plan, **kwargs) def add_subwf(self, sub_wf: WorkflowBase, **kwargs) -> Node: return", "[] output_names = list(self.interface.outputs.keys()) # The reason the length 1 case is separate", "the workflow is in a ready state, which means * Has at least", "= get_promise(bd, outputs_cache) literals[k] = p.val return Promise( var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) ) raise FlyteValidationException(\"Binding", "named to the one above. Please see the IDL for more information but", "to_flyte_model(self): if self.on_failure == WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure = 0 else: on_failure = 1 return", "into a Promise object, using a lookup map. Please see get_promise_map for the", "declared with add_workflow_input but haven't yet consumed. This # is an error that", "self.add(n.flyte_entity) # Iterate through the workflow outputs bindings = [] output_names = list(self.interface.outputs.keys())", "intermediate_node_outputs.keys(): intermediate_node_outputs[node] = {} # Retrieve the entity from the node, and call", "return tuple([get_promise(b.binding, intermediate_node_outputs) for b in self.output_bindings]) def add_entity(self, entity: Union[PythonTask, LaunchPlan, WorkflowBase],", "**kwargs) -> Union[Tuple[Promise], Promise, VoidPromise]: # This is done to support the invariant", "run, their outputs are stored in this map. After all nodes are run,", "= set() super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(), ) @property def compilation_state(self) -> CompilationState:", "input_promises else: return [input_value] # Every time an entity is added, mark it", "# TODO do we need this - can this not be in launchplan", "__repr__(self): return super().__repr__() + f\"Nodes ({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\" def execute(self, **kwargs): \"\"\" Called by", "output we want return outputs_cache[binding_data.promise.node][binding_data.promise.var] elif binding_data.scalar is not None: return Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar))", "notwithstanding). However the # implementation of the TaskResolverMixin that this workflow class inherits", "to the global start node. \"\"\" return self._inputs def __repr__(self): return super().__repr__() +", "return at all # def wf(): # t1() # In the former case", "stored in this map. After all nodes are run, we fill in workflow", "if ctx.compilation_state is not None: raise Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as", "class PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver): \"\"\" Please read :std:ref:`flyte:divedeep-workflows` first for a high-level understanding of", "return self._python_interface @property def interface(self) -> _interface_models.TypedInterface: return self._interface @property def output_bindings(self) ->", "annotations import collections import inspect from dataclasses import dataclass from enum import Enum", "and a map of nodes to its outputs. Basically this takes the place", "name self._workflow_metadata = workflow_metadata self._workflow_metadata_defaults = workflow_metadata_defaults self._python_interface = python_interface self._interface = transform_interface_to_typed_interface(python_interface)", "set() self._nodes = [] self._output_bindings: Optional[List[_literal_models.Binding]] = [] FlyteEntities.entities.append(self) super().__init__(**kwargs) @property def name(self)", "FlyteValueException(results, f\"{results} received but should've been VoidPromise or None.\") # if there's only", "-> Interface: \"\"\" Adds an input to the workflow. \"\"\" if input_name in", "super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(), ) @property def compilation_state(self) -> CompilationState: \"\"\" Compilation", "local executions always work with Promise objects # holding Flyte literal values. Even", "specify the python_type type for {output_name}\" f\" starting with the container type (e.g.", "a tuple here, if it's a one element named tuple, then we do", ") # b.var is the name of the input to the task #", "styles. For PythonFunctionWorkflows, the Python function is run, for the ImperativeWorkflow, each node", "if len(self.python_interface.outputs) == 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but should've been VoidPromise", "@property def nodes(self) -> List[Node]: return self._nodes def __repr__(self): return ( f\"WorkflowBase -", ") if self.python_interface.output_tuple_name is None: raise AssertionError( \"Outputs specification for Workflow does not", "# collection/map out of it. if len(output_names) == 1: if isinstance(workflow_outputs, tuple): if", "traditional sense of the word. \"\"\" ctx = FlyteContextManager.current_context() self._input_parameters = transform_inputs_to_parameters(ctx, self.python_interface)", "is not None and expected_outputs == 1): return create_native_named_tuple(ctx, result, self.python_interface) raise ValueError(\"expected", "Workflows are declarative entities that construct a DAG of tasks using the data", "execute(self, **kwargs): raise Exception(\"Should not be called\") def _local_execute(self, ctx: FlyteContext, **kwargs) ->", "var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), ) elif binding_data.map is not None: literals = {} for k,", "add an entity, all the inputs to the entity must be bound. \"\"\"", "ReferenceEntity, WorkflowReference from flytekit.core.type_engine import TypeEngine from flytekit.loggers import logger from flytekit.models import", "return at compile time anyways, but this allows flytekit to raise # the", "= [Promise(var, wf_outputs_as_literal_dict[var]) for var in expected_output_names] return create_task_output(new_promises, self.python_interface) class ImperativeWorkflow(WorkflowBase): def", "input to the workflow. \"\"\" if input_name in self._inputs: raise FlyteValidationException(f\"Input {input_name} has", "there's only one output, if len(expected_output_names) == 1: if entity.python_interface.output_tuple_name and isinstance(results, tuple):", "== 1: if entity.python_interface.output_tuple_name and isinstance(results, tuple): intermediate_node_outputs[node][expected_output_names[0]] = results[0] else: intermediate_node_outputs[node][expected_output_names[0]] =", "default input promise bindings, but then override with the provided inputs, if any", "return wrapper class ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow): \"\"\" A reference workflow is a pointer to", "it and make a binding # collection/map out of it. if len(output_names) ==", "workflow_outputs[0] t = self.python_interface.outputs[output_names[0]] b = binding_from_python_std( ctx, output_names[0], self.interface.outputs[output_names[0]].type, workflow_outputs, t, )", "\" f\"Inputs ({len(self._python_interface.inputs)}): {self._python_interface.inputs} && \" f\"Outputs ({len(self._python_interface.outputs)}): {self._python_interface.outputs} && \" f\"Output bindings:", "[k for k in self.python_interface.outputs.keys()] output_tuple = collections.namedtuple(self.python_interface.output_tuple_name, variables) nones = [None for", "inputs construct is just here to help workflow authors detect issues a bit", "all nodes and workflow i/o changes were done with the functions above, which", "not True and self.interruptible is not False: raise FlyteValidationException(f\"Interruptible must be boolean, {self.interruptible}", "time anyways, but this allows flytekit to raise # the error earlier. self._unbound_inputs", "# keeps track of workflow inputs that you've declared with add_workflow_input but haven't", "== 0: return False if len(self._unbound_inputs) > 0: return False return True class", "outputs.\", ) return VoidPromise(self.name) # Because we should've already returned in the above", "let the binding creation unwrap it and make a binding # collection/map out", "@property def workflow_metadata_defaults(self): return self._workflow_metadata_defaults @property def python_interface(self) -> Interface: return self._python_interface @property", "import dataclass from enum import Enum from typing import Any, Callable, Dict, List,", "k not in self.interface.inputs: raise ValueError(f\"Received unexpected keyword argument {k}\") if isinstance(v, Promise):", ") as child_ctx: result = self._local_execute(child_ctx, **input_kwargs) expected_outputs = len(self.python_interface.outputs) if expected_outputs ==", "if len(self.python_interface.outputs) != 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but interface has {len(self.python_interface.outputs)}", "initiate a network call to Admin, which is why the user is asked", "if k not in self.interface.inputs: raise ValueError(f\"Received unexpected keyword argument {k}\") if isinstance(v,", "import Enum from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union", "None: raise Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: b = binding_from_python_std(", "not tasks launched from this workflow are by default interruptible \"\"\" def wrapper(fn):", "the expected interface. If at registration time the interface provided causes an issue", "\"\"\" This function returns whether or not the workflow is in a ready", "**kwargs): \"\"\" The call pattern for Workflows is close to, but not exactly,", "List[Node]: return self._nodes def __repr__(self): return ( f\"WorkflowBase - {self._name} && \" f\"Inputs", "we get None if isinstance(function_outputs, VoidPromise) or function_outputs is None: if len(self.python_interface.outputs) !=", "List[Node]: return self._compilation_state.nodes @property def inputs(self) -> Dict[str, Promise]: \"\"\" This holds the", "through the function itself because the body of the function is what expresses", "add_entity(self, entity: Union[PythonTask, LaunchPlan, WorkflowBase], **kwargs) -> Node: \"\"\" Anytime you add an", "value for {k}\") with FlyteContextManager.with_context( ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) ) ) as child_ctx: result =", "else: raise Exception(f\"Workflow local execution expected 0 outputs but something received {result}\") if", "dict): input_promises = [] for _, v in input_value.items(): input_promises.extend(get_input_values(v)) return input_promises else:", "\"\"\" Anytime you add an entity, all the inputs to the entity must", "want to # iterate through the list here, instead we should let the", "comp_ctx.compilation_state.nodes: if isinstance(n.flyte_entity, PythonAutoContainerTask) and n.flyte_entity.task_resolver == self: logger.debug(f\"WF {self.name} saving task {n.flyte_entity.name}\")", "self._compilation_state = CompilationState(prefix=\"\") self._inputs = {} # This unbound inputs construct is just", "\" ) def __call__(self, *args, **kwargs): \"\"\" The call pattern for Workflows is", "the global input node, i.e. the inputs to the workflow. # _local_execute should've", "priority # Again, we're using the output_tuple_name as a proxy. if self.python_interface.output_tuple_name and", "if _workflow_function: return wrapper(_workflow_function) else: return wrapper class ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow): \"\"\" A reference", "be returned. \"\"\" def wrapper(fn) -> ReferenceWorkflow: interface = transform_signature_to_interface(inspect.signature(fn)) return ReferenceWorkflow(project, domain,", "can be in launch plan only, but is here only so that we", "defaults that are handed down to a workflow's tasks, whereas WorkflowMetadata represents metadata", "-> execute From execute, different things happen for the two Workflow styles. For", "entity should've been already declared, we can just iterate through the nodes in", "flytekit.common.exceptions.user import FlyteValidationException, FlyteValueException from flytekit.core.base_task import PythonTask from flytekit.core.class_based_resolver import ClassStorageTaskResolver from", "node, i.e. the inputs to the workflow. # _local_execute should've already ensured that", "f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if ctx.compilation_state is not None else \"\" with FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self)) )", "with the provided inputs, if any input_kwargs = construct_input_promises([k for k in self.interface.inputs.keys()])", "function. That is, if it's a tuple, then it # should be a", "a user can call a sub-workflow with a Python native value. for k,", "is not None and ctx.execution_state.mode == ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ): if ctx.execution_state.branch_eval_mode == BranchEvalMode.BRANCH_SKIPPED: if", "the rest of the details. \"\"\" if binding_data.promise is not None: if not", "val=TypeEngine.to_literal(ctx, v, t, self.interface.inputs[k].type)) # The output of this will always be a", "= set() self._nodes = [] self._output_bindings: Optional[List[_literal_models.Binding]] = [] FlyteEntities.entities.append(self) super().__init__(**kwargs) @property def", "name of the upstream node's output we want return outputs_cache[binding_data.promise.node][binding_data.promise.var] elif binding_data.scalar is", "from the given node output. \"\"\" if output_name in self._python_interface.outputs: raise FlyteValidationException(f\"Output {output_name}", "= [] for bd in binding_data.collection.bindings: p = get_promise(bd, outputs_cache) literals.append(p.val) return Promise(", "the workflow runs on Flyte. That is, workflows should not call non-Flyte entities", "earlier. It just # keeps track of workflow inputs that you've declared with", "is added, mark it as used. The above function though will gather all", "for naming outputs - and single-length-NamedTuples are # particularly troublesome but elegant handling", "execution context return self._local_execute(ctx, **input_kwargs) # Last is starting a local workflow execution", "This class is similarly named to the one above. Please see the IDL", "def nodes(self) -> List[Node]: return self._nodes def __repr__(self): return ( f\"WorkflowBase - {self._name}", "flytekit.models.core import workflow as _workflow_model GLOBAL_START_NODE = Node( id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None, bindings=[], upstream_nodes=[], flyte_entity=None,", "of the name instead of value? all_input_values = get_input_values(kwargs) for input_value in filter(lambda", "construct a DAG of tasks using the data flow between tasks. Unlike a", "self._inputs = {} self._unbound_inputs = set() self._nodes = [] self._output_bindings: Optional[List[_literal_models.Binding]] = []", "= collections.namedtuple(self.python_interface.output_tuple_name, variables) nones = [None for _ in self.python_interface.outputs.keys()] return output_tuple(*nones) else:", "compilation, an error will be returned. \"\"\" def wrapper(fn) -> ReferenceWorkflow: interface =", "return self._name.split(\".\")[-1] @property def workflow_metadata(self) -> Optional[WorkflowMetadata]: return self._workflow_metadata @property def workflow_metadata_defaults(self): return", "def __init__( self, name: str, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False,", "We don't want to # iterate through the list here, instead we should", "construct_input_promises(inputs: List[str]): return { input_name: Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) for input_name in inputs }", "self._nodes def __repr__(self): return ( f\"WorkflowBase - {self._name} && \" f\"Inputs ({len(self._python_interface.inputs)}): {self._python_interface.inputs}", ") expected_output_names = list(self.python_interface.outputs.keys()) if len(expected_output_names) == 1: # Here we have to", "elegant handling of them is not a high priority # Again, we're using", "ready(self) -> bool: \"\"\" This function returns whether or not the workflow is", "argument is implicitly passed and represents the decorated function. :param failure_policy: Use the", "its outputs. Basically this takes the place of propeller in resolving bindings, pulling", "clause\") t = self.python_interface.outputs[out] b = binding_from_python_std( ctx, out, self.interface.outputs[out].type, workflow_outputs[i], t, )", "* Has at least one node * All workflow inputs are bound These", "value. for k, v in kwargs.items(): if not isinstance(v, Promise): t = self.python_interface.inputs[k]", "that entity should've been already declared, we can just iterate through the nodes", "on Flyte. That is, workflows should not call non-Flyte entities since they are", "though will gather all the input # values but we're only interested in", "self._inputs[input_name] def add_workflow_output( self, output_name: str, p: Union[Promise, List[Promise], Dict[str, Promise]], python_type: Optional[Type]", "wf output {output_name} from Promise provided {python_type}\") flyte_type = TypeEngine.to_literal_type(python_type=python_type) ctx = FlyteContext.current_context()", "workflow is a pointer to a workflow that already exists on your Flyte", "Exception(\"Should not be called\") def _local_execute(self, ctx: FlyteContext, **kwargs) -> Union[Tuple[Promise], Promise, VoidPromise]:", "= self.execute(**kwargs) # First handle the empty return case. # A workflow function", "high priority # Again, we're using the output_tuple_name as a proxy. if self.python_interface.output_tuple_name", "This # is an error that Admin would return at compile time anyways,", "not None: raise Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: n =", "output. \"\"\" if output_name in self._python_interface.outputs: raise FlyteValidationException(f\"Output {output_name} already exists in workflow", "completed nodes and filling in the necessary inputs. \"\"\" entity_kwargs = {} for", "self.python_interface.output_tuple_name is None: raise AssertionError( \"Outputs specification for Workflow does not define a", "do not match\") def execute(self, **kwargs): raise Exception(\"Should not be called\") def _local_execute(self,", "them to be used in the compilation. This mimics a 'closure' in the", "It just # keeps track of workflow inputs that you've declared with add_workflow_input", "then we return a single element if len(self.output_bindings) == 1: # Again use", "don't have to do the # conversion here in this loop. The reason", "= p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring python type for wf output {output_name} from Promise provided {python_type}\")", "== 1: return bindings[0] return tuple(bindings) def execute(self, **kwargs): \"\"\" This function is", "None super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=default_metadata, python_interface=native_interface, ) @property def function(self): return self._workflow_function def", "This mimics a 'closure' in the traditional sense of the word. \"\"\" ctx", "local execution for imperative workflows runs. Because when an entity is added using", "native value. for k, v in kwargs.items(): if not isinstance(v, Promise): t =", "received but should've been VoidPromise or None.\" ) expected_output_names = list(self.python_interface.outputs.keys()) if len(expected_output_names)", "in the node's entity's input arguments, which are specified using the bindings list,", "to help workflow authors detect issues a bit earlier. It just # keeps", "self._input_parameters = None super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=default_metadata, python_interface=native_interface, ) @property def function(self): return", "the name of the upstream node's output we want return outputs_cache[binding_data.promise.node][binding_data.promise.var] elif binding_data.scalar", "is None: continue # pragma: no cover # Move along, nothing to assign", "if len(output_names) == 1: if isinstance(workflow_outputs, tuple): if len(workflow_outputs) != 1: raise AssertionError(", "**kwargs): \"\"\" Supply static Python native values in the kwargs if you want", "between workflows and tasks. Since tasks call execute from dispatch_execute which is in", "want return outputs_cache[binding_data.promise.node][binding_data.promise.var] elif binding_data.scalar is not None: return Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar)) elif binding_data.collection", "class ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow): \"\"\" A reference workflow is a pointer to a workflow", "version: str, ) -> Callable[[Callable[..., Any]], ReferenceWorkflow]: \"\"\" A reference workflow is a", "not None: return create_and_link_node(ctx, entity=self, interface=self.python_interface, **input_kwargs) # This condition is hit when", "Because we should've already returned in the above check, we just raise an", "have to be of the NodeOutput type {type(binding_data.promise)} found\" ) # b.var is", "**kwargs): \"\"\" This function is here only to try to streamline the pattern", "workflow_outputs, t, ) bindings.append(b) elif len(output_names) > 1: if not isinstance(workflow_outputs, tuple): raise", "interface. If at registration time the interface provided causes an issue with compilation,", ") def __call__(self, *args, **kwargs): \"\"\" The call pattern for Workflows is close", "binding_data.promise is not None: if not isinstance(binding_data.promise, NodeOutput): raise FlyteValidationException( f\"Binding data Promises", "= {expected_output_names[0]: function_outputs[0]} else: wf_outputs_as_map = {expected_output_names[0]: function_outputs} else: wf_outputs_as_map = {expected_output_names[i]: function_outputs[i]", "the nodes in order. for node in self.compilation_state.nodes: if node not in intermediate_node_outputs.keys():", "# Again, we're using the output_tuple_name as a proxy. if self.python_interface.output_tuple_name and isinstance(function_outputs,", "if isinstance(workflow_outputs[i], ConditionalSection): raise AssertionError(\"A Conditional block (if-else) should always end with an", "# Because we should've already returned in the above check, we just raise", "class has to keep track of its own compilation state. \"\"\" return self._compilation_state", "-> Node: return self.add_entity(sub_wf, **kwargs) def ready(self) -> bool: \"\"\" This function returns", "0 else: on_failure = 1 return _workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass class WorkflowMetadataDefaults(object): \"\"\" This class", "will fill in the node's entity's input arguments, which are specified using the", "a pointer to a workflow that already exists on your Flyte installation. This", "Interface: \"\"\" Adds an input to the workflow. \"\"\" if input_name in self._inputs:", "raise Exception(\"Should not be called\") def _local_execute(self, ctx: FlyteContext, **kwargs) -> Union[Tuple[Promise], Promise,", "not be called\") def _local_execute(self, ctx: FlyteContext, **kwargs) -> Union[Tuple[Promise], Promise, VoidPromise]: #", "The above function though will gather all the input # values but we're", "all_input_values): if input_value in self._unbound_inputs: self._unbound_inputs.remove(input_value) return n def add_workflow_input(self, input_name: str, python_type:", "intermediate_node_outputs[node] = {} # Retrieve the entity from the node, and call it", "VoidPromise, binding_from_python_std, create_and_link_node, create_native_named_tuple, create_task_output, translate_inputs_to_literals, ) from flytekit.core.python_auto_container import PythonAutoContainerTask from flytekit.core.reference_entity", "sub_wf: WorkflowBase, **kwargs) -> Node: return self.add_entity(sub_wf, **kwargs) def ready(self) -> bool: \"\"\"", "ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) ) ) as child_ctx: result = self._local_execute(child_ctx, **input_kwargs) expected_outputs = len(self.python_interface.outputs)", "in order. for node in self.compilation_state.nodes: if node not in intermediate_node_outputs.keys(): intermediate_node_outputs[node] =", "we're dealing with a one-element # named tuple if self.python_interface.output_tuple_name: return (get_promise(self.output_bindings[0].binding, intermediate_node_outputs),)", "( f\"WorkflowBase - {self._name} && \" f\"Inputs ({len(self._python_interface.inputs)}): {self._python_interface.inputs} && \" f\"Outputs ({len(self._python_interface.outputs)}):", "Dict[Node, Dict[str, Promise]] # Start things off with the outputs of the global", "or None.\" ) expected_output_names = list(self.python_interface.outputs.keys()) if len(expected_output_names) == 1: # Here we", "def __init__( self, project: str, domain: str, name: str, version: str, inputs: Dict[str,", "object, using a lookup map. Please see get_promise_map for the rest of the", "if self.on_failure == WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure = 0 else: on_failure = 1 return _workflow_model.WorkflowMetadata(on_failure=on_failure)", "self.python_interface) class ImperativeWorkflow(WorkflowBase): def __init__( self, name: str, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible:", "get_promise(b.binding, outputs_cache) return entity_kwargs class WorkflowBase(object): def __init__( self, name: str, workflow_metadata: WorkflowMetadata,", "in input_value.items(): input_promises.extend(get_input_values(v)) return input_promises else: return [input_value] # Every time an entity", "transform_interface_to_typed_interface(self._python_interface) def add_task(self, task: PythonTask, **kwargs) -> Node: return self.add_entity(task, **kwargs) def add_launch_plan(self,", "# conversion here in this loop. The reason is because we don't prevent", "evaluated at serialization-time (aka compile-time). This is because while we can determine the", "def get_promise(binding_data: _literal_models.BindingData, outputs_cache: Dict[Node, Dict[str, Promise]]) -> Promise: \"\"\" This is a", "= create_node(entity=entity, **kwargs) def get_input_values(input_value): if isinstance(input_value, list): input_promises = [] for x", "raise AssertionError(\"A Conditional block (if-else) should always end with an `else_()` clause\") t", "fill them in using the node output tracker map we have. entity =", "sort. To keep track of outputs, we create a map to start things", "call it by looking up the promises the node's bindings require, # and", "# implementation of the TaskResolverMixin that this workflow class inherits from (ClassStorageTaskResolver) #", "using the output_tuple_name as a proxy. if self.python_interface.output_tuple_name and isinstance(function_outputs, tuple): wf_outputs_as_map =", "see the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for more usage examples. :param _workflow_function: This argument is implicitly", "or not tasks launched from this workflow are by default interruptible \"\"\" def", "in self.python_interface.outputs.keys()] output_tuple = collections.namedtuple(self.python_interface.output_tuple_name, variables) nones = [None for _ in self.python_interface.outputs.keys()]", "or less stateless (the future-proofing get_all_tasks function notwithstanding). However the # implementation of", "get_promise(bd, outputs_cache) literals.append(p.val) return Promise( var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), ) elif binding_data.map is not None:", "= {} self._unbound_inputs = set() self._nodes = [] self._output_bindings: Optional[List[_literal_models.Binding]] = [] FlyteEntities.entities.append(self)", "information. \"\"\" def __init__( self, workflow_function: Callable, metadata: Optional[WorkflowMetadata], default_metadata: Optional[WorkflowMetadataDefaults], ): name", "literal values. Even in a wf, a user can call a sub-workflow with", "list here, instead we should let the binding creation unwrap it and make", "Dict[Node, Dict[str, Promise]] ) -> Dict[str, Promise]: \"\"\" Local execution of imperatively defined", "platform, local runs notwithstanding). Please see the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for more usage examples. :param", "flytekit.core.reference_entity import ReferenceEntity, WorkflowReference from flytekit.core.type_engine import TypeEngine from flytekit.loggers import logger from", "time the interface provided causes an issue with compilation, an error will be", "in self.output_bindings]) def add_entity(self, entity: Union[PythonTask, LaunchPlan, WorkflowBase], **kwargs) -> Node: \"\"\" Anytime", "support the invariant that Workflow local executions always work with Promise objects #", "ImperativeWorkflow(WorkflowBase): def __init__( self, name: str, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] =", "decorated with the :py:func:`@workflow <flytekit.workflow>` decorator. Please see notes on that object for", "Union[PythonTask, LaunchPlan, WorkflowBase], **kwargs) -> Node: \"\"\" Anytime you add an entity, all", "= [] prefix = f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if ctx.compilation_state is not None else \"\" with", "__repr__(self): return ( f\"WorkflowBase - {self._name} && \" f\"Inputs ({len(self._python_interface.inputs)}): {self._python_interface.inputs} && \"", "the user is asked to provide the expected interface. If at registration time", "an input to the workflow. \"\"\" if input_name in self._inputs: raise FlyteValidationException(f\"Input {input_name}", "ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow): \"\"\" A reference workflow is a pointer to a workflow that", "be bound. \"\"\" # circular import from flytekit.core.node_creation import create_node ctx = FlyteContext.current_context()", "t: PythonAutoContainerTask) -> str: return f\"{self.name}.{t.__module__}.{t.name}\" def compile(self, **kwargs): \"\"\" Supply static Python", "input_kwargs.items(): if k not in self.interface.inputs: raise ValueError(f\"Received unexpected keyword argument {k}\") if", "= results[0] else: intermediate_node_outputs[node][expected_output_names[0]] = results else: if len(results) != len(expected_output_names): raise FlyteValueException(results,", "return self._compilation_state @property def nodes(self) -> List[Node]: return self._compilation_state.nodes @property def inputs(self) ->", "{n.flyte_entity.name}\") self.add(n.flyte_entity) # Iterate through the workflow outputs bindings = [] output_names =", "workflow( _workflow_function=None, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False, ): \"\"\" This", "= ( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ) @dataclass class WorkflowMetadata(object): on_failure: WorkflowFailurePolicy def __post_init__(self): if (", "None # We are already in a local execution, just continue the execution", "into Promises that match the workflow's # interface. We do that by extracting", "will be returned. \"\"\" def wrapper(fn) -> ReferenceWorkflow: interface = transform_signature_to_interface(inspect.signature(fn)) return ReferenceWorkflow(project,", "from flytekit.common.exceptions.user import FlyteValidationException, FlyteValueException from flytekit.core.base_task import PythonTask from flytekit.core.class_based_resolver import ClassStorageTaskResolver", "== 0: raise FlyteValueException(results, f\"{results} received but should've been VoidPromise or None.\") #", "out the literals, and creating new Promises wf_outputs_as_literal_dict = translate_inputs_to_literals( ctx, wf_outputs_as_map, flyte_interface_types=self.interface.outputs,", "the workflow's # interface. We do that by extracting out the literals, and", "workflow. The nodes in these Promise objects should always point to the global", "intermediate_node_outputs = {GLOBAL_START_NODE: {}} # type: Dict[Node, Dict[str, Promise]] # Start things off", "and domain self._nodes = all_nodes self._output_bindings = bindings if not output_names: return None", "and actual outputs do not match\") def execute(self, **kwargs): raise Exception(\"Should not be", "= _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE = ( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ) @dataclass class WorkflowMetadata(object): on_failure: WorkflowFailurePolicy def", "\"\"\" Add an output with the given name from the given node output.", "exactly, the call pattern for Tasks. For local execution, it goes __call__ ->", "if len(output_names) != len(workflow_outputs): raise Exception(f\"Length mismatch {len(output_names)} vs {len(workflow_outputs)}\") for i, out", "returned. \"\"\" def __init__( self, project: str, domain: str, name: str, version: str,", "is None or isinstance(result, VoidPromise): return None else: raise Exception(f\"Workflow local execution expected", "just one node at a time. if len(self.python_interface.outputs) == 0: return VoidPromise(self.name) #", "additional information. \"\"\" def __init__( self, workflow_function: Callable, metadata: Optional[WorkflowMetadata], default_metadata: Optional[WorkflowMetadataDefaults], ):", "in the kwargs if you want them to be used in the compilation.", "WorkflowMetadata(object): on_failure: WorkflowFailurePolicy def __post_init__(self): if ( self.on_failure != WorkflowFailurePolicy.FAIL_IMMEDIATELY and self.on_failure !=", "raise ValueError(f\"Received unexpected keyword argument {k}\") if isinstance(v, Promise): raise ValueError(f\"Received a promise", "Dict[str, Type] ): super().__init__(WorkflowReference(project, domain, name, version), inputs, outputs) def reference_workflow( project: str,", "[input_value] # Every time an entity is added, mark it as used. The", "but is here only so that we don't have to re-evaluate. Or #", "This condition is hit when this workflow (self) is being called as part", "Run some sanity checks # Even though the _local_execute call generally expects inputs", "project and domain self._nodes = all_nodes self._output_bindings = bindings if not output_names: return", "import PythonAutoContainerTask from flytekit.core.reference_entity import ReferenceEntity, WorkflowReference from flytekit.core.type_engine import TypeEngine from flytekit.loggers", "one task or other entity call at a time. This is why this", "if len(self.python_interface.outputs) == 0: return VoidPromise(self.name) # The values that we return below", "at a time. if len(self.python_interface.outputs) == 0: return VoidPromise(self.name) # The values that", "{self._python_interface.inputs} && \" f\"Outputs ({len(self._python_interface.outputs)}): {self._python_interface.outputs} && \" f\"Output bindings: {self._output_bindings} && \"", "in the latter we get None if isinstance(function_outputs, VoidPromise) or function_outputs is None:", "+ f\"Nodes ({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\" def execute(self, **kwargs): \"\"\" Called by _local_execute. This function", "the workflow would've returned had it been declared # functionally, and 2) what", "values in the kwargs if you want them to be used in the", "filter(lambda x: isinstance(x, Promise), all_input_values): if input_value in self._unbound_inputs: self._unbound_inputs.remove(input_value) return n def", "name: str, version: str, inputs: Dict[str, Type], outputs: Dict[str, Type] ): super().__init__(WorkflowReference(project, domain,", "return self._workflow_metadata_defaults @property def python_interface(self) -> Interface: return self._python_interface @property def interface(self) ->", "in input_kwargs.items(): if k not in self.interface.inputs: raise ValueError(f\"Received unexpected keyword argument {k}\")", "function_outputs, f\"{function_outputs} received but interface has {len(self.python_interface.outputs)} outputs.\", ) return VoidPromise(self.name) # Because", "k, v in kwargs.items(): if not isinstance(v, Promise): t = self.python_interface.inputs[k] kwargs[k] =", "str, workflow_metadata: WorkflowMetadata, workflow_metadata_defaults: WorkflowMetadataDefaults, python_interface: Interface, **kwargs, ): self._name = name self._workflow_metadata", "specifying inputs # as direct scalars, which means there's another Promise-generating loop inside", "out of it. if len(output_names) == 1: if isinstance(workflow_outputs, tuple): if len(workflow_outputs) !=", "only, but is here only so that we don't have to re-evaluate. Or", "each node. intermediate_node_outputs = {GLOBAL_START_NODE: {}} # type: Dict[Node, Dict[str, Promise]] # Start", "For local execution, it goes __call__ -> _local_execute -> execute From execute, different", "specification indicates only one return value, received {len(workflow_outputs)}\" ) if self.python_interface.output_tuple_name is None:", "that all nodes and workflow i/o changes were done with the functions above,", "other previous node. \"\"\" if not self.ready(): raise FlyteValidationException(f\"Workflow not ready, wf is", "prevent users from specifying inputs # as direct scalars, which means there's another", "We are already in a local execution, just continue the execution context return", "not evaluated again when the workflow runs on Flyte. That is, workflows should", "see get_promise_map for the rest of the details. \"\"\" if binding_data.promise is not", "= FlyteContext.current_context() if ctx.compilation_state is not None: raise Exception(\"Can't already be compiling\") with", "not isinstance(binding_data.promise, NodeOutput): raise FlyteValidationException( f\"Binding data Promises have to be of the", "for k, v in input_kwargs.items(): if k not in self.interface.inputs: raise ValueError(f\"Received unexpected", "data flow between tasks. Unlike a task, the function body of a workflow", "outputs of the global input node, i.e. the inputs to the workflow. #", "PythonAutoContainerTask) and n.flyte_entity.task_resolver == self: logger.debug(f\"WF {self.name} saving task {n.flyte_entity.name}\") self.add(n.flyte_entity) # Iterate", "FlyteValueException from flytekit.core.base_task import PythonTask from flytekit.core.class_based_resolver import ClassStorageTaskResolver from flytekit.core.condition import ConditionalSection", "None: raise AssertionError( \"Outputs specification for Workflow does not define a tuple, but", "import annotations import collections import inspect from dataclasses import dataclass from enum import", "output_name: str, p: Union[Promise, List[Promise], Dict[str, Promise]], python_type: Optional[Type] = None ): \"\"\"", "kwargs passed in input_kwargs = self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs) # The first condition is compilation.", "typing.NamedTuple of # length one. That convention is used for naming outputs -", "Even though the _local_execute call generally expects inputs to be Promises, we don't", "a one element named tuple, then we do a one-element non-named tuple, #", "of them is not a high priority # Again, we're using the output_tuple_name", "outputs of each node. intermediate_node_outputs = {GLOBAL_START_NODE: {}} # type: Dict[Node, Dict[str, Promise]]", "specified using the bindings list, and a map of nodes to its outputs.", "iterate through the list here, instead we should let the binding creation unwrap", "bindings.append(b) # Save all the things necessary to create an SdkWorkflow, except for", "wf {self.name}.\") self._python_interface = self._python_interface.with_inputs(extra_inputs={input_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name] = Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE,", "and expected_outputs == 1): return create_native_named_tuple(ctx, result, self.python_interface) raise ValueError(\"expected outputs and actual", "it's a tuple, then it # should be a tuple here, if it's", "import workflow as _workflow_model GLOBAL_START_NODE = Node( id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None, bindings=[], upstream_nodes=[], flyte_entity=None, )", "AssertionError(\"The Workflow specification indicates multiple return values, received only one\") if len(output_names) !=", "and then fill them in using the node output tracker map we have.", "done node by node. This function will fill in the node's entity's input", "# Last is starting a local workflow execution else: # Run some sanity", "things are run, their outputs are stored in this map. After all nodes", "(self) is being called as part of a parent's workflow local run. #", "p = get_promise(bd, outputs_cache) literals.append(p.val) return Promise( var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), ) elif binding_data.map is", "does store state. This loop adds Tasks that are defined within the body", "not None else \"\" with FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self)) ) as comp_ctx: # Construct", "input_promises = [] for _, v in input_value.items(): input_promises.extend(get_input_values(v)) return input_promises else: return", "indicates multiple return values, received only one\") if len(output_names) != len(workflow_outputs): raise Exception(f\"Length", "This function is how local execution for imperative workflows runs. Because when an", "assume that all nodes and workflow i/o changes were done with the functions", "of a workflow is evaluated at serialization-time (aka compile-time). This is because while", "execution for imperative workflows runs. Because when an entity is added using the", "flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs, ) # Recreate new promises that use the workflow's output names.", "in launch plan only, but is here only so that we don't have", "condition is hit when this workflow (self) is being called as part of", ") -> Callable[[Callable[..., Any]], ReferenceWorkflow]: \"\"\" A reference workflow is a pointer to", "Or # we can re-evaluate. self._input_parameters = None super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=default_metadata, python_interface=native_interface,", "sub-workflow with a Python native value. for k, v in kwargs.items(): if not", "self.python_interface.inputs[k] kwargs[k] = Promise(var=k, val=TypeEngine.to_literal(ctx, v, t, self.interface.inputs[k].type)) # The output of this", "extracting out the literals, and creating new Promises wf_outputs_as_literal_dict = translate_inputs_to_literals( ctx, wf_outputs_as_map,", "): \"\"\" This decorator declares a function to be a Flyte workflow. Workflows", "of the function is what expresses the workflow structure. It's also important to", "the decorated function. :param failure_policy: Use the options in flytekit.WorkflowFailurePolicy :param interruptible: Whether", "the ones that are Promises so let's filter for those. # There's probably", "an `else_()` clause\") t = self.python_interface.outputs[out] b = binding_from_python_std( ctx, out, self.interface.outputs[out].type, workflow_outputs[i],", ":py:func:`@workflow <flytekit.workflow>` decorator. Please see notes on that object for additional information. \"\"\"", "in filter(lambda x: isinstance(x, Promise), all_input_values): if input_value in self._unbound_inputs: self._unbound_inputs.remove(input_value) return n", "IDL for more information but essentially, this WorkflowMetadataDefaults class represents the defaults that", "through the workflow outputs bindings = [] output_names = list(self.interface.outputs.keys()) # The reason", "ensured that all the values in kwargs are Promise objects for k, v", "the fact that the wf could've been declared with a typing.NamedTuple of #", "tasks, whereas WorkflowMetadata represents metadata about the workflow itself. \"\"\" interruptible: bool def", "PythonFunctionWorkflows, the Python function is run, for the ImperativeWorkflow, each node is run", "found\" ) # b.var is the name of the input to the task", "Again, we're using the output_tuple_name as a proxy. if self.python_interface.output_tuple_name and isinstance(function_outputs, tuple):", "we have to handle the fact that the wf could've been declared with", "override with kwargs passed in input_kwargs = self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs) # The first condition", "do we need this - can this not be in launchplan only? #", "as direct scalars, which means there's another Promise-generating loop inside _local_execute too for", "one node at a time. if len(self.python_interface.outputs) == 0: return VoidPromise(self.name) # The", "but should've been VoidPromise or None.\") # if there's only one output, if", "maybe key off of the name instead of value? all_input_values = get_input_values(kwargs) for", "map. Please see get_promise_map for the rest of the details. \"\"\" if binding_data.promise", "): \"\"\" Add an output with the given name from the given node", "run through the function itself because the body of the function is what", "respect to the platform, local runs notwithstanding). Please see the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for more", "part of a parent's workflow local run. # The context specifying the local", "self._name @property def short_name(self) -> str: return self._name.split(\".\")[-1] @property def workflow_metadata(self) -> Optional[WorkflowMetadata]:", "should always end with an `else_()` clause\") t = self.python_interface.outputs[out] b = binding_from_python_std(", "ctx = FlyteContextManager.current_context() # Get default agruements and override with kwargs passed in", "we force the user to declare entities already in a topological sort. To", "returned in the above check, we just raise an error here. if len(self.python_interface.outputs)", "raise an error here. if len(self.python_interface.outputs) == 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received", "for those. # There's probably a way to clean this up, maybe key", "ReferenceWorkflow: interface = transform_signature_to_interface(inspect.signature(fn)) return ReferenceWorkflow(project, domain, name, version, interface.inputs, interface.outputs) return wrapper", "Create a map that holds the outputs of each node. intermediate_node_outputs = {GLOBAL_START_NODE:", "an issue with compilation, an error will be returned. \"\"\" def wrapper(fn) ->", "using the bindings list, and a map of nodes to its outputs. Basically", "to the one above. Please see the IDL for more information but essentially,", "def wf(): # return t1() # or it may not return at all", "idx, r in enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]] = r # The rest of this function", "anything # def wf(): # return t1() # or it may not return", "proxy. if self.python_interface.output_tuple_name and isinstance(function_outputs, tuple): wf_outputs_as_map = {expected_output_names[0]: function_outputs[0]} else: wf_outputs_as_map =", "WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) workflow_instance = PythonFunctionWorkflow( fn, metadata=workflow_metadata, default_metadata=workflow_metadata_defaults ) workflow_instance.compile() return", "though the _local_execute call generally expects inputs to be Promises, we don't have", "just # keeps track of workflow inputs that you've declared with add_workflow_input but", "def execute(self, **kwargs): \"\"\" This function is here only to try to streamline", "already ensured that all the values in kwargs are Promise objects for k,", "itself. for n in comp_ctx.compilation_state.nodes: if isinstance(n.flyte_entity, PythonAutoContainerTask) and n.flyte_entity.task_resolver == self: logger.debug(f\"WF", "network call to Admin, which is why the user is asked to provide", "str, version: str, inputs: Dict[str, Type], outputs: Dict[str, Type] ): super().__init__(WorkflowReference(project, domain, name,", "those. # There's probably a way to clean this up, maybe key off", "t = self.python_interface.inputs[k] kwargs[k] = Promise(var=k, val=TypeEngine.to_literal(ctx, v, t, self.interface.inputs[k].type)) # The output", "a parent's workflow local run. # The context specifying the local workflow execution", "input_value.items(): input_promises.extend(get_input_values(v)) return input_promises else: return [input_value] # Every time an entity is", "self._unbound_inputs = set() super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(), ) @property def compilation_state(self) ->", "TaskResolverMixin that this workflow class inherits from (ClassStorageTaskResolver) # does store state. This", "function though will gather all the input # values but we're only interested", "= [] FlyteEntities.entities.append(self) super().__init__(**kwargs) @property def name(self) -> str: return self._name @property def", "a whole rather # than just one node at a time. if len(self.python_interface.outputs)", "or dict of Promises, you must specify the python_type type for {output_name}\" f\"", "this will always be a combination of Python native values and Promises containing", "all nodes are run, we fill in workflow level outputs the same way", "the one output might be a list. We don't want to # iterate", "value? all_input_values = get_input_values(kwargs) for input_value in filter(lambda x: isinstance(x, Promise), all_input_values): if", "The task resolver interface itself is # more or less stateless (the future-proofing", "self.python_interface) all_nodes = [] prefix = f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if ctx.compilation_state is not None else", "all the input # values but we're only interested in the ones that", "is in _local_execute, workflows should also call an execute inside _local_execute. This makes", "t1() # or it may not return at all # def wf(): #", "Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: b = binding_from_python_std( ctx, output_name,", "= transform_interface_to_typed_interface(python_interface) self._inputs = {} self._unbound_inputs = set() self._nodes = [] self._output_bindings: Optional[List[_literal_models.Binding]]", "as _literal_models from flytekit.models.core import workflow as _workflow_model GLOBAL_START_NODE = Node( id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None,", "asked to provide the expected interface. If at registration time the interface provided", "\"\"\" This is a helper function that will turn a binding into a", "{} # This unbound inputs construct is just here to help workflow authors", "not None: if not isinstance(binding_data.promise, NodeOutput): raise FlyteValidationException( f\"Binding data Promises have to", "the # implementation of the TaskResolverMixin that this workflow class inherits from (ClassStorageTaskResolver)", ") @property def function(self): return self._workflow_function def task_name(self, t: PythonAutoContainerTask) -> str: return", "from flytekit.core.python_auto_container import PythonAutoContainerTask from flytekit.core.reference_entity import ReferenceEntity, WorkflowReference from flytekit.core.type_engine import TypeEngine", "create_node(entity=entity, **kwargs) def get_input_values(input_value): if isinstance(input_value, list): input_promises = [] for x in", "authors detect issues a bit earlier. It just # keeps track of workflow", "= None, interruptible: Optional[bool] = False, ): \"\"\" This decorator declares a function", "0: return VoidPromise(self.name) # The values that we return below from the output", "Promise( var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), ) elif binding_data.map is not None: literals = {} for", "Start things off with the outputs of the global input node, i.e. the", "ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ): if ctx.execution_state.branch_eval_mode == BranchEvalMode.BRANCH_SKIPPED: if self.python_interface and self.python_interface.output_tuple_name: variables = [k", "Promises wf_outputs_as_literal_dict = translate_inputs_to_literals( ctx, wf_outputs_as_map, flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs, ) # Recreate new promises", "only to try to streamline the pattern between workflows and tasks. Since tasks", "for Workflow executions\") ctx = FlyteContextManager.current_context() # Get default agruements and override with", "the user to declare entities already in a topological sort. To keep track", "interface has {len(self.python_interface.outputs)} outputs.\", ) return VoidPromise(self.name) # Because we should've already returned", "inputs. \"\"\" entity_kwargs = {} for b in bindings: entity_kwargs[b.var] = get_promise(b.binding, outputs_cache)", "LaunchPlan from flytekit.core.node import Node from flytekit.core.promise import ( NodeOutput, Promise, VoidPromise, binding_from_python_std,", "keeps track of workflow inputs that you've declared with add_workflow_input but haven't yet", "self._nodes = [] self._output_bindings: Optional[List[_literal_models.Binding]] = [] FlyteEntities.entities.append(self) super().__init__(**kwargs) @property def name(self) ->", "we should've already returned in the above check, we just raise an error", "bindings: List[_literal_models.Binding], outputs_cache: Dict[Node, Dict[str, Promise]] ) -> Dict[str, Promise]: \"\"\" Local execution", "two Workflow styles. For PythonFunctionWorkflows, the Python function is run, for the ImperativeWorkflow,", "keep track of outputs, we create a map to start things off, filled", "literals, and creating new Promises wf_outputs_as_literal_dict = translate_inputs_to_literals( ctx, wf_outputs_as_map, flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs, )", "1: if entity.python_interface.output_tuple_name and isinstance(results, tuple): intermediate_node_outputs[node][expected_output_names[0]] = results[0] else: intermediate_node_outputs[node][expected_output_names[0]] = results", "the one above. Please see the IDL for more information but essentially, this", "style here has to match what 1) what the workflow would've returned had", "Enum from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union from", "# This is done to support the invariant that Workflow local executions always", "VoidPromise or None.\" ) expected_output_names = list(self.python_interface.outputs.keys()) if len(expected_output_names) == 1: # Here", "workflow authors detect issues a bit earlier. It just # keeps track of", "at registration time the interface provided causes an issue with compilation, an error", "): metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) self._compilation_state = CompilationState(prefix=\"\") self._inputs", "can call a sub-workflow with a Python native value. for k, v in", "Handle the calling and outputs of each node's entity results = entity(**entity_kwargs) expected_output_names", "raise FlyteValidationException(f\"Output {output_name} already exists in workflow {self.name}\") if python_type is None: if", "task by looking at the function's signature, workflows need to run through the", "k, v in kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k] = v # Next iterate through the nodes", "in self._inputs: raise FlyteValidationException(f\"Input {input_name} has already been specified for wf {self.name}.\") self._python_interface", "flytekit.core.promise import ( NodeOutput, Promise, VoidPromise, binding_from_python_std, create_and_link_node, create_native_named_tuple, create_task_output, translate_inputs_to_literals, ) from", "we're only interested in the ones that are Promises so let's filter for", "# A workflow function may return a task that doesn't return anything #", "we do a one-element non-named tuple, # if it's a single element then", "({len(self._python_interface.inputs)}): {self._python_interface.inputs} && \" f\"Outputs ({len(self._python_interface.outputs)}): {self._python_interface.outputs} && \" f\"Output bindings: {self._output_bindings} &&", "previous node. \"\"\" if not self.ready(): raise FlyteValidationException(f\"Workflow not ready, wf is currently", "node's output we want return outputs_cache[binding_data.promise.node][binding_data.promise.var] elif binding_data.scalar is not None: return Promise(var=\"placeholder\",", "workflow execution has already been set. elif ( ctx.execution_state is not None and", "WorkflowMetadataDefaults(interruptible) workflow_instance = PythonFunctionWorkflow( fn, metadata=workflow_metadata, default_metadata=workflow_metadata_defaults ) workflow_instance.compile() return workflow_instance if _workflow_function:", "a function and decorated with the :py:func:`@workflow <flytekit.workflow>` decorator. Please see notes on", "CompilationState(prefix=\"\") self._inputs = {} # This unbound inputs construct is just here to", "FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: b = binding_from_python_std( ctx, output_name, expected_literal_type=flyte_type, t_value=p, t_value_type=python_type ) self._output_bindings.append(b)", "binding_from_python_std( ctx, output_name, expected_literal_type=flyte_type, t_value=p, t_value_type=python_type ) self._output_bindings.append(b) self._python_interface = self._python_interface.with_outputs(extra_outputs={output_name: python_type}) self._interface", "inputs (if any). As things are run, their outputs are stored in this", "level outputs the same way as any other previous node. \"\"\" if not", "ctx.compilation_state is not None: return create_and_link_node(ctx, entity=self, interface=self.python_interface, **input_kwargs) # This condition is", "not isinstance(workflow_outputs, tuple): raise AssertionError(\"The Workflow specification indicates multiple return values, received only", "= [] for _, v in input_value.items(): input_promises.extend(get_input_values(v)) return input_promises else: return [input_value]", "This argument is implicitly passed and represents the decorated function. :param failure_policy: Use", "here, if it's a one element named tuple, then we do a one-element", "entity.python_interface.output_tuple_name and isinstance(results, tuple): intermediate_node_outputs[node][expected_output_names[0]] = results[0] else: intermediate_node_outputs[node][expected_output_names[0]] = results else: if", "\"\"\" Please read :std:ref:`flyte:divedeep-workflows` first for a high-level understanding of what workflows are", "your Flyte installation. This object will not initiate a network call to Admin,", "call execute from dispatch_execute which is in _local_execute, workflows should also call an", "entity is added using the add_entity function, all inputs to that entity should've", "case we get the task's VoidPromise, in the latter we get None if", "an entity, all the inputs to the entity must be bound. \"\"\" #", "workflow's output bindings. # The return style here has to match what 1)", "expected_literal_type=flyte_type, t_value=p, t_value_type=python_type ) self._output_bindings.append(b) self._python_interface = self._python_interface.with_outputs(extra_outputs={output_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) def", "= construct_input_promises([k for k in self.interface.inputs.keys()]) input_kwargs.update(kwargs) workflow_outputs = self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes) # This", "here, instead we should let the binding creation unwrap it and make a", "inside _local_execute. This makes mocking cleaner. \"\"\" return self._workflow_function(**kwargs) def workflow( _workflow_function=None, failure_policy:", "= self._local_execute(child_ctx, **input_kwargs) expected_outputs = len(self.python_interface.outputs) if expected_outputs == 0: if result is", "in Flyte. This Python object represents a workflow defined by a function and", "): if ctx.execution_state.branch_eval_mode == BranchEvalMode.BRANCH_SKIPPED: if self.python_interface and self.python_interface.output_tuple_name: variables = [k for", "the entity from the node, and call it by looking up the promises", "one output might be a list. We don't want to # iterate through", "the binding creation unwrap it and make a binding # collection/map out of", "CompilationState, ExecutionState, FlyteContext, FlyteContextManager, FlyteEntities, ) from flytekit.core.interface import ( Interface, transform_inputs_to_parameters, transform_interface_to_typed_interface,", "\"\"\" Compilation is done a bit at a time, one task or other", "already returned in the above check, we just raise an Exception here. if", "for x in input_value: input_promises.extend(get_input_values(x)) return input_promises if isinstance(input_value, dict): input_promises = []", "in input_value: input_promises.extend(get_input_values(x)) return input_promises if isinstance(input_value, dict): input_promises = [] for _,", "def wrapper(fn): workflow_metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) workflow_instance = PythonFunctionWorkflow(", "return n def add_workflow_input(self, input_name: str, python_type: Type) -> Interface: \"\"\" Adds an", "set() super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(), ) @property def compilation_state(self) -> CompilationState: \"\"\"", "= Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) self._unbound_inputs.add(self._inputs[input_name]) return self._inputs[input_name] def add_workflow_output( self, output_name: str, p:", "\"\"\" def wrapper(fn): workflow_metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) workflow_instance =", "entities already in a topological sort. To keep track of outputs, we create", "are run, we fill in workflow level outputs the same way as any", "the defaults that are handed down to a workflow's tasks, whereas WorkflowMetadata represents", "topological sort. To keep track of outputs, we create a map to start", "= FlyteContextManager.current_context() self._input_parameters = transform_inputs_to_parameters(ctx, self.python_interface) all_nodes = [] prefix = f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if", "= f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function = workflow_function native_interface = transform_signature_to_interface(inspect.signature(workflow_function)) # TODO do we need", "on_failure: WorkflowFailurePolicy def __post_init__(self): if ( self.on_failure != WorkflowFailurePolicy.FAIL_IMMEDIATELY and self.on_failure != WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE", "_local_execute call generally expects inputs to be Promises, we don't have to do", "execute, different things happen for the two Workflow styles. For PythonFunctionWorkflows, the Python", "are by default interruptible \"\"\" def wrapper(fn): workflow_metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults", "we don't have to re-evaluate. Or # we can re-evaluate. self._input_parameters = None", "from this workflow are by default interruptible \"\"\" def wrapper(fn): workflow_metadata = WorkflowMetadata(on_failure=failure_policy", "launch plan only, but is here only so that we don't have to", "transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name] = Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) self._unbound_inputs.add(self._inputs[input_name]) return self._inputs[input_name] def add_workflow_output( self, output_name:", "not a high priority # Again, we're using the output_tuple_name as a proxy.", "workflow_metadata_defaults=default_metadata, python_interface=native_interface, ) @property def function(self): return self._workflow_function def task_name(self, t: PythonAutoContainerTask) ->", "(if any). As things are run, their outputs are stored in this map.", "from the tasks into Promises that match the workflow's # interface. We do", "done a bit at a time, one task or other entity call at", "by a function and decorated with the :py:func:`@workflow <flytekit.workflow>` decorator. Please see notes", "add_workflow_input but haven't yet consumed. This # is an error that Admin would", "FlyteValueException( function_outputs, f\"{function_outputs} received but interface has {len(self.python_interface.outputs)} outputs.\", ) return VoidPromise(self.name) #", "workflow inputs are bound These conditions assume that all nodes and workflow i/o", "WorkflowFailurePolicy.FAIL_IMMEDIATELY and self.on_failure != WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ): raise FlyteValidationException(f\"Failure policy {self.on_failure} not acceptable\") def", "input_name: Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) for input_name in inputs } def get_promise(binding_data: _literal_models.BindingData, outputs_cache:", "create_task_output(new_promises, self.python_interface) class ImperativeWorkflow(WorkflowBase): def __init__( self, name: str, failure_policy: Optional[WorkflowFailurePolicy] = None,", "[] for x in input_value: input_promises.extend(get_input_values(x)) return input_promises if isinstance(input_value, dict): input_promises =", "Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: n = create_node(entity=entity, **kwargs) def", "{ input_name: Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) for input_name in inputs } def get_promise(binding_data: _literal_models.BindingData,", "v, t, self.interface.inputs[k].type)) # The output of this will always be a combination", "and 2) what a user would return in mock function. That is, if", "isinstance(input_value, list): input_promises = [] for x in input_value: input_promises.extend(get_input_values(x)) return input_promises if", "def __init__( self, name: str, workflow_metadata: WorkflowMetadata, workflow_metadata_defaults: WorkflowMetadataDefaults, python_interface: Interface, **kwargs, ):", "task {n.flyte_entity.name}\") self.add(n.flyte_entity) # Iterate through the workflow outputs bindings = [] output_names", "is not None: return Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar)) elif binding_data.collection is not None: literals =", "python_interface=Interface(), ) @property def compilation_state(self) -> CompilationState: \"\"\" Compilation is done a bit", "node's bindings require, # and then fill them in using the node output", "inputs # as direct scalars, which means there's another Promise-generating loop inside _local_execute", "self._python_interface = self._python_interface.with_inputs(extra_inputs={input_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name] = Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) self._unbound_inputs.add(self._inputs[input_name])", "case is separate is because the one output might be a list. We", "call, when expecting a native value for {k}\") with FlyteContextManager.with_context( ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) )", "and n.flyte_entity.task_resolver == self: logger.debug(f\"WF {self.name} saving task {n.flyte_entity.name}\") self.add(n.flyte_entity) # Iterate through", "is asked to provide the expected interface. If at registration time the interface", "metadata about the workflow itself. \"\"\" interruptible: bool def __post_init__(self): if self.interruptible is", "one-element non-named tuple, # if it's a single element then we return a", "isinstance(x, Promise), all_input_values): if input_value in self._unbound_inputs: self._unbound_inputs.remove(input_value) return n def add_workflow_input(self, input_name:", "if not isinstance(workflow_outputs, tuple): raise AssertionError(\"The Workflow specification indicates multiple return values, received", "for wf output {output_name} from Promise provided {python_type}\") flyte_type = TypeEngine.to_literal_type(python_type=python_type) ctx =", "bound These conditions assume that all nodes and workflow i/o changes were done", "when this workflow (self) is being called as part of a parent's workflow", "raise Exception(f\"Workflow local execution expected 0 outputs but something received {result}\") if (1", "need to repackage the promises coming from the tasks into Promises that match", "FlyteValidationException(f\"Workflow not ready, wf is currently {self}\") # Create a map that holds", "= self._python_interface.with_outputs(extra_outputs={output_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) def add_task(self, task: PythonTask, **kwargs) -> Node:", "creation unwrap it and make a binding # collection/map out of it. if", "the body of the function is what expresses the workflow structure. It's also", "close to, but not exactly, the call pattern for Tasks. For local execution,", "hit when this workflow (self) is being called as part of a parent's", "len(self.output_bindings) == 1: # Again use presence of output_tuple_name to understand that we're", "1) what the workflow would've returned had it been declared # functionally, and", "return (get_promise(self.output_bindings[0].binding, intermediate_node_outputs),) # Just a normal single element return get_promise(self.output_bindings[0].binding, intermediate_node_outputs) return", "**kwargs, ): self._name = name self._workflow_metadata = workflow_metadata self._workflow_metadata_defaults = workflow_metadata_defaults self._python_interface =", "The call pattern for Workflows is close to, but not exactly, the call", "from flytekit.models.core import workflow as _workflow_model GLOBAL_START_NODE = Node( id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None, bindings=[], upstream_nodes=[],", "Node: return self.add_entity(sub_wf, **kwargs) def ready(self) -> bool: \"\"\" This function returns whether", "notwithstanding, it is not evaluated again when the workflow runs on Flyte. That", "literals[k] = p.val return Promise( var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) ) raise FlyteValidationException(\"Binding type unrecognized.\") def", "scalars, which means there's another Promise-generating loop inside _local_execute too for k, v", "first condition is compilation. if ctx.compilation_state is not None: return create_and_link_node(ctx, entity=self, interface=self.python_interface,", "data Promises have to be of the NodeOutput type {type(binding_data.promise)} found\" ) #", "function_outputs[0]} else: wf_outputs_as_map = {expected_output_names[0]: function_outputs} else: wf_outputs_as_map = {expected_output_names[i]: function_outputs[i] for i,", "wf_outputs_as_map = {expected_output_names[i]: function_outputs[i] for i, _ in enumerate(function_outputs)} # Basically we need", "flytekit.core.context_manager import ( BranchEvalMode, CompilationState, ExecutionState, FlyteContext, FlyteContextManager, FlyteEntities, ) from flytekit.core.interface import", "to be pulled by fulfilling all of the # workflow's output bindings. #", "that, local execution notwithstanding, it is not evaluated again when the workflow runs", "name from the given node output. \"\"\" if output_name in self._python_interface.outputs: raise FlyteValidationException(f\"Output", "return self._output_bindings @property def nodes(self) -> List[Node]: return self._nodes def __repr__(self): return (", "pragma: no cover # Move along, nothing to assign # Because we should've", "tuple, but return value is a tuple\" ) workflow_outputs = workflow_outputs[0] t =", "interface as _interface_models from flytekit.models import literals as _literal_models from flytekit.models.core import workflow", "default agruements and override with kwargs passed in input_kwargs = self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs) #", "n.flyte_entity.task_resolver == self: logger.debug(f\"WF {self.name} saving task {n.flyte_entity.name}\") self.add(n.flyte_entity) # Iterate through the", "bindings require, # and then fill them in using the node output tracker", "get_promise(bd, outputs_cache) literals[k] = p.val return Promise( var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) ) raise FlyteValidationException(\"Binding type", "return get_promise(self.output_bindings[0].binding, intermediate_node_outputs) return tuple([get_promise(b.binding, intermediate_node_outputs) for b in self.output_bindings]) def add_entity(self, entity:", "Optional[bool] = False, ): \"\"\" This decorator declares a function to be a", "already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: n = create_node(entity=entity, **kwargs) def get_input_values(input_value):", "False if len(self._unbound_inputs) > 0: return False return True class PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver): \"\"\"", "functions above, which do additional checking. \"\"\" if len(self.compilation_state.nodes) == 0: return False", "v in input_kwargs.items(): if k not in self.interface.inputs: raise ValueError(f\"Received unexpected keyword argument", "from flytekit.core.node import Node from flytekit.core.promise import ( NodeOutput, Promise, VoidPromise, binding_from_python_std, create_and_link_node,", "entity from the node, and call it by looking up the promises the", "could've been declared with a typing.NamedTuple of # length one. That convention is", "is None: if len(self.python_interface.outputs) != 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but interface", "in comp_ctx.compilation_state.nodes: if isinstance(n.flyte_entity, PythonAutoContainerTask) and n.flyte_entity.task_resolver == self: logger.debug(f\"WF {self.name} saving task", "it # should be a tuple here, if it's a one element named", "_interface_models from flytekit.models import literals as _literal_models from flytekit.models.core import workflow as _workflow_model", "the # workflow's output bindings. # The return style here has to match", "on_failure = 0 else: on_failure = 1 return _workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass class WorkflowMetadataDefaults(object): \"\"\"", "Add an output with the given name from the given node output. \"\"\"", "None: if type(p) == list or type(p) == dict: raise FlyteValidationException( f\"If specifying", "workflow_instance if _workflow_function: return wrapper(_workflow_function) else: return wrapper class ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow): \"\"\" A", "f\"{function_outputs} received but should've been VoidPromise or None.\" ) expected_output_names = list(self.python_interface.outputs.keys()) if", "ctx: FlyteContext, **kwargs) -> Union[Tuple[Promise], Promise, VoidPromise]: # This is done to support", "workflow_outputs = workflow_outputs[0] t = self.python_interface.outputs[output_names[0]] b = binding_from_python_std( ctx, output_names[0], self.interface.outputs[output_names[0]].type, workflow_outputs,", "is done node by node. This function will fill in the node's entity's", "Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) for input_name in inputs } def get_promise(binding_data: _literal_models.BindingData, outputs_cache: Dict[Node,", "should not call non-Flyte entities since they are only run once (again, this", "ctx = FlyteContext.current_context() if ctx.compilation_state is not None: raise Exception(\"Can't already be compiling\")", "compilation state. \"\"\" return self._compilation_state @property def nodes(self) -> List[Node]: return self._compilation_state.nodes @property", "map. After all nodes are run, we fill in workflow level outputs the", "name = f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function = workflow_function native_interface = transform_signature_to_interface(inspect.signature(workflow_function)) # TODO do we", "not ready, wf is currently {self}\") # Create a map that holds the", "is not False: raise FlyteValidationException(f\"Interruptible must be boolean, {self.interruptible} invalid\") def to_flyte_model(self): return", "v # Next iterate through the nodes in order. for node in self.compilation_state.nodes:", "return self.add_entity(task, **kwargs) def add_launch_plan(self, launch_plan: LaunchPlan, **kwargs) -> Node: return self.add_entity(launch_plan, **kwargs)", "Python native values in the kwargs if you want them to be used", "will be returned. \"\"\" def __init__( self, project: str, domain: str, name: str,", "if entity.python_interface.output_tuple_name and isinstance(results, tuple): intermediate_node_outputs[node][expected_output_names[0]] = results[0] else: intermediate_node_outputs[node][expected_output_names[0]] = results else:", "Optional[WorkflowMetadataDefaults], ): name = f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function = workflow_function native_interface = transform_signature_to_interface(inspect.signature(workflow_function)) # TODO", "local workflow execution has already been set. elif ( ctx.execution_state is not None", "from flytekit.models import interface as _interface_models from flytekit.models import literals as _literal_models from", "execute From execute, different things happen for the two Workflow styles. For PythonFunctionWorkflows,", "len(workflow_outputs) != 1: raise AssertionError( f\"The Workflow specification indicates only one return value,", "self._python_interface = python_interface self._interface = transform_interface_to_typed_interface(python_interface) self._inputs = {} self._unbound_inputs = set() self._nodes", "self.add_entity(sub_wf, **kwargs) def ready(self) -> bool: \"\"\" This function returns whether or not", "return None if len(output_names) == 1: return bindings[0] return tuple(bindings) def execute(self, **kwargs):", "@property def name(self) -> str: return self._name @property def short_name(self) -> str: return", "self.on_failure == WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure = 0 else: on_failure = 1 return _workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass", "and we shouldn't run into any dependency issues. That is, we force the", "promise bindings, but then override with the provided inputs, if any input_kwargs =", "we get the task's VoidPromise, in the latter we get None if isinstance(function_outputs,", "# This can be in launch plan only, but is here only so", "one\") if len(output_names) != len(workflow_outputs): raise Exception(f\"Length mismatch {len(output_names)} vs {len(workflow_outputs)}\") for i,", "raise FlyteValidationException( f\"Binding data Promises have to be of the NodeOutput type {type(binding_data.promise)}", "for _ in self.python_interface.outputs.keys()] return output_tuple(*nones) else: return None # We are already", "Please see notes on that object for additional information. \"\"\" def __init__( self,", "the place of propeller in resolving bindings, pulling in outputs from previously completed", "that we return below from the output have to be pulled by fulfilling", "but we're only interested in the ones that are Promises so let's filter", "ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self)) ) as comp_ctx: # Construct the default input promise bindings, but", "WorkflowReference from flytekit.core.type_engine import TypeEngine from flytekit.loggers import logger from flytekit.models import interface", "self._name = name self._workflow_metadata = workflow_metadata self._workflow_metadata_defaults = workflow_metadata_defaults self._python_interface = python_interface self._interface", "output_names[0], self.interface.outputs[output_names[0]].type, workflow_outputs, t, ) bindings.append(b) elif len(output_names) > 1: if not isinstance(workflow_outputs,", "# The context specifying the local workflow execution has already been set. elif", "FlyteValueException( function_outputs, f\"{function_outputs} received but should've been VoidPromise or None.\" ) expected_output_names =", "node output. \"\"\" if output_name in self._python_interface.outputs: raise FlyteValidationException(f\"Output {output_name} already exists in", "what 1) what the workflow would've returned had it been declared # functionally,", "ctx.compilation_state is not None: raise Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx:", "for the two Workflow styles. For PythonFunctionWorkflows, the Python function is run, for", "name: str, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False, ): metadata =", "f\"The Workflow specification indicates only one return value, received {len(workflow_outputs)}\" ) if self.python_interface.output_tuple_name", "to streamline the pattern between workflows and tasks. Since tasks call execute from", "of each node's entity results = entity(**entity_kwargs) expected_output_names = list(entity.python_interface.outputs.keys()) if isinstance(results, VoidPromise)", "self._name.split(\".\")[-1] @property def workflow_metadata(self) -> Optional[WorkflowMetadata]: return self._workflow_metadata @property def workflow_metadata_defaults(self): return self._workflow_metadata_defaults", "\"\"\" entity_kwargs = {} for b in bindings: entity_kwargs[b.var] = get_promise(b.binding, outputs_cache) return", "Interface, **kwargs, ): self._name = name self._workflow_metadata = workflow_metadata self._workflow_metadata_defaults = workflow_metadata_defaults self._python_interface", "\"\"\" return self._workflow_function(**kwargs) def workflow( _workflow_function=None, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] =", "= WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) workflow_instance = PythonFunctionWorkflow( fn, metadata=workflow_metadata, default_metadata=workflow_metadata_defaults", "when an entity is added using the add_entity function, all inputs to that", "all the inputs to the entity must be bound. \"\"\" # circular import", "reason is because we don't prevent users from specifying inputs # as direct", "# Retrieve the entity from the node, and call it by looking up", "workflow_metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) workflow_instance = PythonFunctionWorkflow( fn, metadata=workflow_metadata,", "flyte_entity=None, ) class WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY = _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE = ( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ) @dataclass", "raise # the error earlier. self._unbound_inputs = set() super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(),", "ConditionalSection): raise AssertionError(\"A Conditional block (if-else) should always end with an `else_()` clause\")", "{}} # type: Dict[Node, Dict[str, Promise]] # Start things off with the outputs", "already declared, we can just iterate through the nodes in order and we", "expects inputs to be Promises, we don't have to do the # conversion", "are # particularly troublesome but elegant handling of them is not a high", "specified for wf {self.name}.\") self._python_interface = self._python_interface.with_inputs(extra_inputs={input_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name] =", "the local workflow execution has already been set. elif ( ctx.execution_state is not", "# if there's only one output, if len(expected_output_names) == 1: if entity.python_interface.output_tuple_name and", "must specify the python_type type for {output_name}\" f\" starting with the container type", "str: return self._name.split(\".\")[-1] @property def workflow_metadata(self) -> Optional[WorkflowMetadata]: return self._workflow_metadata @property def workflow_metadata_defaults(self):", "-> Optional[WorkflowMetadata]: return self._workflow_metadata @property def workflow_metadata_defaults(self): return self._workflow_metadata_defaults @property def python_interface(self) ->", "kwargs if you want them to be used in the compilation. This mimics", "workflow as _workflow_model GLOBAL_START_NODE = Node( id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None, bindings=[], upstream_nodes=[], flyte_entity=None, ) class", "but not exactly, the call pattern for Tasks. For local execution, it goes", "object for additional information. \"\"\" def __init__( self, workflow_function: Callable, metadata: Optional[WorkflowMetadata], default_metadata:", "workflow is in a ready state, which means * Has at least one", "from dispatch_execute which is in _local_execute, workflows should also call an execute inside", "wf is currently {self}\") # Create a map that holds the outputs of", "( ctx.execution_state is not None and ctx.execution_state.mode == ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ): if ctx.execution_state.branch_eval_mode ==", "we should've already returned in the above check, we just raise an Exception", "to the workflow # object itself. for n in comp_ctx.compilation_state.nodes: if isinstance(n.flyte_entity, PythonAutoContainerTask)", "or results is None: continue # pragma: no cover # Move along, nothing", "been specified for wf {self.name}.\") self._python_interface = self._python_interface.with_inputs(extra_inputs={input_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name]", "been declared with a typing.NamedTuple of # length one. That convention is used", "!= len(expected_output_names): raise FlyteValueException(results, f\"Different lengths {results} {expected_output_names}\") for idx, r in enumerate(results):", "up, maybe key off of the name instead of value? all_input_values = get_input_values(kwargs)", "ctx.execution_state.mode == ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ): if ctx.execution_state.branch_eval_mode == BranchEvalMode.BRANCH_SKIPPED: if self.python_interface and self.python_interface.output_tuple_name: variables", "return VoidPromise(self.name) # Because we should've already returned in the above check, we", "be a tuple here, if it's a one element named tuple, then we", "the options in flytekit.WorkflowFailurePolicy :param interruptible: Whether or not tasks launched from this", "for bd in binding_data.collection.bindings: p = get_promise(bd, outputs_cache) literals.append(p.val) return Promise( var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)),", "inputs(self) -> Dict[str, Promise]: \"\"\" This holds the input promises to the workflow.", "raise FlyteValueException( function_outputs, f\"{function_outputs} received but interface has {len(self.python_interface.outputs)} outputs.\", ) return VoidPromise(self.name)", "if isinstance(function_outputs, VoidPromise) or function_outputs is None: if len(self.python_interface.outputs) != 0: raise FlyteValueException(", "we're using the output_tuple_name as a proxy. if self.python_interface.output_tuple_name and isinstance(function_outputs, tuple): wf_outputs_as_map", "in using the node output tracker map we have. entity = node.flyte_entity entity_kwargs", "1): return create_native_named_tuple(ctx, result, self.python_interface) raise ValueError(\"expected outputs and actual outputs do not", "node. \"\"\" return self._inputs def __repr__(self): return super().__repr__() + f\"Nodes ({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\" def", "The context specifying the local workflow execution has already been set. elif (", "import literals as _literal_models from flytekit.models.core import workflow as _workflow_model GLOBAL_START_NODE = Node(", "already exists in workflow {self.name}\") if python_type is None: if type(p) == list", "CompilationState: \"\"\" Compilation is done a bit at a time, one task or", "from dataclasses import dataclass from enum import Enum from typing import Any, Callable,", "about the workflow itself. \"\"\" interruptible: bool def __post_init__(self): if self.interruptible is not", "isinstance(workflow_outputs[i], ConditionalSection): raise AssertionError(\"A Conditional block (if-else) should always end with an `else_()`", "return bindings[0] return tuple(bindings) def execute(self, **kwargs): \"\"\" This function is here only", "FlyteContextManager.with_context( ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) ) ) as child_ctx: result = self._local_execute(child_ctx, **input_kwargs) expected_outputs =", "var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) ) raise FlyteValidationException(\"Binding type unrecognized.\") def get_promise_map( bindings: List[_literal_models.Binding], outputs_cache: Dict[Node,", "is None: if type(p) == list or type(p) == dict: raise FlyteValidationException( f\"If", "can re-evaluate. self._input_parameters = None super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=default_metadata, python_interface=native_interface, ) @property def", "one above. Please see the IDL for more information but essentially, this WorkflowMetadataDefaults", ") python_type = p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring python type for wf output {output_name} from Promise", "len(output_names) == 1: return bindings[0] return tuple(bindings) def execute(self, **kwargs): \"\"\" This function", "may not return at all # def wf(): # t1() # In the", "!= WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ): raise FlyteValidationException(f\"Failure policy {self.on_failure} not acceptable\") def to_flyte_model(self): if self.on_failure", "a local workflow execution else: # Run some sanity checks # Even though", "return t1() # or it may not return at all # def wf():", "python_type: Optional[Type] = None ): \"\"\" Add an output with the given name", "the workflow. \"\"\" if input_name in self._inputs: raise FlyteValidationException(f\"Input {input_name} has already been", "compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: b = binding_from_python_std( ctx, output_name, expected_literal_type=flyte_type, t_value=p, t_value_type=python_type", ":param failure_policy: Use the options in flytekit.WorkflowFailurePolicy :param interruptible: Whether or not tasks", "a workflow call, when expecting a native value for {k}\") with FlyteContextManager.with_context( ctx.with_execution_state(", "@property def interface(self) -> _interface_models.TypedInterface: return self._interface @property def output_bindings(self) -> List[_literal_models.Binding]: return", "from flytekit.core.base_task import PythonTask from flytekit.core.class_based_resolver import ClassStorageTaskResolver from flytekit.core.condition import ConditionalSection from", "expected_outputs == len(result)) or (result is not None and expected_outputs == 1): return", "returned in the above check, we just raise an Exception here. if len(entity.python_interface.outputs)", "and self.on_failure != WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ): raise FlyteValidationException(f\"Failure policy {self.on_failure} not acceptable\") def to_flyte_model(self):", "@property def python_interface(self) -> Interface: return self._python_interface @property def interface(self) -> _interface_models.TypedInterface: return", "Please read :std:ref:`flyte:divedeep-workflows` first for a high-level understanding of what workflows are in", "function returns whether or not the workflow is in a ready state, which", "interruptible: Whether or not tasks launched from this workflow are by default interruptible", "and outputs of each node's entity results = entity(**entity_kwargs) expected_output_names = list(entity.python_interface.outputs.keys()) if", "is here only to try to streamline the pattern between workflows and tasks.", "# t1() # In the former case we get the task's VoidPromise, in", "This is why this workflow class has to keep track of its own", "flytekit.core.type_engine import TypeEngine from flytekit.loggers import logger from flytekit.models import interface as _interface_models", "all the values in kwargs are Promise objects for k, v in kwargs.items():", "here in this loop. The reason is because we don't prevent users from", "in self.compilation_state.nodes: if node not in intermediate_node_outputs.keys(): intermediate_node_outputs[node] = {} # Retrieve the", "the input # values but we're only interested in the ones that are", "for n in comp_ctx.compilation_state.nodes: if isinstance(n.flyte_entity, PythonAutoContainerTask) and n.flyte_entity.task_resolver == self: logger.debug(f\"WF {self.name}", "workflow inputs that you've declared with add_workflow_input but haven't yet consumed. This #", "for k in self.python_interface.outputs.keys()] output_tuple = collections.namedtuple(self.python_interface.output_tuple_name, variables) nones = [None for _", "plan only, but is here only so that we don't have to re-evaluate.", "bindings[0] return tuple(bindings) def execute(self, **kwargs): \"\"\" This function is here only to", "None or isinstance(result, VoidPromise): return None else: raise Exception(f\"Workflow local execution expected 0", "raise ValueError(\"expected outputs and actual outputs do not match\") def execute(self, **kwargs): raise", "been declared # functionally, and 2) what a user would return in mock", "self.add_entity(launch_plan, **kwargs) def add_subwf(self, sub_wf: WorkflowBase, **kwargs) -> Node: return self.add_entity(sub_wf, **kwargs) def", "should let the binding creation unwrap it and make a binding # collection/map", "FlyteContextManager.current_context() # Get default agruements and override with kwargs passed in input_kwargs =", "b.var is the name of the input to the task # binding_data.promise.var is", "== 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but should've been VoidPromise or None.\"", "Dict, List, Optional, Tuple, Type, Union from flytekit.common import constants as _common_constants from", "b in self.output_bindings]) def add_entity(self, entity: Union[PythonTask, LaunchPlan, WorkflowBase], **kwargs) -> Node: \"\"\"", "let's filter for those. # There's probably a way to clean this up,", "self._inputs def __repr__(self): return super().__repr__() + f\"Nodes ({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\" def execute(self, **kwargs): \"\"\"", "self.python_interface.outputs.keys()] return output_tuple(*nones) else: return None # We are already in a local", "outputs but something received {result}\") if (1 < expected_outputs == len(result)) or (result", "# We are already in a local execution, just continue the execution context", "**kwargs) def ready(self) -> bool: \"\"\" This function returns whether or not the", "len(self.compilation_state.nodes) == 0: return False if len(self._unbound_inputs) > 0: return False return True", "**kwargs) -> Node: return self.add_entity(sub_wf, **kwargs) def ready(self) -> bool: \"\"\" This function", "WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY = _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE = ( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ) @dataclass class WorkflowMetadata(object): on_failure:", "node not in intermediate_node_outputs.keys(): intermediate_node_outputs[node] = {} # Retrieve the entity from the", "own compilation state. \"\"\" return self._compilation_state @property def nodes(self) -> List[Node]: return self._compilation_state.nodes", "not output_names: return None if len(output_names) == 1: return bindings[0] return tuple(bindings) def", "to a workflow that already exists on your Flyte installation. This object will", "allows flytekit to raise # the error earlier. self._unbound_inputs = set() super().__init__( name=name,", "to that entity should've been already declared, we can just iterate through the", "str: return f\"{self.name}.{t.__module__}.{t.name}\" def compile(self, **kwargs): \"\"\" Supply static Python native values in", "# The first condition is compilation. if ctx.compilation_state is not None: return create_and_link_node(ctx,", "return self._workflow_function def task_name(self, t: PythonAutoContainerTask) -> str: return f\"{self.name}.{t.__module__}.{t.name}\" def compile(self, **kwargs):", "__post_init__(self): if ( self.on_failure != WorkflowFailurePolicy.FAIL_IMMEDIATELY and self.on_failure != WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ): raise FlyteValidationException(f\"Failure", "user can call a sub-workflow with a Python native value. for k, v", "the task resolver change. The task resolver interface itself is # more or", "self, name: str, workflow_metadata: WorkflowMetadata, workflow_metadata_defaults: WorkflowMetadataDefaults, python_interface: Interface, **kwargs, ): self._name =", "in outputs from previously completed nodes and filling in the necessary inputs. \"\"\"", "Compilation is done a bit at a time, one task or other entity", "Called by _local_execute. This function is how local execution for imperative workflows runs.", "be a combination of Python native values and Promises containing Flyte # Literals.", "i.e. the inputs to the workflow. # _local_execute should've already ensured that all", "why this workflow class has to keep track of its own compilation state.", "kwargs are Promise objects for k, v in kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k] = v #", "entity results = entity(**entity_kwargs) expected_output_names = list(entity.python_interface.outputs.keys()) if isinstance(results, VoidPromise) or results is", "Python native values and Promises containing Flyte # Literals. function_outputs = self.execute(**kwargs) #", "def __init__( self, workflow_function: Callable, metadata: Optional[WorkflowMetadata], default_metadata: Optional[WorkflowMetadataDefaults], ): name = f\"{workflow_function.__module__}.{workflow_function.__name__}\"", "object itself. for n in comp_ctx.compilation_state.nodes: if isinstance(n.flyte_entity, PythonAutoContainerTask) and n.flyte_entity.task_resolver == self:", "entity_kwargs[b.var] = get_promise(b.binding, outputs_cache) return entity_kwargs class WorkflowBase(object): def __init__( self, name: str,", "len(entity.python_interface.outputs) == 0: raise FlyteValueException(results, f\"{results} received but should've been VoidPromise or None.\")", "been VoidPromise or None.\" ) expected_output_names = list(self.python_interface.outputs.keys()) if len(expected_output_names) == 1: #", "super().__init__(WorkflowReference(project, domain, name, version), inputs, outputs) def reference_workflow( project: str, domain: str, name:", "that match the workflow's # interface. We do that by extracting out the", "call an execute inside _local_execute. This makes mocking cleaner. \"\"\" return self._workflow_function(**kwargs) def", "import FlyteValidationException, FlyteValueException from flytekit.core.base_task import PythonTask from flytekit.core.class_based_resolver import ClassStorageTaskResolver from flytekit.core.condition", "re-evaluate. Or # we can re-evaluate. self._input_parameters = None super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=default_metadata,", "import ( NodeOutput, Promise, VoidPromise, binding_from_python_std, create_and_link_node, create_native_named_tuple, create_task_output, translate_inputs_to_literals, ) from flytekit.core.python_auto_container", "== BranchEvalMode.BRANCH_SKIPPED: if self.python_interface and self.python_interface.output_tuple_name: variables = [k for k in self.python_interface.outputs.keys()]", "compilation, an error will be returned. \"\"\" def __init__( self, project: str, domain:", "self.interface.inputs[k].type)) # The output of this will always be a combination of Python", "only one output, if len(expected_output_names) == 1: if entity.python_interface.output_tuple_name and isinstance(results, tuple): intermediate_node_outputs[node][expected_output_names[0]]", "import Any, Callable, Dict, List, Optional, Tuple, Type, Union from flytekit.common import constants", "binding_data.promise.var is the name of the upstream node's output we want return outputs_cache[binding_data.promise.node][binding_data.promise.var]", "It's also important to note that, local execution notwithstanding, it is not evaluated", "re-evaluate. self._input_parameters = None super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=default_metadata, python_interface=native_interface, ) @property def function(self):", "with FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self)) ) as comp_ctx: # Construct the default input promise", "self: logger.debug(f\"WF {self.name} saving task {n.flyte_entity.name}\") self.add(n.flyte_entity) # Iterate through the workflow outputs", "how local execution for imperative workflows runs. Because when an entity is added", "all of the # workflow's output bindings. # The return style here has", "python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name] = Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) self._unbound_inputs.add(self._inputs[input_name]) return self._inputs[input_name] def", "a sub-workflow with a Python native value. for k, v in kwargs.items(): if", "goes __call__ -> _local_execute -> execute From execute, different things happen for the", "Has at least one node * All workflow inputs are bound These conditions", "be called\") def _local_execute(self, ctx: FlyteContext, **kwargs) -> Union[Tuple[Promise], Promise, VoidPromise]: # This", "t1() # In the former case we get the task's VoidPromise, in the", "self.python_interface.output_tuple_name: return (get_promise(self.output_bindings[0].binding, intermediate_node_outputs),) # Just a normal single element return get_promise(self.output_bindings[0].binding, intermediate_node_outputs)", "Type] ): super().__init__(WorkflowReference(project, domain, name, version), inputs, outputs) def reference_workflow( project: str, domain:", "**kwargs): \"\"\" Called by _local_execute. This function is how local execution for imperative", "by _local_execute. This function is how local execution for imperative workflows runs. Because", "type(p) == dict: raise FlyteValidationException( f\"If specifying a list or dict of Promises,", "return anything # def wf(): # return t1() # or it may not", "is # more or less stateless (the future-proofing get_all_tasks function notwithstanding). However the", "parent's workflow local run. # The context specifying the local workflow execution has", "function body of a workflow is evaluated at serialization-time (aka compile-time). This is", "WorkflowFailurePolicy def __post_init__(self): if ( self.on_failure != WorkflowFailurePolicy.FAIL_IMMEDIATELY and self.on_failure != WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ):", "for imperative workflows runs. Because when an entity is added using the add_entity", "return self._inputs[input_name] def add_workflow_output( self, output_name: str, p: Union[Promise, List[Promise], Dict[str, Promise]], python_type:", "task resolver interface itself is # more or less stateless (the future-proofing get_all_tasks", "self._compilation_state @property def nodes(self) -> List[Node]: return self._compilation_state.nodes @property def inputs(self) -> Dict[str,", "earlier. self._unbound_inputs = set() super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(), ) @property def compilation_state(self)", "outputs bindings = [] output_names = list(self.interface.outputs.keys()) # The reason the length 1", "bindings, pulling in outputs from previously completed nodes and filling in the necessary", "is just here to help workflow authors detect issues a bit earlier. It", "of workflow inputs that you've declared with add_workflow_input but haven't yet consumed. This", "return [input_value] # Every time an entity is added, mark it as used.", "prefix = f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if ctx.compilation_state is not None else \"\" with FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix,", "missing project and domain self._nodes = all_nodes self._output_bindings = bindings if not output_names:", "of propeller in resolving bindings, pulling in outputs from previously completed nodes and", "for i, out in enumerate(output_names): if isinstance(workflow_outputs[i], ConditionalSection): raise AssertionError(\"A Conditional block (if-else)", "a 'closure' in the traditional sense of the word. \"\"\" ctx = FlyteContextManager.current_context()", "we shouldn't run into any dependency issues. That is, we force the user", "specifying the local workflow execution has already been set. elif ( ctx.execution_state is", "the workflow inputs (if any). As things are run, their outputs are stored", "if len(self.compilation_state.nodes) == 0: return False if len(self._unbound_inputs) > 0: return False return", "VoidPromise, in the latter we get None if isinstance(function_outputs, VoidPromise) or function_outputs is", "again when the workflow runs on Flyte. That is, workflows should not call", "run, we fill in workflow level outputs the same way as any other", "This is because while we can determine the entire structure of a task", "defined workflows is done node by node. This function will fill in the", "Move along, nothing to assign # Because we should've already returned in the", "return value, received {len(workflow_outputs)}\" ) if self.python_interface.output_tuple_name is None: raise AssertionError( \"Outputs specification", "a DAG of tasks using the data flow between tasks. Unlike a task,", "[] FlyteEntities.entities.append(self) super().__init__(**kwargs) @property def name(self) -> str: return self._name @property def short_name(self)", ":param _workflow_function: This argument is implicitly passed and represents the decorated function. :param", "for input_name in inputs } def get_promise(binding_data: _literal_models.BindingData, outputs_cache: Dict[Node, Dict[str, Promise]]) ->", "\"\"\" Called by _local_execute. This function is how local execution for imperative workflows", "return f\"{self.name}.{t.__module__}.{t.name}\" def compile(self, **kwargs): \"\"\" Supply static Python native values in the", "workflows is done node by node. This function will fill in the node's", "has {len(self.python_interface.outputs)} outputs.\", ) return VoidPromise(self.name) # Because we should've already returned in", "for i, _ in enumerate(function_outputs)} # Basically we need to repackage the promises", "to note that, local execution notwithstanding, it is not evaluated again when the", "conditions assume that all nodes and workflow i/o changes were done with the", "raise Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: b = binding_from_python_std( ctx,", "return value is a tuple\" ) workflow_outputs = workflow_outputs[0] t = self.python_interface.outputs[output_names[0]] b", "inside _local_execute too for k, v in input_kwargs.items(): if k not in self.interface.inputs:", "nodes in these Promise objects should always point to the global start node.", "{output_name} from Promise provided {python_type}\") flyte_type = TypeEngine.to_literal_type(python_type=python_type) ctx = FlyteContext.current_context() if ctx.compilation_state", "{expected_output_names}\") for idx, r in enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]] = r # The rest of", "of the task resolver change. The task resolver interface itself is # more", "is used for naming outputs - and single-length-NamedTuples are # particularly troublesome but", "any). As things are run, their outputs are stored in this map. After", "must be boolean, {self.interruptible} invalid\") def to_flyte_model(self): return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def construct_input_promises(inputs: List[str]): return", "continue # pragma: no cover # Move along, nothing to assign # Because", "add_launch_plan(self, launch_plan: LaunchPlan, **kwargs) -> Node: return self.add_entity(launch_plan, **kwargs) def add_subwf(self, sub_wf: WorkflowBase,", "objects should always point to the global start node. \"\"\" return self._inputs def", "Flyte. This Python object represents a workflow defined by a function and decorated", "is not None else \"\" with FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self)) ) as comp_ctx: #", "pattern for Workflows is close to, but not exactly, the call pattern for", "returned had it been declared # functionally, and 2) what a user would", "FlyteContext, FlyteContextManager, FlyteEntities, ) from flytekit.core.interface import ( Interface, transform_inputs_to_parameters, transform_interface_to_typed_interface, transform_signature_to_interface, )", "notes on that object for additional information. \"\"\" def __init__( self, workflow_function: Callable,", "task's VoidPromise, in the latter we get None if isinstance(function_outputs, VoidPromise) or function_outputs", "\"\"\" if binding_data.promise is not None: if not isinstance(binding_data.promise, NodeOutput): raise FlyteValidationException( f\"Binding", "block (if-else) should always end with an `else_()` clause\") t = self.python_interface.outputs[out] b", "in enumerate(function_outputs)} # Basically we need to repackage the promises coming from the", "= transform_inputs_to_parameters(ctx, self.python_interface) all_nodes = [] prefix = f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if ctx.compilation_state is not", "should've already returned in the above check, we just raise an Exception here.", "def __call__(self, *args, **kwargs): \"\"\" The call pattern for Workflows is close to,", "Node from flytekit.core.promise import ( NodeOutput, Promise, VoidPromise, binding_from_python_std, create_and_link_node, create_native_named_tuple, create_task_output, translate_inputs_to_literals,", "makes mocking cleaner. \"\"\" return self._workflow_function(**kwargs) def workflow( _workflow_function=None, failure_policy: Optional[WorkflowFailurePolicy] = None,", "class WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY = _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE = ( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ) @dataclass class WorkflowMetadata(object):", "ReferenceWorkflow]: \"\"\" A reference workflow is a pointer to a workflow that already", "inputs that you've declared with add_workflow_input but haven't yet consumed. This # is", "run. # The context specifying the local workflow execution has already been set.", "length 1 case is separate is because the one output might be a", "Node: \"\"\" Anytime you add an entity, all the inputs to the entity", "SdkWorkflow, except for the missing project and domain self._nodes = all_nodes self._output_bindings =", "have. entity = node.flyte_entity entity_kwargs = get_promise_map(node.bindings, intermediate_node_outputs) # Handle the calling and", "generally expects inputs to be Promises, we don't have to do the #", ") return VoidPromise(self.name) # Because we should've already returned in the above check,", "the above but now we're doing it for the workflow as a whole", "\"\"\" The call pattern for Workflows is close to, but not exactly, the", "Promise, VoidPromise, binding_from_python_std, create_and_link_node, create_native_named_tuple, create_task_output, translate_inputs_to_literals, ) from flytekit.core.python_auto_container import PythonAutoContainerTask from", "isinstance(results, VoidPromise) or results is None: continue # pragma: no cover # Move", "the data flow between tasks. Unlike a task, the function body of a", "Promises that match the workflow's # interface. We do that by extracting out", "future-proofing get_all_tasks function notwithstanding). However the # implementation of the TaskResolverMixin that this", "function. :param failure_policy: Use the options in flytekit.WorkflowFailurePolicy :param interruptible: Whether or not", "not be in launchplan only? # This can be in launch plan only,", "that will turn a binding into a Promise object, using a lookup map.", "ValueError(\"expected outputs and actual outputs do not match\") def execute(self, **kwargs): raise Exception(\"Should", "imperatively defined workflows is done node by node. This function will fill in", "detect issues a bit earlier. It just # keeps track of workflow inputs", "input node, i.e. the inputs to the workflow. # _local_execute should've already ensured", "not define a tuple, but return value is a tuple\" ) workflow_outputs =", "assign # Because we should've already returned in the above check, we just", ") elif binding_data.map is not None: literals = {} for k, bd in", "WorkflowBase, **kwargs) -> Node: return self.add_entity(sub_wf, **kwargs) def ready(self) -> bool: \"\"\" This", "v in kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k] = v # Next iterate through the nodes in", "return style here has to match what 1) what the workflow would've returned", "FlyteValidationException(f\"Input {input_name} has already been specified for wf {self.name}.\") self._python_interface = self._python_interface.with_inputs(extra_inputs={input_name: python_type})", "Please see the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for more usage examples. :param _workflow_function: This argument is", "type unrecognized.\") def get_promise_map( bindings: List[_literal_models.Binding], outputs_cache: Dict[Node, Dict[str, Promise]] ) -> Dict[str,", "in self.interface.inputs: raise ValueError(f\"Received unexpected keyword argument {k}\") if isinstance(v, Promise): raise ValueError(f\"Received", "workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(), ) @property def compilation_state(self) -> CompilationState: \"\"\" Compilation is done a", "or other entity call at a time. This is why this workflow class", "are defined within the body of the workflow to the workflow # object", "# The output of this will always be a combination of Python native", "class ImperativeWorkflow(WorkflowBase): def __init__( self, name: str, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool]", "PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver): \"\"\" Please read :std:ref:`flyte:divedeep-workflows` first for a high-level understanding of what", "[] for bd in binding_data.collection.bindings: p = get_promise(bd, outputs_cache) literals.append(p.val) return Promise( var=\"placeholder\",", "conversion here in this loop. The reason is because we don't prevent users", "def to_flyte_model(self): return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def construct_input_promises(inputs: List[str]): return { input_name: Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name))", "helper function that will turn a binding into a Promise object, using a", "and creating new Promises wf_outputs_as_literal_dict = translate_inputs_to_literals( ctx, wf_outputs_as_map, flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs, ) #", "been set. elif ( ctx.execution_state is not None and ctx.execution_state.mode == ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ):", "add_workflow_input(self, input_name: str, python_type: Type) -> Interface: \"\"\" Adds an input to the", "(1 < expected_outputs == len(result)) or (result is not None and expected_outputs ==", "&& \" f\"Outputs ({len(self._python_interface.outputs)}): {self._python_interface.outputs} && \" f\"Output bindings: {self._output_bindings} && \" )", "def ready(self) -> bool: \"\"\" This function returns whether or not the workflow", "the length 1 case is separate is because the one output might be", "the add_entity function, all inputs to that entity should've been already declared, we", "Any]], ReferenceWorkflow]: \"\"\" A reference workflow is a pointer to a workflow that", "done with the functions above, which do additional checking. \"\"\" if len(self.compilation_state.nodes) ==", "self.execute(**kwargs) # First handle the empty return case. # A workflow function may", "will turn a binding into a Promise object, using a lookup map. Please", "FlyteContext, **kwargs) -> Union[Tuple[Promise], Promise, VoidPromise]: # This is done to support the", "Basically this takes the place of propeller in resolving bindings, pulling in outputs", "f\" starting with the container type (e.g. List[int]\" ) python_type = p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring", "native values and Promises containing Flyte # Literals. function_outputs = self.execute(**kwargs) # First", "= entity(**entity_kwargs) expected_output_names = list(entity.python_interface.outputs.keys()) if isinstance(results, VoidPromise) or results is None: continue", "FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: n = create_node(entity=entity, **kwargs) def get_input_values(input_value): if isinstance(input_value, list): input_promises", "because the one output might be a list. We don't want to #", "any other previous node. \"\"\" if not self.ready(): raise FlyteValidationException(f\"Workflow not ready, wf", "not None and ctx.execution_state.mode == ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ): if ctx.execution_state.branch_eval_mode == BranchEvalMode.BRANCH_SKIPPED: if self.python_interface", "# Iterate through the workflow outputs bindings = [] output_names = list(self.interface.outputs.keys()) #", "you add an entity, all the inputs to the entity must be bound.", "not initiate a network call to Admin, which is why the user is", "be a Flyte workflow. Workflows are declarative entities that construct a DAG of", "# and then fill them in using the node output tracker map we", "once (again, this is with respect to the platform, local runs notwithstanding). Please", "names. new_promises = [Promise(var, wf_outputs_as_literal_dict[var]) for var in expected_output_names] return create_task_output(new_promises, self.python_interface) class", "self._workflow_metadata @property def workflow_metadata_defaults(self): return self._workflow_metadata_defaults @property def python_interface(self) -> Interface: return self._python_interface", "output might be a list. We don't want to # iterate through the", "Type, Union from flytekit.common import constants as _common_constants from flytekit.common.exceptions.user import FlyteValidationException, FlyteValueException", "just continue the execution context return self._local_execute(ctx, **input_kwargs) # Last is starting a", "the python_type type for {output_name}\" f\" starting with the container type (e.g. List[int]\"", "version), inputs, outputs) def reference_workflow( project: str, domain: str, name: str, version: str,", "and call it by looking up the promises the node's bindings require, #", "return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def construct_input_promises(inputs: List[str]): return { input_name: Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) for input_name", "for wf {self.name}.\") self._python_interface = self._python_interface.with_inputs(extra_inputs={input_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name] = Promise(var=input_name,", "workflow_function native_interface = transform_signature_to_interface(inspect.signature(workflow_function)) # TODO do we need this - can this", "or it may not return at all # def wf(): # t1() #", "its own compilation state. \"\"\" return self._compilation_state @property def nodes(self) -> List[Node]: return", "node output tracker map we have. entity = node.flyte_entity entity_kwargs = get_promise_map(node.bindings, intermediate_node_outputs)", "enum import Enum from typing import Any, Callable, Dict, List, Optional, Tuple, Type,", "class WorkflowBase(object): def __init__( self, name: str, workflow_metadata: WorkflowMetadata, workflow_metadata_defaults: WorkflowMetadataDefaults, python_interface: Interface,", "None and ctx.execution_state.mode == ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ): if ctx.execution_state.branch_eval_mode == BranchEvalMode.BRANCH_SKIPPED: if self.python_interface and", "with a Python native value. for k, v in kwargs.items(): if not isinstance(v,", "= None, interruptible: Optional[bool] = False, ): metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults", "high-level understanding of what workflows are in Flyte. This Python object represents a", "self._workflow_function = workflow_function native_interface = transform_signature_to_interface(inspect.signature(workflow_function)) # TODO do we need this -", "may return a task that doesn't return anything # def wf(): # return", "error will be returned. \"\"\" def __init__( self, project: str, domain: str, name:", "the literals, and creating new Promises wf_outputs_as_literal_dict = translate_inputs_to_literals( ctx, wf_outputs_as_map, flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs,", "the node, and call it by looking up the promises the node's bindings", "issue with compilation, an error will be returned. \"\"\" def __init__( self, project:", "above but now we're doing it for the workflow as a whole rather", "This unbound inputs construct is just here to help workflow authors detect issues", "already in a local execution, just continue the execution context return self._local_execute(ctx, **input_kwargs)", "workflow {self.name}\") if python_type is None: if type(p) == list or type(p) ==", "Dict[str, Promise]] ) -> Dict[str, Promise]: \"\"\" Local execution of imperatively defined workflows", "output_bindings(self) -> List[_literal_models.Binding]: return self._output_bindings @property def nodes(self) -> List[Node]: return self._nodes def", "return ( f\"WorkflowBase - {self._name} && \" f\"Inputs ({len(self._python_interface.inputs)}): {self._python_interface.inputs} && \" f\"Outputs", "of the # workflow's output bindings. # The return style here has to", "Tasks that are defined within the body of the workflow to the workflow", "only one\") if len(output_names) != len(workflow_outputs): raise Exception(f\"Length mismatch {len(output_names)} vs {len(workflow_outputs)}\") for", "k, bd in binding_data.map.bindings.items(): p = get_promise(bd, outputs_cache) literals[k] = p.val return Promise(", "create_node ctx = FlyteContext.current_context() if ctx.compilation_state is not None: raise Exception(\"Can't already be", "A reference workflow is a pointer to a workflow that already exists on", "if self.python_interface.output_tuple_name and isinstance(function_outputs, tuple): wf_outputs_as_map = {expected_output_names[0]: function_outputs[0]} else: wf_outputs_as_map = {expected_output_names[0]:", "def execute(self, **kwargs): raise Exception(\"Should not be called\") def _local_execute(self, ctx: FlyteContext, **kwargs)", "0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but should've been VoidPromise or None.\" )", "= self.python_interface.outputs[out] b = binding_from_python_std( ctx, out, self.interface.outputs[out].type, workflow_outputs[i], t, ) bindings.append(b) #", "to # iterate through the list here, instead we should let the binding", "loop was added as part of the task resolver change. The task resolver", "the inputs to the workflow. # _local_execute should've already ensured that all the", "Workflow local executions always work with Promise objects # holding Flyte literal values.", "else: wf_outputs_as_map = {expected_output_names[i]: function_outputs[i] for i, _ in enumerate(function_outputs)} # Basically we", "start node. \"\"\" return self._inputs def __repr__(self): return super().__repr__() + f\"Nodes ({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\"", "self._nodes = all_nodes self._output_bindings = bindings if not output_names: return None if len(output_names)", "_interface_models.TypedInterface: return self._interface @property def output_bindings(self) -> List[_literal_models.Binding]: return self._output_bindings @property def nodes(self)", "only run once (again, this is with respect to the platform, local runs", "is because we don't prevent users from specifying inputs # as direct scalars,", "in a ready state, which means * Has at least one node *", "t, ) bindings.append(b) # Save all the things necessary to create an SdkWorkflow,", "isinstance(v, Promise): raise ValueError(f\"Received a promise for a workflow call, when expecting a", "elif binding_data.scalar is not None: return Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar)) elif binding_data.collection is not None:", "an error that Admin would return at compile time anyways, but this allows", "workflow_instance.compile() return workflow_instance if _workflow_function: return wrapper(_workflow_function) else: return wrapper class ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow):", "): raise FlyteValidationException(f\"Failure policy {self.on_failure} not acceptable\") def to_flyte_model(self): if self.on_failure == WorkflowFailurePolicy.FAIL_IMMEDIATELY:", "workflows runs. Because when an entity is added using the add_entity function, all", "k in self.interface.inputs.keys()]) input_kwargs.update(kwargs) workflow_outputs = self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes) # This little loop was", "Promise( var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) ) raise FlyteValidationException(\"Binding type unrecognized.\") def get_promise_map( bindings: List[_literal_models.Binding], outputs_cache:", "__call__ -> _local_execute -> execute From execute, different things happen for the two", "Promise), all_input_values): if input_value in self._unbound_inputs: self._unbound_inputs.remove(input_value) return n def add_workflow_input(self, input_name: str,", "is evaluated at serialization-time (aka compile-time). This is because while we can determine", "an issue with compilation, an error will be returned. \"\"\" def __init__( self,", "user to declare entities already in a topological sort. To keep track of", "single element if len(self.output_bindings) == 1: # Again use presence of output_tuple_name to", "flytekit.core.node_creation import create_node ctx = FlyteContext.current_context() if ctx.compilation_state is not None: raise Exception(\"Can't", "str, version: str, ) -> Callable[[Callable[..., Any]], ReferenceWorkflow]: \"\"\" A reference workflow is", "map that holds the outputs of each node. intermediate_node_outputs = {GLOBAL_START_NODE: {}} #", "None: if not isinstance(binding_data.promise, NodeOutput): raise FlyteValidationException( f\"Binding data Promises have to be", "to do the # conversion here in this loop. The reason is because", "if len(output_names) == 1: return bindings[0] return tuple(bindings) def execute(self, **kwargs): \"\"\" This", "for input_value in filter(lambda x: isinstance(x, Promise), all_input_values): if input_value in self._unbound_inputs: self._unbound_inputs.remove(input_value)", "end with an `else_()` clause\") t = self.python_interface.outputs[out] b = binding_from_python_std( ctx, out,", "the entire structure of a task by looking at the function's signature, workflows", "Type) -> Interface: \"\"\" Adds an input to the workflow. \"\"\" if input_name", "output_names = list(self.interface.outputs.keys()) # The reason the length 1 case is separate is", "WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) self._compilation_state = CompilationState(prefix=\"\") self._inputs = {} #", "# Just a normal single element return get_promise(self.output_bindings[0].binding, intermediate_node_outputs) return tuple([get_promise(b.binding, intermediate_node_outputs) for", "if isinstance(input_value, list): input_promises = [] for x in input_value: input_promises.extend(get_input_values(x)) return input_promises", "the body of the workflow to the workflow # object itself. for n", "the error earlier. self._unbound_inputs = set() super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(), ) @property", "import Node from flytekit.core.promise import ( NodeOutput, Promise, VoidPromise, binding_from_python_std, create_and_link_node, create_native_named_tuple, create_task_output,", "track of outputs, we create a map to start things off, filled in", "binding_data.scalar is not None: return Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar)) elif binding_data.collection is not None: literals", "the entity must be bound. \"\"\" # circular import from flytekit.core.node_creation import create_node", "list or dict of Promises, you must specify the python_type type for {output_name}\"", "from flytekit.core.launch_plan import LaunchPlan from flytekit.core.node import Node from flytekit.core.promise import ( NodeOutput,", "the task # binding_data.promise.var is the name of the upstream node's output we", "not None: literals = {} for k, bd in binding_data.map.bindings.items(): p = get_promise(bd,", "results[0] else: intermediate_node_outputs[node][expected_output_names[0]] = results else: if len(results) != len(expected_output_names): raise FlyteValueException(results, f\"Different", "from flytekit.core.node_creation import create_node ctx = FlyteContext.current_context() if ctx.compilation_state is not None: raise", "workflow structure. It's also important to note that, local execution notwithstanding, it is", "translate_inputs_to_literals( ctx, wf_outputs_as_map, flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs, ) # Recreate new promises that use the", "bindings = [] output_names = list(self.interface.outputs.keys()) # The reason the length 1 case", "_workflow_model GLOBAL_START_NODE = Node( id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None, bindings=[], upstream_nodes=[], flyte_entity=None, ) class WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY", "self.python_interface.output_tuple_name and isinstance(function_outputs, tuple): wf_outputs_as_map = {expected_output_names[0]: function_outputs[0]} else: wf_outputs_as_map = {expected_output_names[0]: function_outputs}", ") @dataclass class WorkflowMetadata(object): on_failure: WorkflowFailurePolicy def __post_init__(self): if ( self.on_failure != WorkflowFailurePolicy.FAIL_IMMEDIATELY", "interface=self.python_interface, **input_kwargs) # This condition is hit when this workflow (self) is being", "FlyteContextManager.current_context() self._input_parameters = transform_inputs_to_parameters(ctx, self.python_interface) all_nodes = [] prefix = f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if ctx.compilation_state", "as a whole rather # than just one node at a time. if", "workflow (self) is being called as part of a parent's workflow local run.", "from flytekit.core.type_engine import TypeEngine from flytekit.loggers import logger from flytekit.models import interface as", "Please see get_promise_map for the rest of the details. \"\"\" if binding_data.promise is", "what expresses the workflow structure. It's also important to note that, local execution", "ctx: n = create_node(entity=entity, **kwargs) def get_input_values(input_value): if isinstance(input_value, list): input_promises = []", "would return in mock function. That is, if it's a tuple, then it", "that already exists on your Flyte installation. This object will not initiate a", "literals = {} for k, bd in binding_data.map.bindings.items(): p = get_promise(bd, outputs_cache) literals[k]", "an error will be returned. \"\"\" def __init__( self, project: str, domain: str,", "specification for Workflow does not define a tuple, but return value is a", "and isinstance(function_outputs, tuple): wf_outputs_as_map = {expected_output_names[0]: function_outputs[0]} else: wf_outputs_as_map = {expected_output_names[0]: function_outputs} else:", "since they are only run once (again, this is with respect to the", "for k, bd in binding_data.map.bindings.items(): p = get_promise(bd, outputs_cache) literals[k] = p.val return", "nodes and filling in the necessary inputs. \"\"\" entity_kwargs = {} for b", "{len(workflow_outputs)}\") for i, out in enumerate(output_names): if isinstance(workflow_outputs[i], ConditionalSection): raise AssertionError(\"A Conditional block", "tasks. Unlike a task, the function body of a workflow is evaluated at", "value is a tuple\" ) workflow_outputs = workflow_outputs[0] t = self.python_interface.outputs[output_names[0]] b =", "import PythonTask from flytekit.core.class_based_resolver import ClassStorageTaskResolver from flytekit.core.condition import ConditionalSection from flytekit.core.context_manager import", "done to support the invariant that Workflow local executions always work with Promise", "each node's entity results = entity(**entity_kwargs) expected_output_names = list(entity.python_interface.outputs.keys()) if isinstance(results, VoidPromise) or", "a ready state, which means * Has at least one node * All", "# Literals. function_outputs = self.execute(**kwargs) # First handle the empty return case. #", "a function to be a Flyte workflow. Workflows are declarative entities that construct", "( Interface, transform_inputs_to_parameters, transform_interface_to_typed_interface, transform_signature_to_interface, ) from flytekit.core.launch_plan import LaunchPlan from flytekit.core.node import", "decorator. Please see notes on that object for additional information. \"\"\" def __init__(", "# def wf(): # return t1() # or it may not return at", "necessary inputs. \"\"\" entity_kwargs = {} for b in bindings: entity_kwargs[b.var] = get_promise(b.binding,", "is not True and self.interruptible is not False: raise FlyteValidationException(f\"Interruptible must be boolean,", "Flyte literal values. Even in a wf, a user can call a sub-workflow", "launched from this workflow are by default interruptible \"\"\" def wrapper(fn): workflow_metadata =", "\"\"\" This holds the input promises to the workflow. The nodes in these", "raise an Exception here. if len(entity.python_interface.outputs) == 0: raise FlyteValueException(results, f\"{results} received but", "executions\") ctx = FlyteContextManager.current_context() # Get default agruements and override with kwargs passed", "similarly named to the one above. Please see the IDL for more information", "0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but interface has {len(self.python_interface.outputs)} outputs.\", ) return", "nodes in order. for node in self.compilation_state.nodes: if node not in intermediate_node_outputs.keys(): intermediate_node_outputs[node]", "\"\"\" interruptible: bool def __post_init__(self): if self.interruptible is not True and self.interruptible is", "passed in input_kwargs = self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs) # The first condition is compilation. if", "length one. That convention is used for naming outputs - and single-length-NamedTuples are", "track of its own compilation state. \"\"\" return self._compilation_state @property def nodes(self) ->", "wf, a user can call a sub-workflow with a Python native value. for", "VoidPromise or None.\") # if there's only one output, if len(expected_output_names) == 1:", "already been specified for wf {self.name}.\") self._python_interface = self._python_interface.with_inputs(extra_inputs={input_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface)", "{result}\") if (1 < expected_outputs == len(result)) or (result is not None and", "{expected_output_names[0]: function_outputs[0]} else: wf_outputs_as_map = {expected_output_names[0]: function_outputs} else: wf_outputs_as_map = {expected_output_names[i]: function_outputs[i] for", "received {len(workflow_outputs)}\" ) if self.python_interface.output_tuple_name is None: raise AssertionError( \"Outputs specification for Workflow", "the promises coming from the tasks into Promises that match the workflow's #", "not None: raise Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: b =", "mock function. That is, if it's a tuple, then it # should be", "= python_interface self._interface = transform_interface_to_typed_interface(python_interface) self._inputs = {} self._unbound_inputs = set() self._nodes =", "self.interruptible is not True and self.interruptible is not False: raise FlyteValidationException(f\"Interruptible must be", "up the promises the node's bindings require, # and then fill them in", "some sanity checks # Even though the _local_execute call generally expects inputs to", "function is how local execution for imperative workflows runs. Because when an entity", "metadata=workflow_metadata, default_metadata=workflow_metadata_defaults ) workflow_instance.compile() return workflow_instance if _workflow_function: return wrapper(_workflow_function) else: return wrapper", "here. if len(self.python_interface.outputs) == 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but should've been", "the function's signature, workflows need to run through the function itself because the", "function that will turn a binding into a Promise object, using a lookup", "the empty return case. # A workflow function may return a task that", ") from flytekit.core.python_auto_container import PythonAutoContainerTask from flytekit.core.reference_entity import ReferenceEntity, WorkflowReference from flytekit.core.type_engine import", "for the missing project and domain self._nodes = all_nodes self._output_bindings = bindings if", "ExecutionState, FlyteContext, FlyteContextManager, FlyteEntities, ) from flytekit.core.interface import ( Interface, transform_inputs_to_parameters, transform_interface_to_typed_interface, transform_signature_to_interface,", "to clean this up, maybe key off of the name instead of value?", "a binding # collection/map out of it. if len(output_names) == 1: if isinstance(workflow_outputs,", "# pragma: no cover # Move along, nothing to assign # Because we", "a one-element non-named tuple, # if it's a single element then we return", "is because the one output might be a list. We don't want to", "case. # A workflow function may return a task that doesn't return anything", "None: raise Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: n = create_node(entity=entity,", "tuple): intermediate_node_outputs[node][expected_output_names[0]] = results[0] else: intermediate_node_outputs[node][expected_output_names[0]] = results else: if len(results) != len(expected_output_names):", "a time. if len(self.python_interface.outputs) == 0: return VoidPromise(self.name) # The values that we", "in the ones that are Promises so let's filter for those. # There's", "the missing project and domain self._nodes = all_nodes self._output_bindings = bindings if not", "structure of a task by looking at the function's signature, workflows need to", "get_input_values(input_value): if isinstance(input_value, list): input_promises = [] for x in input_value: input_promises.extend(get_input_values(x)) return", "be in launchplan only? # This can be in launch plan only, but", "f\"Output bindings: {self._output_bindings} && \" ) def __call__(self, *args, **kwargs): \"\"\" The call", "that by extracting out the literals, and creating new Promises wf_outputs_as_literal_dict = translate_inputs_to_literals(", ") -> Dict[str, Promise]: \"\"\" Local execution of imperatively defined workflows is done", "to the platform, local runs notwithstanding). Please see the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for more usage", "container type (e.g. List[int]\" ) python_type = p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring python type for wf", "self.ready(): raise FlyteValidationException(f\"Workflow not ready, wf is currently {self}\") # Create a map", "previously completed nodes and filling in the necessary inputs. \"\"\" entity_kwargs = {}", "with the given name from the given node output. \"\"\" if output_name in", "objects # holding Flyte literal values. Even in a wf, a user can", "mark it as used. The above function though will gather all the input", "time, one task or other entity call at a time. This is why", "\"\"\" # circular import from flytekit.core.node_creation import create_node ctx = FlyteContext.current_context() if ctx.compilation_state", "name=name, workflow_metadata=metadata, workflow_metadata_defaults=default_metadata, python_interface=native_interface, ) @property def function(self): return self._workflow_function def task_name(self, t:", "naming outputs - and single-length-NamedTuples are # particularly troublesome but elegant handling of", "python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) def add_task(self, task: PythonTask, **kwargs) -> Node: return self.add_entity(task,", "this map. After all nodes are run, we fill in workflow level outputs", "element if len(self.output_bindings) == 1: # Again use presence of output_tuple_name to understand", "this up, maybe key off of the name instead of value? all_input_values =", "None if len(output_names) == 1: return bindings[0] return tuple(bindings) def execute(self, **kwargs): \"\"\"", "Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False, ): \"\"\" This decorator declares a", "should've been VoidPromise or None.\") # if there's only one output, if len(expected_output_names)", "class inherits from (ClassStorageTaskResolver) # does store state. This loop adds Tasks that", "\"Outputs specification for Workflow does not define a tuple, but return value is", "( NodeOutput, Promise, VoidPromise, binding_from_python_std, create_and_link_node, create_native_named_tuple, create_task_output, translate_inputs_to_literals, ) from flytekit.core.python_auto_container import", "binding_from_python_std( ctx, out, self.interface.outputs[out].type, workflow_outputs[i], t, ) bindings.append(b) # Save all the things", "workflow to the workflow # object itself. for n in comp_ctx.compilation_state.nodes: if isinstance(n.flyte_entity,", "This holds the input promises to the workflow. The nodes in these Promise", "a workflow's tasks, whereas WorkflowMetadata represents metadata about the workflow itself. \"\"\" interruptible:", "for the workflow as a whole rather # than just one node at", "= workflow_outputs[0] t = self.python_interface.outputs[output_names[0]] b = binding_from_python_std( ctx, output_names[0], self.interface.outputs[output_names[0]].type, workflow_outputs, t,", "in enumerate(output_names): if isinstance(workflow_outputs[i], ConditionalSection): raise AssertionError(\"A Conditional block (if-else) should always end", "wf could've been declared with a typing.NamedTuple of # length one. That convention", "the workflow outputs bindings = [] output_names = list(self.interface.outputs.keys()) # The reason the", "at least one node * All workflow inputs are bound These conditions assume", "the workflow structure. It's also important to note that, local execution notwithstanding, it", "0: raise FlyteValueException(results, f\"{results} received but should've been VoidPromise or None.\") # if", "\"\"\" if len(args) > 0: raise AssertionError(\"Only Keyword Arguments are supported for Workflow", "use presence of output_tuple_name to understand that we're dealing with a one-element #", "ctx, output_name, expected_literal_type=flyte_type, t_value=p, t_value_type=python_type ) self._output_bindings.append(b) self._python_interface = self._python_interface.with_outputs(extra_outputs={output_name: python_type}) self._interface =", "-> List[_literal_models.Binding]: return self._output_bindings @property def nodes(self) -> List[Node]: return self._nodes def __repr__(self):", "to create an SdkWorkflow, except for the missing project and domain self._nodes =", "the input promises to the workflow. The nodes in these Promise objects should", "that holds the outputs of each node. intermediate_node_outputs = {GLOBAL_START_NODE: {}} # type:", "return super().__repr__() + f\"Nodes ({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\" def execute(self, **kwargs): \"\"\" Called by _local_execute.", "return in mock function. That is, if it's a tuple, then it #", "outputs, we create a map to start things off, filled in only with", "self.on_failure != WorkflowFailurePolicy.FAIL_IMMEDIATELY and self.on_failure != WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ): raise FlyteValidationException(f\"Failure policy {self.on_failure} not", "details. \"\"\" if binding_data.promise is not None: if not isinstance(binding_data.promise, NodeOutput): raise FlyteValidationException(", "self, name: str, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False, ): metadata", "name(self) -> str: return self._name @property def short_name(self) -> str: return self._name.split(\".\")[-1] @property", "(the future-proofing get_all_tasks function notwithstanding). However the # implementation of the TaskResolverMixin that", "launch_plan: LaunchPlan, **kwargs) -> Node: return self.add_entity(launch_plan, **kwargs) def add_subwf(self, sub_wf: WorkflowBase, **kwargs)", "python type for wf output {output_name} from Promise provided {python_type}\") flyte_type = TypeEngine.to_literal_type(python_type=python_type)", "provided {python_type}\") flyte_type = TypeEngine.to_literal_type(python_type=python_type) ctx = FlyteContext.current_context() if ctx.compilation_state is not None:", "Flyte # Literals. function_outputs = self.execute(**kwargs) # First handle the empty return case.", "them in using the node output tracker map we have. entity = node.flyte_entity", "the NodeOutput type {type(binding_data.promise)} found\" ) # b.var is the name of the", "Exception(f\"Length mismatch {len(output_names)} vs {len(workflow_outputs)}\") for i, out in enumerate(output_names): if isinstance(workflow_outputs[i], ConditionalSection):", "is hit when this workflow (self) is being called as part of a", "raise FlyteValueException(results, f\"{results} received but should've been VoidPromise or None.\") # if there's", "self.python_interface and self.python_interface.output_tuple_name: variables = [k for k in self.python_interface.outputs.keys()] output_tuple = collections.namedtuple(self.python_interface.output_tuple_name,", "flytekit.core.node import Node from flytekit.core.promise import ( NodeOutput, Promise, VoidPromise, binding_from_python_std, create_and_link_node, create_native_named_tuple,", "FAIL_AFTER_EXECUTABLE_NODES_COMPLETE = ( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ) @dataclass class WorkflowMetadata(object): on_failure: WorkflowFailurePolicy def __post_init__(self): if", "the function is what expresses the workflow structure. It's also important to note", "if not isinstance(binding_data.promise, NodeOutput): raise FlyteValidationException( f\"Binding data Promises have to be of", "# The reason the length 1 case is separate is because the one", "Exception(f\"Workflow local execution expected 0 outputs but something received {result}\") if (1 <", "is how local execution for imperative workflows runs. Because when an entity is", "is similarly named to the one above. Please see the IDL for more", "name of the input to the task # binding_data.promise.var is the name of", "p.val return Promise( var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) ) raise FlyteValidationException(\"Binding type unrecognized.\") def get_promise_map( bindings:", "= Promise(var=k, val=TypeEngine.to_literal(ctx, v, t, self.interface.inputs[k].type)) # The output of this will always", "# There's probably a way to clean this up, maybe key off of", "These conditions assume that all nodes and workflow i/o changes were done with", "else: return [input_value] # Every time an entity is added, mark it as", "in self.interface.inputs.keys()]) input_kwargs.update(kwargs) workflow_outputs = self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes) # This little loop was added", "= [] output_names = list(self.interface.outputs.keys()) # The reason the length 1 case is", "boolean, {self.interruptible} invalid\") def to_flyte_model(self): return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def construct_input_promises(inputs: List[str]): return { input_name:", "executions always work with Promise objects # holding Flyte literal values. Even in", "with the outputs of the global input node, i.e. the inputs to the", "= p.val return Promise( var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) ) raise FlyteValidationException(\"Binding type unrecognized.\") def get_promise_map(", "in self._unbound_inputs: self._unbound_inputs.remove(input_value) return n def add_workflow_input(self, input_name: str, python_type: Type) -> Interface:", "# b.var is the name of the input to the task # binding_data.promise.var", "convention is used for naming outputs - and single-length-NamedTuples are # particularly troublesome", "Dict[str, Promise]]) -> Promise: \"\"\" This is a helper function that will turn", "the invariant that Workflow local executions always work with Promise objects # holding", "task, the function body of a workflow is evaluated at serialization-time (aka compile-time).", "== 1: # Here we have to handle the fact that the wf", "workflow. Workflows are declarative entities that construct a DAG of tasks using the", "_local_execute should've already ensured that all the values in kwargs are Promise objects", "entities that construct a DAG of tasks using the data flow between tasks.", "== WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure = 0 else: on_failure = 1 return _workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass class", "evaluated again when the workflow runs on Flyte. That is, workflows should not", "looking at the function's signature, workflows need to run through the function itself", "if ctx.compilation_state is not None else \"\" with FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self)) ) as", "a way to clean this up, maybe key off of the name instead", "a time. This is why this workflow class has to keep track of", "mocking cleaner. \"\"\" return self._workflow_function(**kwargs) def workflow( _workflow_function=None, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible:", "inputs to the workflow. # _local_execute should've already ensured that all the values", "# iterate through the list here, instead we should let the binding creation", "of the TaskResolverMixin that this workflow class inherits from (ClassStorageTaskResolver) # does store", "call generally expects inputs to be Promises, we don't have to do the", "@property def inputs(self) -> Dict[str, Promise]: \"\"\" This holds the input promises to", "def workflow_metadata_defaults(self): return self._workflow_metadata_defaults @property def python_interface(self) -> Interface: return self._python_interface @property def", "self._workflow_function(**kwargs) def workflow( _workflow_function=None, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False, ):", "more usage examples. :param _workflow_function: This argument is implicitly passed and represents the", "handle the fact that the wf could've been declared with a typing.NamedTuple of", "python_interface=native_interface, ) @property def function(self): return self._workflow_function def task_name(self, t: PythonAutoContainerTask) -> str:", "interruptible \"\"\" def wrapper(fn): workflow_metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) workflow_instance", "above function though will gather all the input # values but we're only", "we return a single element if len(self.output_bindings) == 1: # Again use presence", "the promises the node's bindings require, # and then fill them in using", "a typing.NamedTuple of # length one. That convention is used for naming outputs", "TODO do we need this - can this not be in launchplan only?", "are run, their outputs are stored in this map. After all nodes are", "keep track of its own compilation state. \"\"\" return self._compilation_state @property def nodes(self)", "**kwargs) def add_subwf(self, sub_wf: WorkflowBase, **kwargs) -> Node: return self.add_entity(sub_wf, **kwargs) def ready(self)", "can just iterate through the nodes in order and we shouldn't run into", "v in kwargs.items(): if not isinstance(v, Promise): t = self.python_interface.inputs[k] kwargs[k] = Promise(var=k,", "def output_bindings(self) -> List[_literal_models.Binding]: return self._output_bindings @property def nodes(self) -> List[Node]: return self._nodes", "As things are run, their outputs are stored in this map. After all", "p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring python type for wf output {output_name} from Promise provided {python_type}\") flyte_type", "super().__init__(**kwargs) @property def name(self) -> str: return self._name @property def short_name(self) -> str:", "default interruptible \"\"\" def wrapper(fn): workflow_metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible)", "project: str, domain: str, name: str, version: str, ) -> Callable[[Callable[..., Any]], ReferenceWorkflow]:", "def workflow_metadata(self) -> Optional[WorkflowMetadata]: return self._workflow_metadata @property def workflow_metadata_defaults(self): return self._workflow_metadata_defaults @property def", "self._workflow_metadata = workflow_metadata self._workflow_metadata_defaults = workflow_metadata_defaults self._python_interface = python_interface self._interface = transform_interface_to_typed_interface(python_interface) self._inputs", "): name = f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function = workflow_function native_interface = transform_signature_to_interface(inspect.signature(workflow_function)) # TODO do", "__init__( self, project: str, domain: str, name: str, version: str, inputs: Dict[str, Type],", "= self.python_interface.inputs[k] kwargs[k] = Promise(var=k, val=TypeEngine.to_literal(ctx, v, t, self.interface.inputs[k].type)) # The output of", "add_subwf(self, sub_wf: WorkflowBase, **kwargs) -> Node: return self.add_entity(sub_wf, **kwargs) def ready(self) -> bool:", "return self.add_entity(sub_wf, **kwargs) def ready(self) -> bool: \"\"\" This function returns whether or", "we're doing it for the workflow as a whole rather # than just", "reason the length 1 case is separate is because the one output might", "holding Flyte literal values. Even in a wf, a user can call a", "# In the former case we get the task's VoidPromise, in the latter", "default_metadata=workflow_metadata_defaults ) workflow_instance.compile() return workflow_instance if _workflow_function: return wrapper(_workflow_function) else: return wrapper class", "execution else: # Run some sanity checks # Even though the _local_execute call", "output_tuple(*nones) else: return None # We are already in a local execution, just", ") ) as child_ctx: result = self._local_execute(child_ctx, **input_kwargs) expected_outputs = len(self.python_interface.outputs) if expected_outputs", "is in a ready state, which means * Has at least one node", "Dict[str, Type], outputs: Dict[str, Type] ): super().__init__(WorkflowReference(project, domain, name, version), inputs, outputs) def", "binding_from_python_std, create_and_link_node, create_native_named_tuple, create_task_output, translate_inputs_to_literals, ) from flytekit.core.python_auto_container import PythonAutoContainerTask from flytekit.core.reference_entity import", "!= len(workflow_outputs): raise Exception(f\"Length mismatch {len(output_names)} vs {len(workflow_outputs)}\") for i, out in enumerate(output_names):", "at compile time anyways, but this allows flytekit to raise # the error", "\"\"\" Local execution of imperatively defined workflows is done node by node. This", "= list(self.python_interface.outputs.keys()) if len(expected_output_names) == 1: # Here we have to handle the", "use the workflow's output names. new_promises = [Promise(var, wf_outputs_as_literal_dict[var]) for var in expected_output_names]", "help workflow authors detect issues a bit earlier. It just # keeps track", "as used. The above function though will gather all the input # values", "this is with respect to the platform, local runs notwithstanding). Please see the", "len(expected_output_names) == 1: if entity.python_interface.output_tuple_name and isinstance(results, tuple): intermediate_node_outputs[node][expected_output_names[0]] = results[0] else: intermediate_node_outputs[node][expected_output_names[0]]", "workflow_instance = PythonFunctionWorkflow( fn, metadata=workflow_metadata, default_metadata=workflow_metadata_defaults ) workflow_instance.compile() return workflow_instance if _workflow_function: return", "FlyteValidationException, FlyteValueException from flytekit.core.base_task import PythonTask from flytekit.core.class_based_resolver import ClassStorageTaskResolver from flytekit.core.condition import", "{type(binding_data.promise)} found\" ) # b.var is the name of the input to the", "in the above check, we just raise an error here. if len(self.python_interface.outputs) ==", "checks # Even though the _local_execute call generally expects inputs to be Promises,", "Python function is run, for the ImperativeWorkflow, each node is run one at", "@property def compilation_state(self) -> CompilationState: \"\"\" Compilation is done a bit at a", "self._local_execute(child_ctx, **input_kwargs) expected_outputs = len(self.python_interface.outputs) if expected_outputs == 0: if result is None", "**kwargs) -> Node: \"\"\" Anytime you add an entity, all the inputs to", "x: isinstance(x, Promise), all_input_values): if input_value in self._unbound_inputs: self._unbound_inputs.remove(input_value) return n def add_workflow_input(self,", "one-element # named tuple if self.python_interface.output_tuple_name: return (get_promise(self.output_bindings[0].binding, intermediate_node_outputs),) # Just a normal", "logger from flytekit.models import interface as _interface_models from flytekit.models import literals as _literal_models", "from the node, and call it by looking up the promises the node's", "str: return self._name @property def short_name(self) -> str: return self._name.split(\".\")[-1] @property def workflow_metadata(self)", "need this - can this not be in launchplan only? # This can", "another Promise-generating loop inside _local_execute too for k, v in input_kwargs.items(): if k", "else: return wrapper class ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow): \"\"\" A reference workflow is a pointer", "the workflow as a whole rather # than just one node at a", "so let's filter for those. # There's probably a way to clean this", "do a one-element non-named tuple, # if it's a single element then we", "= self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs) # The first condition is compilation. if ctx.compilation_state is not", "> 0: raise AssertionError(\"Only Keyword Arguments are supported for Workflow executions\") ctx =", "the given node output. \"\"\" if output_name in self._python_interface.outputs: raise FlyteValidationException(f\"Output {output_name} already", "in _local_execute, workflows should also call an execute inside _local_execute. This makes mocking", "on your Flyte installation. This object will not initiate a network call to", "= binding_from_python_std( ctx, output_name, expected_literal_type=flyte_type, t_value=p, t_value_type=python_type ) self._output_bindings.append(b) self._python_interface = self._python_interface.with_outputs(extra_outputs={output_name: python_type})", "be pulled by fulfilling all of the # workflow's output bindings. # The", "else: wf_outputs_as_map = {expected_output_names[0]: function_outputs} else: wf_outputs_as_map = {expected_output_names[i]: function_outputs[i] for i, _", "This function is here only to try to streamline the pattern between workflows", "str, domain: str, name: str, version: str, inputs: Dict[str, Type], outputs: Dict[str, Type]", "exists on your Flyte installation. This object will not initiate a network call", "flytekit.core.python_auto_container import PythonAutoContainerTask from flytekit.core.reference_entity import ReferenceEntity, WorkflowReference from flytekit.core.type_engine import TypeEngine from", "also important to note that, local execution notwithstanding, it is not evaluated again", "return input_promises if isinstance(input_value, dict): input_promises = [] for _, v in input_value.items():", "a map that holds the outputs of each node. intermediate_node_outputs = {GLOBAL_START_NODE: {}}", "FlyteValidationException(f\"Output {output_name} already exists in workflow {self.name}\") if python_type is None: if type(p)", "# return t1() # or it may not return at all # def", "= f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if ctx.compilation_state is not None else \"\" with FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self))", "more or less stateless (the future-proofing get_all_tasks function notwithstanding). However the # implementation", "values. Even in a wf, a user can call a sub-workflow with a", "tuple): wf_outputs_as_map = {expected_output_names[0]: function_outputs[0]} else: wf_outputs_as_map = {expected_output_names[0]: function_outputs} else: wf_outputs_as_map =", "Node( id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None, bindings=[], upstream_nodes=[], flyte_entity=None, ) class WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY = _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE", "nodes in order and we shouldn't run into any dependency issues. That is,", "single-length-NamedTuples are # particularly troublesome but elegant handling of them is not a", "in self._python_interface.outputs: raise FlyteValidationException(f\"Output {output_name} already exists in workflow {self.name}\") if python_type is", "this not be in launchplan only? # This can be in launch plan", "{self.name} saving task {n.flyte_entity.name}\") self.add(n.flyte_entity) # Iterate through the workflow outputs bindings =", "inherits from (ClassStorageTaskResolver) # does store state. This loop adds Tasks that are", "interface provided causes an issue with compilation, an error will be returned. \"\"\"", "this WorkflowMetadataDefaults class represents the defaults that are handed down to a workflow's", "FlyteContextManager, FlyteEntities, ) from flytekit.core.interface import ( Interface, transform_inputs_to_parameters, transform_interface_to_typed_interface, transform_signature_to_interface, ) from", "error earlier. self._unbound_inputs = set() super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(), ) @property def", "not return at all # def wf(): # t1() # In the former", "if self.python_interface and self.python_interface.output_tuple_name: variables = [k for k in self.python_interface.outputs.keys()] output_tuple =", "input_value in self._unbound_inputs: self._unbound_inputs.remove(input_value) return n def add_workflow_input(self, input_name: str, python_type: Type) ->", "intermediate_node_outputs) for b in self.output_bindings]) def add_entity(self, entity: Union[PythonTask, LaunchPlan, WorkflowBase], **kwargs) ->", "ImperativeWorkflow, each node is run one at a time. \"\"\" if len(args) >", "the global start node. \"\"\" return self._inputs def __repr__(self): return super().__repr__() + f\"Nodes", "if (1 < expected_outputs == len(result)) or (result is not None and expected_outputs", "&& \" f\"Inputs ({len(self._python_interface.inputs)}): {self._python_interface.inputs} && \" f\"Outputs ({len(self._python_interface.outputs)}): {self._python_interface.outputs} && \" f\"Output", "function to be a Flyte workflow. Workflows are declarative entities that construct a", "# or it may not return at all # def wf(): # t1()", "the given name from the given node output. \"\"\" if output_name in self._python_interface.outputs:", "local execution, it goes __call__ -> _local_execute -> execute From execute, different things", "FAIL_IMMEDIATELY = _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE = ( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ) @dataclass class WorkflowMetadata(object): on_failure: WorkflowFailurePolicy", "x in input_value: input_promises.extend(get_input_values(x)) return input_promises if isinstance(input_value, dict): input_promises = [] for", "def get_promise_map( bindings: List[_literal_models.Binding], outputs_cache: Dict[Node, Dict[str, Promise]] ) -> Dict[str, Promise]: \"\"\"", "workflows should not call non-Flyte entities since they are only run once (again,", "we need this - can this not be in launchplan only? # This", "functionally, and 2) what a user would return in mock function. That is,", "execution notwithstanding, it is not evaluated again when the workflow runs on Flyte.", "you want them to be used in the compilation. This mimics a 'closure'", "def name(self) -> str: return self._name @property def short_name(self) -> str: return self._name.split(\".\")[-1]", "specification indicates multiple return values, received only one\") if len(output_names) != len(workflow_outputs): raise", "should always point to the global start node. \"\"\" return self._inputs def __repr__(self):", "order. for node in self.compilation_state.nodes: if node not in intermediate_node_outputs.keys(): intermediate_node_outputs[node] = {}", "in this loop. The reason is because we don't prevent users from specifying", "shouldn't run into any dependency issues. That is, we force the user to", "List, Optional, Tuple, Type, Union from flytekit.common import constants as _common_constants from flytekit.common.exceptions.user", "Tasks. For local execution, it goes __call__ -> _local_execute -> execute From execute,", "input_promises if isinstance(input_value, dict): input_promises = [] for _, v in input_value.items(): input_promises.extend(get_input_values(v))", "input # values but we're only interested in the ones that are Promises", "to keep track of its own compilation state. \"\"\" return self._compilation_state @property def", "has to keep track of its own compilation state. \"\"\" return self._compilation_state @property", "wf(): # t1() # In the former case we get the task's VoidPromise,", "input_kwargs.update(kwargs) # The first condition is compilation. if ctx.compilation_state is not None: return", "# Handle the calling and outputs of each node's entity results = entity(**entity_kwargs)", "a network call to Admin, which is why the user is asked to", "is with respect to the platform, local runs notwithstanding). Please see the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py`", "do additional checking. \"\"\" if len(self.compilation_state.nodes) == 0: return False if len(self._unbound_inputs) >", "is not None: return create_and_link_node(ctx, entity=self, interface=self.python_interface, **input_kwargs) # This condition is hit", "this workflow (self) is being called as part of a parent's workflow local", "order and we shouldn't run into any dependency issues. That is, we force", "a tuple\" ) workflow_outputs = workflow_outputs[0] t = self.python_interface.outputs[output_names[0]] b = binding_from_python_std( ctx,", "is implicitly passed and represents the decorated function. :param failure_policy: Use the options", "Workflow specification indicates multiple return values, received only one\") if len(output_names) != len(workflow_outputs):", "# values but we're only interested in the ones that are Promises so", "one node * All workflow inputs are bound These conditions assume that all", "translate_inputs_to_literals, ) from flytekit.core.python_auto_container import PythonAutoContainerTask from flytekit.core.reference_entity import ReferenceEntity, WorkflowReference from flytekit.core.type_engine", "Union[Promise, List[Promise], Dict[str, Promise]], python_type: Optional[Type] = None ): \"\"\" Add an output", "return values, received only one\") if len(output_names) != len(workflow_outputs): raise Exception(f\"Length mismatch {len(output_names)}", "= len(self.python_interface.outputs) if expected_outputs == 0: if result is None or isinstance(result, VoidPromise):", "is the name of the input to the task # binding_data.promise.var is the", "input arguments, which are specified using the bindings list, and a map of", "match what 1) what the workflow would've returned had it been declared #", "self._input_parameters = transform_inputs_to_parameters(ctx, self.python_interface) all_nodes = [] prefix = f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if ctx.compilation_state is", "as child_ctx: result = self._local_execute(child_ctx, **input_kwargs) expected_outputs = len(self.python_interface.outputs) if expected_outputs == 0:", "WorkflowMetadataDefaults(object): \"\"\" This class is similarly named to the one above. Please see", "the Python function is run, for the ImperativeWorkflow, each node is run one", ") workflow_instance.compile() return workflow_instance if _workflow_function: return wrapper(_workflow_function) else: return wrapper class ReferenceWorkflow(ReferenceEntity,", "of # length one. That convention is used for naming outputs - and", "if len(workflow_outputs) != 1: raise AssertionError( f\"The Workflow specification indicates only one return", "pattern between workflows and tasks. Since tasks call execute from dispatch_execute which is", "b in bindings: entity_kwargs[b.var] = get_promise(b.binding, outputs_cache) return entity_kwargs class WorkflowBase(object): def __init__(", "self._workflow_metadata_defaults = workflow_metadata_defaults self._python_interface = python_interface self._interface = transform_interface_to_typed_interface(python_interface) self._inputs = {} self._unbound_inputs", "domain, name, version), inputs, outputs) def reference_workflow( project: str, domain: str, name: str,", "which means there's another Promise-generating loop inside _local_execute too for k, v in", "**kwargs) -> Node: return self.add_entity(task, **kwargs) def add_launch_plan(self, launch_plan: LaunchPlan, **kwargs) -> Node:", "# workflow's output bindings. # The return style here has to match what", "rather # than just one node at a time. if len(self.python_interface.outputs) == 0:", "is None: raise AssertionError( \"Outputs specification for Workflow does not define a tuple,", "the node output tracker map we have. entity = node.flyte_entity entity_kwargs = get_promise_map(node.bindings,", "str, python_type: Type) -> Interface: \"\"\" Adds an input to the workflow. \"\"\"", "if self.python_interface.output_tuple_name is None: raise AssertionError( \"Outputs specification for Workflow does not define", "for b in self.output_bindings]) def add_entity(self, entity: Union[PythonTask, LaunchPlan, WorkflowBase], **kwargs) -> Node:", "python_interface: Interface, **kwargs, ): self._name = name self._workflow_metadata = workflow_metadata self._workflow_metadata_defaults = workflow_metadata_defaults", "in inputs } def get_promise(binding_data: _literal_models.BindingData, outputs_cache: Dict[Node, Dict[str, Promise]]) -> Promise: \"\"\"", "PythonAutoContainerTask from flytekit.core.reference_entity import ReferenceEntity, WorkflowReference from flytekit.core.type_engine import TypeEngine from flytekit.loggers import", "def __repr__(self): return ( f\"WorkflowBase - {self._name} && \" f\"Inputs ({len(self._python_interface.inputs)}): {self._python_interface.inputs} &&", "if you want them to be used in the compilation. This mimics a", "{} for b in bindings: entity_kwargs[b.var] = get_promise(b.binding, outputs_cache) return entity_kwargs class WorkflowBase(object):", "to the workflow. # _local_execute should've already ensured that all the values in", "for additional information. \"\"\" def __init__( self, workflow_function: Callable, metadata: Optional[WorkflowMetadata], default_metadata: Optional[WorkflowMetadataDefaults],", "require, # and then fill them in using the node output tracker map", "runs on Flyte. That is, workflows should not call non-Flyte entities since they", "!= 1: raise AssertionError( f\"The Workflow specification indicates only one return value, received", "output tracker map we have. entity = node.flyte_entity entity_kwargs = get_promise_map(node.bindings, intermediate_node_outputs) #", "workflow level outputs the same way as any other previous node. \"\"\" if", "function_outputs = self.execute(**kwargs) # First handle the empty return case. # A workflow", "import create_node ctx = FlyteContext.current_context() if ctx.compilation_state is not None: raise Exception(\"Can't already", "_local_execute too for k, v in input_kwargs.items(): if k not in self.interface.inputs: raise", "must be bound. \"\"\" # circular import from flytekit.core.node_creation import create_node ctx =", "a wf, a user can call a sub-workflow with a Python native value.", "outputs the same way as any other previous node. \"\"\" if not self.ready():", "var=input_name)) self._unbound_inputs.add(self._inputs[input_name]) return self._inputs[input_name] def add_workflow_output( self, output_name: str, p: Union[Promise, List[Promise], Dict[str,", "particularly troublesome but elegant handling of them is not a high priority #", "using the add_entity function, all inputs to that entity should've been already declared,", "in only with the workflow inputs (if any). As things are run, their", "all the things necessary to create an SdkWorkflow, except for the missing project", "things happen for the two Workflow styles. For PythonFunctionWorkflows, the Python function is", "# Construct the default input promise bindings, but then override with the provided", "here only so that we don't have to re-evaluate. Or # we can", "= name self._workflow_metadata = workflow_metadata self._workflow_metadata_defaults = workflow_metadata_defaults self._python_interface = python_interface self._interface =", "self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs) # The first condition is compilation. if ctx.compilation_state is not None:", "flytekit.core.class_based_resolver import ClassStorageTaskResolver from flytekit.core.condition import ConditionalSection from flytekit.core.context_manager import ( BranchEvalMode, CompilationState,", "called\") def _local_execute(self, ctx: FlyteContext, **kwargs) -> Union[Tuple[Promise], Promise, VoidPromise]: # This is", "an entity is added, mark it as used. The above function though will", "this - can this not be in launchplan only? # This can be", "This decorator declares a function to be a Flyte workflow. Workflows are declarative", "entity is added, mark it as used. The above function though will gather", "element then we return a single element if len(self.output_bindings) == 1: # Again", "and workflow i/o changes were done with the functions above, which do additional", "super().__repr__() + f\"Nodes ({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\" def execute(self, **kwargs): \"\"\" Called by _local_execute. This", "should've already ensured that all the values in kwargs are Promise objects for", "def interface(self) -> _interface_models.TypedInterface: return self._interface @property def output_bindings(self) -> List[_literal_models.Binding]: return self._output_bindings", "&& \" f\"Output bindings: {self._output_bindings} && \" ) def __call__(self, *args, **kwargs): \"\"\"", "f\"Inputs ({len(self._python_interface.inputs)}): {self._python_interface.inputs} && \" f\"Outputs ({len(self._python_interface.outputs)}): {self._python_interface.outputs} && \" f\"Output bindings: {self._output_bindings}", "Workflow styles. For PythonFunctionWorkflows, the Python function is run, for the ImperativeWorkflow, each", "the node's bindings require, # and then fill them in using the node", "if isinstance(v, Promise): raise ValueError(f\"Received a promise for a workflow call, when expecting", "name: str, workflow_metadata: WorkflowMetadata, workflow_metadata_defaults: WorkflowMetadataDefaults, python_interface: Interface, **kwargs, ): self._name = name", "empty return case. # A workflow function may return a task that doesn't", "True class PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver): \"\"\" Please read :std:ref:`flyte:divedeep-workflows` first for a high-level understanding", "-> List[Node]: return self._compilation_state.nodes @property def inputs(self) -> Dict[str, Promise]: \"\"\" This holds", "return case. # A workflow function may return a task that doesn't return", "compilation_state(self) -> CompilationState: \"\"\" Compilation is done a bit at a time, one", "enumerate(function_outputs)} # Basically we need to repackage the promises coming from the tasks", "This little loop was added as part of the task resolver change. The", "are Promise objects for k, v in kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k] = v # Next", "output names. new_promises = [Promise(var, wf_outputs_as_literal_dict[var]) for var in expected_output_names] return create_task_output(new_promises, self.python_interface)", "# The return style here has to match what 1) what the workflow", "False, ): metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) self._compilation_state = CompilationState(prefix=\"\")", "in mock function. That is, if it's a tuple, then it # should", "`else_()` clause\") t = self.python_interface.outputs[out] b = binding_from_python_std( ctx, out, self.interface.outputs[out].type, workflow_outputs[i], t,", "outputs. Basically this takes the place of propeller in resolving bindings, pulling in", "Tuple, Type, Union from flytekit.common import constants as _common_constants from flytekit.common.exceptions.user import FlyteValidationException,", "list, and a map of nodes to its outputs. Basically this takes the", "so that we don't have to re-evaluate. Or # we can re-evaluate. self._input_parameters", "Arguments are supported for Workflow executions\") ctx = FlyteContextManager.current_context() # Get default agruements", "force the user to declare entities already in a topological sort. To keep", "if input_name in self._inputs: raise FlyteValidationException(f\"Input {input_name} has already been specified for wf", "= 1 return _workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass class WorkflowMetadataDefaults(object): \"\"\" This class is similarly named", "self._output_bindings.append(b) self._python_interface = self._python_interface.with_outputs(extra_outputs={output_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) def add_task(self, task: PythonTask, **kwargs)", "None: return create_and_link_node(ctx, entity=self, interface=self.python_interface, **input_kwargs) # This condition is hit when this", "of each node. intermediate_node_outputs = {GLOBAL_START_NODE: {}} # type: Dict[Node, Dict[str, Promise]] #", "wf_outputs_as_literal_dict[var]) for var in expected_output_names] return create_task_output(new_promises, self.python_interface) class ImperativeWorkflow(WorkflowBase): def __init__( self,", "isinstance(results, tuple): intermediate_node_outputs[node][expected_output_names[0]] = results[0] else: intermediate_node_outputs[node][expected_output_names[0]] = results else: if len(results) !=", "read :std:ref:`flyte:divedeep-workflows` first for a high-level understanding of what workflows are in Flyte.", "local workflow execution else: # Run some sanity checks # Even though the", "has to match what 1) what the workflow would've returned had it been", "= Node( id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None, bindings=[], upstream_nodes=[], flyte_entity=None, ) class WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY = _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY", "The reason is because we don't prevent users from specifying inputs # as", "structure. It's also important to note that, local execution notwithstanding, it is not", "ctx, wf_outputs_as_map, flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs, ) # Recreate new promises that use the workflow's", "PythonFunctionWorkflow): \"\"\" A reference workflow is a pointer to a workflow that already", "type: Dict[Node, Dict[str, Promise]] # Start things off with the outputs of the", "element return get_promise(self.output_bindings[0].binding, intermediate_node_outputs) return tuple([get_promise(b.binding, intermediate_node_outputs) for b in self.output_bindings]) def add_entity(self,", "would return at compile time anyways, but this allows flytekit to raise #", "{} self._unbound_inputs = set() self._nodes = [] self._output_bindings: Optional[List[_literal_models.Binding]] = [] FlyteEntities.entities.append(self) super().__init__(**kwargs)", "python_type type for {output_name}\" f\" starting with the container type (e.g. List[int]\" )", "wf_outputs_as_literal_dict = translate_inputs_to_literals( ctx, wf_outputs_as_map, flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs, ) # Recreate new promises that", "__call__(self, *args, **kwargs): \"\"\" The call pattern for Workflows is close to, but", "len(expected_output_names) == 1: # Here we have to handle the fact that the", "f\"If specifying a list or dict of Promises, you must specify the python_type", "whereas WorkflowMetadata represents metadata about the workflow itself. \"\"\" interruptible: bool def __post_init__(self):", "as _common_constants from flytekit.common.exceptions.user import FlyteValidationException, FlyteValueException from flytekit.core.base_task import PythonTask from flytekit.core.class_based_resolver", "of a task by looking at the function's signature, workflows need to run", "input to the task # binding_data.promise.var is the name of the upstream node's", "({len(self._python_interface.outputs)}): {self._python_interface.outputs} && \" f\"Output bindings: {self._output_bindings} && \" ) def __call__(self, *args,", "it as used. The above function though will gather all the input #", "but interface has {len(self.python_interface.outputs)} outputs.\", ) return VoidPromise(self.name) # Because we should've already", "\"\"\" Supply static Python native values in the kwargs if you want them", "as part of a parent's workflow local run. # The context specifying the", "LaunchPlan, WorkflowBase], **kwargs) -> Node: \"\"\" Anytime you add an entity, all the", "0: return False if len(self._unbound_inputs) > 0: return False return True class PythonFunctionWorkflow(WorkflowBase,", "binding # collection/map out of it. if len(output_names) == 1: if isinstance(workflow_outputs, tuple):", "\"\"\" if output_name in self._python_interface.outputs: raise FlyteValidationException(f\"Output {output_name} already exists in workflow {self.name}\")", "= [None for _ in self.python_interface.outputs.keys()] return output_tuple(*nones) else: return None # We", "in these Promise objects should always point to the global start node. \"\"\"", "coming from the tasks into Promises that match the workflow's # interface. We", "and filling in the necessary inputs. \"\"\" entity_kwargs = {} for b in", "fill in workflow level outputs the same way as any other previous node.", "The values that we return below from the output have to be pulled", "Promises containing Flyte # Literals. function_outputs = self.execute(**kwargs) # First handle the empty", "That convention is used for naming outputs - and single-length-NamedTuples are # particularly", "flytekit.core.interface import ( Interface, transform_inputs_to_parameters, transform_interface_to_typed_interface, transform_signature_to_interface, ) from flytekit.core.launch_plan import LaunchPlan from", "None: literals = [] for bd in binding_data.collection.bindings: p = get_promise(bd, outputs_cache) literals.append(p.val)", "is, workflows should not call non-Flyte entities since they are only run once", "values and Promises containing Flyte # Literals. function_outputs = self.execute(**kwargs) # First handle", "expected_output_names] return create_task_output(new_promises, self.python_interface) class ImperativeWorkflow(WorkflowBase): def __init__( self, name: str, failure_policy: Optional[WorkflowFailurePolicy]", "other entity call at a time. This is why this workflow class has", "different things happen for the two Workflow styles. For PythonFunctionWorkflows, the Python function", "else: intermediate_node_outputs[node][expected_output_names[0]] = results else: if len(results) != len(expected_output_names): raise FlyteValueException(results, f\"Different lengths", "input_value in filter(lambda x: isinstance(x, Promise), all_input_values): if input_value in self._unbound_inputs: self._unbound_inputs.remove(input_value) return", "{input_name} has already been specified for wf {self.name}.\") self._python_interface = self._python_interface.with_inputs(extra_inputs={input_name: python_type}) self._interface", "if it's a one element named tuple, then we do a one-element non-named", "**input_kwargs) # This condition is hit when this workflow (self) is being called", "create_task_output, translate_inputs_to_literals, ) from flytekit.core.python_auto_container import PythonAutoContainerTask from flytekit.core.reference_entity import ReferenceEntity, WorkflowReference from", "return self._interface @property def output_bindings(self) -> List[_literal_models.Binding]: return self._output_bindings @property def nodes(self) ->", "be Promises, we don't have to do the # conversion here in this", "_workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ) @dataclass class WorkflowMetadata(object): on_failure: WorkflowFailurePolicy def __post_init__(self): if ( self.on_failure !=", "function is run, for the ImperativeWorkflow, each node is run one at a", "a single element if len(self.output_bindings) == 1: # Again use presence of output_tuple_name", "clean this up, maybe key off of the name instead of value? all_input_values", "expected 0 outputs but something received {result}\") if (1 < expected_outputs == len(result))", "unwrap it and make a binding # collection/map out of it. if len(output_names)", "Since tasks call execute from dispatch_execute which is in _local_execute, workflows should also", "Promises have to be of the NodeOutput type {type(binding_data.promise)} found\" ) # b.var", "in intermediate_node_outputs.keys(): intermediate_node_outputs[node] = {} # Retrieve the entity from the node, and", "workflow_metadata_defaults(self): return self._workflow_metadata_defaults @property def python_interface(self) -> Interface: return self._python_interface @property def interface(self)", "= [k for k in self.python_interface.outputs.keys()] output_tuple = collections.namedtuple(self.python_interface.output_tuple_name, variables) nones = [None", "defined by a function and decorated with the :py:func:`@workflow <flytekit.workflow>` decorator. Please see", "by extracting out the literals, and creating new Promises wf_outputs_as_literal_dict = translate_inputs_to_literals( ctx,", "return wrapper(_workflow_function) else: return wrapper class ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow): \"\"\" A reference workflow is", "added, mark it as used. The above function though will gather all the", "create_native_named_tuple, create_task_output, translate_inputs_to_literals, ) from flytekit.core.python_auto_container import PythonAutoContainerTask from flytekit.core.reference_entity import ReferenceEntity, WorkflowReference", "at all # def wf(): # t1() # In the former case we", "that construct a DAG of tasks using the data flow between tasks. Unlike", "True and self.interruptible is not False: raise FlyteValidationException(f\"Interruptible must be boolean, {self.interruptible} invalid\")", "workflow is evaluated at serialization-time (aka compile-time). This is because while we can", "return self._inputs def __repr__(self): return super().__repr__() + f\"Nodes ({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\" def execute(self, **kwargs):", "# This condition is hit when this workflow (self) is being called as", "have to handle the fact that the wf could've been declared with a", "the workflow. # _local_execute should've already ensured that all the values in kwargs", "output_names: return None if len(output_names) == 1: return bindings[0] return tuple(bindings) def execute(self,", "not the workflow is in a ready state, which means * Has at", "declared # functionally, and 2) what a user would return in mock function.", "Every time an entity is added, mark it as used. The above function", "to re-evaluate. Or # we can re-evaluate. self._input_parameters = None super().__init__( name=name, workflow_metadata=metadata,", "python_type is None: if type(p) == list or type(p) == dict: raise FlyteValidationException(", "# Create a map that holds the outputs of each node. intermediate_node_outputs =", "user would return in mock function. That is, if it's a tuple, then", "return below from the output have to be pulled by fulfilling all of", "but essentially, this WorkflowMetadataDefaults class represents the defaults that are handed down to", "provided causes an issue with compilation, an error will be returned. \"\"\" def", "FlyteValidationException( f\"Binding data Promises have to be of the NodeOutput type {type(binding_data.promise)} found\"", "# Get default agruements and override with kwargs passed in input_kwargs = self.python_interface.default_inputs_as_kwargs", "received only one\") if len(output_names) != len(workflow_outputs): raise Exception(f\"Length mismatch {len(output_names)} vs {len(workflow_outputs)}\")", "list or type(p) == dict: raise FlyteValidationException( f\"If specifying a list or dict", "= get_promise_map(node.bindings, intermediate_node_outputs) # Handle the calling and outputs of each node's entity", "of output_tuple_name to understand that we're dealing with a one-element # named tuple", "the outputs of the global input node, i.e. the inputs to the workflow.", "# Recreate new promises that use the workflow's output names. new_promises = [Promise(var,", "return self._workflow_metadata @property def workflow_metadata_defaults(self): return self._workflow_metadata_defaults @property def python_interface(self) -> Interface: return", "The reason the length 1 case is separate is because the one output", "else: if len(results) != len(expected_output_names): raise FlyteValueException(results, f\"Different lengths {results} {expected_output_names}\") for idx,", "{len(output_names)} vs {len(workflow_outputs)}\") for i, out in enumerate(output_names): if isinstance(workflow_outputs[i], ConditionalSection): raise AssertionError(\"A", "LaunchPlan, **kwargs) -> Node: return self.add_entity(launch_plan, **kwargs) def add_subwf(self, sub_wf: WorkflowBase, **kwargs) ->", "and isinstance(results, tuple): intermediate_node_outputs[node][expected_output_names[0]] = results[0] else: intermediate_node_outputs[node][expected_output_names[0]] = results else: if len(results)", "unbound inputs construct is just here to help workflow authors detect issues a", "more information but essentially, this WorkflowMetadataDefaults class represents the defaults that are handed", "return output_tuple(*nones) else: return None # We are already in a local execution,", "non-Flyte entities since they are only run once (again, this is with respect", "workflow_metadata_defaults self._python_interface = python_interface self._interface = transform_interface_to_typed_interface(python_interface) self._inputs = {} self._unbound_inputs = set()", "while we can determine the entire structure of a task by looking at", "the outputs of each node. intermediate_node_outputs = {GLOBAL_START_NODE: {}} # type: Dict[Node, Dict[str,", "is an error that Admin would return at compile time anyways, but this", "elif len(output_names) > 1: if not isinstance(workflow_outputs, tuple): raise AssertionError(\"The Workflow specification indicates", "Promises so let's filter for those. # There's probably a way to clean", "self.interruptible is not False: raise FlyteValidationException(f\"Interruptible must be boolean, {self.interruptible} invalid\") def to_flyte_model(self):", "not False: raise FlyteValidationException(f\"Interruptible must be boolean, {self.interruptible} invalid\") def to_flyte_model(self): return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible)", "that use the workflow's output names. new_promises = [Promise(var, wf_outputs_as_literal_dict[var]) for var in", "to the workflow. The nodes in these Promise objects should always point to", "False return True class PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver): \"\"\" Please read :std:ref:`flyte:divedeep-workflows` first for a", "Please see the IDL for more information but essentially, this WorkflowMetadataDefaults class represents", "Promise(var=k, val=TypeEngine.to_literal(ctx, v, t, self.interface.inputs[k].type)) # The output of this will always be", "presence of output_tuple_name to understand that we're dealing with a one-element # named", "== self: logger.debug(f\"WF {self.name} saving task {n.flyte_entity.name}\") self.add(n.flyte_entity) # Iterate through the workflow", "This is done to support the invariant that Workflow local executions always work", "single element return get_promise(self.output_bindings[0].binding, intermediate_node_outputs) return tuple([get_promise(b.binding, intermediate_node_outputs) for b in self.output_bindings]) def", "ctx.compilation_state is not None else \"\" with FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self)) ) as comp_ctx:", "this workflow are by default interruptible \"\"\" def wrapper(fn): workflow_metadata = WorkflowMetadata(on_failure=failure_policy or", "agruements and override with kwargs passed in input_kwargs = self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs) # The", "a single element then we return a single element if len(self.output_bindings) == 1:", "t = self.python_interface.outputs[output_names[0]] b = binding_from_python_std( ctx, output_names[0], self.interface.outputs[output_names[0]].type, workflow_outputs, t, ) bindings.append(b)", "interruptible: bool def __post_init__(self): if self.interruptible is not True and self.interruptible is not", "or None.\") # if there's only one output, if len(expected_output_names) == 1: if", "self._python_interface.with_outputs(extra_outputs={output_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) def add_task(self, task: PythonTask, **kwargs) -> Node: return", "from previously completed nodes and filling in the necessary inputs. \"\"\" entity_kwargs =", "body of the workflow to the workflow # object itself. for n in", "the # conversion here in this loop. The reason is because we don't", "# First handle the empty return case. # A workflow function may return", "which do additional checking. \"\"\" if len(self.compilation_state.nodes) == 0: return False if len(self._unbound_inputs)", "if output_name in self._python_interface.outputs: raise FlyteValidationException(f\"Output {output_name} already exists in workflow {self.name}\") if", "None else: raise Exception(f\"Workflow local execution expected 0 outputs but something received {result}\")", "and tasks. Since tasks call execute from dispatch_execute which is in _local_execute, workflows", "in binding_data.collection.bindings: p = get_promise(bd, outputs_cache) literals.append(p.val) return Promise( var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), ) elif", "get_input_values(kwargs) for input_value in filter(lambda x: isinstance(x, Promise), all_input_values): if input_value in self._unbound_inputs:", "inputs, if any input_kwargs = construct_input_promises([k for k in self.interface.inputs.keys()]) input_kwargs.update(kwargs) workflow_outputs =", "-> str: return self._name.split(\".\")[-1] @property def workflow_metadata(self) -> Optional[WorkflowMetadata]: return self._workflow_metadata @property def", ") bindings.append(b) elif len(output_names) > 1: if not isinstance(workflow_outputs, tuple): raise AssertionError(\"The Workflow", "results else: if len(results) != len(expected_output_names): raise FlyteValueException(results, f\"Different lengths {results} {expected_output_names}\") for", "tracker map we have. entity = node.flyte_entity entity_kwargs = get_promise_map(node.bindings, intermediate_node_outputs) # Handle", "this workflow class inherits from (ClassStorageTaskResolver) # does store state. This loop adds", "entity(**entity_kwargs) expected_output_names = list(entity.python_interface.outputs.keys()) if isinstance(results, VoidPromise) or results is None: continue #", "name: str, version: str, ) -> Callable[[Callable[..., Any]], ReferenceWorkflow]: \"\"\" A reference workflow", "place of propeller in resolving bindings, pulling in outputs from previously completed nodes", "of Promises, you must specify the python_type type for {output_name}\" f\" starting with", "\" f\"Output bindings: {self._output_bindings} && \" ) def __call__(self, *args, **kwargs): \"\"\" The", "outputs: Dict[str, Type] ): super().__init__(WorkflowReference(project, domain, name, version), inputs, outputs) def reference_workflow( project:", "import ConditionalSection from flytekit.core.context_manager import ( BranchEvalMode, CompilationState, ExecutionState, FlyteContext, FlyteContextManager, FlyteEntities, )", "get_promise(binding_data: _literal_models.BindingData, outputs_cache: Dict[Node, Dict[str, Promise]]) -> Promise: \"\"\" This is a helper", "to match what 1) what the workflow would've returned had it been declared", "WorkflowMetadataDefaults(interruptible) self._compilation_state = CompilationState(prefix=\"\") self._inputs = {} # This unbound inputs construct is", "= [] self._output_bindings: Optional[List[_literal_models.Binding]] = [] FlyteEntities.entities.append(self) super().__init__(**kwargs) @property def name(self) -> str:", "of value? all_input_values = get_input_values(kwargs) for input_value in filter(lambda x: isinstance(x, Promise), all_input_values):", "0: if result is None or isinstance(result, VoidPromise): return None else: raise Exception(f\"Workflow", "Flyte. That is, workflows should not call non-Flyte entities since they are only", "i, out in enumerate(output_names): if isinstance(workflow_outputs[i], ConditionalSection): raise AssertionError(\"A Conditional block (if-else) should", "a task by looking at the function's signature, workflows need to run through", "passed and represents the decorated function. :param failure_policy: Use the options in flytekit.WorkflowFailurePolicy", "named tuple, then we do a one-element non-named tuple, # if it's a", "= get_promise(b.binding, outputs_cache) return entity_kwargs class WorkflowBase(object): def __init__( self, name: str, workflow_metadata:", "to repackage the promises coming from the tasks into Promises that match the", "raise AssertionError(\"Only Keyword Arguments are supported for Workflow executions\") ctx = FlyteContextManager.current_context() #", "be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: b = binding_from_python_std( ctx, output_name, expected_literal_type=flyte_type, t_value=p,", "PythonAutoContainerTask) -> str: return f\"{self.name}.{t.__module__}.{t.name}\" def compile(self, **kwargs): \"\"\" Supply static Python native", "from flytekit.core.context_manager import ( BranchEvalMode, CompilationState, ExecutionState, FlyteContext, FlyteContextManager, FlyteEntities, ) from flytekit.core.interface", ") self._output_bindings.append(b) self._python_interface = self._python_interface.with_outputs(extra_outputs={output_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) def add_task(self, task: PythonTask,", "_workflow_function: This argument is implicitly passed and represents the decorated function. :param failure_policy:", "Flyte installation. This object will not initiate a network call to Admin, which", "values that we return below from the output have to be pulled by", "**kwargs) def add_launch_plan(self, launch_plan: LaunchPlan, **kwargs) -> Node: return self.add_entity(launch_plan, **kwargs) def add_subwf(self,", "handed down to a workflow's tasks, whereas WorkflowMetadata represents metadata about the workflow", "== 0: if result is None or isinstance(result, VoidPromise): return None else: raise", "and Promises containing Flyte # Literals. function_outputs = self.execute(**kwargs) # First handle the", "Recreate new promises that use the workflow's output names. new_promises = [Promise(var, wf_outputs_as_literal_dict[var])", "but haven't yet consumed. This # is an error that Admin would return", "* All workflow inputs are bound These conditions assume that all nodes and", "# type: Dict[Node, Dict[str, Promise]] # Start things off with the outputs of", "is done to support the invariant that Workflow local executions always work with", "_literal_models from flytekit.models.core import workflow as _workflow_model GLOBAL_START_NODE = Node( id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None, bindings=[],", "is run, for the ImperativeWorkflow, each node is run one at a time.", "is not None: raise Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: n", "loop adds Tasks that are defined within the body of the workflow to", "are stored in this map. After all nodes are run, we fill in", "by looking up the promises the node's bindings require, # and then fill", "transform_signature_to_interface(inspect.signature(workflow_function)) # TODO do we need this - can this not be in", "dict: raise FlyteValidationException( f\"If specifying a list or dict of Promises, you must", "input_kwargs = construct_input_promises([k for k in self.interface.inputs.keys()]) input_kwargs.update(kwargs) workflow_outputs = self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes) #", "get_promise_map(node.bindings, intermediate_node_outputs) # Handle the calling and outputs of each node's entity results", "dataclass from enum import Enum from typing import Any, Callable, Dict, List, Optional,", "at a time, one task or other entity call at a time. This", "(get_promise(self.output_bindings[0].binding, intermediate_node_outputs),) # Just a normal single element return get_promise(self.output_bindings[0].binding, intermediate_node_outputs) return tuple([get_promise(b.binding,", "val=_literal_models.Literal(scalar=binding_data.scalar)) elif binding_data.collection is not None: literals = [] for bd in binding_data.collection.bindings:", "from (ClassStorageTaskResolver) # does store state. This loop adds Tasks that are defined", "only one return value, received {len(workflow_outputs)}\" ) if self.python_interface.output_tuple_name is None: raise AssertionError(", "outputs do not match\") def execute(self, **kwargs): raise Exception(\"Should not be called\") def", "function, all inputs to that entity should've been already declared, we can just", "a combination of Python native values and Promises containing Flyte # Literals. function_outputs", "That is, workflows should not call non-Flyte entities since they are only run", "this takes the place of propeller in resolving bindings, pulling in outputs from", "outputs) def reference_workflow( project: str, domain: str, name: str, version: str, ) ->", "function's signature, workflows need to run through the function itself because the body", "[] prefix = f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if ctx.compilation_state is not None else \"\" with FlyteContextManager.with_context(", "to provide the expected interface. If at registration time the interface provided causes", "workflow_function: Callable, metadata: Optional[WorkflowMetadata], default_metadata: Optional[WorkflowMetadataDefaults], ): name = f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function = workflow_function", "__init__( self, name: str, workflow_metadata: WorkflowMetadata, workflow_metadata_defaults: WorkflowMetadataDefaults, python_interface: Interface, **kwargs, ): self._name", "Promise objects for k, v in kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k] = v # Next iterate", "it for the workflow as a whole rather # than just one node", "self._interface = transform_interface_to_typed_interface(python_interface) self._inputs = {} self._unbound_inputs = set() self._nodes = [] self._output_bindings:", "implicitly passed and represents the decorated function. :param failure_policy: Use the options in", "been VoidPromise or None.\") # if there's only one output, if len(expected_output_names) ==", "is separate is because the one output might be a list. We don't", "elif binding_data.collection is not None: literals = [] for bd in binding_data.collection.bindings: p", "== dict: raise FlyteValidationException( f\"If specifying a list or dict of Promises, you", "provide the expected interface. If at registration time the interface provided causes an", "version: str, inputs: Dict[str, Type], outputs: Dict[str, Type] ): super().__init__(WorkflowReference(project, domain, name, version),", "we don't prevent users from specifying inputs # as direct scalars, which means", "r # The rest of this function looks like the above but now", "the values in kwargs are Promise objects for k, v in kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k]", "in expected_output_names] return create_task_output(new_promises, self.python_interface) class ImperativeWorkflow(WorkflowBase): def __init__( self, name: str, failure_policy:", "now we're doing it for the workflow as a whole rather # than", "the :py:func:`@workflow <flytekit.workflow>` decorator. Please see notes on that object for additional information.", "these Promise objects should always point to the global start node. \"\"\" return", "expected_outputs == 1): return create_native_named_tuple(ctx, result, self.python_interface) raise ValueError(\"expected outputs and actual outputs", "each node is run one at a time. \"\"\" if len(args) > 0:", "global start node. \"\"\" return self._inputs def __repr__(self): return super().__repr__() + f\"Nodes ({len(self.compilation_state.nodes)}):", "collections import inspect from dataclasses import dataclass from enum import Enum from typing", "change. The task resolver interface itself is # more or less stateless (the", "at a time. \"\"\" if len(args) > 0: raise AssertionError(\"Only Keyword Arguments are", "we should let the binding creation unwrap it and make a binding #", "a task that doesn't return anything # def wf(): # return t1() #", "VoidPromise(self.name) # The values that we return below from the output have to", "f\"{function_outputs} received but interface has {len(self.python_interface.outputs)} outputs.\", ) return VoidPromise(self.name) # Because we", "indicates only one return value, received {len(workflow_outputs)}\" ) if self.python_interface.output_tuple_name is None: raise", "{self._name} && \" f\"Inputs ({len(self._python_interface.inputs)}): {self._python_interface.inputs} && \" f\"Outputs ({len(self._python_interface.outputs)}): {self._python_interface.outputs} && \"", "the upstream node's output we want return outputs_cache[binding_data.promise.node][binding_data.promise.var] elif binding_data.scalar is not None:", "to be Promises, we don't have to do the # conversion here in", "essentially, this WorkflowMetadataDefaults class represents the defaults that are handed down to a", "of this function looks like the above but now we're doing it for", "len(self._unbound_inputs) > 0: return False return True class PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver): \"\"\" Please read", "Any, Callable, Dict, List, Optional, Tuple, Type, Union from flytekit.common import constants as", "f\"Binding data Promises have to be of the NodeOutput type {type(binding_data.promise)} found\" )", "is close to, but not exactly, the call pattern for Tasks. For local", "tuple here, if it's a one element named tuple, then we do a", "FlyteEntities, ) from flytekit.core.interface import ( Interface, transform_inputs_to_parameters, transform_interface_to_typed_interface, transform_signature_to_interface, ) from flytekit.core.launch_plan", "return create_native_named_tuple(ctx, result, self.python_interface) raise ValueError(\"expected outputs and actual outputs do not match\")", "which is why the user is asked to provide the expected interface. If", "new Promises wf_outputs_as_literal_dict = translate_inputs_to_literals( ctx, wf_outputs_as_map, flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs, ) # Recreate new", "> 1: if not isinstance(workflow_outputs, tuple): raise AssertionError(\"The Workflow specification indicates multiple return", "flytekit.WorkflowFailurePolicy :param interruptible: Whether or not tasks launched from this workflow are by", "import TypeEngine from flytekit.loggers import logger from flytekit.models import interface as _interface_models from", "error here. if len(self.python_interface.outputs) == 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but should've", "Workflows is close to, but not exactly, the call pattern for Tasks. For", "t_value=p, t_value_type=python_type ) self._output_bindings.append(b) self._python_interface = self._python_interface.with_outputs(extra_outputs={output_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) def add_task(self,", "promises coming from the tasks into Promises that match the workflow's # interface.", "short_name(self) -> str: return self._name.split(\".\")[-1] @property def workflow_metadata(self) -> Optional[WorkflowMetadata]: return self._workflow_metadata @property", "run once (again, this is with respect to the platform, local runs notwithstanding).", "do that by extracting out the literals, and creating new Promises wf_outputs_as_literal_dict =", "task # binding_data.promise.var is the name of the upstream node's output we want", "wf_outputs_as_map = {expected_output_names[0]: function_outputs[0]} else: wf_outputs_as_map = {expected_output_names[0]: function_outputs} else: wf_outputs_as_map = {expected_output_names[i]:", "def add_launch_plan(self, launch_plan: LaunchPlan, **kwargs) -> Node: return self.add_entity(launch_plan, **kwargs) def add_subwf(self, sub_wf:", "self.python_interface.outputs.keys()] output_tuple = collections.namedtuple(self.python_interface.output_tuple_name, variables) nones = [None for _ in self.python_interface.outputs.keys()] return", "This function will fill in the node's entity's input arguments, which are specified", "from the output have to be pulled by fulfilling all of the #", "are bound These conditions assume that all nodes and workflow i/o changes were", "if isinstance(workflow_outputs, tuple): if len(workflow_outputs) != 1: raise AssertionError( f\"The Workflow specification indicates", "should be a tuple here, if it's a one element named tuple, then", "return tuple(bindings) def execute(self, **kwargs): \"\"\" This function is here only to try", "loop. The reason is because we don't prevent users from specifying inputs #", "task or other entity call at a time. This is why this workflow", "bindings, but then override with the provided inputs, if any input_kwargs = construct_input_promises([k", "logger.debug(f\"Inferring python type for wf output {output_name} from Promise provided {python_type}\") flyte_type =", "issue with compilation, an error will be returned. \"\"\" def wrapper(fn) -> ReferenceWorkflow:", "= {} for b in bindings: entity_kwargs[b.var] = get_promise(b.binding, outputs_cache) return entity_kwargs class", "Promises, we don't have to do the # conversion here in this loop.", "for var in expected_output_names] return create_task_output(new_promises, self.python_interface) class ImperativeWorkflow(WorkflowBase): def __init__( self, name:", "not call non-Flyte entities since they are only run once (again, this is", "After all nodes are run, we fill in workflow level outputs the same", "for the ImperativeWorkflow, each node is run one at a time. \"\"\" if", "the workflow. The nodes in these Promise objects should always point to the", "a Promise object, using a lookup map. Please see get_promise_map for the rest", "the workflow's output names. new_promises = [Promise(var, wf_outputs_as_literal_dict[var]) for var in expected_output_names] return", "constants as _common_constants from flytekit.common.exceptions.user import FlyteValidationException, FlyteValueException from flytekit.core.base_task import PythonTask from", "# as direct scalars, which means there's another Promise-generating loop inside _local_execute too", "outputs_cache: Dict[Node, Dict[str, Promise]]) -> Promise: \"\"\" This is a helper function that", "return create_and_link_node(ctx, entity=self, interface=self.python_interface, **input_kwargs) # This condition is hit when this workflow", "entity=self, interface=self.python_interface, **input_kwargs) # This condition is hit when this workflow (self) is", "here to help workflow authors detect issues a bit earlier. It just #", "function_outputs, f\"{function_outputs} received but should've been VoidPromise or None.\" ) expected_output_names = list(self.python_interface.outputs.keys())", "= 0 else: on_failure = 1 return _workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass class WorkflowMetadataDefaults(object): \"\"\" This", "an entity is added using the add_entity function, all inputs to that entity", "# should be a tuple here, if it's a one element named tuple,", "instead of value? all_input_values = get_input_values(kwargs) for input_value in filter(lambda x: isinstance(x, Promise),", "self._inputs: raise FlyteValidationException(f\"Input {input_name} has already been specified for wf {self.name}.\") self._python_interface =", "str, name: str, version: str, inputs: Dict[str, Type], outputs: Dict[str, Type] ): super().__init__(WorkflowReference(project,", "Whether or not tasks launched from this workflow are by default interruptible \"\"\"", "one. That convention is used for naming outputs - and single-length-NamedTuples are #", "as _interface_models from flytekit.models import literals as _literal_models from flytekit.models.core import workflow as", "for more usage examples. :param _workflow_function: This argument is implicitly passed and represents", "don't want to # iterate through the list here, instead we should let", "entity_kwargs class WorkflowBase(object): def __init__( self, name: str, workflow_metadata: WorkflowMetadata, workflow_metadata_defaults: WorkflowMetadataDefaults, python_interface:", "Python object represents a workflow defined by a function and decorated with the", "direct scalars, which means there's another Promise-generating loop inside _local_execute too for k,", "return a single element if len(self.output_bindings) == 1: # Again use presence of", "element named tuple, then we do a one-element non-named tuple, # if it's", "None.\") # if there's only one output, if len(expected_output_names) == 1: if entity.python_interface.output_tuple_name", "- {self._name} && \" f\"Inputs ({len(self._python_interface.inputs)}): {self._python_interface.inputs} && \" f\"Outputs ({len(self._python_interface.outputs)}): {self._python_interface.outputs} &&", "workflow_metadata=metadata, workflow_metadata_defaults=default_metadata, python_interface=native_interface, ) @property def function(self): return self._workflow_function def task_name(self, t: PythonAutoContainerTask)", "all_nodes self._output_bindings = bindings if not output_names: return None if len(output_names) == 1:", "@dataclass class WorkflowMetadataDefaults(object): \"\"\" This class is similarly named to the one above.", "the details. \"\"\" if binding_data.promise is not None: if not isinstance(binding_data.promise, NodeOutput): raise", "@property def workflow_metadata(self) -> Optional[WorkflowMetadata]: return self._workflow_metadata @property def workflow_metadata_defaults(self): return self._workflow_metadata_defaults @property", "the execution context return self._local_execute(ctx, **input_kwargs) # Last is starting a local workflow", "the pattern between workflows and tasks. Since tasks call execute from dispatch_execute which", "if self.interruptible is not True and self.interruptible is not False: raise FlyteValidationException(f\"Interruptible must", "defined within the body of the workflow to the workflow # object itself.", "None: continue # pragma: no cover # Move along, nothing to assign #", "return create_task_output(new_promises, self.python_interface) class ImperativeWorkflow(WorkflowBase): def __init__( self, name: str, failure_policy: Optional[WorkflowFailurePolicy] =", "construct is just here to help workflow authors detect issues a bit earlier.", "Adds an input to the workflow. \"\"\" if input_name in self._inputs: raise FlyteValidationException(f\"Input", "being called as part of a parent's workflow local run. # The context", "argument {k}\") if isinstance(v, Promise): raise ValueError(f\"Received a promise for a workflow call,", "doing it for the workflow as a whole rather # than just one", "state. This loop adds Tasks that are defined within the body of the", "we fill in workflow level outputs the same way as any other previous", "= self.python_interface.outputs[output_names[0]] b = binding_from_python_std( ctx, output_names[0], self.interface.outputs[output_names[0]].type, workflow_outputs, t, ) bindings.append(b) elif", "we can just iterate through the nodes in order and we shouldn't run", "Dict[str, Promise]] # Start things off with the outputs of the global input", "= transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name] = Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) self._unbound_inputs.add(self._inputs[input_name]) return self._inputs[input_name] def add_workflow_output( self,", "None, interruptible: Optional[bool] = False, ): \"\"\" This decorator declares a function to", "fulfilling all of the # workflow's output bindings. # The return style here", "self._python_interface.outputs: raise FlyteValidationException(f\"Output {output_name} already exists in workflow {self.name}\") if python_type is None:", "literals as _literal_models from flytekit.models.core import workflow as _workflow_model GLOBAL_START_NODE = Node( id=_common_constants.GLOBAL_INPUT_NODE_ID,", "because the body of the function is what expresses the workflow structure. It's", "would've returned had it been declared # functionally, and 2) what a user", "if len(entity.python_interface.outputs) == 0: raise FlyteValueException(results, f\"{results} received but should've been VoidPromise or", "turn a binding into a Promise object, using a lookup map. Please see", "get None if isinstance(function_outputs, VoidPromise) or function_outputs is None: if len(self.python_interface.outputs) != 0:", "used. The above function though will gather all the input # values but", "adds Tasks that are defined within the body of the workflow to the", "troublesome but elegant handling of them is not a high priority # Again,", "PythonTask from flytekit.core.class_based_resolver import ClassStorageTaskResolver from flytekit.core.condition import ConditionalSection from flytekit.core.context_manager import (", "if not self.ready(): raise FlyteValidationException(f\"Workflow not ready, wf is currently {self}\") # Create", "None: literals = {} for k, bd in binding_data.map.bindings.items(): p = get_promise(bd, outputs_cache)", "the tasks into Promises that match the workflow's # interface. We do that", "track of workflow inputs that you've declared with add_workflow_input but haven't yet consumed.", "-> Interface: return self._python_interface @property def interface(self) -> _interface_models.TypedInterface: return self._interface @property def", "registration time the interface provided causes an issue with compilation, an error will", "word. \"\"\" ctx = FlyteContextManager.current_context() self._input_parameters = transform_inputs_to_parameters(ctx, self.python_interface) all_nodes = [] prefix", "Get default agruements and override with kwargs passed in input_kwargs = self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs)", "WorkflowMetadata, workflow_metadata_defaults: WorkflowMetadataDefaults, python_interface: Interface, **kwargs, ): self._name = name self._workflow_metadata = workflow_metadata", "their outputs are stored in this map. After all nodes are run, we", "it may not return at all # def wf(): # t1() # In", "unrecognized.\") def get_promise_map( bindings: List[_literal_models.Binding], outputs_cache: Dict[Node, Dict[str, Promise]] ) -> Dict[str, Promise]:", "reference_workflow( project: str, domain: str, name: str, version: str, ) -> Callable[[Callable[..., Any]],", "bool def __post_init__(self): if self.interruptible is not True and self.interruptible is not False:", "metadata: Optional[WorkflowMetadata], default_metadata: Optional[WorkflowMetadataDefaults], ): name = f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function = workflow_function native_interface =", "= binding_from_python_std( ctx, output_names[0], self.interface.outputs[output_names[0]].type, workflow_outputs, t, ) bindings.append(b) elif len(output_names) > 1:", "bit earlier. It just # keeps track of workflow inputs that you've declared", "is not None: literals = [] for bd in binding_data.collection.bindings: p = get_promise(bd,", "to the task # binding_data.promise.var is the name of the upstream node's output", "= list(entity.python_interface.outputs.keys()) if isinstance(results, VoidPromise) or results is None: continue # pragma: no", "represents metadata about the workflow itself. \"\"\" interruptible: bool def __post_init__(self): if self.interruptible", "flytekit.common import constants as _common_constants from flytekit.common.exceptions.user import FlyteValidationException, FlyteValueException from flytekit.core.base_task import", "error that Admin would return at compile time anyways, but this allows flytekit", "single element then we return a single element if len(self.output_bindings) == 1: #", "# Start things off with the outputs of the global input node, i.e.", "{self._output_bindings} && \" ) def __call__(self, *args, **kwargs): \"\"\" The call pattern for", "add_task(self, task: PythonTask, **kwargs) -> Node: return self.add_entity(task, **kwargs) def add_launch_plan(self, launch_plan: LaunchPlan,", "Use the options in flytekit.WorkflowFailurePolicy :param interruptible: Whether or not tasks launched from", "in resolving bindings, pulling in outputs from previously completed nodes and filling in", "import ( Interface, transform_inputs_to_parameters, transform_interface_to_typed_interface, transform_signature_to_interface, ) from flytekit.core.launch_plan import LaunchPlan from flytekit.core.node", "transform_signature_to_interface, ) from flytekit.core.launch_plan import LaunchPlan from flytekit.core.node import Node from flytekit.core.promise import", "return workflow_instance if _workflow_function: return wrapper(_workflow_function) else: return wrapper class ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow): \"\"\"", "vs {len(workflow_outputs)}\") for i, out in enumerate(output_names): if isinstance(workflow_outputs[i], ConditionalSection): raise AssertionError(\"A Conditional", "FlyteValidationException(\"Binding type unrecognized.\") def get_promise_map( bindings: List[_literal_models.Binding], outputs_cache: Dict[Node, Dict[str, Promise]] ) ->", "workflow would've returned had it been declared # functionally, and 2) what a", "!= 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but interface has {len(self.python_interface.outputs)} outputs.\", )", "what a user would return in mock function. That is, if it's a", "_workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass class WorkflowMetadataDefaults(object): \"\"\" This class is similarly named to the one", "name=name, workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(), ) @property def compilation_state(self) -> CompilationState: \"\"\" Compilation is", "ctx.execution_state.branch_eval_mode == BranchEvalMode.BRANCH_SKIPPED: if self.python_interface and self.python_interface.output_tuple_name: variables = [k for k in", "imperative workflows runs. Because when an entity is added using the add_entity function,", "execute(self, **kwargs): \"\"\" This function is here only to try to streamline the", "match\") def execute(self, **kwargs): raise Exception(\"Should not be called\") def _local_execute(self, ctx: FlyteContext,", "of what workflows are in Flyte. This Python object represents a workflow defined", "len(self.python_interface.outputs) == 0: return VoidPromise(self.name) # The values that we return below from", "interested in the ones that are Promises so let's filter for those. #", "too for k, v in input_kwargs.items(): if k not in self.interface.inputs: raise ValueError(f\"Received", "# This little loop was added as part of the task resolver change.", "def compile(self, **kwargs): \"\"\" Supply static Python native values in the kwargs if", "the ImperativeWorkflow, each node is run one at a time. \"\"\" if len(args)", "a bit earlier. It just # keeps track of workflow inputs that you've", "you've declared with add_workflow_input but haven't yet consumed. This # is an error", "ClassStorageTaskResolver from flytekit.core.condition import ConditionalSection from flytekit.core.context_manager import ( BranchEvalMode, CompilationState, ExecutionState, FlyteContext,", "filling in the necessary inputs. \"\"\" entity_kwargs = {} for b in bindings:", "output bindings. # The return style here has to match what 1) what", "is, if it's a tuple, then it # should be a tuple here,", "to declare entities already in a topological sort. To keep track of outputs,", "an error here. if len(self.python_interface.outputs) == 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but", "variables) nones = [None for _ in self.python_interface.outputs.keys()] return output_tuple(*nones) else: return None", "handle the empty return case. # A workflow function may return a task", "{len(self.python_interface.outputs)} outputs.\", ) return VoidPromise(self.name) # Because we should've already returned in the", "what the workflow would've returned had it been declared # functionally, and 2)", "class represents the defaults that are handed down to a workflow's tasks, whereas", "= {} # This unbound inputs construct is just here to help workflow", "isinstance(binding_data.promise, NodeOutput): raise FlyteValidationException( f\"Binding data Promises have to be of the NodeOutput", "workflow's output names. new_promises = [Promise(var, wf_outputs_as_literal_dict[var]) for var in expected_output_names] return create_task_output(new_promises,", "python_interface(self) -> Interface: return self._python_interface @property def interface(self) -> _interface_models.TypedInterface: return self._interface @property", "it's a single element then we return a single element if len(self.output_bindings) ==", "with the :py:func:`@workflow <flytekit.workflow>` decorator. Please see notes on that object for additional", "Python native value. for k, v in kwargs.items(): if not isinstance(v, Promise): t", "Literals. function_outputs = self.execute(**kwargs) # First handle the empty return case. # A", "_local_execute. This makes mocking cleaner. \"\"\" return self._workflow_function(**kwargs) def workflow( _workflow_function=None, failure_policy: Optional[WorkflowFailurePolicy]", "from flytekit.core.condition import ConditionalSection from flytekit.core.context_manager import ( BranchEvalMode, CompilationState, ExecutionState, FlyteContext, FlyteContextManager,", "except for the missing project and domain self._nodes = all_nodes self._output_bindings = bindings", "*args, **kwargs): \"\"\" The call pattern for Workflows is close to, but not", "to_flyte_model(self): return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def construct_input_promises(inputs: List[str]): return { input_name: Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) for", "add_workflow_output( self, output_name: str, p: Union[Promise, List[Promise], Dict[str, Promise]], python_type: Optional[Type] = None", "tuple([get_promise(b.binding, intermediate_node_outputs) for b in self.output_bindings]) def add_entity(self, entity: Union[PythonTask, LaunchPlan, WorkflowBase], **kwargs)", "return _workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass class WorkflowMetadataDefaults(object): \"\"\" This class is similarly named to the", "t, self.interface.inputs[k].type)) # The output of this will always be a combination of", "declare entities already in a topological sort. To keep track of outputs, we", "<flytekit.workflow>` decorator. Please see notes on that object for additional information. \"\"\" def", "return Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar)) elif binding_data.collection is not None: literals = [] for bd", "get the task's VoidPromise, in the latter we get None if isinstance(function_outputs, VoidPromise)", "be used in the compilation. This mimics a 'closure' in the traditional sense", "local execution, just continue the execution context return self._local_execute(ctx, **input_kwargs) # Last is", "child_ctx: result = self._local_execute(child_ctx, **input_kwargs) expected_outputs = len(self.python_interface.outputs) if expected_outputs == 0: if", "for a high-level understanding of what workflows are in Flyte. This Python object", "return entity_kwargs class WorkflowBase(object): def __init__( self, name: str, workflow_metadata: WorkflowMetadata, workflow_metadata_defaults: WorkflowMetadataDefaults,", "def add_subwf(self, sub_wf: WorkflowBase, **kwargs) -> Node: return self.add_entity(sub_wf, **kwargs) def ready(self) ->", "def add_task(self, task: PythonTask, **kwargs) -> Node: return self.add_entity(task, **kwargs) def add_launch_plan(self, launch_plan:", "is here only so that we don't have to re-evaluate. Or # we", "the former case we get the task's VoidPromise, in the latter we get", "= get_input_values(kwargs) for input_value in filter(lambda x: isinstance(x, Promise), all_input_values): if input_value in", "Callable[[Callable[..., Any]], ReferenceWorkflow]: \"\"\" A reference workflow is a pointer to a workflow", "if any input_kwargs = construct_input_promises([k for k in self.interface.inputs.keys()]) input_kwargs.update(kwargs) workflow_outputs = self._workflow_function(**input_kwargs)", "binding creation unwrap it and make a binding # collection/map out of it.", "-> List[Node]: return self._nodes def __repr__(self): return ( f\"WorkflowBase - {self._name} && \"", "input promises to the workflow. The nodes in these Promise objects should always", "for k, v in kwargs.items(): if not isinstance(v, Promise): t = self.python_interface.inputs[k] kwargs[k]", "represents a workflow defined by a function and decorated with the :py:func:`@workflow <flytekit.workflow>`", "in enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]] = r # The rest of this function looks like", "note that, local execution notwithstanding, it is not evaluated again when the workflow", "task that doesn't return anything # def wf(): # return t1() # or", "an Exception here. if len(entity.python_interface.outputs) == 0: raise FlyteValueException(results, f\"{results} received but should've", "in a wf, a user can call a sub-workflow with a Python native", "is not None: literals = {} for k, bd in binding_data.map.bindings.items(): p =", "takes the place of propeller in resolving bindings, pulling in outputs from previously", "This function returns whether or not the workflow is in a ready state,", "return input_promises else: return [input_value] # Every time an entity is added, mark", "workflow function may return a task that doesn't return anything # def wf():", "the workflow # object itself. for n in comp_ctx.compilation_state.nodes: if isinstance(n.flyte_entity, PythonAutoContainerTask) and", "Just a normal single element return get_promise(self.output_bindings[0].binding, intermediate_node_outputs) return tuple([get_promise(b.binding, intermediate_node_outputs) for b", "declarative entities that construct a DAG of tasks using the data flow between", "WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) self._compilation_state = CompilationState(prefix=\"\") self._inputs = {} # This unbound", "Flyte workflow. Workflows are declarative entities that construct a DAG of tasks using", "is not evaluated again when the workflow runs on Flyte. That is, workflows", "execution, it goes __call__ -> _local_execute -> execute From execute, different things happen", "class is similarly named to the one above. Please see the IDL for", "entity, all the inputs to the entity must be bound. \"\"\" # circular", "# binding_data.promise.var is the name of the upstream node's output we want return", "instead we should let the binding creation unwrap it and make a binding", "work with Promise objects # holding Flyte literal values. Even in a wf,", "-> Node: \"\"\" Anytime you add an entity, all the inputs to the", "input_value: input_promises.extend(get_input_values(x)) return input_promises if isinstance(input_value, dict): input_promises = [] for _, v", "run into any dependency issues. That is, we force the user to declare", "supported for Workflow executions\") ctx = FlyteContextManager.current_context() # Get default agruements and override", "acceptable\") def to_flyte_model(self): if self.on_failure == WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure = 0 else: on_failure =", "task: PythonTask, **kwargs) -> Node: return self.add_entity(task, **kwargs) def add_launch_plan(self, launch_plan: LaunchPlan, **kwargs)", "python_type: Type) -> Interface: \"\"\" Adds an input to the workflow. \"\"\" if", "Interface, transform_inputs_to_parameters, transform_interface_to_typed_interface, transform_signature_to_interface, ) from flytekit.core.launch_plan import LaunchPlan from flytekit.core.node import Node", "self._compilation_state.nodes @property def inputs(self) -> Dict[str, Promise]: \"\"\" This holds the input promises", "def __repr__(self): return super().__repr__() + f\"Nodes ({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\" def execute(self, **kwargs): \"\"\" Called", "def function(self): return self._workflow_function def task_name(self, t: PythonAutoContainerTask) -> str: return f\"{self.name}.{t.__module__}.{t.name}\" def", "cleaner. \"\"\" return self._workflow_function(**kwargs) def workflow( _workflow_function=None, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool]", "# we can re-evaluate. self._input_parameters = None super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=default_metadata, python_interface=native_interface, )", "== 1: # Again use presence of output_tuple_name to understand that we're dealing", "all_input_values = get_input_values(kwargs) for input_value in filter(lambda x: isinstance(x, Promise), all_input_values): if input_value", "a Flyte workflow. Workflows are declarative entities that construct a DAG of tasks", "WorkflowMetadataDefaults, python_interface: Interface, **kwargs, ): self._name = name self._workflow_metadata = workflow_metadata self._workflow_metadata_defaults =", "= FlyteContextManager.current_context() # Get default agruements and override with kwargs passed in input_kwargs", "and ctx.execution_state.mode == ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ): if ctx.execution_state.branch_eval_mode == BranchEvalMode.BRANCH_SKIPPED: if self.python_interface and self.python_interface.output_tuple_name:", "result = self._local_execute(child_ctx, **input_kwargs) expected_outputs = len(self.python_interface.outputs) if expected_outputs == 0: if result", "be a list. We don't want to # iterate through the list here,", "want them to be used in the compilation. This mimics a 'closure' in", "entity = node.flyte_entity entity_kwargs = get_promise_map(node.bindings, intermediate_node_outputs) # Handle the calling and outputs", "or (result is not None and expected_outputs == 1): return create_native_named_tuple(ctx, result, self.python_interface)", "ctx = FlyteContextManager.current_context() self._input_parameters = transform_inputs_to_parameters(ctx, self.python_interface) all_nodes = [] prefix = f\"{ctx.compilation_state.prefix}-{self.short_name}-\"", "as ctx: n = create_node(entity=entity, **kwargs) def get_input_values(input_value): if isinstance(input_value, list): input_promises =", "BranchEvalMode, CompilationState, ExecutionState, FlyteContext, FlyteContextManager, FlyteEntities, ) from flytekit.core.interface import ( Interface, transform_inputs_to_parameters,", "along, nothing to assign # Because we should've already returned in the above", "and make a binding # collection/map out of it. if len(output_names) == 1:", "out in enumerate(output_names): if isinstance(workflow_outputs[i], ConditionalSection): raise AssertionError(\"A Conditional block (if-else) should always", "_ in enumerate(function_outputs)} # Basically we need to repackage the promises coming from", "def task_name(self, t: PythonAutoContainerTask) -> str: return f\"{self.name}.{t.__module__}.{t.name}\" def compile(self, **kwargs): \"\"\" Supply", "the container type (e.g. List[int]\" ) python_type = p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring python type for", "b = binding_from_python_std( ctx, output_names[0], self.interface.outputs[output_names[0]].type, workflow_outputs, t, ) bindings.append(b) elif len(output_names) >", "False, ): \"\"\" This decorator declares a function to be a Flyte workflow.", "WorkflowMetadataDefaults class represents the defaults that are handed down to a workflow's tasks,", "one output, if len(expected_output_names) == 1: if entity.python_interface.output_tuple_name and isinstance(results, tuple): intermediate_node_outputs[node][expected_output_names[0]] =", "loop inside _local_execute too for k, v in input_kwargs.items(): if k not in", "a one-element # named tuple if self.python_interface.output_tuple_name: return (get_promise(self.output_bindings[0].binding, intermediate_node_outputs),) # Just a", "already been set. elif ( ctx.execution_state is not None and ctx.execution_state.mode == ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION", "{python_type}\") flyte_type = TypeEngine.to_literal_type(python_type=python_type) ctx = FlyteContext.current_context() if ctx.compilation_state is not None: raise", "{self.compilation_state.nodes}\" def execute(self, **kwargs): \"\"\" Called by _local_execute. This function is how local", "part of the task resolver change. The task resolver interface itself is #", "elif binding_data.map is not None: literals = {} for k, bd in binding_data.map.bindings.items():", "to run through the function itself because the body of the function is", "def __post_init__(self): if self.interruptible is not True and self.interruptible is not False: raise", "in input_kwargs = self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs) # The first condition is compilation. if ctx.compilation_state", "Promise]] # Start things off with the outputs of the global input node,", "_local_execute(self, ctx: FlyteContext, **kwargs) -> Union[Tuple[Promise], Promise, VoidPromise]: # This is done to", "then it # should be a tuple here, if it's a one element", "= self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes) # This little loop was added as part of the", "workflow class inherits from (ClassStorageTaskResolver) # does store state. This loop adds Tasks", "inspect from dataclasses import dataclass from enum import Enum from typing import Any,", "Optional[Type] = None ): \"\"\" Add an output with the given name from", "stateless (the future-proofing get_all_tasks function notwithstanding). However the # implementation of the TaskResolverMixin", "for {k}\") with FlyteContextManager.with_context( ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) ) ) as child_ctx: result = self._local_execute(child_ctx,", "We do that by extracting out the literals, and creating new Promises wf_outputs_as_literal_dict", "== 0: return VoidPromise(self.name) # The values that we return below from the", "List[Promise], Dict[str, Promise]], python_type: Optional[Type] = None ): \"\"\" Add an output with", "execute inside _local_execute. This makes mocking cleaner. \"\"\" return self._workflow_function(**kwargs) def workflow( _workflow_function=None,", "\"\"\" This function is here only to try to streamline the pattern between", "always point to the global start node. \"\"\" return self._inputs def __repr__(self): return", "to be a Flyte workflow. Workflows are declarative entities that construct a DAG", "_local_execute. This function is how local execution for imperative workflows runs. Because when", "tuple): if len(workflow_outputs) != 1: raise AssertionError( f\"The Workflow specification indicates only one", "to raise # the error earlier. self._unbound_inputs = set() super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults,", "create_native_named_tuple(ctx, result, self.python_interface) raise ValueError(\"expected outputs and actual outputs do not match\") def", "we need to repackage the promises coming from the tasks into Promises that", "flytekit to raise # the error earlier. self._unbound_inputs = set() super().__init__( name=name, workflow_metadata=metadata,", "node. intermediate_node_outputs = {GLOBAL_START_NODE: {}} # type: Dict[Node, Dict[str, Promise]] # Start things", "metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) self._compilation_state = CompilationState(prefix=\"\") self._inputs =", "tasks into Promises that match the workflow's # interface. We do that by", "off, filled in only with the workflow inputs (if any). As things are", "python_type = p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring python type for wf output {output_name} from Promise provided", "rest of this function looks like the above but now we're doing it", "the name of the input to the task # binding_data.promise.var is the name", "Dict[str, Promise]: \"\"\" This holds the input promises to the workflow. The nodes", "will not initiate a network call to Admin, which is why the user", "output_name, expected_literal_type=flyte_type, t_value=p, t_value_type=python_type ) self._output_bindings.append(b) self._python_interface = self._python_interface.with_outputs(extra_outputs={output_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface)", "self.interface.outputs[out].type, workflow_outputs[i], t, ) bindings.append(b) # Save all the things necessary to create", "Admin would return at compile time anyways, but this allows flytekit to raise", "wf_outputs_as_map = {expected_output_names[0]: function_outputs} else: wf_outputs_as_map = {expected_output_names[i]: function_outputs[i] for i, _ in", "of the workflow to the workflow # object itself. for n in comp_ctx.compilation_state.nodes:", "it is not evaluated again when the workflow runs on Flyte. That is,", "already returned in the above check, we just raise an error here. if", "of a parent's workflow local run. # The context specifying the local workflow", "with respect to the platform, local runs notwithstanding). Please see the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for", "will gather all the input # values but we're only interested in the", "them is not a high priority # Again, we're using the output_tuple_name as", "transform_interface_to_typed_interface(python_interface) self._inputs = {} self._unbound_inputs = set() self._nodes = [] self._output_bindings: Optional[List[_literal_models.Binding]] =", "through the list here, instead we should let the binding creation unwrap it", "enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]] = r # The rest of this function looks like the", "< expected_outputs == len(result)) or (result is not None and expected_outputs == 1):", "state. \"\"\" return self._compilation_state @property def nodes(self) -> List[Node]: return self._compilation_state.nodes @property def", "with kwargs passed in input_kwargs = self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs) # The first condition is", "# more or less stateless (the future-proofing get_all_tasks function notwithstanding). However the #", "return Promise( var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), ) elif binding_data.map is not None: literals = {}", "are declarative entities that construct a DAG of tasks using the data flow", "tasks. Since tasks call execute from dispatch_execute which is in _local_execute, workflows should", "self._output_bindings @property def nodes(self) -> List[Node]: return self._nodes def __repr__(self): return ( f\"WorkflowBase", "None and expected_outputs == 1): return create_native_named_tuple(ctx, result, self.python_interface) raise ValueError(\"expected outputs and", "task resolver change. The task resolver interface itself is # more or less", ":std:ref:`flyte:divedeep-workflows` first for a high-level understanding of what workflows are in Flyte. This", "failure_policy: Use the options in flytekit.WorkflowFailurePolicy :param interruptible: Whether or not tasks launched", "map to start things off, filled in only with the workflow inputs (if", "self.python_interface.output_tuple_name: variables = [k for k in self.python_interface.outputs.keys()] output_tuple = collections.namedtuple(self.python_interface.output_tuple_name, variables) nones", "NodeOutput type {type(binding_data.promise)} found\" ) # b.var is the name of the input", "using a lookup map. Please see get_promise_map for the rest of the details.", "def add_workflow_input(self, input_name: str, python_type: Type) -> Interface: \"\"\" Adds an input to", "see notes on that object for additional information. \"\"\" def __init__( self, workflow_function:", "native values in the kwargs if you want them to be used in", "we can re-evaluate. self._input_parameters = None super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=default_metadata, python_interface=native_interface, ) @property", "Workflow specification indicates only one return value, received {len(workflow_outputs)}\" ) if self.python_interface.output_tuple_name is", "This makes mocking cleaner. \"\"\" return self._workflow_function(**kwargs) def workflow( _workflow_function=None, failure_policy: Optional[WorkflowFailurePolicy] =", "WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ): raise FlyteValidationException(f\"Failure policy {self.on_failure} not acceptable\") def to_flyte_model(self): if self.on_failure ==", "workflow's tasks, whereas WorkflowMetadata represents metadata about the workflow itself. \"\"\" interruptible: bool", "if python_type is None: if type(p) == list or type(p) == dict: raise", "means there's another Promise-generating loop inside _local_execute too for k, v in input_kwargs.items():", "has already been specified for wf {self.name}.\") self._python_interface = self._python_interface.with_inputs(extra_inputs={input_name: python_type}) self._interface =", "self._unbound_inputs.remove(input_value) return n def add_workflow_input(self, input_name: str, python_type: Type) -> Interface: \"\"\" Adds", "name, version), inputs, outputs) def reference_workflow( project: str, domain: str, name: str, version:", "decorated function. :param failure_policy: Use the options in flytekit.WorkflowFailurePolicy :param interruptible: Whether or", "and decorated with the :py:func:`@workflow <flytekit.workflow>` decorator. Please see notes on that object", "\"\" with FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self)) ) as comp_ctx: # Construct the default input", "default_metadata: Optional[WorkflowMetadataDefaults], ): name = f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function = workflow_function native_interface = transform_signature_to_interface(inspect.signature(workflow_function)) #", "= {} # Retrieve the entity from the node, and call it by", "compilation. This mimics a 'closure' in the traditional sense of the word. \"\"\"", "p = get_promise(bd, outputs_cache) literals[k] = p.val return Promise( var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) ) raise", "get_promise_map for the rest of the details. \"\"\" if binding_data.promise is not None:", "AssertionError( f\"The Workflow specification indicates only one return value, received {len(workflow_outputs)}\" ) if", "compile-time). This is because while we can determine the entire structure of a", "_workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE = ( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ) @dataclass class WorkflowMetadata(object): on_failure: WorkflowFailurePolicy def __post_init__(self):", "raise AssertionError(\"The Workflow specification indicates multiple return values, received only one\") if len(output_names)", "_workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def construct_input_promises(inputs: List[str]): return { input_name: Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) for input_name in", "promises that use the workflow's output names. new_promises = [Promise(var, wf_outputs_as_literal_dict[var]) for var", "-> _interface_models.TypedInterface: return self._interface @property def output_bindings(self) -> List[_literal_models.Binding]: return self._output_bindings @property def", "yet consumed. This # is an error that Admin would return at compile", "that object for additional information. \"\"\" def __init__( self, workflow_function: Callable, metadata: Optional[WorkflowMetadata],", "wrapper(_workflow_function) else: return wrapper class ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow): \"\"\" A reference workflow is a", "self._python_interface = self._python_interface.with_outputs(extra_outputs={output_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) def add_task(self, task: PythonTask, **kwargs) ->", "from Promise provided {python_type}\") flyte_type = TypeEngine.to_literal_type(python_type=python_type) ctx = FlyteContext.current_context() if ctx.compilation_state is", "outputs_cache) literals.append(p.val) return Promise( var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), ) elif binding_data.map is not None: literals", "if len(expected_output_names) == 1: # Here we have to handle the fact that", "time. This is why this workflow class has to keep track of its", "and represents the decorated function. :param failure_policy: Use the options in flytekit.WorkflowFailurePolicy :param", "of nodes to its outputs. Basically this takes the place of propeller in", "that the wf could've been declared with a typing.NamedTuple of # length one.", "tuple, then we do a one-element non-named tuple, # if it's a single", "resolver interface itself is # more or less stateless (the future-proofing get_all_tasks function", "_literal_models.BindingData, outputs_cache: Dict[Node, Dict[str, Promise]]) -> Promise: \"\"\" This is a helper function", "with Promise objects # holding Flyte literal values. Even in a wf, a", "bit at a time, one task or other entity call at a time.", "node * All workflow inputs are bound These conditions assume that all nodes", "failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False, ): \"\"\" This decorator declares", "at serialization-time (aka compile-time). This is because while we can determine the entire", "VoidPromise): return None else: raise Exception(f\"Workflow local execution expected 0 outputs but something", "get_promise_map( bindings: List[_literal_models.Binding], outputs_cache: Dict[Node, Dict[str, Promise]] ) -> Dict[str, Promise]: \"\"\" Local", "with the container type (e.g. List[int]\" ) python_type = p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring python type", "self._interface = transform_interface_to_typed_interface(self._python_interface) def add_task(self, task: PythonTask, **kwargs) -> Node: return self.add_entity(task, **kwargs)", "len(self.python_interface.outputs) != 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but interface has {len(self.python_interface.outputs)} outputs.\",", "is, we force the user to declare entities already in a topological sort.", "changes were done with the functions above, which do additional checking. \"\"\" if", "raise FlyteValidationException(f\"Failure policy {self.on_failure} not acceptable\") def to_flyte_model(self): if self.on_failure == WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure", "Dict[Node, Dict[str, Promise]]) -> Promise: \"\"\" This is a helper function that will", "anyways, but this allows flytekit to raise # the error earlier. self._unbound_inputs =", "= None ): \"\"\" Add an output with the given name from the", "raise FlyteValueException(results, f\"Different lengths {results} {expected_output_names}\") for idx, r in enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]] =", "a high priority # Again, we're using the output_tuple_name as a proxy. if", "for _, v in input_value.items(): input_promises.extend(get_input_values(v)) return input_promises else: return [input_value] # Every", ":param interruptible: Whether or not tasks launched from this workflow are by default", "for more information but essentially, this WorkflowMetadataDefaults class represents the defaults that are", "match the workflow's # interface. We do that by extracting out the literals,", "repackage the promises coming from the tasks into Promises that match the workflow's", "things off, filled in only with the workflow inputs (if any). As things", "less stateless (the future-proofing get_all_tasks function notwithstanding). However the # implementation of the", "compile(self, **kwargs): \"\"\" Supply static Python native values in the kwargs if you", "Promises, you must specify the python_type type for {output_name}\" f\" starting with the", "we can determine the entire structure of a task by looking at the", "compile time anyways, but this allows flytekit to raise # the error earlier.", "function may return a task that doesn't return anything # def wf(): #", "all_nodes = [] prefix = f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if ctx.compilation_state is not None else \"\"", "is compilation. if ctx.compilation_state is not None: return create_and_link_node(ctx, entity=self, interface=self.python_interface, **input_kwargs) #", "self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes) # This little loop was added as part of the task", "we have. entity = node.flyte_entity entity_kwargs = get_promise_map(node.bindings, intermediate_node_outputs) # Handle the calling", "out, self.interface.outputs[out].type, workflow_outputs[i], t, ) bindings.append(b) # Save all the things necessary to", "options in flytekit.WorkflowFailurePolicy :param interruptible: Whether or not tasks launched from this workflow", "received {result}\") if (1 < expected_outputs == len(result)) or (result is not None", "body of the function is what expresses the workflow structure. It's also important", "self, workflow_function: Callable, metadata: Optional[WorkflowMetadata], default_metadata: Optional[WorkflowMetadataDefaults], ): name = f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function =", "call pattern for Tasks. For local execution, it goes __call__ -> _local_execute ->", "self._local_execute(ctx, **input_kwargs) # Last is starting a local workflow execution else: # Run", "isinstance(input_value, dict): input_promises = [] for _, v in input_value.items(): input_promises.extend(get_input_values(v)) return input_promises", "isinstance(function_outputs, tuple): wf_outputs_as_map = {expected_output_names[0]: function_outputs[0]} else: wf_outputs_as_map = {expected_output_names[0]: function_outputs} else: wf_outputs_as_map", "on_failure = 1 return _workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass class WorkflowMetadataDefaults(object): \"\"\" This class is similarly", "# holding Flyte literal values. Even in a wf, a user can call", "# does store state. This loop adds Tasks that are defined within the", ") bindings.append(b) # Save all the things necessary to create an SdkWorkflow, except", "just iterate through the nodes in order and we shouldn't run into any", "input_kwargs.update(kwargs) workflow_outputs = self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes) # This little loop was added as part", "to its outputs. Basically this takes the place of propeller in resolving bindings,", "for a workflow call, when expecting a native value for {k}\") with FlyteContextManager.with_context(", "have to be pulled by fulfilling all of the # workflow's output bindings.", "AssertionError(\"A Conditional block (if-else) should always end with an `else_()` clause\") t =", "FlyteContext.current_context() if ctx.compilation_state is not None: raise Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state))", "return None # We are already in a local execution, just continue the", "None: if len(self.python_interface.outputs) != 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but interface has", "of its own compilation state. \"\"\" return self._compilation_state @property def nodes(self) -> List[Node]:", "ctx, out, self.interface.outputs[out].type, workflow_outputs[i], t, ) bindings.append(b) # Save all the things necessary", "def construct_input_promises(inputs: List[str]): return { input_name: Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) for input_name in inputs", "Optional, Tuple, Type, Union from flytekit.common import constants as _common_constants from flytekit.common.exceptions.user import", "Promise]]) -> Promise: \"\"\" This is a helper function that will turn a", "used in the compilation. This mimics a 'closure' in the traditional sense of", "raise AssertionError( \"Outputs specification for Workflow does not define a tuple, but return", "return self._nodes def __repr__(self): return ( f\"WorkflowBase - {self._name} && \" f\"Inputs ({len(self._python_interface.inputs)}):", "typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union from flytekit.common import", "-> ReferenceWorkflow: interface = transform_signature_to_interface(inspect.signature(fn)) return ReferenceWorkflow(project, domain, name, version, interface.inputs, interface.outputs) return", "create_and_link_node, create_native_named_tuple, create_task_output, translate_inputs_to_literals, ) from flytekit.core.python_auto_container import PythonAutoContainerTask from flytekit.core.reference_entity import ReferenceEntity,", "creating new Promises wf_outputs_as_literal_dict = translate_inputs_to_literals( ctx, wf_outputs_as_map, flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs, ) # Recreate", "else \"\" with FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self)) ) as comp_ctx: # Construct the default", "nodes(self) -> List[Node]: return self._compilation_state.nodes @property def inputs(self) -> Dict[str, Promise]: \"\"\" This", "{expected_output_names[i]: function_outputs[i] for i, _ in enumerate(function_outputs)} # Basically we need to repackage", "1: return bindings[0] return tuple(bindings) def execute(self, **kwargs): \"\"\" This function is here", "are Promises so let's filter for those. # There's probably a way to", "output with the given name from the given node output. \"\"\" if output_name", "the task's VoidPromise, in the latter we get None if isinstance(function_outputs, VoidPromise) or", "class WorkflowMetadataDefaults(object): \"\"\" This class is similarly named to the one above. Please", "self._unbound_inputs: self._unbound_inputs.remove(input_value) return n def add_workflow_input(self, input_name: str, python_type: Type) -> Interface: \"\"\"", "return Promise( var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) ) raise FlyteValidationException(\"Binding type unrecognized.\") def get_promise_map( bindings: List[_literal_models.Binding],", "f\"{results} received but should've been VoidPromise or None.\") # if there's only one", "1: if isinstance(workflow_outputs, tuple): if len(workflow_outputs) != 1: raise AssertionError( f\"The Workflow specification", "not isinstance(v, Promise): t = self.python_interface.inputs[k] kwargs[k] = Promise(var=k, val=TypeEngine.to_literal(ctx, v, t, self.interface.inputs[k].type))", "metadata=None, bindings=[], upstream_nodes=[], flyte_entity=None, ) class WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY = _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE = (", "i, _ in enumerate(function_outputs)} # Basically we need to repackage the promises coming", "This can be in launch plan only, but is here only so that", "node by node. This function will fill in the node's entity's input arguments,", "promises the node's bindings require, # and then fill them in using the", "the kwargs if you want them to be used in the compilation. This", "None if isinstance(function_outputs, VoidPromise) or function_outputs is None: if len(self.python_interface.outputs) != 0: raise", "with compilation, an error will be returned. \"\"\" def wrapper(fn) -> ReferenceWorkflow: interface", "just raise an Exception here. if len(entity.python_interface.outputs) == 0: raise FlyteValueException(results, f\"{results} received", "a local execution, just continue the execution context return self._local_execute(ctx, **input_kwargs) # Last", "condition is compilation. if ctx.compilation_state is not None: return create_and_link_node(ctx, entity=self, interface=self.python_interface, **input_kwargs)", "workflow_metadata(self) -> Optional[WorkflowMetadata]: return self._workflow_metadata @property def workflow_metadata_defaults(self): return self._workflow_metadata_defaults @property def python_interface(self)", "bd in binding_data.collection.bindings: p = get_promise(bd, outputs_cache) literals.append(p.val) return Promise( var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), )", "This Python object represents a workflow defined by a function and decorated with", "workflow_metadata: WorkflowMetadata, workflow_metadata_defaults: WorkflowMetadataDefaults, python_interface: Interface, **kwargs, ): self._name = name self._workflow_metadata =", "key off of the name instead of value? all_input_values = get_input_values(kwargs) for input_value", "b = binding_from_python_std( ctx, output_name, expected_literal_type=flyte_type, t_value=p, t_value_type=python_type ) self._output_bindings.append(b) self._python_interface = self._python_interface.with_outputs(extra_outputs={output_name:", "= results else: if len(results) != len(expected_output_names): raise FlyteValueException(results, f\"Different lengths {results} {expected_output_names}\")", "bool: \"\"\" This function returns whether or not the workflow is in a", "is not None: if not isinstance(binding_data.promise, NodeOutput): raise FlyteValidationException( f\"Binding data Promises have", "tasks using the data flow between tasks. Unlike a task, the function body", "we just raise an error here. if len(self.python_interface.outputs) == 0: raise FlyteValueException( function_outputs,", "or function_outputs is None: if len(self.python_interface.outputs) != 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received", "don't have to re-evaluate. Or # we can re-evaluate. self._input_parameters = None super().__init__(", "expected_outputs == 0: if result is None or isinstance(result, VoidPromise): return None else:", "issues. That is, we force the user to declare entities already in a", "self._python_interface.with_inputs(extra_inputs={input_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name] = Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) self._unbound_inputs.add(self._inputs[input_name]) return self._inputs[input_name]", "-> Dict[str, Promise]: \"\"\" This holds the input promises to the workflow. The", "The rest of this function looks like the above but now we're doing", "something received {result}\") if (1 < expected_outputs == len(result)) or (result is not", "if isinstance(input_value, dict): input_promises = [] for _, v in input_value.items(): input_promises.extend(get_input_values(v)) return", "of it. if len(output_names) == 1: if isinstance(workflow_outputs, tuple): if len(workflow_outputs) != 1:", "f\"Outputs ({len(self._python_interface.outputs)}): {self._python_interface.outputs} && \" f\"Output bindings: {self._output_bindings} && \" ) def __call__(self,", "str, domain: str, name: str, version: str, ) -> Callable[[Callable[..., Any]], ReferenceWorkflow]: \"\"\"", "transform_inputs_to_parameters, transform_interface_to_typed_interface, transform_signature_to_interface, ) from flytekit.core.launch_plan import LaunchPlan from flytekit.core.node import Node from", "= r # The rest of this function looks like the above but", "the default input promise bindings, but then override with the provided inputs, if", "[] self._output_bindings: Optional[List[_literal_models.Binding]] = [] FlyteEntities.entities.append(self) super().__init__(**kwargs) @property def name(self) -> str: return", "tuple, then it # should be a tuple here, if it's a one", "that we don't have to re-evaluate. Or # we can re-evaluate. self._input_parameters =", "using the data flow between tasks. Unlike a task, the function body of", "of the details. \"\"\" if binding_data.promise is not None: if not isinstance(binding_data.promise, NodeOutput):", "== len(result)) or (result is not None and expected_outputs == 1): return create_native_named_tuple(ctx,", "# is an error that Admin would return at compile time anyways, but", "entity_kwargs = get_promise_map(node.bindings, intermediate_node_outputs) # Handle the calling and outputs of each node's", "workflow execution else: # Run some sanity checks # Even though the _local_execute", "they are only run once (again, this is with respect to the platform,", "function is what expresses the workflow structure. It's also important to note that,", "This is a helper function that will turn a binding into a Promise", "currently {self}\") # Create a map that holds the outputs of each node.", "return True class PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver): \"\"\" Please read :std:ref:`flyte:divedeep-workflows` first for a high-level", "1: # Here we have to handle the fact that the wf could've", "output_tuple_name to understand that we're dealing with a one-element # named tuple if", "WorkflowMetadata represents metadata about the workflow itself. \"\"\" interruptible: bool def __post_init__(self): if", "execution has already been set. elif ( ctx.execution_state is not None and ctx.execution_state.mode", "error will be returned. \"\"\" def wrapper(fn) -> ReferenceWorkflow: interface = transform_signature_to_interface(inspect.signature(fn)) return", "have to do the # conversion here in this loop. The reason is", "or not the workflow is in a ready state, which means * Has", "-> Dict[str, Promise]: \"\"\" Local execution of imperatively defined workflows is done node", "create a map to start things off, filled in only with the workflow", "Here we have to handle the fact that the wf could've been declared", "this allows flytekit to raise # the error earlier. self._unbound_inputs = set() super().__init__(", "\"\"\" def __init__( self, workflow_function: Callable, metadata: Optional[WorkflowMetadata], default_metadata: Optional[WorkflowMetadataDefaults], ): name =", "len(output_names) > 1: if not isinstance(workflow_outputs, tuple): raise AssertionError(\"The Workflow specification indicates multiple", "dependency issues. That is, we force the user to declare entities already in", "can this not be in launchplan only? # This can be in launch", "implementation of the TaskResolverMixin that this workflow class inherits from (ClassStorageTaskResolver) # does", "multiple return values, received only one\") if len(output_names) != len(workflow_outputs): raise Exception(f\"Length mismatch", "run one at a time. \"\"\" if len(args) > 0: raise AssertionError(\"Only Keyword", "Promise, VoidPromise]: # This is done to support the invariant that Workflow local", "__init__( self, workflow_function: Callable, metadata: Optional[WorkflowMetadata], default_metadata: Optional[WorkflowMetadataDefaults], ): name = f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function", "# The rest of this function looks like the above but now we're", "@dataclass class WorkflowMetadata(object): on_failure: WorkflowFailurePolicy def __post_init__(self): if ( self.on_failure != WorkflowFailurePolicy.FAIL_IMMEDIATELY and", "(ClassStorageTaskResolver) # does store state. This loop adds Tasks that are defined within", "In the former case we get the task's VoidPromise, in the latter we", "body of a workflow is evaluated at serialization-time (aka compile-time). This is because", "Promise]: \"\"\" Local execution of imperatively defined workflows is done node by node.", "node.flyte_entity entity_kwargs = get_promise_map(node.bindings, intermediate_node_outputs) # Handle the calling and outputs of each", "which is in _local_execute, workflows should also call an execute inside _local_execute. This", "binding_data.collection.bindings: p = get_promise(bd, outputs_cache) literals.append(p.val) return Promise( var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), ) elif binding_data.map", "NodeOutput, Promise, VoidPromise, binding_from_python_std, create_and_link_node, create_native_named_tuple, create_task_output, translate_inputs_to_literals, ) from flytekit.core.python_auto_container import PythonAutoContainerTask", "Admin, which is why the user is asked to provide the expected interface.", "There's probably a way to clean this up, maybe key off of the", "but return value is a tuple\" ) workflow_outputs = workflow_outputs[0] t = self.python_interface.outputs[output_names[0]]", "the node's entity's input arguments, which are specified using the bindings list, and", "as _workflow_model GLOBAL_START_NODE = Node( id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None, bindings=[], upstream_nodes=[], flyte_entity=None, ) class WorkflowFailurePolicy(Enum):", "list(entity.python_interface.outputs.keys()) if isinstance(results, VoidPromise) or results is None: continue # pragma: no cover", "self.interface.inputs: raise ValueError(f\"Received unexpected keyword argument {k}\") if isinstance(v, Promise): raise ValueError(f\"Received a", "a time, one task or other entity call at a time. This is", "Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False, ): metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY)", "dataclasses import dataclass from enum import Enum from typing import Any, Callable, Dict,", "be of the NodeOutput type {type(binding_data.promise)} found\" ) # b.var is the name", "an execute inside _local_execute. This makes mocking cleaner. \"\"\" return self._workflow_function(**kwargs) def workflow(", "get_all_tasks function notwithstanding). However the # implementation of the TaskResolverMixin that this workflow", "f\"WorkflowBase - {self._name} && \" f\"Inputs ({len(self._python_interface.inputs)}): {self._python_interface.inputs} && \" f\"Outputs ({len(self._python_interface.outputs)}): {self._python_interface.outputs}", "expecting a native value for {k}\") with FlyteContextManager.with_context( ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) ) ) as", "var=input_name)) for input_name in inputs } def get_promise(binding_data: _literal_models.BindingData, outputs_cache: Dict[Node, Dict[str, Promise]])", "signature, workflows need to run through the function itself because the body of", "are supported for Workflow executions\") ctx = FlyteContextManager.current_context() # Get default agruements and", "\"\"\" def __init__( self, project: str, domain: str, name: str, version: str, inputs:", "off of the name instead of value? all_input_values = get_input_values(kwargs) for input_value in", "1: raise AssertionError( f\"The Workflow specification indicates only one return value, received {len(workflow_outputs)}\"", "time. if len(self.python_interface.outputs) == 0: return VoidPromise(self.name) # The values that we return", "only so that we don't have to re-evaluate. Or # we can re-evaluate.", "(aka compile-time). This is because while we can determine the entire structure of", "return outputs_cache[binding_data.promise.node][binding_data.promise.var] elif binding_data.scalar is not None: return Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar)) elif binding_data.collection is", "the provided inputs, if any input_kwargs = construct_input_promises([k for k in self.interface.inputs.keys()]) input_kwargs.update(kwargs)", "def nodes(self) -> List[Node]: return self._compilation_state.nodes @property def inputs(self) -> Dict[str, Promise]: \"\"\"", "which means * Has at least one node * All workflow inputs are", "ValueError(f\"Received a promise for a workflow call, when expecting a native value for", "# Again use presence of output_tuple_name to understand that we're dealing with a", "import LaunchPlan from flytekit.core.node import Node from flytekit.core.promise import ( NodeOutput, Promise, VoidPromise,", "list(self.python_interface.outputs.keys()) if len(expected_output_names) == 1: # Here we have to handle the fact", ") @property def compilation_state(self) -> CompilationState: \"\"\" Compilation is done a bit at", "for the rest of the details. \"\"\" if binding_data.promise is not None: if", "type {type(binding_data.promise)} found\" ) # b.var is the name of the input to", "Iterate through the workflow outputs bindings = [] output_names = list(self.interface.outputs.keys()) # The", "the workflow itself. \"\"\" interruptible: bool def __post_init__(self): if self.interruptible is not True", "} def get_promise(binding_data: _literal_models.BindingData, outputs_cache: Dict[Node, Dict[str, Promise]]) -> Promise: \"\"\" This is", "-> str: return f\"{self.name}.{t.__module__}.{t.name}\" def compile(self, **kwargs): \"\"\" Supply static Python native values", "if there's only one output, if len(expected_output_names) == 1: if entity.python_interface.output_tuple_name and isinstance(results,", "workflow that already exists on your Flyte installation. This object will not initiate", "( self.on_failure != WorkflowFailurePolicy.FAIL_IMMEDIATELY and self.on_failure != WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ): raise FlyteValidationException(f\"Failure policy {self.on_failure}", "mismatch {len(output_names)} vs {len(workflow_outputs)}\") for i, out in enumerate(output_names): if isinstance(workflow_outputs[i], ConditionalSection): raise", "= TypeEngine.to_literal_type(python_type=python_type) ctx = FlyteContext.current_context() if ctx.compilation_state is not None: raise Exception(\"Can't already", "received but should've been VoidPromise or None.\") # if there's only one output,", "create_and_link_node(ctx, entity=self, interface=self.python_interface, **input_kwargs) # This condition is hit when this workflow (self)", "if isinstance(results, VoidPromise) or results is None: continue # pragma: no cover #", "do the # conversion here in this loop. The reason is because we", "# circular import from flytekit.core.node_creation import create_node ctx = FlyteContext.current_context() if ctx.compilation_state is", "within the body of the workflow to the workflow # object itself. for", "understand that we're dealing with a one-element # named tuple if self.python_interface.output_tuple_name: return", "if expected_outputs == 0: if result is None or isinstance(result, VoidPromise): return None", "has already been set. elif ( ctx.execution_state is not None and ctx.execution_state.mode ==", "node. \"\"\" if not self.ready(): raise FlyteValidationException(f\"Workflow not ready, wf is currently {self}\")", "Workflow does not define a tuple, but return value is a tuple\" )", "if len(self._unbound_inputs) > 0: return False return True class PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver): \"\"\" Please", "policy {self.on_failure} not acceptable\") def to_flyte_model(self): if self.on_failure == WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure = 0", "just here to help workflow authors detect issues a bit earlier. It just", "ClassStorageTaskResolver): \"\"\" Please read :std:ref:`flyte:divedeep-workflows` first for a high-level understanding of what workflows", "): super().__init__(WorkflowReference(project, domain, name, version), inputs, outputs) def reference_workflow( project: str, domain: str,", "kwargs.items(): if not isinstance(v, Promise): t = self.python_interface.inputs[k] kwargs[k] = Promise(var=k, val=TypeEngine.to_literal(ctx, v,", "above check, we just raise an error here. if len(self.python_interface.outputs) == 0: raise", "entity call at a time. This is why this workflow class has to", "saving task {n.flyte_entity.name}\") self.add(n.flyte_entity) # Iterate through the workflow outputs bindings = []", "node, and call it by looking up the promises the node's bindings require,", "else: on_failure = 1 return _workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass class WorkflowMetadataDefaults(object): \"\"\" This class is", "\"\"\" if len(self.compilation_state.nodes) == 0: return False if len(self._unbound_inputs) > 0: return False", "from specifying inputs # as direct scalars, which means there's another Promise-generating loop", "values, received only one\") if len(output_names) != len(workflow_outputs): raise Exception(f\"Length mismatch {len(output_names)} vs", "create an SdkWorkflow, except for the missing project and domain self._nodes = all_nodes", "the two Workflow styles. For PythonFunctionWorkflows, the Python function is run, for the", "flyte_type = TypeEngine.to_literal_type(python_type=python_type) ctx = FlyteContext.current_context() if ctx.compilation_state is not None: raise Exception(\"Can't", "we don't have to do the # conversion here in this loop. The", "= {expected_output_names[i]: function_outputs[i] for i, _ in enumerate(function_outputs)} # Basically we need to", "workflow_outputs[i], t, ) bindings.append(b) # Save all the things necessary to create an", "val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) self._unbound_inputs.add(self._inputs[input_name]) return self._inputs[input_name] def add_workflow_output( self, output_name: str, p: Union[Promise, List[Promise],", "bindings list, and a map of nodes to its outputs. Basically this takes", "that Admin would return at compile time anyways, but this allows flytekit to", "tuple\" ) workflow_outputs = workflow_outputs[0] t = self.python_interface.outputs[output_names[0]] b = binding_from_python_std( ctx, output_names[0],", "2) what a user would return in mock function. That is, if it's", "non-named tuple, # if it's a single element then we return a single", "itself. \"\"\" interruptible: bool def __post_init__(self): if self.interruptible is not True and self.interruptible", "-> CompilationState: \"\"\" Compilation is done a bit at a time, one task", "we return below from the output have to be pulled by fulfilling all", "Conditional block (if-else) should always end with an `else_()` clause\") t = self.python_interface.outputs[out]", "def compilation_state(self) -> CompilationState: \"\"\" Compilation is done a bit at a time,", "failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False, ): metadata = WorkflowMetadata(on_failure=failure_policy or", "import ReferenceEntity, WorkflowReference from flytekit.core.type_engine import TypeEngine from flytekit.loggers import logger from flytekit.models", "\"\"\" Adds an input to the workflow. \"\"\" if input_name in self._inputs: raise", "id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None, bindings=[], upstream_nodes=[], flyte_entity=None, ) class WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY = _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE =", "named tuple if self.python_interface.output_tuple_name: return (get_promise(self.output_bindings[0].binding, intermediate_node_outputs),) # Just a normal single element", "FlyteValidationException(f\"Interruptible must be boolean, {self.interruptible} invalid\") def to_flyte_model(self): return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def construct_input_promises(inputs: List[str]):", "that are handed down to a workflow's tasks, whereas WorkflowMetadata represents metadata about", "runs. Because when an entity is added using the add_entity function, all inputs", "promises to the workflow. The nodes in these Promise objects should always point", "this loop. The reason is because we don't prevent users from specifying inputs", "transform_interface_to_typed_interface, transform_signature_to_interface, ) from flytekit.core.launch_plan import LaunchPlan from flytekit.core.node import Node from flytekit.core.promise", "above. Please see the IDL for more information but essentially, this WorkflowMetadataDefaults class", "as part of the task resolver change. The task resolver interface itself is", "\"\"\" return self._compilation_state @property def nodes(self) -> List[Node]: return self._compilation_state.nodes @property def inputs(self)", "execution expected 0 outputs but something received {result}\") if (1 < expected_outputs ==", "i/o changes were done with the functions above, which do additional checking. \"\"\"", "keyword argument {k}\") if isinstance(v, Promise): raise ValueError(f\"Received a promise for a workflow", "outputs_cache[binding_data.promise.node][binding_data.promise.var] elif binding_data.scalar is not None: return Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar)) elif binding_data.collection is not", "not exactly, the call pattern for Tasks. For local execution, it goes __call__", "Again use presence of output_tuple_name to understand that we're dealing with a one-element", "installation. This object will not initiate a network call to Admin, which is", "collection/map out of it. if len(output_names) == 1: if isinstance(workflow_outputs, tuple): if len(workflow_outputs)", "raise FlyteValidationException( f\"If specifying a list or dict of Promises, you must specify", "transform_inputs_to_parameters(ctx, self.python_interface) all_nodes = [] prefix = f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if ctx.compilation_state is not None", "the word. \"\"\" ctx = FlyteContextManager.current_context() self._input_parameters = transform_inputs_to_parameters(ctx, self.python_interface) all_nodes = []", "self, project: str, domain: str, name: str, version: str, inputs: Dict[str, Type], outputs:", ") raise FlyteValidationException(\"Binding type unrecognized.\") def get_promise_map( bindings: List[_literal_models.Binding], outputs_cache: Dict[Node, Dict[str, Promise]]", "import collections import inspect from dataclasses import dataclass from enum import Enum from", "binding_data.collection is not None: literals = [] for bd in binding_data.collection.bindings: p =", "self._inputs[input_name] = Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) self._unbound_inputs.add(self._inputs[input_name]) return self._inputs[input_name] def add_workflow_output( self, output_name: str,", "fact that the wf could've been declared with a typing.NamedTuple of # length", "entity must be bound. \"\"\" # circular import from flytekit.core.node_creation import create_node ctx", "of the input to the task # binding_data.promise.var is the name of the", "str, inputs: Dict[str, Type], outputs: Dict[str, Type] ): super().__init__(WorkflowReference(project, domain, name, version), inputs,", "Promise): t = self.python_interface.inputs[k] kwargs[k] = Promise(var=k, val=TypeEngine.to_literal(ctx, v, t, self.interface.inputs[k].type)) # The", "self._output_bindings: Optional[List[_literal_models.Binding]] = [] FlyteEntities.entities.append(self) super().__init__(**kwargs) @property def name(self) -> str: return self._name", "holds the input promises to the workflow. The nodes in these Promise objects", "new promises that use the workflow's output names. new_promises = [Promise(var, wf_outputs_as_literal_dict[var]) for", "This object will not initiate a network call to Admin, which is why", "return False return True class PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver): \"\"\" Please read :std:ref:`flyte:divedeep-workflows` first for", "{self.interruptible} invalid\") def to_flyte_model(self): return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def construct_input_promises(inputs: List[str]): return { input_name: Promise(var=input_name,", "== 1: if isinstance(workflow_outputs, tuple): if len(workflow_outputs) != 1: raise AssertionError( f\"The Workflow", "it been declared # functionally, and 2) what a user would return in", "context specifying the local workflow execution has already been set. elif ( ctx.execution_state", "raise FlyteValueException( function_outputs, f\"{function_outputs} received but should've been VoidPromise or None.\" ) expected_output_names", "However the # implementation of the TaskResolverMixin that this workflow class inherits from", "entity's input arguments, which are specified using the bindings list, and a map", "isinstance(result, VoidPromise): return None else: raise Exception(f\"Workflow local execution expected 0 outputs but", "workflow outputs bindings = [] output_names = list(self.interface.outputs.keys()) # The reason the length", "len(output_names) != len(workflow_outputs): raise Exception(f\"Length mismatch {len(output_names)} vs {len(workflow_outputs)}\") for i, out in", "object will not initiate a network call to Admin, which is why the", "which are specified using the bindings list, and a map of nodes to", "literals = [] for bd in binding_data.collection.bindings: p = get_promise(bd, outputs_cache) literals.append(p.val) return", "wf_outputs_as_map, flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs, ) # Recreate new promises that use the workflow's output", "lookup map. Please see get_promise_map for the rest of the details. \"\"\" if", "workflow_metadata self._workflow_metadata_defaults = workflow_metadata_defaults self._python_interface = python_interface self._interface = transform_interface_to_typed_interface(python_interface) self._inputs = {}", "propeller in resolving bindings, pulling in outputs from previously completed nodes and filling", "see the IDL for more information but essentially, this WorkflowMetadataDefaults class represents the", "point to the global start node. \"\"\" return self._inputs def __repr__(self): return super().__repr__()", "inputs are bound These conditions assume that all nodes and workflow i/o changes", "Promise): raise ValueError(f\"Received a promise for a workflow call, when expecting a native", "to be used in the compilation. This mimics a 'closure' in the traditional", "check, we just raise an Exception here. if len(entity.python_interface.outputs) == 0: raise FlyteValueException(results,", "input_kwargs = self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs) # The first condition is compilation. if ctx.compilation_state is", "ready state, which means * Has at least one node * All workflow", "\"\"\" This class is similarly named to the one above. Please see the", "kwargs[k] = Promise(var=k, val=TypeEngine.to_literal(ctx, v, t, self.interface.inputs[k].type)) # The output of this will", "flytekit.loggers import logger from flytekit.models import interface as _interface_models from flytekit.models import literals", "invalid\") def to_flyte_model(self): return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def construct_input_promises(inputs: List[str]): return { input_name: Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE,", "context return self._local_execute(ctx, **input_kwargs) # Last is starting a local workflow execution else:", "might be a list. We don't want to # iterate through the list", "expected_outputs = len(self.python_interface.outputs) if expected_outputs == 0: if result is None or isinstance(result,", "collections.namedtuple(self.python_interface.output_tuple_name, variables) nones = [None for _ in self.python_interface.outputs.keys()] return output_tuple(*nones) else: return", "the inputs to the entity must be bound. \"\"\" # circular import from", "will always be a combination of Python native values and Promises containing Flyte", "but something received {result}\") if (1 < expected_outputs == len(result)) or (result is", "and single-length-NamedTuples are # particularly troublesome but elegant handling of them is not", "From execute, different things happen for the two Workflow styles. For PythonFunctionWorkflows, the", "# _local_execute should've already ensured that all the values in kwargs are Promise", "self.add_entity(task, **kwargs) def add_launch_plan(self, launch_plan: LaunchPlan, **kwargs) -> Node: return self.add_entity(launch_plan, **kwargs) def", "if type(p) == list or type(p) == dict: raise FlyteValidationException( f\"If specifying a", "because while we can determine the entire structure of a task by looking", "raise FlyteValidationException(f\"Interruptible must be boolean, {self.interruptible} invalid\") def to_flyte_model(self): return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def construct_input_promises(inputs:", "compilation. if ctx.compilation_state is not None: return create_and_link_node(ctx, entity=self, interface=self.python_interface, **input_kwargs) # This", "a map to start things off, filled in only with the workflow inputs", "the output have to be pulled by fulfilling all of the # workflow's", "len(self.python_interface.outputs) == 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but should've been VoidPromise or", "map we have. entity = node.flyte_entity entity_kwargs = get_promise_map(node.bindings, intermediate_node_outputs) # Handle the", "a map of nodes to its outputs. Basically this takes the place of", "execute(self, **kwargs): \"\"\" Called by _local_execute. This function is how local execution for", "k in self.python_interface.outputs.keys()] output_tuple = collections.namedtuple(self.python_interface.output_tuple_name, variables) nones = [None for _ in", "flytekit.models import interface as _interface_models from flytekit.models import literals as _literal_models from flytekit.models.core", "is what expresses the workflow structure. It's also important to note that, local", "promise for a workflow call, when expecting a native value for {k}\") with", "at a time. This is why this workflow class has to keep track", "function_outputs[i] for i, _ in enumerate(function_outputs)} # Basically we need to repackage the", "flytekit.core.launch_plan import LaunchPlan from flytekit.core.node import Node from flytekit.core.promise import ( NodeOutput, Promise,", "important to note that, local execution notwithstanding, it is not evaluated again when", "workflow as a whole rather # than just one node at a time.", "PythonTask, **kwargs) -> Node: return self.add_entity(task, **kwargs) def add_launch_plan(self, launch_plan: LaunchPlan, **kwargs) ->", "NodeOutput): raise FlyteValidationException( f\"Binding data Promises have to be of the NodeOutput type", "little loop was added as part of the task resolver change. The task", "if node not in intermediate_node_outputs.keys(): intermediate_node_outputs[node] = {} # Retrieve the entity from", "def short_name(self) -> str: return self._name.split(\".\")[-1] @property def workflow_metadata(self) -> Optional[WorkflowMetadata]: return self._workflow_metadata", "outputs - and single-length-NamedTuples are # particularly troublesome but elegant handling of them", "self._interface @property def output_bindings(self) -> List[_literal_models.Binding]: return self._output_bindings @property def nodes(self) -> List[Node]:", "that you've declared with add_workflow_input but haven't yet consumed. This # is an", "pulled by fulfilling all of the # workflow's output bindings. # The return", "function itself because the body of the function is what expresses the workflow", "new_promises = [Promise(var, wf_outputs_as_literal_dict[var]) for var in expected_output_names] return create_task_output(new_promises, self.python_interface) class ImperativeWorkflow(WorkflowBase):", "def add_workflow_output( self, output_name: str, p: Union[Promise, List[Promise], Dict[str, Promise]], python_type: Optional[Type] =", "of the NodeOutput type {type(binding_data.promise)} found\" ) # b.var is the name of", "native_types=self.python_interface.outputs, ) # Recreate new promises that use the workflow's output names. new_promises", "binding_from_python_std( ctx, output_names[0], self.interface.outputs[output_names[0]].type, workflow_outputs, t, ) bindings.append(b) elif len(output_names) > 1: if", "outputs from previously completed nodes and filling in the necessary inputs. \"\"\" entity_kwargs", "circular import from flytekit.core.node_creation import create_node ctx = FlyteContext.current_context() if ctx.compilation_state is not", "FlyteEntities.entities.append(self) super().__init__(**kwargs) @property def name(self) -> str: return self._name @property def short_name(self) ->", "\" f\"Outputs ({len(self._python_interface.outputs)}): {self._python_interface.outputs} && \" f\"Output bindings: {self._output_bindings} && \" ) def", "[Promise(var, wf_outputs_as_literal_dict[var]) for var in expected_output_names] return create_task_output(new_promises, self.python_interface) class ImperativeWorkflow(WorkflowBase): def __init__(", "user is asked to provide the expected interface. If at registration time the", "Workflow executions\") ctx = FlyteContextManager.current_context() # Get default agruements and override with kwargs", "= list(self.interface.outputs.keys()) # The reason the length 1 case is separate is because", "reference workflow is a pointer to a workflow that already exists on your", "output of this will always be a combination of Python native values and", "workflow # object itself. for n in comp_ctx.compilation_state.nodes: if isinstance(n.flyte_entity, PythonAutoContainerTask) and n.flyte_entity.task_resolver", "represents the decorated function. :param failure_policy: Use the options in flytekit.WorkflowFailurePolicy :param interruptible:", "False: raise FlyteValidationException(f\"Interruptible must be boolean, {self.interruptible} invalid\") def to_flyte_model(self): return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def", "causes an issue with compilation, an error will be returned. \"\"\" def __init__(", "WorkflowBase], **kwargs) -> Node: \"\"\" Anytime you add an entity, all the inputs", "whole rather # than just one node at a time. if len(self.python_interface.outputs) ==", "self.compilation_state.nodes: if node not in intermediate_node_outputs.keys(): intermediate_node_outputs[node] = {} # Retrieve the entity", "ValueError(f\"Received unexpected keyword argument {k}\") if isinstance(v, Promise): raise ValueError(f\"Received a promise for", "below from the output have to be pulled by fulfilling all of the", "): self._name = name self._workflow_metadata = workflow_metadata self._workflow_metadata_defaults = workflow_metadata_defaults self._python_interface = python_interface", "a binding into a Promise object, using a lookup map. Please see get_promise_map", "Interface: return self._python_interface @property def interface(self) -> _interface_models.TypedInterface: return self._interface @property def output_bindings(self)", "off with the outputs of the global input node, i.e. the inputs to", "intermediate_node_outputs[node][expected_output_names[0]] = results[0] else: intermediate_node_outputs[node][expected_output_names[0]] = results else: if len(results) != len(expected_output_names): raise", "value, received {len(workflow_outputs)}\" ) if self.python_interface.output_tuple_name is None: raise AssertionError( \"Outputs specification for", "None: return Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar)) elif binding_data.collection is not None: literals = [] for", "\"\"\" return self._inputs def __repr__(self): return super().__repr__() + f\"Nodes ({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\" def execute(self,", "execution, just continue the execution context return self._local_execute(ctx, **input_kwargs) # Last is starting", "a high-level understanding of what workflows are in Flyte. This Python object represents", "= all_nodes self._output_bindings = bindings if not output_names: return None if len(output_names) ==", "interruptible: Optional[bool] = False, ): \"\"\" This decorator declares a function to be", "used for naming outputs - and single-length-NamedTuples are # particularly troublesome but elegant", "self.output_bindings]) def add_entity(self, entity: Union[PythonTask, LaunchPlan, WorkflowBase], **kwargs) -> Node: \"\"\" Anytime you", "don't prevent users from specifying inputs # as direct scalars, which means there's", "call a sub-workflow with a Python native value. for k, v in kwargs.items():", "# This unbound inputs construct is just here to help workflow authors detect", "The first condition is compilation. if ctx.compilation_state is not None: return create_and_link_node(ctx, entity=self,", "in bindings: entity_kwargs[b.var] = get_promise(b.binding, outputs_cache) return entity_kwargs class WorkflowBase(object): def __init__( self,", "things off with the outputs of the global input node, i.e. the inputs", "if len(args) > 0: raise AssertionError(\"Only Keyword Arguments are supported for Workflow executions\")", "function looks like the above but now we're doing it for the workflow", "a normal single element return get_promise(self.output_bindings[0].binding, intermediate_node_outputs) return tuple([get_promise(b.binding, intermediate_node_outputs) for b in", "are handed down to a workflow's tasks, whereas WorkflowMetadata represents metadata about the", "pattern for Tasks. For local execution, it goes __call__ -> _local_execute -> execute", "workflow. \"\"\" if input_name in self._inputs: raise FlyteValidationException(f\"Input {input_name} has already been specified", "{output_name}\" f\" starting with the container type (e.g. List[int]\" ) python_type = p.ref.node.flyte_entity.python_interface.outputs[p.var]", "t, ) bindings.append(b) elif len(output_names) > 1: if not isinstance(workflow_outputs, tuple): raise AssertionError(\"The", "# Save all the things necessary to create an SdkWorkflow, except for the", "is why the user is asked to provide the expected interface. If at", "to try to streamline the pattern between workflows and tasks. Since tasks call", "Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar)) elif binding_data.collection is not None: literals = [] for bd in", "inputs to that entity should've been already declared, we can just iterate through", "like the above but now we're doing it for the workflow as a", "the function itself because the body of the function is what expresses the", "(again, this is with respect to the platform, local runs notwithstanding). Please see", "{self._python_interface.outputs} && \" f\"Output bindings: {self._output_bindings} && \" ) def __call__(self, *args, **kwargs):", "received but interface has {len(self.python_interface.outputs)} outputs.\", ) return VoidPromise(self.name) # Because we should've", "\"\"\" if not self.ready(): raise FlyteValidationException(f\"Workflow not ready, wf is currently {self}\") #", "type(p) == list or type(p) == dict: raise FlyteValidationException( f\"If specifying a list", "isinstance(workflow_outputs, tuple): if len(workflow_outputs) != 1: raise AssertionError( f\"The Workflow specification indicates only", "ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) ) ) as child_ctx: result = self._local_execute(child_ctx, **input_kwargs) expected_outputs = len(self.python_interface.outputs) if", "return self._local_execute(ctx, **input_kwargs) # Last is starting a local workflow execution else: #", "in a topological sort. To keep track of outputs, we create a map", "&& \" ) def __call__(self, *args, **kwargs): \"\"\" The call pattern for Workflows", "if it's a tuple, then it # should be a tuple here, if", "be returned. \"\"\" def __init__( self, project: str, domain: str, name: str, version:", "we just raise an Exception here. if len(entity.python_interface.outputs) == 0: raise FlyteValueException(results, f\"{results}", "been already declared, we can just iterate through the nodes in order and", "val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), ) elif binding_data.map is not None: literals = {} for k, bd", "Promise]] ) -> Dict[str, Promise]: \"\"\" Local execution of imperatively defined workflows is", "import inspect from dataclasses import dataclass from enum import Enum from typing import", "function_outputs} else: wf_outputs_as_map = {expected_output_names[i]: function_outputs[i] for i, _ in enumerate(function_outputs)} # Basically", "project: str, domain: str, name: str, version: str, inputs: Dict[str, Type], outputs: Dict[str,", "len(result)) or (result is not None and expected_outputs == 1): return create_native_named_tuple(ctx, result,", "Supply static Python native values in the kwargs if you want them to", "separate is because the one output might be a list. We don't want", "itself is # more or less stateless (the future-proofing get_all_tasks function notwithstanding). However", "the necessary inputs. \"\"\" entity_kwargs = {} for b in bindings: entity_kwargs[b.var] =", "given name from the given node output. \"\"\" if output_name in self._python_interface.outputs: raise", "the things necessary to create an SdkWorkflow, except for the missing project and", "output {output_name} from Promise provided {python_type}\") flyte_type = TypeEngine.to_literal_type(python_type=python_type) ctx = FlyteContext.current_context() if", "if binding_data.promise is not None: if not isinstance(binding_data.promise, NodeOutput): raise FlyteValidationException( f\"Binding data", "input_name in inputs } def get_promise(binding_data: _literal_models.BindingData, outputs_cache: Dict[Node, Dict[str, Promise]]) -> Promise:", "tuple, # if it's a single element then we return a single element", "workflow runs on Flyte. That is, workflows should not call non-Flyte entities since", "and self.interruptible is not False: raise FlyteValidationException(f\"Interruptible must be boolean, {self.interruptible} invalid\") def", "import ( BranchEvalMode, CompilationState, ExecutionState, FlyteContext, FlyteContextManager, FlyteEntities, ) from flytekit.core.interface import (", "for Workflow does not define a tuple, but return value is a tuple\"", "@property def nodes(self) -> List[Node]: return self._compilation_state.nodes @property def inputs(self) -> Dict[str, Promise]:", "intermediate_node_outputs[node][expected_output_names[idx]] = r # The rest of this function looks like the above", "entity_kwargs = {} for b in bindings: entity_kwargs[b.var] = get_promise(b.binding, outputs_cache) return entity_kwargs", "FlyteValueException(results, f\"Different lengths {results} {expected_output_names}\") for idx, r in enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]] = r", "Promise objects # holding Flyte literal values. Even in a wf, a user", "var in expected_output_names] return create_task_output(new_promises, self.python_interface) class ImperativeWorkflow(WorkflowBase): def __init__( self, name: str,", "the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for more usage examples. :param _workflow_function: This argument is implicitly passed", "Type], outputs: Dict[str, Type] ): super().__init__(WorkflowReference(project, domain, name, version), inputs, outputs) def reference_workflow(", "return False if len(self._unbound_inputs) > 0: return False return True class PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver):", "-> Union[Tuple[Promise], Promise, VoidPromise]: # This is done to support the invariant that", "is a helper function that will turn a binding into a Promise object,", "(e.g. List[int]\" ) python_type = p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring python type for wf output {output_name}", "Promise-generating loop inside _local_execute too for k, v in input_kwargs.items(): if k not", "as any other previous node. \"\"\" if not self.ready(): raise FlyteValidationException(f\"Workflow not ready,", "it. if len(output_names) == 1: if isinstance(workflow_outputs, tuple): if len(workflow_outputs) != 1: raise", "If at registration time the interface provided causes an issue with compilation, an", "time an entity is added, mark it as used. The above function though", "that this workflow class inherits from (ClassStorageTaskResolver) # does store state. This loop", "rest of the details. \"\"\" if binding_data.promise is not None: if not isinstance(binding_data.promise,", ") # Recreate new promises that use the workflow's output names. new_promises =", "str, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False, ): metadata = WorkflowMetadata(on_failure=failure_policy", "ConditionalSection from flytekit.core.context_manager import ( BranchEvalMode, CompilationState, ExecutionState, FlyteContext, FlyteContextManager, FlyteEntities, ) from", "local execution expected 0 outputs but something received {result}\") if (1 < expected_outputs", "filled in only with the workflow inputs (if any). As things are run,", "in the above check, we just raise an Exception here. if len(entity.python_interface.outputs) ==", "actual outputs do not match\") def execute(self, **kwargs): raise Exception(\"Should not be called\")", "if self.python_interface.output_tuple_name: return (get_promise(self.output_bindings[0].binding, intermediate_node_outputs),) # Just a normal single element return get_promise(self.output_bindings[0].binding,", "start things off, filled in only with the workflow inputs (if any). As", "local run. # The context specifying the local workflow execution has already been", "BranchEvalMode.BRANCH_SKIPPED: if self.python_interface and self.python_interface.output_tuple_name: variables = [k for k in self.python_interface.outputs.keys()] output_tuple", "input_name in self._inputs: raise FlyteValidationException(f\"Input {input_name} has already been specified for wf {self.name}.\")", "Optional[WorkflowMetadata]: return self._workflow_metadata @property def workflow_metadata_defaults(self): return self._workflow_metadata_defaults @property def python_interface(self) -> Interface:", "_workflow_function=None, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False, ): \"\"\" This decorator", "why the user is asked to provide the expected interface. If at registration", "isinstance(workflow_outputs, tuple): raise AssertionError(\"The Workflow specification indicates multiple return values, received only one\")", "already exists on your Flyte installation. This object will not initiate a network", "Node: return self.add_entity(launch_plan, **kwargs) def add_subwf(self, sub_wf: WorkflowBase, **kwargs) -> Node: return self.add_entity(sub_wf,", ") as comp_ctx: # Construct the default input promise bindings, but then override", "the TaskResolverMixin that this workflow class inherits from (ClassStorageTaskResolver) # does store state.", "causes an issue with compilation, an error will be returned. \"\"\" def wrapper(fn)", "= transform_interface_to_typed_interface(self._python_interface) def add_task(self, task: PythonTask, **kwargs) -> Node: return self.add_entity(task, **kwargs) def", "@property def short_name(self) -> str: return self._name.split(\".\")[-1] @property def workflow_metadata(self) -> Optional[WorkflowMetadata]: return", "Union[Tuple[Promise], Promise, VoidPromise]: # This is done to support the invariant that Workflow", "t = self.python_interface.outputs[out] b = binding_from_python_std( ctx, out, self.interface.outputs[out].type, workflow_outputs[i], t, ) bindings.append(b)", "def wrapper(fn) -> ReferenceWorkflow: interface = transform_signature_to_interface(inspect.signature(fn)) return ReferenceWorkflow(project, domain, name, version, interface.inputs,", "type for {output_name}\" f\" starting with the container type (e.g. List[int]\" ) python_type", "logger.debug(f\"WF {self.name} saving task {n.flyte_entity.name}\") self.add(n.flyte_entity) # Iterate through the workflow outputs bindings", "from flytekit.common import constants as _common_constants from flytekit.common.exceptions.user import FlyteValidationException, FlyteValueException from flytekit.core.base_task", "is run one at a time. \"\"\" if len(args) > 0: raise AssertionError(\"Only", "result, self.python_interface) raise ValueError(\"expected outputs and actual outputs do not match\") def execute(self,", "None, interruptible: Optional[bool] = False, ): metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults =", "-> bool: \"\"\" This function returns whether or not the workflow is in", "added as part of the task resolver change. The task resolver interface itself", "in this map. After all nodes are run, we fill in workflow level", "but should've been VoidPromise or None.\" ) expected_output_names = list(self.python_interface.outputs.keys()) if len(expected_output_names) ==", ") from flytekit.core.launch_plan import LaunchPlan from flytekit.core.node import Node from flytekit.core.promise import (", "else: return None # We are already in a local execution, just continue", "streamline the pattern between workflows and tasks. Since tasks call execute from dispatch_execute", "set. elif ( ctx.execution_state is not None and ctx.execution_state.mode == ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ): if", "# named tuple if self.python_interface.output_tuple_name: return (get_promise(self.output_bindings[0].binding, intermediate_node_outputs),) # Just a normal single", "Promise: \"\"\" This is a helper function that will turn a binding into", "def get_input_values(input_value): if isinstance(input_value, list): input_promises = [] for x in input_value: input_promises.extend(get_input_values(x))", "for {output_name}\" f\" starting with the container type (e.g. List[int]\" ) python_type =", "is because while we can determine the entire structure of a task by", "-> _local_execute -> execute From execute, different things happen for the two Workflow", "be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: n = create_node(entity=entity, **kwargs) def get_input_values(input_value): if", "first for a high-level understanding of what workflows are in Flyte. This Python", "GLOBAL_START_NODE = Node( id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None, bindings=[], upstream_nodes=[], flyte_entity=None, ) class WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY =", "all inputs to that entity should've been already declared, we can just iterate", "Promise objects should always point to the global start node. \"\"\" return self._inputs", "additional checking. \"\"\" if len(self.compilation_state.nodes) == 0: return False if len(self._unbound_inputs) > 0:", "{self.name}\") if python_type is None: if type(p) == list or type(p) == dict:", "a native value for {k}\") with FlyteContextManager.with_context( ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) ) ) as child_ctx:", "but elegant handling of them is not a high priority # Again, we're", "to support the invariant that Workflow local executions always work with Promise objects", "the calling and outputs of each node's entity results = entity(**entity_kwargs) expected_output_names =", "TypeEngine from flytekit.loggers import logger from flytekit.models import interface as _interface_models from flytekit.models", "Dict[str, Promise]], python_type: Optional[Type] = None ): \"\"\" Add an output with the", "all_nodes.extend(comp_ctx.compilation_state.nodes) # This little loop was added as part of the task resolver", "len(self.python_interface.outputs) if expected_outputs == 0: if result is None or isinstance(result, VoidPromise): return", "with an `else_()` clause\") t = self.python_interface.outputs[out] b = binding_from_python_std( ctx, out, self.interface.outputs[out].type,", "workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) self._compilation_state = CompilationState(prefix=\"\") self._inputs = {} # This unbound inputs", "should've been already declared, we can just iterate through the nodes in order", "understanding of what workflows are in Flyte. This Python object represents a workflow", "iterate through the nodes in order and we shouldn't run into any dependency", "usage examples. :param _workflow_function: This argument is implicitly passed and represents the decorated", "notwithstanding). Please see the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for more usage examples. :param _workflow_function: This argument", "flytekit.core.condition import ConditionalSection from flytekit.core.context_manager import ( BranchEvalMode, CompilationState, ExecutionState, FlyteContext, FlyteContextManager, FlyteEntities,", "of outputs, we create a map to start things off, filled in only", "[None for _ in self.python_interface.outputs.keys()] return output_tuple(*nones) else: return None # We are", "return None else: raise Exception(f\"Workflow local execution expected 0 outputs but something received", "output have to be pulled by fulfilling all of the # workflow's output", "workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) workflow_instance = PythonFunctionWorkflow( fn, metadata=workflow_metadata, default_metadata=workflow_metadata_defaults ) workflow_instance.compile() return workflow_instance", "any dependency issues. That is, we force the user to declare entities already", "be in launch plan only, but is here only so that we don't", "on that object for additional information. \"\"\" def __init__( self, workflow_function: Callable, metadata:", "the interface provided causes an issue with compilation, an error will be returned.", "ctx: b = binding_from_python_std( ctx, output_name, expected_literal_type=flyte_type, t_value=p, t_value_type=python_type ) self._output_bindings.append(b) self._python_interface =", "no cover # Move along, nothing to assign # Because we should've already", "TypeEngine.to_literal_type(python_type=python_type) ctx = FlyteContext.current_context() if ctx.compilation_state is not None: raise Exception(\"Can't already be", "expected_output_names = list(entity.python_interface.outputs.keys()) if isinstance(results, VoidPromise) or results is None: continue # pragma:", "-> Node: return self.add_entity(task, **kwargs) def add_launch_plan(self, launch_plan: LaunchPlan, **kwargs) -> Node: return", "= transform_signature_to_interface(inspect.signature(workflow_function)) # TODO do we need this - can this not be", "is a pointer to a workflow that already exists on your Flyte installation.", "was added as part of the task resolver change. The task resolver interface", "def execute(self, **kwargs): \"\"\" Called by _local_execute. This function is how local execution", "Even in a wf, a user can call a sub-workflow with a Python", "node at a time. if len(self.python_interface.outputs) == 0: return VoidPromise(self.name) # The values", "what workflows are in Flyte. This Python object represents a workflow defined by", "elif ( ctx.execution_state is not None and ctx.execution_state.mode == ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ): if ctx.execution_state.branch_eval_mode", "happen for the two Workflow styles. For PythonFunctionWorkflows, the Python function is run,", "List[str]): return { input_name: Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) for input_name in inputs } def", "= {expected_output_names[0]: function_outputs} else: wf_outputs_as_map = {expected_output_names[i]: function_outputs[i] for i, _ in enumerate(function_outputs)}", "if len(expected_output_names) == 1: if entity.python_interface.output_tuple_name and isinstance(results, tuple): intermediate_node_outputs[node][expected_output_names[0]] = results[0] else:", "List[_literal_models.Binding], outputs_cache: Dict[Node, Dict[str, Promise]] ) -> Dict[str, Promise]: \"\"\" Local execution of", "len(workflow_outputs): raise Exception(f\"Length mismatch {len(output_names)} vs {len(workflow_outputs)}\") for i, out in enumerate(output_names): if", "returned. \"\"\" def wrapper(fn) -> ReferenceWorkflow: interface = transform_signature_to_interface(inspect.signature(fn)) return ReferenceWorkflow(project, domain, name,", "entity: Union[PythonTask, LaunchPlan, WorkflowBase], **kwargs) -> Node: \"\"\" Anytime you add an entity,", "that Workflow local executions always work with Promise objects # holding Flyte literal", "to Admin, which is why the user is asked to provide the expected", "run, for the ImperativeWorkflow, each node is run one at a time. \"\"\"", "information but essentially, this WorkflowMetadataDefaults class represents the defaults that are handed down", "function_outputs is None: if len(self.python_interface.outputs) != 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but", "call at a time. This is why this workflow class has to keep", "node's entity results = entity(**entity_kwargs) expected_output_names = list(entity.python_interface.outputs.keys()) if isinstance(results, VoidPromise) or results", "variables = [k for k in self.python_interface.outputs.keys()] output_tuple = collections.namedtuple(self.python_interface.output_tuple_name, variables) nones =", "# Move along, nothing to assign # Because we should've already returned in", "with compilation, an error will be returned. \"\"\" def __init__( self, project: str,", "check, we just raise an error here. if len(self.python_interface.outputs) == 0: raise FlyteValueException(", "workflow defined by a function and decorated with the :py:func:`@workflow <flytekit.workflow>` decorator. Please", "Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) self._unbound_inputs.add(self._inputs[input_name]) return self._inputs[input_name] def add_workflow_output( self, output_name: str, p: Union[Promise,", "for Workflows is close to, but not exactly, the call pattern for Tasks.", "self.python_interface) raise ValueError(\"expected outputs and actual outputs do not match\") def execute(self, **kwargs):", "__future__ import annotations import collections import inspect from dataclasses import dataclass from enum", "self._workflow_function def task_name(self, t: PythonAutoContainerTask) -> str: return f\"{self.name}.{t.__module__}.{t.name}\" def compile(self, **kwargs): \"\"\"", "a bit at a time, one task or other entity call at a", "Promise]: \"\"\" This holds the input promises to the workflow. The nodes in", "def __post_init__(self): if ( self.on_failure != WorkflowFailurePolicy.FAIL_IMMEDIATELY and self.on_failure != WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ): raise", "have to re-evaluate. Or # we can re-evaluate. self._input_parameters = None super().__init__( name=name,", "can determine the entire structure of a task by looking at the function's", "str, name: str, version: str, ) -> Callable[[Callable[..., Any]], ReferenceWorkflow]: \"\"\" A reference", "it by looking up the promises the node's bindings require, # and then", "= bindings if not output_names: return None if len(output_names) == 1: return bindings[0]", "the name instead of value? all_input_values = get_input_values(kwargs) for input_value in filter(lambda x:", "self._workflow_metadata_defaults @property def python_interface(self) -> Interface: return self._python_interface @property def interface(self) -> _interface_models.TypedInterface:", "or isinstance(result, VoidPromise): return None else: raise Exception(f\"Workflow local execution expected 0 outputs", "of Python native values and Promises containing Flyte # Literals. function_outputs = self.execute(**kwargs)", "if len(results) != len(expected_output_names): raise FlyteValueException(results, f\"Different lengths {results} {expected_output_names}\") for idx, r", "necessary to create an SdkWorkflow, except for the missing project and domain self._nodes", "between tasks. Unlike a task, the function body of a workflow is evaluated", "least one node * All workflow inputs are bound These conditions assume that", "with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: n = create_node(entity=entity, **kwargs) def get_input_values(input_value): if isinstance(input_value, list):", "of the word. \"\"\" ctx = FlyteContextManager.current_context() self._input_parameters = transform_inputs_to_parameters(ctx, self.python_interface) all_nodes =", "resolving bindings, pulling in outputs from previously completed nodes and filling in the", "def _local_execute(self, ctx: FlyteContext, **kwargs) -> Union[Tuple[Promise], Promise, VoidPromise]: # This is done", "None.\" ) expected_output_names = list(self.python_interface.outputs.keys()) if len(expected_output_names) == 1: # Here we have", "= False, ): metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) self._compilation_state =", "the workflow to the workflow # object itself. for n in comp_ctx.compilation_state.nodes: if", "examples. :param _workflow_function: This argument is implicitly passed and represents the decorated function.", "tasks launched from this workflow are by default interruptible \"\"\" def wrapper(fn): workflow_metadata", "# if it's a single element then we return a single element if", "a task, the function body of a workflow is evaluated at serialization-time (aka", "the _local_execute call generally expects inputs to be Promises, we don't have to", "from flytekit.core.reference_entity import ReferenceEntity, WorkflowReference from flytekit.core.type_engine import TypeEngine from flytekit.loggers import logger", "return self.add_entity(launch_plan, **kwargs) def add_subwf(self, sub_wf: WorkflowBase, **kwargs) -> Node: return self.add_entity(sub_wf, **kwargs)", "as comp_ctx: # Construct the default input promise bindings, but then override with", "if not output_names: return None if len(output_names) == 1: return bindings[0] return tuple(bindings)", "in a local execution, just continue the execution context return self._local_execute(ctx, **input_kwargs) #", "for Tasks. For local execution, it goes __call__ -> _local_execute -> execute From", "in kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k] = v # Next iterate through the nodes in order.", "class WorkflowMetadata(object): on_failure: WorkflowFailurePolicy def __post_init__(self): if ( self.on_failure != WorkflowFailurePolicy.FAIL_IMMEDIATELY and self.on_failure", "the above check, we just raise an error here. if len(self.python_interface.outputs) == 0:", "in launchplan only? # This can be in launch plan only, but is", "bd in binding_data.map.bindings.items(): p = get_promise(bd, outputs_cache) literals[k] = p.val return Promise( var=\"placeholder\",", "here. if len(entity.python_interface.outputs) == 0: raise FlyteValueException(results, f\"{results} received but should've been VoidPromise", "_common_constants from flytekit.common.exceptions.user import FlyteValidationException, FlyteValueException from flytekit.core.base_task import PythonTask from flytekit.core.class_based_resolver import", "isinstance(function_outputs, VoidPromise) or function_outputs is None: if len(self.python_interface.outputs) != 0: raise FlyteValueException( function_outputs,", "specifying a list or dict of Promises, you must specify the python_type type", "inputs, outputs) def reference_workflow( project: str, domain: str, name: str, version: str, )", "0: return False return True class PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver): \"\"\" Please read :std:ref:`flyte:divedeep-workflows` first", "the call pattern for Tasks. For local execution, it goes __call__ -> _local_execute", "**kwargs) def get_input_values(input_value): if isinstance(input_value, list): input_promises = [] for x in input_value:", "None else \"\" with FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self)) ) as comp_ctx: # Construct the", "inputs to be Promises, we don't have to do the # conversion here", "any input_kwargs = construct_input_promises([k for k in self.interface.inputs.keys()]) input_kwargs.update(kwargs) workflow_outputs = self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes)", "This loop adds Tasks that are defined within the body of the workflow", "map of nodes to its outputs. Basically this takes the place of propeller", "because we don't prevent users from specifying inputs # as direct scalars, which", "in order and we shouldn't run into any dependency issues. That is, we", "len(expected_output_names): raise FlyteValueException(results, f\"Different lengths {results} {expected_output_names}\") for idx, r in enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]]", "entities since they are only run once (again, this is with respect to", "is the name of the upstream node's output we want return outputs_cache[binding_data.promise.node][binding_data.promise.var] elif", "if ctx.compilation_state is not None: return create_and_link_node(ctx, entity=self, interface=self.python_interface, **input_kwargs) # This condition", "from __future__ import annotations import collections import inspect from dataclasses import dataclass from", "from flytekit.core.class_based_resolver import ClassStorageTaskResolver from flytekit.core.condition import ConditionalSection from flytekit.core.context_manager import ( BranchEvalMode,", "f\"Different lengths {results} {expected_output_names}\") for idx, r in enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]] = r #", "iterate through the nodes in order. for node in self.compilation_state.nodes: if node not", "get_promise(self.output_bindings[0].binding, intermediate_node_outputs) return tuple([get_promise(b.binding, intermediate_node_outputs) for b in self.output_bindings]) def add_entity(self, entity: Union[PythonTask,", "node's entity's input arguments, which are specified using the bindings list, and a", "to assign # Because we should've already returned in the above check, we", "input_name: str, python_type: Type) -> Interface: \"\"\" Adds an input to the workflow.", "in the compilation. This mimics a 'closure' in the traditional sense of the", "f\"{self.name}.{t.__module__}.{t.name}\" def compile(self, **kwargs): \"\"\" Supply static Python native values in the kwargs", "a topological sort. To keep track of outputs, we create a map to", "raise Exception(f\"Length mismatch {len(output_names)} vs {len(workflow_outputs)}\") for i, out in enumerate(output_names): if isinstance(workflow_outputs[i],", "try to streamline the pattern between workflows and tasks. Since tasks call execute", "global input node, i.e. the inputs to the workflow. # _local_execute should've already", "inputs } def get_promise(binding_data: _literal_models.BindingData, outputs_cache: Dict[Node, Dict[str, Promise]]) -> Promise: \"\"\" This", "self.on_failure != WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ): raise FlyteValidationException(f\"Failure policy {self.on_failure} not acceptable\") def to_flyte_model(self): if", "workflow inputs (if any). As things are run, their outputs are stored in", "not in intermediate_node_outputs.keys(): intermediate_node_outputs[node] = {} # Retrieve the entity from the node,", "with a one-element # named tuple if self.python_interface.output_tuple_name: return (get_promise(self.output_bindings[0].binding, intermediate_node_outputs),) # Just", "intermediate_node_outputs[node][expected_output_names[0]] = results else: if len(results) != len(expected_output_names): raise FlyteValueException(results, f\"Different lengths {results}", "-> Promise: \"\"\" This is a helper function that will turn a binding", "binding_data.map.bindings.items(): p = get_promise(bd, outputs_cache) literals[k] = p.val return Promise( var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) )", "That is, we force the user to declare entities already in a topological", "- can this not be in launchplan only? # This can be in", "bindings. # The return style here has to match what 1) what the", "node in self.compilation_state.nodes: if node not in intermediate_node_outputs.keys(): intermediate_node_outputs[node] = {} # Retrieve", "a workflow that already exists on your Flyte installation. This object will not", "through the nodes in order. for node in self.compilation_state.nodes: if node not in", "function will fill in the node's entity's input arguments, which are specified using", "All workflow inputs are bound These conditions assume that all nodes and workflow", "workflow local run. # The context specifying the local workflow execution has already", "That is, if it's a tuple, then it # should be a tuple", "the latter we get None if isinstance(function_outputs, VoidPromise) or function_outputs is None: if", "if not isinstance(v, Promise): t = self.python_interface.inputs[k] kwargs[k] = Promise(var=k, val=TypeEngine.to_literal(ctx, v, t,", "that are defined within the body of the workflow to the workflow #", "a helper function that will turn a binding into a Promise object, using", "domain self._nodes = all_nodes self._output_bindings = bindings if not output_names: return None if", "nodes(self) -> List[Node]: return self._nodes def __repr__(self): return ( f\"WorkflowBase - {self._name} &&", "of this will always be a combination of Python native values and Promises", "that are Promises so let's filter for those. # There's probably a way", "**input_kwargs) # Last is starting a local workflow execution else: # Run some", "import constants as _common_constants from flytekit.common.exceptions.user import FlyteValidationException, FlyteValueException from flytekit.core.base_task import PythonTask" ]
[ "+ betas[T - 1, U - 1]) # The above is also equivalent", "Unless required by applicable law or agreed to in writing, software # distributed", "if T != max_T: raise ValueError(f\"Input length mismatch! Given T: {T}, Expected max", "- 1] # // grad to last blank transition grads[T - 1, U", "Unused. Tensor of shape [T, U] which represents the backward variable. blank: Index", "1, blank]) return -reg def transduce(log_probs, labels, blank=0, fastemit_lambda=0.0): \"\"\" Args: log_probs: 3D", "forward_pass(log_probs, labels, blank) betas, ll_backward = backward_pass(log_probs, labels, blank) grads = compute_gradient(log_probs, alphas,", "# for u in range(0, U - 1): # emit = alphas[t, u]", "also equivalent to below, without need of computing the betas alignment matrix reg", "fastemit_lambda ) ll += reg costs.append(ll) return costs, grads class _RNNT(Function): @staticmethod def", "- 1, blank] for u in reversed(range(U - 1)): betas[T - 1, u]", "raise ValueError(f\"Input length mismatch! Given T: {T}, Expected max T from input lengths:", "u, l] return grads def fastemit_regularization(log_probs, labels, alphas, betas, blank, fastemit_lambda): \"\"\" Describes", "-reg def transduce(log_probs, labels, blank=0, fastemit_lambda=0.0): \"\"\" Args: log_probs: 3D array with shape", "check_contiguous(var, name): if not var.is_contiguous(): raise ValueError(\"{} must be contiguous\".format(name)) def check_dim(var, dim,", "log_like = betas[0, 0] # == alphas[T - 1, U - 1] +", "blank, fastemit_lambda): \"\"\" Computes the gradients of the log_probs with respect to the", "the gradients of the activation matrix. \"\"\" grads = np.zeros_like(log_probs) costs = []", "U != max_U + 1: raise ValueError(f\"Output length mismatch! Given U: {U}, Expected", "forward variable. betas: Tensor of shape [T, U] which represents the backward variable.", "1] + log_probs[t, u - 1, labels[u - 1]] alphas[t, u] = np.logaddexp(emit,", "this forward step. \"\"\" T, U, _ = log_probs.shape alphas = np.zeros((T, U),", "of the log_probs with respect to the log probability of this step occuring.", "# General calculation of the fastemit regularization alignments T, U, _ = log_probs.shape", "- 1] = log_probs[T - 1, U - 1, blank] for t in", "u] = np.logaddexp(emit, no_emit) return betas, betas[0, 0] def compute_gradient(log_probs, alphas, betas, labels,", "grads = -np.exp(grads + log_probs - log_like) if fastemit_lambda > 0.0: for u,", "[T, U] which represents the forward variable. betas: Unused. Tensor of shape [T,", "1, u] = betas[T - 1, u + 1] + log_probs[T - 1,", "log_probs.shape # alignment = np.zeros((T, U), dtype='float32') # # for t in range(0,", "blank token. fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: float: The negative", "blank: Id of the blank token. fastemit_lambda: Float scaling factor for FastEmit regularization.", "self.rnnt = _RNNT.apply def forward(self, acts, labels, act_lens, label_lens): assert len(labels.size()) == 2", "acts, labels, act_lens, label_lens): assert len(labels.size()) == 2 _assert_no_grad(labels) _assert_no_grad(act_lens) _assert_no_grad(label_lens) certify_inputs(acts, labels,", "log_probs[t - 1, 0, blank] for u in range(1, U): alphas[0, u] =", "a length per example. \" f\"Given lengths dim: {lengths.shape[0]}, \" f\"Log probs dim", "for u, l in enumerate(labels): grads[:, u, l] = alphas[:, u] + betas[:,", "# reg = fastemit_lambda * (alignment[T - 1, U - 1]) # The", "normalized with log-softmax. labels: [B, U+1] - ground truth labels with <SOS> padded", "= log_probs.shape[1:3] if T != max_T: raise ValueError(f\"Input length mismatch! Given T: {T},", "U, _ = log_probs.shape grads = np.full(log_probs.shape, -float(\"inf\")) log_like = betas[0, 0] #", "# The above is equivalent to below, without need of computing above #", "[T, U, V+1] labels: Unused. Labels of shape [B, U] alphas: Tensor of", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "Labels of shape [B, U] blank: Index of the blank token. Returns: A", "for FastEmit regularization. Returns: float: The negative log-likelihood 3D array: Gradients with respect", "alignments T, U, _ = log_probs.shape # alignment = np.zeros((T, U), dtype='float32') #", "= betas[0, 0] # == alphas[T - 1, U - 1] + betas[T", "regularized negative log likelihood - lambda * P˜(At, u|x) \"\"\" # General calculation", "# # Copyright 2018-2019, <NAME> # # Licensed under the Apache License, Version", "\" f\"Given label lengths dim : {label_lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\"", "1)): betas[t, U - 1] = betas[t + 1, U - 1] +", "= alphas[:, u] + betas[:, u + 1] grads = -np.exp(grads + log_probs", "def forward(ctx, acts, labels, act_lens, label_lens, blank, fastemit_lambda): costs, grads = transduce_batch( acts.detach().cpu().numpy(),", "1, \"label_lenghts\") max_T = torch.max(lengths) max_U = torch.max(label_lengths) T, U = log_probs.shape[1:3] if", "the forward variable. betas: Tensor of shape [T, U] which represents the backward", "for u in range(0, U - 1): # emit = alphas[t, u] +", "respect to the unnormalized input actications 2d arrays: Alphas matrix (TxU) 2d array:", "for FastEmit regularization. Returns: Batch of transducer forward log probabilities (loss) and the", "1, blank] for t in reversed(range(T - 1)): betas[t, U - 1] =", "t, name): if var.dtype is not t: raise TypeError(\"{} must be {}\".format(name, t))", "check_dim(lengths, 1, \"lenghts\") check_dim(label_lengths, 1, \"label_lenghts\") max_T = torch.max(lengths) max_U = torch.max(label_lengths) T,", "reg = fastemit_lambda * (alphas[T - 1, U - 1] + betas[T -", "the activation matrix. \"\"\" grads = np.zeros_like(log_probs) costs = [] for b in", "labels[u]] betas[t, u] = np.logaddexp(emit, no_emit) return betas, betas[0, 0] def compute_gradient(log_probs, alphas,", "ll_backward = backward_pass(log_probs, labels, blank) grads = compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda)", "transduce(log_probs, labels, blank=0, fastemit_lambda=0.0): \"\"\" Args: log_probs: 3D array with shape [input len,", "is not t: raise TypeError(\"{} must be {}\".format(name, t)) def check_contiguous(var, name): if", "in reversed(range(U - 1)): no_emit = betas[t + 1, u] + log_probs[t, u,", "log probability \"\"\" T, U, _ = log_probs.shape grads = np.full(log_probs.shape, -float(\"inf\")) log_like", "as not requiring gradients\" ) def forward_pass(log_probs, labels, blank): \"\"\" Computes probability of", "with log-softmax. labels: [B, U+1] - ground truth labels with <SOS> padded as", "!= max_T: raise ValueError(f\"Input length mismatch! Given T: {T}, Expected max T from", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "l in enumerate(labels): grads[:, u, l] = alphas[:, u] + betas[:, u +", "this backward step. \"\"\" T, U, _ = log_probs.shape betas = np.zeros((T, U),", "shape [input len, output len + 1, vocab size] labels: 1D array with", "the target sequence. blank: Id of the blank token. fastemit_lambda: Float scaling factor", "labels, blank) betas, ll_backward = backward_pass(log_probs, labels, blank) grads = compute_gradient(log_probs, alphas, betas,", "Alphas matrix (TxU) 2d array: Betas matrix (TxU) \"\"\" alphas, ll_forward = forward_pass(log_probs,", "respect to the log probability of this step occuring. Args: Args: log_probs: Tensor", "Length vector of the acoustic sequence. glen: Length vector of the target sequence.", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "torch.FloatTensor([sum(costs)]) grads = torch.Tensor(grads).to(acts) ctx.grads = grads return costs @staticmethod def backward(ctx, grad_output):", "1]] alphas[t, u] = np.logaddexp(emit, no_emit) loglike = alphas[T - 1, U -", "u in range(1, U): no_emit = alphas[t - 1, u] + log_probs[t -", "shape [T, U, V+1] labels: Unused. Labels of shape [B, U] alphas: Tensor", "u, labels[u]] for t in reversed(range(T - 1)): for u in reversed(range(U -", "RNNTLoss(Module): \"\"\" Parameters: `blank_label` (int): default 0 - label index of blank token", "+ log_probs[t - 1, 0, blank] for u in range(1, U): alphas[0, u]", "log_probs - please \" \"mark other tensors as not requiring gradients\" ) def", "computed for log_probs - please \" \"mark other tensors as not requiring gradients\"", "- 1], blank, fastemit_lambda) grads[b, :t, :u, :] = g reg = fastemit_regularization(", "of this forward step. \"\"\" T, U, _ = log_probs.shape alphas = np.zeros((T,", "reversed(range(T - 1)): for u in reversed(range(U - 1)): no_emit = betas[t +", "T, U, _ = log_probs.shape alphas = np.zeros((T, U), dtype='f') for t in", "tuple of the backward variable probabilities - beta of shape [T, U] and", "u - 1, labels[u - 1]] for t in range(1, T): for u", "which represents the backward variable. labels: Labels of shape [B, U] blank: Index", "U from target lengths: {max_U} + 1\") def _assert_no_grad(tensor): assert not tensor.requires_grad, (", "- ground truth labels with <SOS> padded as blank token in the beginning.", "= fastemit_lambda self.rnnt = _RNNT.apply def forward(self, acts, labels, act_lens, label_lens): assert len(labels.size())", "1): # emit = alphas[t, u] + log_probs[t, u, labels[u]] + betas[t, u", "per example. \" f\"Given lengths dim: {lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\"", "the specific language governing permissions and # limitations under the License. import numpy", "- 1, labels[u - 1]] alphas[t, u] = np.logaddexp(emit, no_emit) loglike = alphas[T", "variable probabilities - beta of shape [T, U] and the log likelihood of", "0] def compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda): \"\"\" Computes the gradients of", "betas[t, U - 1] # # for t in range(0, T): # for", "which represents the forward variable. betas: Tensor of shape [T, U] which represents", "U, _ = log_probs.shape # alignment = np.zeros((T, U), dtype='float32') # # for", "+ 1 ll, g, alphas, betas = transduce(log_probs[b, :t, :u, :], labels[b, :", "(alignment[T - 1, U - 1]) # The above is equivalent to below,", "with shape [output time steps] blank: Index of the blank token. fastemit_lambda: Float", "T - 1, :] + betas[1:, :] # // grad to label transition", "- 1] = betas[t + 1, U - 1] + log_probs[t, U -", "step occuring. Args: Args: log_probs: Tensor of shape [T, U, V+1] alphas: Tensor", "return costs @staticmethod def backward(ctx, grad_output): return ctx.grads, None, None, None, None, None", "need of computing the betas alignment matrix reg = fastemit_lambda * (alphas[T -", "super(RNNTLoss, self).__init__() self.blank = blank self.fastemit_lambda = fastemit_lambda self.rnnt = _RNNT.apply def forward(self,", "U, V+1] labels: Labels of shape [B, U] blank: Index of the blank", "[T, U] which represents the backward variable. labels: Labels of shape [B, U]", "in enumerate(labels): grads[:, u, l] = alphas[:, u] + betas[:, u + 1]", "\"log_probs\") check_type(labels, torch.int32, \"labels\") check_type(label_lengths, torch.int32, \"label_lengths\") check_type(lengths, torch.int32, \"lengths\") check_contiguous(log_probs, \"log_probs\") check_contiguous(labels,", "be {}\".format(name, t)) def check_contiguous(var, name): if not var.is_contiguous(): raise ValueError(\"{} must be", "grads, alphas, betas def transduce_batch(log_probs, labels, flen, glen, blank=0, fastemit_lambda=0.0): \"\"\" Compute the", "blank, fastemit_lambda ) ll += reg costs.append(ll) return costs, grads class _RNNT(Function): @staticmethod", "Computes probability of the forward variable alpha. Args: log_probs: Tensor of shape [T,", "betas: Unused. Tensor of shape [T, U] which represents the backward variable. blank:", "raise ValueError( \"Must have a label length per example. \" f\"Given label lengths", "- 1, U - 1] = log_probs[T - 1, U - 1, blank]", "1], alphas, betas, blank, fastemit_lambda ) ll += reg costs.append(ll) return costs, grads", "check_dim(var, dim, name): if len(var.shape) != dim: raise ValueError(\"{} must be {}D\".format(name, dim))", "T: {T}, Expected max T from input lengths: {max_T}\") if U != max_U", "not use this file except in compliance with the License. # You may", "blank] for t in reversed(range(T - 1)): betas[t, U - 1] = betas[t", "np.logaddexp(emit, no_emit) loglike = alphas[T - 1, U - 1] + log_probs[T -", "\"\"\" Parameters: `blank_label` (int): default 0 - label index of blank token fastemit_lambda:", "and the log likelihood of this forward step. \"\"\" T, U, _ =", "= torch.randn(1, 2, 5, 3) labels = torch.tensor([[0, 2, 1, 2]], dtype=torch.int32) act_lens", "import Module def check_type(var, t, name): if var.dtype is not t: raise TypeError(\"{}", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "lambda * P˜(At, u|x) \"\"\" # General calculation of the fastemit regularization alignments", "and # limitations under the License. # # Copyright 2018-2019, <NAME> # #", "of shape [T, U] which represents the backward variable. labels: Labels of shape", "blank token. fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: Batch of transducer", "- 1]) # The above is equivalent to below, without need of computing", "None class RNNTLoss(Module): \"\"\" Parameters: `blank_label` (int): default 0 - label index of", "return ctx.grads, None, None, None, None, None class RNNTLoss(Module): \"\"\" Parameters: `blank_label` (int):", "+ 1] + log_probs[t, u, labels[u]] betas[t, u] = np.logaddexp(emit, no_emit) return betas,", "1, u, blank] emit = alphas[t, u - 1] + log_probs[t, u -", "U] which represents the backward variable. labels: Labels of shape [B, U] blank:", "agreed to in writing, software # distributed under the License is distributed on", "- 1, 0, blank] for u in range(1, U): alphas[0, u] = alphas[0,", "transducer forward log probabilities (loss) and the gradients of the activation matrix. \"\"\"", "acts.detach().cpu().numpy(), labels.cpu().numpy(), act_lens.cpu().numpy(), label_lens.cpu().numpy(), blank, fastemit_lambda, ) costs = torch.FloatTensor([sum(costs)]) grads = torch.Tensor(grads).to(acts)", "without need of computing the betas alignment matrix reg = fastemit_lambda * (alphas[T", "3D array: Gradients with respect to the unnormalized input actications 2d arrays: Alphas", "Variable from torch.nn import Module def check_type(var, t, name): if var.dtype is not", "blank: Index of the blank token. Returns: A tuple of the backward variable", "computing above # reg = fastemit_lambda * (alphas[T - 1, U - 1]", "return -reg def transduce(log_probs, labels, blank=0, fastemit_lambda=0.0): \"\"\" Args: log_probs: 3D array with", "forward(self, acts, labels, act_lens, label_lens): assert len(labels.size()) == 2 _assert_no_grad(labels) _assert_no_grad(act_lens) _assert_no_grad(label_lens) certify_inputs(acts,", "vector of the target sequence. blank: Id of the blank token. fastemit_lambda: Float", "the transducer loss of the batch. Args: log_probs: [B, T, U, V+1]. Activation", "shape [B, U] blank: Index of the blank token. Returns: A tuple of", "probability \"\"\" T, U, _ = log_probs.shape grads = np.full(log_probs.shape, -float(\"inf\")) log_like =", "labels[b, : u - 1], blank, fastemit_lambda) grads[b, :t, :u, :] = g", "dim: {lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\" ) if label_lengths.shape[0] != log_probs.shape[0]:", "u + 1] grads = -np.exp(grads + log_probs - log_like) if fastemit_lambda >", "0, fastemit_lambda: float = 0.0): super(RNNTLoss, self).__init__() self.blank = blank self.fastemit_lambda = fastemit_lambda", "= 0, fastemit_lambda: float = 0.0): super(RNNTLoss, self).__init__() self.blank = blank self.fastemit_lambda =", "with respect to the forward log probability \"\"\" T, U, _ = log_probs.shape", "Batch of transducer forward log probabilities (loss) and the gradients of the activation", "The regularized negative log likelihood - lambda * P˜(At, u|x) \"\"\" # General", "U - 1, blank] = alphas[T - 1, U - 1] grads[: T", "= fastemit_lambda * (alphas[T - 1, U - 1] + betas[T - 1,", "to in writing, software # distributed under the License is distributed on an", "def transduce(log_probs, labels, blank=0, fastemit_lambda=0.0): \"\"\" Args: log_probs: 3D array with shape [input", "log_probs[t, u, blank] emit = betas[t, u + 1] + log_probs[t, u, labels[u]]", "backward_pass(log_probs, labels, blank): \"\"\" Computes probability of the backward variable beta. Args: log_probs:", "- 1] + betas[t, U - 1] # # for t in range(0,", "fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: float: The negative log-likelihood 3D", "implied. # See the License for the specific language governing permissions and #", "== 2 _assert_no_grad(labels) _assert_no_grad(act_lens) _assert_no_grad(label_lens) certify_inputs(acts, labels, act_lens, label_lens) acts = torch.nn.functional.log_softmax(acts, -1)", "regularization. Returns: float: The negative log-likelihood 3D array: Gradients with respect to the", "of the forward variable probabilities - alpha of shape [T, U] and the", "labels, act_lens, label_lens): assert len(labels.size()) == 2 _assert_no_grad(labels) _assert_no_grad(act_lens) _assert_no_grad(label_lens) certify_inputs(acts, labels, act_lens,", "gradients of the activation matrix. \"\"\" grads = np.zeros_like(log_probs) costs = [] for", "# check_type(log_probs, torch.float32, \"log_probs\") check_type(labels, torch.int32, \"labels\") check_type(label_lengths, torch.int32, \"label_lengths\") check_type(lengths, torch.int32, \"lengths\")", ":] + betas[1:, :] # // grad to label transition for u, l", "U = log_probs.shape[1:3] if T != max_T: raise ValueError(f\"Input length mismatch! Given T:", "variable. labels: Labels of shape [B, U] blank: Index of the blank token.", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "1] + log_probs[T - 1, U - 1, blank] return alphas, loglike def", "self.fastemit_lambda) if __name__ == '__main__': loss = RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0) acts = torch.randn(1, 2,", "the forward log probability \"\"\" T, U, _ = log_probs.shape grads = np.full(log_probs.shape,", "T): # alignment[t, U - 1] = alphas[t, U - 1] + betas[t,", "alphas, betas def transduce_batch(log_probs, labels, flen, glen, blank=0, fastemit_lambda=0.0): \"\"\" Compute the transducer", "activation matrix. \"\"\" grads = np.zeros_like(log_probs) costs = [] for b in range(log_probs.shape[0]):", "for b in range(log_probs.shape[0]): t = int(flen[b]) u = int(glen[b]) + 1 ll,", "- 1] + log_probs[T - 1, U - 1, blank] return alphas, loglike", "shape [B, U] alphas: Tensor of shape [T, U] which represents the forward", "probability of the backward variable beta. Args: log_probs: Tensor of shape [T, U,", "act_lens = torch.tensor([2], dtype=torch.int32) label_lens = torch.tensor([len(labels[0])], dtype=torch.int32) loss_val = loss(acts, labels, act_lens,", "# See the License for the specific language governing permissions and # limitations", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "padded as blank token in the beginning. flen: Length vector of the acoustic", "len(labels.size()) == 2 _assert_no_grad(labels) _assert_no_grad(act_lens) _assert_no_grad(label_lens) certify_inputs(acts, labels, act_lens, label_lens) acts = torch.nn.functional.log_softmax(acts,", "np.zeros((T, U), dtype='f') for t in range(1, T): alphas[t, 0] = alphas[t -", "l in enumerate(labels): grads[:, u, l] = (1.0 + fastemit_lambda) * grads[:, u,", "and # limitations under the License. import numpy as np import torch from", "alphas, betas, blank, fastemit_lambda): \"\"\" Describes the computation of FastEmit regularization from the", "[input len, output len + 1, vocab size] labels: 1D array with shape", "1] + betas[t, U - 1] # # for t in range(0, T):", "forward log probability \"\"\" T, U, _ = log_probs.shape grads = np.full(log_probs.shape, -float(\"inf\"))", "fastemit_lambda): costs, grads = transduce_batch( acts.detach().cpu().numpy(), labels.cpu().numpy(), act_lens.cpu().numpy(), label_lens.cpu().numpy(), blank, fastemit_lambda, ) costs", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "label_lens): assert len(labels.size()) == 2 _assert_no_grad(labels) _assert_no_grad(act_lens) _assert_no_grad(label_lens) certify_inputs(acts, labels, act_lens, label_lens) acts", "you may not use this file except in compliance with the License. #", "U] and the log likelihood of this backward step. \"\"\" T, U, _", "ValueError( \"Must have a label length per example. \" f\"Given label lengths dim", "default 0 - label index of blank token fastemit_lambda: Float scaling factor for", "U] which represents the backward variable. blank: Index of the blank token. fastemit_lambda:", "alignment matrix reg = fastemit_lambda * (alphas[T - 1, U - 1] +", "= int(glen[b]) + 1 ll, g, alphas, betas = transduce(log_probs[b, :t, :u, :],", "1] = alphas[t, U - 1] + betas[t, U - 1] # #", "- beta of shape [T, U] and the log likelihood of this backward", "betas, ll_backward = backward_pass(log_probs, labels, blank) grads = compute_gradient(log_probs, alphas, betas, labels, blank,", "emit = betas[t, u + 1] + log_probs[t, u, labels[u]] betas[t, u] =", "the backward variable. blank: Index of the blank token. fastemit_lambda: Float scaling factor", "FastEmit regularization from the paper - [FastEmit: Low-latency Streaming ASR with Sequence-level Emission", ") check_dim(log_probs, 4, \"log_probs\") check_dim(labels, 2, \"labels\") check_dim(lengths, 1, \"lenghts\") check_dim(label_lengths, 1, \"label_lenghts\")", "alphas[t, 0] = alphas[t - 1, 0] + log_probs[t - 1, 0, blank]", "the beginning. flen: Length vector of the acoustic sequence. glen: Length vector of", "ASR with Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148) Args: log_probs: Tensor of shape [T, U, V+1]", "length per example. \" f\"Given lengths dim: {lengths.shape[0]}, \" f\"Log probs dim :", "u] + log_probs[t, u, labels[u]] + betas[t, u + 1] # alignment[t, u]", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "dim: raise ValueError(\"{} must be {}D\".format(name, dim)) def certify_inputs(log_probs, labels, lengths, label_lengths): #", "Index of the blank token. Returns: A tuple of the forward variable probabilities", "probs dim : {log_probs.shape[0]}\" ) check_dim(log_probs, 4, \"log_probs\") check_dim(labels, 2, \"labels\") check_dim(lengths, 1,", "the computation of FastEmit regularization from the paper - [FastEmit: Low-latency Streaming ASR", "def check_type(var, t, name): if var.dtype is not t: raise TypeError(\"{} must be", "def certify_inputs(log_probs, labels, lengths, label_lengths): # check_type(log_probs, torch.float32, \"log_probs\") check_type(labels, torch.int32, \"labels\") check_type(label_lengths,", "V+1] alphas: Tensor of shape [T, U] which represents the forward variable. betas:", "mismatch! Given U: {U}, Expected max U from target lengths: {max_U} + 1\")", "log-likelihood 3D array: Gradients with respect to the unnormalized input actications 2d arrays:", "probabilities - alpha of shape [T, U] and the log likelihood of this", "U - 1, blank] for t in reversed(range(T - 1)): betas[t, U -", "Args: log_probs: Tensor of shape [T, U, V+1] alphas: Tensor of shape [T,", "log probability of this step occuring. Args: Args: log_probs: Tensor of shape [T,", "+ 1, vocab size] labels: 1D array with shape [output time steps] blank:", "label_lengths): # check_type(log_probs, torch.float32, \"log_probs\") check_type(labels, torch.int32, \"labels\") check_type(label_lengths, torch.int32, \"label_lengths\") check_type(lengths, torch.int32,", "# reg = fastemit_lambda * (alphas[T - 1, U - 1] + betas[T", "1] + betas[T - 1, U - 1]) # The above is also", "= log_probs.shape alphas = np.zeros((T, U), dtype='f') for t in range(1, T): alphas[t,", "U] blank: Index of the blank token. Returns: Gradients of shape [T, U,", "of this backward step. \"\"\" T, U, _ = log_probs.shape betas = np.zeros((T,", "\"\"\" alphas, ll_forward = forward_pass(log_probs, labels, blank) betas, ll_backward = backward_pass(log_probs, labels, blank)", "fastemit_lambda > 0.0: for u, l in enumerate(labels): grads[:, u, l] = (1.0", "compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda): \"\"\" Computes the gradients of the log_probs", "assert not tensor.requires_grad, ( \"gradients only computed for log_probs - please \" \"mark", "1] + log_probs[T - 1, U - 1, blank]) return -reg def transduce(log_probs,", "blank token. Returns: Gradients of shape [T, U, V+1] with respect to the", "U - 1] grads[: T - 1, :, blank] = alphas[: T -", "betas[t + 1, u] + log_probs[t, u, blank] emit = betas[t, u +", "log_probs.shape alphas = np.zeros((T, U), dtype='f') for t in range(1, T): alphas[t, 0]", "torch.randn(1, 2, 5, 3) labels = torch.tensor([[0, 2, 1, 2]], dtype=torch.int32) act_lens =", "U] which represents the forward variable. betas: Tensor of shape [T, U] which", "1] = log_probs[T - 1, U - 1, blank] for t in reversed(range(T", "[T, U] and the log likelihood of this backward step. \"\"\" T, U,", "variable. betas: Tensor of shape [T, U] which represents the backward variable. labels:", "lengths.shape[0] != log_probs.shape[0]: raise ValueError( f\"Must have a length per example. \" f\"Given", "Tensor of shape [T, U] which represents the forward variable. betas: Tensor of", "log_probs: Tensor of shape [T, U, V+1] alphas: Tensor of shape [T, U]", "{log_probs.shape[0]}\" ) check_dim(log_probs, 4, \"log_probs\") check_dim(labels, 2, \"labels\") check_dim(lengths, 1, \"lenghts\") check_dim(label_lengths, 1,", "[B, U+1] - ground truth labels with <SOS> padded as blank token in", "1] + log_probs[T - 1, u, labels[u]] for t in reversed(range(T - 1)):", "of shape [B, U] alphas: Tensor of shape [T, U] which represents the", "# The above is also equivalent to below, without need of computing the", "\"\"\" Describes the computation of FastEmit regularization from the paper - [FastEmit: Low-latency", "alignment[t, u] = emit # reg = fastemit_lambda * (alignment[T - 1, U", "alphas, loglike def backward_pass(log_probs, labels, blank): \"\"\" Computes probability of the backward variable", "u, l in enumerate(labels): grads[:, u, l] = (1.0 + fastemit_lambda) * grads[:,", "betas alignment matrix reg = fastemit_lambda * (alphas[T - 1, U - 1]", "1]] for t in range(1, T): for u in range(1, U): no_emit =", "License. # # Copyright 2018-2019, <NAME> # # Licensed under the Apache License,", "1] # alignment[t, u] = emit # reg = fastemit_lambda * (alignment[T -", "2, \"labels\") check_dim(lengths, 1, \"lenghts\") check_dim(label_lengths, 1, \"label_lenghts\") max_T = torch.max(lengths) max_U =", "language governing permissions and # limitations under the License. # # Copyright 2018-2019,", "the backward variable beta. Args: log_probs: Tensor of shape [T, U, V+1] labels:", "labels[u - 1]] for t in range(1, T): for u in range(1, U):", "= forward_pass(log_probs, labels, blank) betas, ll_backward = backward_pass(log_probs, labels, blank) grads = compute_gradient(log_probs,", "act_lens, label_lens) acts = torch.nn.functional.log_softmax(acts, -1) return self.rnnt(acts, labels, act_lens, label_lens, self.blank, self.fastemit_lambda)", "int(flen[b]) u = int(glen[b]) + 1 ll, g, alphas, betas = transduce(log_probs[b, :t,", "# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under", "betas, labels, blank, fastemit_lambda): \"\"\" Computes the gradients of the log_probs with respect", "= alphas[t, u] + log_probs[t, u, labels[u]] + betas[t, u + 1] #", "grads class _RNNT(Function): @staticmethod def forward(ctx, acts, labels, act_lens, label_lens, blank, fastemit_lambda): costs,", "- 1, labels[u - 1]] for t in range(1, T): for u in", "scaling factor for FastEmit regularization. Returns: The regularized negative log likelihood - lambda", "no_emit) loglike = alphas[T - 1, U - 1] + log_probs[T - 1,", "{U}, Expected max U from target lengths: {max_U} + 1\") def _assert_no_grad(tensor): assert", "u] = alphas[0, u - 1] + log_probs[0, u - 1, labels[u -", "- 1, U - 1] grads[: T - 1, :, blank] = alphas[:", "backward variable. labels: Labels of shape [B, U] blank: Index of the blank", "scaling factor for FastEmit regularization. Returns: Batch of transducer forward log probabilities (loss)", "= fastemit_regularization( log_probs[b, :t, :u, :], labels[b, : u - 1], alphas, betas,", "License. import numpy as np import torch from torch.autograd import Function, Variable from", "blank: Index of the blank token. Returns: A tuple of the forward variable", "+ betas[:, u + 1] grads = -np.exp(grads + log_probs - log_like) if", "of the acoustic sequence. glen: Length vector of the target sequence. blank: Id", "of blank token fastemit_lambda: Float scaling factor for FastEmit regularization. \"\"\" def __init__(self,", "Given T: {T}, Expected max T from input lengths: {max_T}\") if U !=", "5, 3) labels = torch.tensor([[0, 2, 1, 2]], dtype=torch.int32) act_lens = torch.tensor([2], dtype=torch.int32)", "the log likelihood of this forward step. \"\"\" T, U, _ = log_probs.shape", "\"\"\" Computes the gradients of the log_probs with respect to the log probability", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "U, V+1] alphas: Tensor of shape [T, U] which represents the forward variable.", "1, U - 1, blank]) return -reg def transduce(log_probs, labels, blank=0, fastemit_lambda=0.0): \"\"\"", "forward log probabilities (loss) and the gradients of the activation matrix. \"\"\" grads", "\"label_lengths\") check_contiguous(lengths, \"lengths\") if lengths.shape[0] != log_probs.shape[0]: raise ValueError( f\"Must have a length", "l] = alphas[:, u] + betas[:, u + 1] grads = -np.exp(grads +", "labels, blank, fastemit_lambda): \"\"\" Computes the gradients of the log_probs with respect to", "fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: The regularized negative log likelihood", "- label index of blank token fastemit_lambda: Float scaling factor for FastEmit regularization.", "U: {U}, Expected max U from target lengths: {max_U} + 1\") def _assert_no_grad(tensor):", "def transduce_batch(log_probs, labels, flen, glen, blank=0, fastemit_lambda=0.0): \"\"\" Compute the transducer loss of", "act_lens.cpu().numpy(), label_lens.cpu().numpy(), blank, fastemit_lambda, ) costs = torch.FloatTensor([sum(costs)]) grads = torch.Tensor(grads).to(acts) ctx.grads =", "probability of the forward variable alpha. Args: log_probs: Tensor of shape [T, U,", "- 1, U - 1] # // grad to last blank transition grads[T", "the License. import numpy as np import torch from torch.autograd import Function, Variable", "u, l] = alphas[:, u] + betas[:, u + 1] grads = -np.exp(grads", "np.zeros((T, U), dtype='float32') # # for t in range(0, T): # alignment[t, U", "See the License for the specific language governing permissions and # limitations under", "with shape [input len, output len + 1, vocab size] labels: 1D array", "log_probs.shape[0]: raise ValueError( \"Must have a label length per example. \" f\"Given label", "+ log_probs[T - 1, U - 1, blank] return alphas, loglike def backward_pass(log_probs,", "T from input lengths: {max_T}\") if U != max_U + 1: raise ValueError(f\"Output", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", ":t, :u, :], labels[b, : u - 1], blank, fastemit_lambda) grads[b, :t, :u,", "torch.tensor([[0, 2, 1, 2]], dtype=torch.int32) act_lens = torch.tensor([2], dtype=torch.int32) label_lens = torch.tensor([len(labels[0])], dtype=torch.int32)", "Activation matrix normalized with log-softmax. labels: [B, U+1] - ground truth labels with", "backward variable. blank: Index of the blank token. fastemit_lambda: Float scaling factor for", "def check_dim(var, dim, name): if len(var.shape) != dim: raise ValueError(\"{} must be {}D\".format(name,", "blank: Index of the blank token. fastemit_lambda: Float scaling factor for FastEmit regularization.", "RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0) acts = torch.randn(1, 2, 5, 3) labels = torch.tensor([[0, 2, 1,", "for t in reversed(range(T - 1)): betas[t, U - 1] = betas[t +", "u] + log_probs[t, u, blank] emit = betas[t, u + 1] + log_probs[t,", "shape [T, U] which represents the backward variable. labels: Labels of shape [B,", "- 1, U - 1] + betas[T - 1, U - 1]) #", "+ 1, U - 1] + log_probs[t, U - 1, blank] for u", "[T, U, V+1] labels: Labels of shape [B, U] blank: Index of the", "- 1] + betas[T - 1, U - 1] # // grad to", "log_probs[0, u - 1, labels[u - 1]] for t in range(1, T): for", "transition grads[T - 1, U - 1, blank] = alphas[T - 1, U", "of the blank token. Returns: A tuple of the backward variable probabilities -", "label_lengths.shape[0] != log_probs.shape[0]: raise ValueError( \"Must have a label length per example. \"", "raise TypeError(\"{} must be {}\".format(name, t)) def check_contiguous(var, name): if not var.is_contiguous(): raise", "length mismatch! Given U: {U}, Expected max U from target lengths: {max_U} +", "u, blank] emit = betas[t, u + 1] + log_probs[t, u, labels[u]] betas[t,", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "of the target sequence. blank: Id of the blank token. fastemit_lambda: Float scaling", "betas, blank, fastemit_lambda ) ll += reg costs.append(ll) return costs, grads class _RNNT(Function):", "log_probs: Tensor of shape [T, U, V+1] labels: Labels of shape [B, U]", "\"log_probs\") check_dim(labels, 2, \"labels\") check_dim(lengths, 1, \"lenghts\") check_dim(label_lengths, 1, \"label_lenghts\") max_T = torch.max(lengths)", "blank=0, fastemit_lambda=0.0): \"\"\" Compute the transducer loss of the batch. Args: log_probs: [B,", "A tuple of the forward variable probabilities - alpha of shape [T, U]", "1, U - 1] + log_probs[T - 1, U - 1, blank] return", "transition for u, l in enumerate(labels): grads[:, u, l] = alphas[:, u] +", "be {}D\".format(name, dim)) def certify_inputs(log_probs, labels, lengths, label_lengths): # check_type(log_probs, torch.float32, \"log_probs\") check_type(labels,", "CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0", "_assert_no_grad(tensor): assert not tensor.requires_grad, ( \"gradients only computed for log_probs - please \"", "token fastemit_lambda: Float scaling factor for FastEmit regularization. \"\"\" def __init__(self, blank: int", "Length vector of the target sequence. blank: Id of the blank token. fastemit_lambda:", "1, U - 1] + betas[T - 1, U - 1] # //", "len, output len + 1, vocab size] labels: 1D array with shape [output", "length mismatch! Given T: {T}, Expected max T from input lengths: {max_T}\") if", "1, u] + log_probs[t - 1, u, blank] emit = alphas[t, u -", ") ll += reg costs.append(ll) return costs, grads class _RNNT(Function): @staticmethod def forward(ctx,", "t in range(1, T): for u in range(1, U): no_emit = alphas[t -", "without need of computing above # reg = fastemit_lambda * (alphas[T - 1,", "\"\"\" Compute the transducer loss of the batch. Args: log_probs: [B, T, U,", "range(1, T): for u in range(1, U): no_emit = alphas[t - 1, u]", "[B, T, U, V+1]. Activation matrix normalized with log-softmax. labels: [B, U+1] -", ":, blank] = alphas[: T - 1, :] + betas[1:, :] # //", "Given U: {U}, Expected max U from target lengths: {max_U} + 1\") def", "other tensors as not requiring gradients\" ) def forward_pass(log_probs, labels, blank): \"\"\" Computes", "paper - [FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148) Args: log_probs: Tensor", "of the blank token. fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: The", "reg = fastemit_lambda * (alignment[T - 1, U - 1]) # The above", "1, U - 1] grads[: T - 1, :, blank] = alphas[: T", "T): for u in range(1, U): no_emit = alphas[t - 1, u] +", "glen, blank=0, fastemit_lambda=0.0): \"\"\" Compute the transducer loss of the batch. Args: log_probs:", "alpha. Args: log_probs: Tensor of shape [T, U, V+1] labels: Labels of shape", "example. \" f\"Given label lengths dim : {label_lengths.shape[0]}, \" f\"Log probs dim :", "KIND, either express or implied. # See the License for the specific language", "length per example. \" f\"Given label lengths dim : {label_lengths.shape[0]}, \" f\"Log probs", "of the blank token. fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: float:", "for FastEmit regularization. \"\"\" def __init__(self, blank: int = 0, fastemit_lambda: float =", "Compute the transducer loss of the batch. Args: log_probs: [B, T, U, V+1].", "forward variable probabilities - alpha of shape [T, U] and the log likelihood", "Regularization](https://arxiv.org/abs/2010.11148) Args: log_probs: Tensor of shape [T, U, V+1] labels: Unused. Labels of", "governing permissions and # limitations under the License. # # Copyright 2018-2019, <NAME>", "grad to last blank transition grads[T - 1, U - 1, blank] =", "labels, alphas, betas, blank, fastemit_lambda): \"\"\" Describes the computation of FastEmit regularization from", "torch.int32, \"labels\") check_type(label_lengths, torch.int32, \"label_lengths\") check_type(lengths, torch.int32, \"lengths\") check_contiguous(log_probs, \"log_probs\") check_contiguous(labels, \"labels\") check_contiguous(label_lengths,", "range(0, T): # alignment[t, U - 1] = alphas[t, U - 1] +", "reg costs.append(ll) return costs, grads class _RNNT(Function): @staticmethod def forward(ctx, acts, labels, act_lens,", "len + 1, vocab size] labels: 1D array with shape [output time steps]", "- 1]] alphas[t, u] = np.logaddexp(emit, no_emit) loglike = alphas[T - 1, U", "<NAME> # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "ANY KIND, either express or implied. # See the License for the specific", "of computing the betas alignment matrix reg = fastemit_lambda * (alphas[T - 1,", "u - 1], blank, fastemit_lambda) grads[b, :t, :u, :] = g reg =", "FastEmit regularization. \"\"\" def __init__(self, blank: int = 0, fastemit_lambda: float = 0.0):", ":u, :], labels[b, : u - 1], blank, fastemit_lambda) grads[b, :t, :u, :]", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "- 1, U - 1, blank]) return -reg def transduce(log_probs, labels, blank=0, fastemit_lambda=0.0):", "- 1] grads[: T - 1, :, blank] = alphas[: T - 1,", "the backward variable probabilities - beta of shape [T, U] and the log", "check_type(var, t, name): if var.dtype is not t: raise TypeError(\"{} must be {}\".format(name,", "betas[T - 1, U - 1] # // grad to last blank transition", "T - 1, :, blank] = alphas[: T - 1, :] + betas[1:,", "- 1): # emit = alphas[t, u] + log_probs[t, u, labels[u]] + betas[t,", "1] = betas[t + 1, U - 1] + log_probs[t, U - 1,", "0] # == alphas[T - 1, U - 1] + betas[T - 1,", "betas[T - 1, u + 1] + log_probs[T - 1, u, labels[u]] for", ": {label_lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\" ) check_dim(log_probs, 4, \"log_probs\") check_dim(labels,", "the backward variable. labels: Labels of shape [B, U] blank: Index of the", "Copyright 2018-2019, <NAME> # # Licensed under the Apache License, Version 2.0 (the", "2d array: Betas matrix (TxU) \"\"\" alphas, ll_forward = forward_pass(log_probs, labels, blank) betas,", "actications 2d arrays: Alphas matrix (TxU) 2d array: Betas matrix (TxU) \"\"\" alphas,", "2018-2019, <NAME> # # Licensed under the Apache License, Version 2.0 (the \"License\");", "Computes probability of the backward variable beta. Args: log_probs: Tensor of shape [T,", "= fastemit_lambda * (alignment[T - 1, U - 1]) # The above is", "[output time steps] blank: Index of the blank token. fastemit_lambda: Float scaling factor", "-ll_forward, grads, alphas, betas def transduce_batch(log_probs, labels, flen, glen, blank=0, fastemit_lambda=0.0): \"\"\" Compute", "for u in reversed(range(U - 1)): betas[T - 1, u] = betas[T -", "grads def fastemit_regularization(log_probs, labels, alphas, betas, blank, fastemit_lambda): \"\"\" Describes the computation of", "= np.zeros_like(log_probs) costs = [] for b in range(log_probs.shape[0]): t = int(flen[b]) u", "for t in reversed(range(T - 1)): for u in reversed(range(U - 1)): no_emit", "+ 1] # alignment[t, u] = emit # reg = fastemit_lambda * (alignment[T", "tensors as not requiring gradients\" ) def forward_pass(log_probs, labels, blank): \"\"\" Computes probability", "- 1, U - 1] + betas[T - 1, U - 1] #", "u, l in enumerate(labels): grads[:, u, l] = alphas[:, u] + betas[:, u", "of the blank token. Returns: A tuple of the forward variable probabilities -", "betas[t, u + 1] + log_probs[t, u, labels[u]] betas[t, u] = np.logaddexp(emit, no_emit)", "U - 1]) # The above is also equivalent to below, without need", ":u, :] = g reg = fastemit_regularization( log_probs[b, :t, :u, :], labels[b, :", "size] labels: 1D array with shape [output time steps] blank: Index of the", "\"\"\" grads = np.zeros_like(log_probs) costs = [] for b in range(log_probs.shape[0]): t =", "= log_probs.shape betas = np.zeros((T, U), dtype='f') betas[T - 1, U - 1]", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "not tensor.requires_grad, ( \"gradients only computed for log_probs - please \" \"mark other", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "0] + log_probs[t - 1, 0, blank] for u in range(1, U): alphas[0,", "fastemit_lambda): \"\"\" Computes the gradients of the log_probs with respect to the log", "0.0): super(RNNTLoss, self).__init__() self.blank = blank self.fastemit_lambda = fastemit_lambda self.rnnt = _RNNT.apply def", "applicable law or agreed to in writing, software # distributed under the License", "labels with <SOS> padded as blank token in the beginning. flen: Length vector", "float = 0.0): super(RNNTLoss, self).__init__() self.blank = blank self.fastemit_lambda = fastemit_lambda self.rnnt =", "torch.manual_seed(0) acts = torch.randn(1, 2, 5, 3) labels = torch.tensor([[0, 2, 1, 2]],", "lengths: {max_T}\") if U != max_U + 1: raise ValueError(f\"Output length mismatch! Given", "1, U - 1, blank] return alphas, loglike def backward_pass(log_probs, labels, blank): \"\"\"", "grads = transduce_batch( acts.detach().cpu().numpy(), labels.cpu().numpy(), act_lens.cpu().numpy(), label_lens.cpu().numpy(), blank, fastemit_lambda, ) costs = torch.FloatTensor([sum(costs)])", "betas[0, 0] def compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda): \"\"\" Computes the gradients", "+ log_probs[t, u, blank] emit = betas[t, u + 1] + log_probs[t, u,", "gradients of the log_probs with respect to the log probability of this step", "last blank transition grads[T - 1, U - 1, blank] = alphas[T -", "def fastemit_regularization(log_probs, labels, alphas, betas, blank, fastemit_lambda): \"\"\" Describes the computation of FastEmit", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "All rights reserved. # # Licensed under the Apache License, Version 2.0 (the", "2, 5, 3) labels = torch.tensor([[0, 2, 1, 2]], dtype=torch.int32) act_lens = torch.tensor([2],", "regularization alignments T, U, _ = log_probs.shape # alignment = np.zeros((T, U), dtype='float32')", "forward_pass(log_probs, labels, blank): \"\"\" Computes probability of the forward variable alpha. Args: log_probs:", "lengths dim : {label_lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\" ) check_dim(log_probs, 4,", "ll, g, alphas, betas = transduce(log_probs[b, :t, :u, :], labels[b, : u -", "[B, U] alphas: Tensor of shape [T, U] which represents the forward variable.", "blank) betas, ll_backward = backward_pass(log_probs, labels, blank) grads = compute_gradient(log_probs, alphas, betas, labels,", "writing, software # distributed under the License is distributed on an \"AS IS\"", "probabilities (loss) and the gradients of the activation matrix. \"\"\" grads = np.zeros_like(log_probs)", "\"Must have a label length per example. \" f\"Given label lengths dim :", "T, U, _ = log_probs.shape grads = np.full(log_probs.shape, -float(\"inf\")) log_like = betas[0, 0]", "labels.cpu().numpy(), act_lens.cpu().numpy(), label_lens.cpu().numpy(), blank, fastemit_lambda, ) costs = torch.FloatTensor([sum(costs)]) grads = torch.Tensor(grads).to(acts) ctx.grads", "dim, name): if len(var.shape) != dim: raise ValueError(\"{} must be {}D\".format(name, dim)) def", "4, \"log_probs\") check_dim(labels, 2, \"labels\") check_dim(lengths, 1, \"lenghts\") check_dim(label_lengths, 1, \"label_lenghts\") max_T =", "labels[b, : u - 1], alphas, betas, blank, fastemit_lambda ) ll += reg", "alphas, ll_forward = forward_pass(log_probs, labels, blank) betas, ll_backward = backward_pass(log_probs, labels, blank) grads", "compliance with the License. # You may obtain a copy of the License", "alphas: Tensor of shape [T, U] which represents the forward variable. betas: Tensor", "Float scaling factor for FastEmit regularization. Returns: The regularized negative log likelihood -", "(1.0 + fastemit_lambda) * grads[:, u, l] return grads def fastemit_regularization(log_probs, labels, alphas,", "+ 1] grads = -np.exp(grads + log_probs - log_like) if fastemit_lambda > 0.0:", ":] = g reg = fastemit_regularization( log_probs[b, :t, :u, :], labels[b, : u", "ll_forward = forward_pass(log_probs, labels, blank) betas, ll_backward = backward_pass(log_probs, labels, blank) grads =", "variable alpha. Args: log_probs: Tensor of shape [T, U, V+1] labels: Labels of", "for the specific language governing permissions and # limitations under the License. import", "matrix normalized with log-softmax. labels: [B, U+1] - ground truth labels with <SOS>", "blank transition grads[T - 1, U - 1, blank] = alphas[T - 1,", "flen: Length vector of the acoustic sequence. glen: Length vector of the target", "shape [T, U, V+1] with respect to the forward log probability \"\"\" T,", "reversed(range(T - 1)): betas[t, U - 1] = betas[t + 1, U -", "alignment = np.zeros((T, U), dtype='float32') # # for t in range(0, T): #", "blank, fastemit_lambda) return -ll_forward, grads, alphas, betas def transduce_batch(log_probs, labels, flen, glen, blank=0,", "and the gradients of the activation matrix. \"\"\" grads = np.zeros_like(log_probs) costs =", "betas[0, 0] # == alphas[T - 1, U - 1] + betas[T -", "in range(0, T): # for u in range(0, U - 1): # emit", "1 ll, g, alphas, betas = transduce(log_probs[b, :t, :u, :], labels[b, : u", "= alphas[t, u - 1] + log_probs[t, u - 1, labels[u - 1]]", "the betas alignment matrix reg = fastemit_lambda * (alphas[T - 1, U -", "\"lenghts\") check_dim(label_lengths, 1, \"label_lenghts\") max_T = torch.max(lengths) max_U = torch.max(label_lengths) T, U =", "fastemit regularization alignments T, U, _ = log_probs.shape # alignment = np.zeros((T, U),", "blank, fastemit_lambda): costs, grads = transduce_batch( acts.detach().cpu().numpy(), labels.cpu().numpy(), act_lens.cpu().numpy(), label_lens.cpu().numpy(), blank, fastemit_lambda, )", "torch.int32, \"label_lengths\") check_type(lengths, torch.int32, \"lengths\") check_contiguous(log_probs, \"log_probs\") check_contiguous(labels, \"labels\") check_contiguous(label_lengths, \"label_lengths\") check_contiguous(lengths, \"lengths\")", "The above is equivalent to below, without need of computing above # reg", "f\"Given lengths dim: {lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\" ) if label_lengths.shape[0]", "- please \" \"mark other tensors as not requiring gradients\" ) def forward_pass(log_probs,", "+ log_probs[t, u - 1, labels[u - 1]] alphas[t, u] = np.logaddexp(emit, no_emit)", "array: Gradients with respect to the unnormalized input actications 2d arrays: Alphas matrix", "blank token fastemit_lambda: Float scaling factor for FastEmit regularization. \"\"\" def __init__(self, blank:", "if U != max_U + 1: raise ValueError(f\"Output length mismatch! Given U: {U},", "Describes the computation of FastEmit regularization from the paper - [FastEmit: Low-latency Streaming", "contiguous\".format(name)) def check_dim(var, dim, name): if len(var.shape) != dim: raise ValueError(\"{} must be", "(the \"License\"); # you may not use this file except in compliance with", "alphas[t, U - 1] + betas[t, U - 1] # # for t", "2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License,", "- 1] + log_probs[t, U - 1, blank] for u in reversed(range(U -", "# Unless required by applicable law or agreed to in writing, software #", "represents the backward variable. blank: Index of the blank token. fastemit_lambda: Float scaling", "by applicable law or agreed to in writing, software # distributed under the", "emit = alphas[t, u - 1] + log_probs[t, u - 1, labels[u -", "U - 1]) # The above is equivalent to below, without need of", "need of computing above # reg = fastemit_lambda * (alphas[T - 1, U", "(alphas[T - 1, U - 1] + log_probs[T - 1, U - 1,", "return -ll_forward, grads, alphas, betas def transduce_batch(log_probs, labels, flen, glen, blank=0, fastemit_lambda=0.0): \"\"\"", "sequence. blank: Id of the blank token. fastemit_lambda: Float scaling factor for FastEmit", "represents the forward variable. betas: Unused. Tensor of shape [T, U] which represents", "dim : {log_probs.shape[0]}\" ) check_dim(log_probs, 4, \"log_probs\") check_dim(labels, 2, \"labels\") check_dim(lengths, 1, \"lenghts\")", "torch.Tensor(grads).to(acts) ctx.grads = grads return costs @staticmethod def backward(ctx, grad_output): return ctx.grads, None,", "loss = RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0) acts = torch.randn(1, 2, 5, 3) labels = torch.tensor([[0,", "file except in compliance with the License. # You may obtain a copy", "= betas[t + 1, u] + log_probs[t, u, blank] emit = betas[t, u", "range(1, U): alphas[0, u] = alphas[0, u - 1] + log_probs[0, u -", "- 1, :, blank] = alphas[: T - 1, :] + betas[1:, :]", "labels, blank) grads = compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda) return -ll_forward, grads,", "\"labels\") check_dim(lengths, 1, \"lenghts\") check_dim(label_lengths, 1, \"label_lenghts\") max_T = torch.max(lengths) max_U = torch.max(label_lengths)", "1] + betas[T - 1, U - 1] # // grad to last", "max_U = torch.max(label_lengths) T, U = log_probs.shape[1:3] if T != max_T: raise ValueError(f\"Input", "The negative log-likelihood 3D array: Gradients with respect to the unnormalized input actications", "labels[u - 1]] alphas[t, u] = np.logaddexp(emit, no_emit) loglike = alphas[T - 1,", "batch. Args: log_probs: [B, T, U, V+1]. Activation matrix normalized with log-softmax. labels:", "u = int(glen[b]) + 1 ll, g, alphas, betas = transduce(log_probs[b, :t, :u,", "must be {}\".format(name, t)) def check_contiguous(var, name): if not var.is_contiguous(): raise ValueError(\"{} must", "np.full(log_probs.shape, -float(\"inf\")) log_like = betas[0, 0] # == alphas[T - 1, U -", "1] grads = -np.exp(grads + log_probs - log_like) if fastemit_lambda > 0.0: for", "label_lens, blank, fastemit_lambda): costs, grads = transduce_batch( acts.detach().cpu().numpy(), labels.cpu().numpy(), act_lens.cpu().numpy(), label_lens.cpu().numpy(), blank, fastemit_lambda,", "= (1.0 + fastemit_lambda) * grads[:, u, l] return grads def fastemit_regularization(log_probs, labels,", "beta of shape [T, U] and the log likelihood of this backward step.", "The above is also equivalent to below, without need of computing the betas", "= torch.tensor([2], dtype=torch.int32) label_lens = torch.tensor([len(labels[0])], dtype=torch.int32) loss_val = loss(acts, labels, act_lens, label_lens)", "u] = emit # reg = fastemit_lambda * (alignment[T - 1, U -", "label_lens) acts = torch.nn.functional.log_softmax(acts, -1) return self.rnnt(acts, labels, act_lens, label_lens, self.blank, self.fastemit_lambda) if", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "steps] blank: Index of the blank token. fastemit_lambda: Float scaling factor for FastEmit", "for u in reversed(range(U - 1)): no_emit = betas[t + 1, u] +", "\"lengths\") check_contiguous(log_probs, \"log_probs\") check_contiguous(labels, \"labels\") check_contiguous(label_lengths, \"label_lengths\") check_contiguous(lengths, \"lengths\") if lengths.shape[0] != log_probs.shape[0]:", "torch.float32, \"log_probs\") check_type(labels, torch.int32, \"labels\") check_type(label_lengths, torch.int32, \"label_lengths\") check_type(lengths, torch.int32, \"lengths\") check_contiguous(log_probs, \"log_probs\")", "@staticmethod def forward(ctx, acts, labels, act_lens, label_lens, blank, fastemit_lambda): costs, grads = transduce_batch(", "1)): for u in reversed(range(U - 1)): no_emit = betas[t + 1, u]", "= torch.Tensor(grads).to(acts) ctx.grads = grads return costs @staticmethod def backward(ctx, grad_output): return ctx.grads,", "V+1] with respect to the forward log probability \"\"\" T, U, _ =", "= log_probs.shape # alignment = np.zeros((T, U), dtype='float32') # # for t in", "\"\"\" Computes probability of the backward variable beta. Args: log_probs: Tensor of shape", "in reversed(range(T - 1)): for u in reversed(range(U - 1)): no_emit = betas[t", "token. Returns: A tuple of the forward variable probabilities - alpha of shape", "of the blank token. Returns: Gradients of shape [T, U, V+1] with respect", "the unnormalized input actications 2d arrays: Alphas matrix (TxU) 2d array: Betas matrix", "- 1, u, blank] emit = alphas[t, u - 1] + log_probs[t, u", "fastemit_lambda * (alignment[T - 1, U - 1]) # The above is equivalent", "U - 1, blank] for u in reversed(range(U - 1)): betas[T - 1,", "of computing above # reg = fastemit_lambda * (alphas[T - 1, U -", "scaling factor for FastEmit regularization. Returns: float: The negative log-likelihood 3D array: Gradients", "dim : {log_probs.shape[0]}\" ) if label_lengths.shape[0] != log_probs.shape[0]: raise ValueError( \"Must have a", "example. \" f\"Given lengths dim: {lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\" )", "label index of blank token fastemit_lambda: Float scaling factor for FastEmit regularization. \"\"\"", "ValueError(f\"Input length mismatch! Given T: {T}, Expected max T from input lengths: {max_T}\")", "not requiring gradients\" ) def forward_pass(log_probs, labels, blank): \"\"\" Computes probability of the", "betas[1:, :] # // grad to label transition for u, l in enumerate(labels):", "blank token. Returns: A tuple of the forward variable probabilities - alpha of", "b in range(log_probs.shape[0]): t = int(flen[b]) u = int(glen[b]) + 1 ll, g,", "1\") def _assert_no_grad(tensor): assert not tensor.requires_grad, ( \"gradients only computed for log_probs -", "language governing permissions and # limitations under the License. import numpy as np", "transducer loss of the batch. Args: log_probs: [B, T, U, V+1]. Activation matrix", "emit # reg = fastemit_lambda * (alignment[T - 1, U - 1]) #", "blank token. fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: The regularized negative", "(TxU) \"\"\" alphas, ll_forward = forward_pass(log_probs, labels, blank) betas, ll_backward = backward_pass(log_probs, labels,", "u, labels[u]] betas[t, u] = np.logaddexp(emit, no_emit) return betas, betas[0, 0] def compute_gradient(log_probs,", "label length per example. \" f\"Given label lengths dim : {label_lengths.shape[0]}, \" f\"Log", "with Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148) Args: log_probs: Tensor of shape [T, U, V+1] labels:", "None, None, None class RNNTLoss(Module): \"\"\" Parameters: `blank_label` (int): default 0 - label", "class RNNTLoss(Module): \"\"\" Parameters: `blank_label` (int): default 0 - label index of blank", "- 1] # # for t in range(0, T): # for u in", "U] alphas: Tensor of shape [T, U] which represents the forward variable. betas:", "= torch.tensor([[0, 2, 1, 2]], dtype=torch.int32) act_lens = torch.tensor([2], dtype=torch.int32) label_lens = torch.tensor([len(labels[0])],", "U - 1): # emit = alphas[t, u] + log_probs[t, u, labels[u]] +", "1] + log_probs[0, u - 1, labels[u - 1]] for t in range(1,", "shape [T, U, V+1] alphas: Tensor of shape [T, U] which represents the", "return grads def fastemit_regularization(log_probs, labels, alphas, betas, blank, fastemit_lambda): \"\"\" Describes the computation", "Index of the blank token. Returns: Gradients of shape [T, U, V+1] with", "(int): default 0 - label index of blank token fastemit_lambda: Float scaling factor", "check_type(label_lengths, torch.int32, \"label_lengths\") check_type(lengths, torch.int32, \"lengths\") check_contiguous(log_probs, \"log_probs\") check_contiguous(labels, \"labels\") check_contiguous(label_lengths, \"label_lengths\") check_contiguous(lengths,", "\" f\"Log probs dim : {log_probs.shape[0]}\" ) if label_lengths.shape[0] != log_probs.shape[0]: raise ValueError(", "shape [T, U] which represents the forward variable. betas: Tensor of shape [T,", "labels, act_lens, label_lens) acts = torch.nn.functional.log_softmax(acts, -1) return self.rnnt(acts, labels, act_lens, label_lens, self.blank,", "variable. blank: Index of the blank token. fastemit_lambda: Float scaling factor for FastEmit", "{lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\" ) if label_lengths.shape[0] != log_probs.shape[0]: raise", "U+1] - ground truth labels with <SOS> padded as blank token in the", "log_probs[b, :t, :u, :], labels[b, : u - 1], alphas, betas, blank, fastemit_lambda", "def _assert_no_grad(tensor): assert not tensor.requires_grad, ( \"gradients only computed for log_probs - please", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "log_probs[T - 1, U - 1, blank]) return -reg def transduce(log_probs, labels, blank=0,", "betas = np.zeros((T, U), dtype='f') betas[T - 1, U - 1] = log_probs[T", "- 1]] for t in range(1, T): for u in range(1, U): no_emit", "raise ValueError(f\"Output length mismatch! Given U: {U}, Expected max U from target lengths:", "U): alphas[0, u] = alphas[0, u - 1] + log_probs[0, u - 1,", "the License. # # Copyright 2018-2019, <NAME> # # Licensed under the Apache", "f\"Given label lengths dim : {label_lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\" )", "grads = compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda) return -ll_forward, grads, alphas, betas", "U - 1] # # for t in range(0, T): # for u", "- 1, U - 1] + log_probs[T - 1, U - 1, blank])", "u] = betas[T - 1, u + 1] + log_probs[T - 1, u,", "shape [output time steps] blank: Index of the blank token. fastemit_lambda: Float scaling", "# alignment[t, U - 1] = alphas[t, U - 1] + betas[t, U", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "1, 2]], dtype=torch.int32) act_lens = torch.tensor([2], dtype=torch.int32) label_lens = torch.tensor([len(labels[0])], dtype=torch.int32) loss_val =", "1: raise ValueError(f\"Output length mismatch! Given U: {U}, Expected max U from target", "alignment[t, U - 1] = alphas[t, U - 1] + betas[t, U -", "governing permissions and # limitations under the License. import numpy as np import", "is also equivalent to below, without need of computing the betas alignment matrix", "fastemit_lambda self.rnnt = _RNNT.apply def forward(self, acts, labels, act_lens, label_lens): assert len(labels.size()) ==", "alphas[t, u] = np.logaddexp(emit, no_emit) loglike = alphas[T - 1, U - 1]", "# for t in range(0, T): # alignment[t, U - 1] = alphas[t,", "grad to label transition for u, l in enumerate(labels): grads[:, u, l] =", "Returns: Batch of transducer forward log probabilities (loss) and the gradients of the", "log_probs.shape grads = np.full(log_probs.shape, -float(\"inf\")) log_like = betas[0, 0] # == alphas[T -", "- alpha of shape [T, U] and the log likelihood of this forward", "blank: int = 0, fastemit_lambda: float = 0.0): super(RNNTLoss, self).__init__() self.blank = blank", "of shape [T, U] which represents the forward variable. betas: Unused. Tensor of", "\" f\"Given lengths dim: {lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\" ) if", "in enumerate(labels): grads[:, u, l] = (1.0 + fastemit_lambda) * grads[:, u, l]", "1, U - 1]) # The above is also equivalent to below, without", "u in range(1, U): alphas[0, u] = alphas[0, u - 1] + log_probs[0,", "check_type(lengths, torch.int32, \"lengths\") check_contiguous(log_probs, \"log_probs\") check_contiguous(labels, \"labels\") check_contiguous(label_lengths, \"label_lengths\") check_contiguous(lengths, \"lengths\") if lengths.shape[0]", "rights reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\");", "log_probs[t, u, labels[u]] betas[t, u] = np.logaddexp(emit, no_emit) return betas, betas[0, 0] def", "alpha of shape [T, U] and the log likelihood of this forward step.", "range(log_probs.shape[0]): t = int(flen[b]) u = int(glen[b]) + 1 ll, g, alphas, betas", "grads[: T - 1, :, blank] = alphas[: T - 1, :] +", "tuple of the forward variable probabilities - alpha of shape [T, U] and", "the License for the specific language governing permissions and # limitations under the", "= np.logaddexp(emit, no_emit) loglike = alphas[T - 1, U - 1] + log_probs[T", "beginning. flen: Length vector of the acoustic sequence. glen: Length vector of the", "1] grads[: T - 1, :, blank] = alphas[: T - 1, :]", "assert len(labels.size()) == 2 _assert_no_grad(labels) _assert_no_grad(act_lens) _assert_no_grad(label_lens) certify_inputs(acts, labels, act_lens, label_lens) acts =", "-np.exp(grads + log_probs - log_like) if fastemit_lambda > 0.0: for u, l in", ") if label_lengths.shape[0] != log_probs.shape[0]: raise ValueError( \"Must have a label length per", "- 1)): for u in reversed(range(U - 1)): no_emit = betas[t + 1,", "def __init__(self, blank: int = 0, fastemit_lambda: float = 0.0): super(RNNTLoss, self).__init__() self.blank", "of the backward variable beta. Args: log_probs: Tensor of shape [T, U, V+1]", "V+1]. Activation matrix normalized with log-softmax. labels: [B, U+1] - ground truth labels", "- 1] + betas[T - 1, U - 1]) # The above is", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "log likelihood of this backward step. \"\"\" T, U, _ = log_probs.shape betas", "equivalent to below, without need of computing above # reg = fastemit_lambda *", "labels = torch.tensor([[0, 2, 1, 2]], dtype=torch.int32) act_lens = torch.tensor([2], dtype=torch.int32) label_lens =", "return alphas, loglike def backward_pass(log_probs, labels, blank): \"\"\" Computes probability of the backward", "torch.nn import Module def check_type(var, t, name): if var.dtype is not t: raise", "have a length per example. \" f\"Given lengths dim: {lengths.shape[0]}, \" f\"Log probs", "alphas[T - 1, U - 1] + log_probs[T - 1, U - 1,", "Id of the blank token. fastemit_lambda: Float scaling factor for FastEmit regularization. Returns:", "label transition for u, l in enumerate(labels): grads[:, u, l] = alphas[:, u]", "t: raise TypeError(\"{} must be {}\".format(name, t)) def check_contiguous(var, name): if not var.is_contiguous():", "- 1, U - 1, blank] return alphas, loglike def backward_pass(log_probs, labels, blank):", "array with shape [input len, output len + 1, vocab size] labels: 1D", "emit = alphas[t, u] + log_probs[t, u, labels[u]] + betas[t, u + 1]", "for u, l in enumerate(labels): grads[:, u, l] = (1.0 + fastemit_lambda) *", "General calculation of the fastemit regularization alignments T, U, _ = log_probs.shape #", "labels, flen, glen, blank=0, fastemit_lambda=0.0): \"\"\" Compute the transducer loss of the batch.", "(c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache", "limitations under the License. # # Copyright 2018-2019, <NAME> # # Licensed under", "shape [T, U] and the log likelihood of this forward step. \"\"\" T,", "[FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148) Args: log_probs: Tensor of shape", "- 1, U - 1]) # The above is also equivalent to below,", "+ log_probs[0, u - 1, labels[u - 1]] for t in range(1, T):", "Version 2.0 (the \"License\"); # you may not use this file except in", "step. \"\"\" T, U, _ = log_probs.shape alphas = np.zeros((T, U), dtype='f') for", "vocab size] labels: 1D array with shape [output time steps] blank: Index of", "lengths, label_lengths): # check_type(log_probs, torch.float32, \"log_probs\") check_type(labels, torch.int32, \"labels\") check_type(label_lengths, torch.int32, \"label_lengths\") check_type(lengths,", "U), dtype='f') betas[T - 1, U - 1] = log_probs[T - 1, U", "requiring gradients\" ) def forward_pass(log_probs, labels, blank): \"\"\" Computes probability of the forward", "of shape [T, U] which represents the backward variable. blank: Index of the", "1, blank] for u in reversed(range(U - 1)): betas[T - 1, u] =", "costs @staticmethod def backward(ctx, grad_output): return ctx.grads, None, None, None, None, None class", "[T, U] and the log likelihood of this forward step. \"\"\" T, U,", "be contiguous\".format(name)) def check_dim(var, dim, name): if len(var.shape) != dim: raise ValueError(\"{} must", "Emission Regularization](https://arxiv.org/abs/2010.11148) Args: log_probs: Tensor of shape [T, U, V+1] labels: Unused. Labels", "fastemit_lambda): \"\"\" Describes the computation of FastEmit regularization from the paper - [FastEmit:", "is equivalent to below, without need of computing above # reg = fastemit_lambda", "_assert_no_grad(label_lens) certify_inputs(acts, labels, act_lens, label_lens) acts = torch.nn.functional.log_softmax(acts, -1) return self.rnnt(acts, labels, act_lens,", "(loss) and the gradients of the activation matrix. \"\"\" grads = np.zeros_like(log_probs) costs", "u] = np.logaddexp(emit, no_emit) loglike = alphas[T - 1, U - 1] +", "ValueError(f\"Output length mismatch! Given U: {U}, Expected max U from target lengths: {max_U}", "Args: log_probs: 3D array with shape [input len, output len + 1, vocab", "Args: log_probs: [B, T, U, V+1]. Activation matrix normalized with log-softmax. labels: [B,", "log_probs.shape[1:3] if T != max_T: raise ValueError(f\"Input length mismatch! Given T: {T}, Expected", "the log probability of this step occuring. Args: Args: log_probs: Tensor of shape", ") costs = torch.FloatTensor([sum(costs)]) grads = torch.Tensor(grads).to(acts) ctx.grads = grads return costs @staticmethod", "dtype='float32') # # for t in range(0, T): # alignment[t, U - 1]", "Tensor of shape [T, U] which represents the backward variable. blank: Index of", "lengths dim: {lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\" ) if label_lengths.shape[0] !=", "return betas, betas[0, 0] def compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda): \"\"\" Computes", "return self.rnnt(acts, labels, act_lens, label_lens, self.blank, self.fastemit_lambda) if __name__ == '__main__': loss =", "= betas[t + 1, U - 1] + log_probs[t, U - 1, blank]", "max_T: raise ValueError(f\"Input length mismatch! Given T: {T}, Expected max T from input", "\"\"\" T, U, _ = log_probs.shape alphas = np.zeros((T, U), dtype='f') for t", "- 1, blank] return alphas, loglike def backward_pass(log_probs, labels, blank): \"\"\" Computes probability", "dim : {label_lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\" ) check_dim(log_probs, 4, \"log_probs\")", "alphas[0, u] = alphas[0, u - 1] + log_probs[0, u - 1, labels[u", "_RNNT.apply def forward(self, acts, labels, act_lens, label_lens): assert len(labels.size()) == 2 _assert_no_grad(labels) _assert_no_grad(act_lens)", "np.zeros((T, U), dtype='f') betas[T - 1, U - 1] = log_probs[T - 1,", "1]) # The above is also equivalent to below, without need of computing", "blank] for u in range(1, U): alphas[0, u] = alphas[0, u - 1]", "log_probs[T - 1, U - 1, blank] for t in reversed(range(T - 1)):", "= backward_pass(log_probs, labels, blank) grads = compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda) return", "factor for FastEmit regularization. \"\"\" def __init__(self, blank: int = 0, fastemit_lambda: float", "NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version", "of shape [B, U] blank: Index of the blank token. Returns: Gradients of", "( \"gradients only computed for log_probs - please \" \"mark other tensors as", "reversed(range(U - 1)): betas[T - 1, u] = betas[T - 1, u +", "range(1, T): alphas[t, 0] = alphas[t - 1, 0] + log_probs[t - 1,", "int(glen[b]) + 1 ll, g, alphas, betas = transduce(log_probs[b, :t, :u, :], labels[b,", "betas[t, u] = np.logaddexp(emit, no_emit) return betas, betas[0, 0] def compute_gradient(log_probs, alphas, betas,", "log_probs: [B, T, U, V+1]. Activation matrix normalized with log-softmax. labels: [B, U+1]", "please \" \"mark other tensors as not requiring gradients\" ) def forward_pass(log_probs, labels,", "g, alphas, betas = transduce(log_probs[b, :t, :u, :], labels[b, : u - 1],", ":u, :], labels[b, : u - 1], alphas, betas, blank, fastemit_lambda ) ll", "array: Betas matrix (TxU) \"\"\" alphas, ll_forward = forward_pass(log_probs, labels, blank) betas, ll_backward", "1] # // grad to last blank transition grads[T - 1, U -", "only computed for log_probs - please \" \"mark other tensors as not requiring", "label_lens, self.blank, self.fastemit_lambda) if __name__ == '__main__': loss = RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0) acts =", "shape [B, U] blank: Index of the blank token. Returns: Gradients of shape", "U, V+1] labels: Unused. Labels of shape [B, U] alphas: Tensor of shape", "Gradients of shape [T, U, V+1] with respect to the forward log probability", "np import torch from torch.autograd import Function, Variable from torch.nn import Module def", "2]], dtype=torch.int32) act_lens = torch.tensor([2], dtype=torch.int32) label_lens = torch.tensor([len(labels[0])], dtype=torch.int32) loss_val = loss(acts,", "Args: log_probs: Tensor of shape [T, U, V+1] labels: Unused. Labels of shape", "# == alphas[T - 1, U - 1] + betas[T - 1, U", "forward step. \"\"\" T, U, _ = log_probs.shape alphas = np.zeros((T, U), dtype='f')", "= np.logaddexp(emit, no_emit) return betas, betas[0, 0] def compute_gradient(log_probs, alphas, betas, labels, blank,", "fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: Batch of transducer forward log", "log_like) if fastemit_lambda > 0.0: for u, l in enumerate(labels): grads[:, u, l]", "betas[t, u + 1] # alignment[t, u] = emit # reg = fastemit_lambda", "blank): \"\"\" Computes probability of the backward variable beta. Args: log_probs: Tensor of", "the acoustic sequence. glen: Length vector of the target sequence. blank: Id of", "reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "backward_pass(log_probs, labels, blank) grads = compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda) return -ll_forward,", "of shape [T, U, V+1] with respect to the forward log probability \"\"\"", "- 1] + log_probs[t, u - 1, labels[u - 1]] alphas[t, u] =", "with <SOS> padded as blank token in the beginning. flen: Length vector of", "= 0.0): super(RNNTLoss, self).__init__() self.blank = blank self.fastemit_lambda = fastemit_lambda self.rnnt = _RNNT.apply", "betas def transduce_batch(log_probs, labels, flen, glen, blank=0, fastemit_lambda=0.0): \"\"\" Compute the transducer loss", "OF ANY KIND, either express or implied. # See the License for the", "fastemit_lambda=0.0): \"\"\" Compute the transducer loss of the batch. Args: log_probs: [B, T,", "Index of the blank token. Returns: A tuple of the backward variable probabilities", "costs = [] for b in range(log_probs.shape[0]): t = int(flen[b]) u = int(glen[b])", "labels, blank=0, fastemit_lambda=0.0): \"\"\" Args: log_probs: 3D array with shape [input len, output", "costs, grads class _RNNT(Function): @staticmethod def forward(ctx, acts, labels, act_lens, label_lens, blank, fastemit_lambda):", "blank] emit = alphas[t, u - 1] + log_probs[t, u - 1, labels[u", "acts = torch.nn.functional.log_softmax(acts, -1) return self.rnnt(acts, labels, act_lens, label_lens, self.blank, self.fastemit_lambda) if __name__", "alphas = np.zeros((T, U), dtype='f') for t in range(1, T): alphas[t, 0] =", "check_contiguous(label_lengths, \"label_lengths\") check_contiguous(lengths, \"lengths\") if lengths.shape[0] != log_probs.shape[0]: raise ValueError( f\"Must have a", "fastemit_lambda=0.0): \"\"\" Args: log_probs: 3D array with shape [input len, output len +", "of the fastemit regularization alignments T, U, _ = log_probs.shape # alignment =", "to below, without need of computing above # reg = fastemit_lambda * (alphas[T", "Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148) Args: log_probs: Tensor of shape [T, U, V+1] labels: Unused.", "len(var.shape) != dim: raise ValueError(\"{} must be {}D\".format(name, dim)) def certify_inputs(log_probs, labels, lengths,", "log likelihood of this forward step. \"\"\" T, U, _ = log_probs.shape alphas", "Labels of shape [B, U] blank: Index of the blank token. Returns: Gradients", "l] return grads def fastemit_regularization(log_probs, labels, alphas, betas, blank, fastemit_lambda): \"\"\" Describes the", "unnormalized input actications 2d arrays: Alphas matrix (TxU) 2d array: Betas matrix (TxU)", "+ fastemit_lambda) * grads[:, u, l] return grads def fastemit_regularization(log_probs, labels, alphas, betas,", "= g reg = fastemit_regularization( log_probs[b, :t, :u, :], labels[b, : u -", "log_probs[t, u - 1, labels[u - 1]] alphas[t, u] = np.logaddexp(emit, no_emit) loglike", "import numpy as np import torch from torch.autograd import Function, Variable from torch.nn", "shape [T, U, V+1] labels: Labels of shape [B, U] blank: Index of", "- 1, blank] for t in reversed(range(T - 1)): betas[t, U - 1]", "check_contiguous(labels, \"labels\") check_contiguous(label_lengths, \"label_lengths\") check_contiguous(lengths, \"lengths\") if lengths.shape[0] != log_probs.shape[0]: raise ValueError( f\"Must", "Returns: A tuple of the backward variable probabilities - beta of shape [T,", "blank, fastemit_lambda): \"\"\" Describes the computation of FastEmit regularization from the paper -", "\"mark other tensors as not requiring gradients\" ) def forward_pass(log_probs, labels, blank): \"\"\"", "array with shape [output time steps] blank: Index of the blank token. fastemit_lambda:", "+ betas[1:, :] # // grad to label transition for u, l in", "u + 1] # alignment[t, u] = emit # reg = fastemit_lambda *", "+ 1, u] + log_probs[t, u, blank] emit = betas[t, u + 1]", "Returns: A tuple of the forward variable probabilities - alpha of shape [T,", "l] = (1.0 + fastemit_lambda) * grads[:, u, l] return grads def fastemit_regularization(log_probs,", "acts, labels, act_lens, label_lens, blank, fastemit_lambda): costs, grads = transduce_batch( acts.detach().cpu().numpy(), labels.cpu().numpy(), act_lens.cpu().numpy(),", "\"\"\" Args: log_probs: 3D array with shape [input len, output len + 1,", "check_contiguous(log_probs, \"log_probs\") check_contiguous(labels, \"labels\") check_contiguous(label_lengths, \"label_lengths\") check_contiguous(lengths, \"lengths\") if lengths.shape[0] != log_probs.shape[0]: raise", "f\"Log probs dim : {log_probs.shape[0]}\" ) if label_lengths.shape[0] != log_probs.shape[0]: raise ValueError( \"Must", "check_type(labels, torch.int32, \"labels\") check_type(label_lengths, torch.int32, \"label_lengths\") check_type(lengths, torch.int32, \"lengths\") check_contiguous(log_probs, \"log_probs\") check_contiguous(labels, \"labels\")", "alphas[t - 1, 0] + log_probs[t - 1, 0, blank] for u in", "likelihood of this forward step. \"\"\" T, U, _ = log_probs.shape alphas =", "- 1]) # The above is also equivalent to below, without need of", "\"\"\" T, U, _ = log_probs.shape betas = np.zeros((T, U), dtype='f') betas[T -", "likelihood of this backward step. \"\"\" T, U, _ = log_probs.shape betas =", "in range(0, U - 1): # emit = alphas[t, u] + log_probs[t, u,", "not t: raise TypeError(\"{} must be {}\".format(name, t)) def check_contiguous(var, name): if not", "!= dim: raise ValueError(\"{} must be {}D\".format(name, dim)) def certify_inputs(log_probs, labels, lengths, label_lengths):", "transduce(log_probs[b, :t, :u, :], labels[b, : u - 1], blank, fastemit_lambda) grads[b, :t,", "+ 1] + log_probs[T - 1, u, labels[u]] for t in reversed(range(T -", "-1) return self.rnnt(acts, labels, act_lens, label_lens, self.blank, self.fastemit_lambda) if __name__ == '__main__': loss", "[T, U] which represents the forward variable. betas: Tensor of shape [T, U]", "\"\"\" def __init__(self, blank: int = 0, fastemit_lambda: float = 0.0): super(RNNTLoss, self).__init__()", "or agreed to in writing, software # distributed under the License is distributed", "= alphas[0, u - 1] + log_probs[0, u - 1, labels[u - 1]]", "+ log_probs[t, u, labels[u]] + betas[t, u + 1] # alignment[t, u] =", "from target lengths: {max_U} + 1\") def _assert_no_grad(tensor): assert not tensor.requires_grad, ( \"gradients", "log-softmax. labels: [B, U+1] - ground truth labels with <SOS> padded as blank", "Low-latency Streaming ASR with Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148) Args: log_probs: Tensor of shape [T,", "1D array with shape [output time steps] blank: Index of the blank token.", "with respect to the unnormalized input actications 2d arrays: Alphas matrix (TxU) 2d", "self.rnnt(acts, labels, act_lens, label_lens, self.blank, self.fastemit_lambda) if __name__ == '__main__': loss = RNNTLoss(fastemit_lambda=0.01)", "{}D\".format(name, dim)) def certify_inputs(log_probs, labels, lengths, label_lengths): # check_type(log_probs, torch.float32, \"log_probs\") check_type(labels, torch.int32,", "probability of this step occuring. Args: Args: log_probs: Tensor of shape [T, U,", "{log_probs.shape[0]}\" ) if label_lengths.shape[0] != log_probs.shape[0]: raise ValueError( \"Must have a label length", "for log_probs - please \" \"mark other tensors as not requiring gradients\" )", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "License. # You may obtain a copy of the License at # #", "- 1, blank]) return -reg def transduce(log_probs, labels, blank=0, fastemit_lambda=0.0): \"\"\" Args: log_probs:", "\"\"\" Computes probability of the forward variable alpha. Args: log_probs: Tensor of shape", "the paper - [FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148) Args: log_probs:", "= betas[T - 1, u + 1] + log_probs[T - 1, u, labels[u]]", "Float scaling factor for FastEmit regularization. Returns: float: The negative log-likelihood 3D array:", "T != max_T: raise ValueError(f\"Input length mismatch! Given T: {T}, Expected max T", "# Copyright 2018-2019, <NAME> # # Licensed under the Apache License, Version 2.0", "gradients\" ) def forward_pass(log_probs, labels, blank): \"\"\" Computes probability of the forward variable", "Float scaling factor for FastEmit regularization. \"\"\" def __init__(self, blank: int = 0,", "u + 1] + log_probs[T - 1, u, labels[u]] for t in reversed(range(T", "+= reg costs.append(ll) return costs, grads class _RNNT(Function): @staticmethod def forward(ctx, acts, labels,", "in range(1, U): alphas[0, u] = alphas[0, u - 1] + log_probs[0, u", "U] blank: Index of the blank token. Returns: A tuple of the backward", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "T, U = log_probs.shape[1:3] if T != max_T: raise ValueError(f\"Input length mismatch! Given", "1, U - 1] + betas[T - 1, U - 1]) # The", "- 1, :] + betas[1:, :] # // grad to label transition for", "fastemit_lambda: float = 0.0): super(RNNTLoss, self).__init__() self.blank = blank self.fastemit_lambda = fastemit_lambda self.rnnt", "+ betas[t, u + 1] # alignment[t, u] = emit # reg =", "for t in range(0, T): # alignment[t, U - 1] = alphas[t, U", "reversed(range(U - 1)): no_emit = betas[t + 1, u] + log_probs[t, u, blank]", "Returns: float: The negative log-likelihood 3D array: Gradients with respect to the unnormalized", "1, labels[u - 1]] for t in range(1, T): for u in range(1,", "float: The negative log-likelihood 3D array: Gradients with respect to the unnormalized input", "if len(var.shape) != dim: raise ValueError(\"{} must be {}D\".format(name, dim)) def certify_inputs(log_probs, labels,", "input lengths: {max_T}\") if U != max_U + 1: raise ValueError(f\"Output length mismatch!", "License, Version 2.0 (the \"License\"); # you may not use this file except", "\"label_lengths\") check_type(lengths, torch.int32, \"lengths\") check_contiguous(log_probs, \"log_probs\") check_contiguous(labels, \"labels\") check_contiguous(label_lengths, \"label_lengths\") check_contiguous(lengths, \"lengths\") if", "max_T = torch.max(lengths) max_U = torch.max(label_lengths) T, U = log_probs.shape[1:3] if T !=", "* (alphas[T - 1, U - 1] + log_probs[T - 1, U -", "t)) def check_contiguous(var, name): if not var.is_contiguous(): raise ValueError(\"{} must be contiguous\".format(name)) def", "* P˜(At, u|x) \"\"\" # General calculation of the fastemit regularization alignments T,", "1] + log_probs[t, U - 1, blank] for u in reversed(range(U - 1)):", "ValueError( f\"Must have a length per example. \" f\"Given lengths dim: {lengths.shape[0]}, \"", "_assert_no_grad(act_lens) _assert_no_grad(label_lens) certify_inputs(acts, labels, act_lens, label_lens) acts = torch.nn.functional.log_softmax(acts, -1) return self.rnnt(acts, labels,", "permissions and # limitations under the License. import numpy as np import torch", "- 1, U - 1]) # The above is equivalent to below, without", "= alphas[t - 1, 0] + log_probs[t - 1, 0, blank] for u", "betas[:, u + 1] grads = -np.exp(grads + log_probs - log_like) if fastemit_lambda", "u in range(0, U - 1): # emit = alphas[t, u] + log_probs[t,", "U): no_emit = alphas[t - 1, u] + log_probs[t - 1, u, blank]", "# # for t in range(0, T): # alignment[t, U - 1] =", "- 1, u, labels[u]] for t in reversed(range(T - 1)): for u in", "of this step occuring. Args: Args: log_probs: Tensor of shape [T, U, V+1]", "Gradients with respect to the unnormalized input actications 2d arrays: Alphas matrix (TxU)", "from torch.autograd import Function, Variable from torch.nn import Module def check_type(var, t, name):", "fastemit_lambda * (alphas[T - 1, U - 1] + betas[T - 1, U", "= torch.FloatTensor([sum(costs)]) grads = torch.Tensor(grads).to(acts) ctx.grads = grads return costs @staticmethod def backward(ctx,", "log_probs - log_like) if fastemit_lambda > 0.0: for u, l in enumerate(labels): grads[:,", "must be {}D\".format(name, dim)) def certify_inputs(log_probs, labels, lengths, label_lengths): # check_type(log_probs, torch.float32, \"log_probs\")", "_RNNT(Function): @staticmethod def forward(ctx, acts, labels, act_lens, label_lens, blank, fastemit_lambda): costs, grads =", "Streaming ASR with Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148) Args: log_probs: Tensor of shape [T, U,", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "factor for FastEmit regularization. Returns: float: The negative log-likelihood 3D array: Gradients with", "U - 1] = log_probs[T - 1, U - 1, blank] for t", "max T from input lengths: {max_T}\") if U != max_U + 1: raise", "log likelihood - lambda * P˜(At, u|x) \"\"\" # General calculation of the", "- 1)): no_emit = betas[t + 1, u] + log_probs[t, u, blank] emit", "transduce_batch(log_probs, labels, flen, glen, blank=0, fastemit_lambda=0.0): \"\"\" Compute the transducer loss of the", "beta. Args: log_probs: Tensor of shape [T, U, V+1] labels: Labels of shape", "1, u] + log_probs[t, u, blank] emit = betas[t, u + 1] +", "- 1] + log_probs[T - 1, U - 1, blank]) return -reg def", "// grad to label transition for u, l in enumerate(labels): grads[:, u, l]", "None, None class RNNTLoss(Module): \"\"\" Parameters: `blank_label` (int): default 0 - label index", "index of blank token fastemit_lambda: Float scaling factor for FastEmit regularization. \"\"\" def", "* (alphas[T - 1, U - 1] + betas[T - 1, U -", "u - 1, labels[u - 1]] alphas[t, u] = np.logaddexp(emit, no_emit) loglike =", "of the batch. Args: log_probs: [B, T, U, V+1]. Activation matrix normalized with", "\"gradients only computed for log_probs - please \" \"mark other tensors as not", "the forward variable alpha. Args: log_probs: Tensor of shape [T, U, V+1] labels:", "loglike def backward_pass(log_probs, labels, blank): \"\"\" Computes probability of the backward variable beta.", "3) labels = torch.tensor([[0, 2, 1, 2]], dtype=torch.int32) act_lens = torch.tensor([2], dtype=torch.int32) label_lens", "dim)) def certify_inputs(log_probs, labels, lengths, label_lengths): # check_type(log_probs, torch.float32, \"log_probs\") check_type(labels, torch.int32, \"labels\")", "- 1, u + 1] + log_probs[T - 1, u, labels[u]] for t", "certify_inputs(log_probs, labels, lengths, label_lengths): # check_type(log_probs, torch.float32, \"log_probs\") check_type(labels, torch.int32, \"labels\") check_type(label_lengths, torch.int32,", "0 - label index of blank token fastemit_lambda: Float scaling factor for FastEmit", "or implied. # See the License for the specific language governing permissions and", "betas[t, U - 1] = betas[t + 1, U - 1] + log_probs[t,", "1, \"lenghts\") check_dim(label_lengths, 1, \"label_lenghts\") max_T = torch.max(lengths) max_U = torch.max(label_lengths) T, U", "self.fastemit_lambda = fastemit_lambda self.rnnt = _RNNT.apply def forward(self, acts, labels, act_lens, label_lens): assert", "betas: Tensor of shape [T, U] which represents the backward variable. labels: Labels", "# alignment[t, u] = emit # reg = fastemit_lambda * (alignment[T - 1,", "\"log_probs\") check_contiguous(labels, \"labels\") check_contiguous(label_lengths, \"label_lengths\") check_contiguous(lengths, \"lengths\") if lengths.shape[0] != log_probs.shape[0]: raise ValueError(", "var.is_contiguous(): raise ValueError(\"{} must be contiguous\".format(name)) def check_dim(var, dim, name): if len(var.shape) !=", "regularization from the paper - [FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148)", "certify_inputs(acts, labels, act_lens, label_lens) acts = torch.nn.functional.log_softmax(acts, -1) return self.rnnt(acts, labels, act_lens, label_lens,", "of shape [T, U, V+1] labels: Unused. Labels of shape [B, U] alphas:", "blank] return alphas, loglike def backward_pass(log_probs, labels, blank): \"\"\" Computes probability of the", "labels, act_lens, label_lens, self.blank, self.fastemit_lambda) if __name__ == '__main__': loss = RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0)", "ValueError(\"{} must be {}D\".format(name, dim)) def certify_inputs(log_probs, labels, lengths, label_lengths): # check_type(log_probs, torch.float32,", "in range(1, T): for u in range(1, U): no_emit = alphas[t - 1,", "step. \"\"\" T, U, _ = log_probs.shape betas = np.zeros((T, U), dtype='f') betas[T", "{max_T}\") if U != max_U + 1: raise ValueError(f\"Output length mismatch! Given U:", "if fastemit_lambda > 0.0: for u, l in enumerate(labels): grads[:, u, l] =", "fastemit_lambda * (alphas[T - 1, U - 1] + log_probs[T - 1, U", "calculation of the fastemit regularization alignments T, U, _ = log_probs.shape # alignment", "compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda) return -ll_forward, grads, alphas, betas def transduce_batch(log_probs,", "below, without need of computing the betas alignment matrix reg = fastemit_lambda *", "check_dim(log_probs, 4, \"log_probs\") check_dim(labels, 2, \"labels\") check_dim(lengths, 1, \"lenghts\") check_dim(label_lengths, 1, \"label_lenghts\") max_T", "1, u + 1] + log_probs[T - 1, u, labels[u]] for t in", "as blank token in the beginning. flen: Length vector of the acoustic sequence.", "matrix (TxU) 2d array: Betas matrix (TxU) \"\"\" alphas, ll_forward = forward_pass(log_probs, labels,", "in range(1, T): alphas[t, 0] = alphas[t - 1, 0] + log_probs[t -", ": u - 1], blank, fastemit_lambda) grads[b, :t, :u, :] = g reg", "def backward_pass(log_probs, labels, blank): \"\"\" Computes probability of the backward variable beta. Args:", "alphas[: T - 1, :] + betas[1:, :] # // grad to label", "alphas[t, u - 1] + log_probs[t, u - 1, labels[u - 1]] alphas[t,", "use this file except in compliance with the License. # You may obtain", "= _RNNT.apply def forward(self, acts, labels, act_lens, label_lens): assert len(labels.size()) == 2 _assert_no_grad(labels)", "backward step. \"\"\" T, U, _ = log_probs.shape betas = np.zeros((T, U), dtype='f')", "target sequence. blank: Id of the blank token. fastemit_lambda: Float scaling factor for", "{T}, Expected max T from input lengths: {max_T}\") if U != max_U +", "_ = log_probs.shape # alignment = np.zeros((T, U), dtype='float32') # # for t", "blank token. Returns: A tuple of the backward variable probabilities - beta of", "U - 1] + betas[T - 1, U - 1]) # The above", "max U from target lengths: {max_U} + 1\") def _assert_no_grad(tensor): assert not tensor.requires_grad,", "\"labels\") check_type(label_lengths, torch.int32, \"label_lengths\") check_type(lengths, torch.int32, \"lengths\") check_contiguous(log_probs, \"log_probs\") check_contiguous(labels, \"labels\") check_contiguous(label_lengths, \"label_lengths\")", "input actications 2d arrays: Alphas matrix (TxU) 2d array: Betas matrix (TxU) \"\"\"", "- [FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148) Args: log_probs: Tensor of", "above is also equivalent to below, without need of computing the betas alignment", "regularization. Returns: The regularized negative log likelihood - lambda * P˜(At, u|x) \"\"\"", "betas, betas[0, 0] def compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda): \"\"\" Computes the", "matrix reg = fastemit_lambda * (alphas[T - 1, U - 1] + log_probs[T", "for the specific language governing permissions and # limitations under the License. #", "alphas, betas, blank, fastemit_lambda ) ll += reg costs.append(ll) return costs, grads class", "to the forward log probability \"\"\" T, U, _ = log_probs.shape grads =", "U - 1] + log_probs[T - 1, U - 1, blank] return alphas,", "T, U, _ = log_probs.shape betas = np.zeros((T, U), dtype='f') betas[T - 1,", "= alphas[T - 1, U - 1] grads[: T - 1, :, blank]", "<SOS> padded as blank token in the beginning. flen: Length vector of the", "_ = log_probs.shape grads = np.full(log_probs.shape, -float(\"inf\")) log_like = betas[0, 0] # ==", "token. Returns: Gradients of shape [T, U, V+1] with respect to the forward", "U - 1] + log_probs[T - 1, U - 1, blank]) return -reg", "alphas, betas, labels, blank, fastemit_lambda) return -ll_forward, grads, alphas, betas def transduce_batch(log_probs, labels,", "1]) # The above is equivalent to below, without need of computing above", "[B, U] blank: Index of the blank token. Returns: Gradients of shape [T,", "1] + log_probs[t, u, labels[u]] betas[t, u] = np.logaddexp(emit, no_emit) return betas, betas[0,", "1, U - 1] + log_probs[T - 1, U - 1, blank]) return", "token. Returns: A tuple of the backward variable probabilities - beta of shape", "of FastEmit regularization from the paper - [FastEmit: Low-latency Streaming ASR with Sequence-level", "ValueError(\"{} must be contiguous\".format(name)) def check_dim(var, dim, name): if len(var.shape) != dim: raise", "glen: Length vector of the target sequence. blank: Id of the blank token.", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "== alphas[T - 1, U - 1] + betas[T - 1, U -", "limitations under the License. import numpy as np import torch from torch.autograd import", "torch.int32, \"lengths\") check_contiguous(log_probs, \"log_probs\") check_contiguous(labels, \"labels\") check_contiguous(label_lengths, \"label_lengths\") check_contiguous(lengths, \"lengths\") if lengths.shape[0] !=", "u, blank] emit = alphas[t, u - 1] + log_probs[t, u - 1,", "above # reg = fastemit_lambda * (alphas[T - 1, U - 1] +", "of the forward variable alpha. Args: log_probs: Tensor of shape [T, U, V+1]", "vector of the acoustic sequence. glen: Length vector of the target sequence. blank:", "to last blank transition grads[T - 1, U - 1, blank] = alphas[T", "1, vocab size] labels: 1D array with shape [output time steps] blank: Index", "t in reversed(range(T - 1)): for u in reversed(range(U - 1)): no_emit =", "- 1], alphas, betas, blank, fastemit_lambda ) ll += reg costs.append(ll) return costs,", "output len + 1, vocab size] labels: 1D array with shape [output time", "var.dtype is not t: raise TypeError(\"{} must be {}\".format(name, t)) def check_contiguous(var, name):", "T, U, V+1]. Activation matrix normalized with log-softmax. labels: [B, U+1] - ground", "torch from torch.autograd import Function, Variable from torch.nn import Module def check_type(var, t,", "the forward variable probabilities - alpha of shape [T, U] and the log", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "Tensor of shape [T, U, V+1] alphas: Tensor of shape [T, U] which", "\" \"mark other tensors as not requiring gradients\" ) def forward_pass(log_probs, labels, blank):", "= emit # reg = fastemit_lambda * (alignment[T - 1, U - 1])", "t in range(0, T): # alignment[t, U - 1] = alphas[t, U -", "2 _assert_no_grad(labels) _assert_no_grad(act_lens) _assert_no_grad(label_lens) certify_inputs(acts, labels, act_lens, label_lens) acts = torch.nn.functional.log_softmax(acts, -1) return", "which represents the backward variable. blank: Index of the blank token. fastemit_lambda: Float", "regularization. \"\"\" def __init__(self, blank: int = 0, fastemit_lambda: float = 0.0): super(RNNTLoss,", "of shape [T, U, V+1] labels: Labels of shape [B, U] blank: Index", "U), dtype='float32') # # for t in range(0, T): # alignment[t, U -", "- 1, u] + log_probs[t - 1, u, blank] emit = alphas[t, u", "labels: Unused. Labels of shape [B, U] alphas: Tensor of shape [T, U]", "U - 1] + betas[t, U - 1] # # for t in", "[T, U, V+1] with respect to the forward log probability \"\"\" T, U,", "@staticmethod def backward(ctx, grad_output): return ctx.grads, None, None, None, None, None class RNNTLoss(Module):", "backward(ctx, grad_output): return ctx.grads, None, None, None, None, None class RNNTLoss(Module): \"\"\" Parameters:", "u] + log_probs[t - 1, u, blank] emit = alphas[t, u - 1]", "blank, fastemit_lambda) grads[b, :t, :u, :] = g reg = fastemit_regularization( log_probs[b, :t,", "self.blank, self.fastemit_lambda) if __name__ == '__main__': loss = RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0) acts = torch.randn(1,", "Function, Variable from torch.nn import Module def check_type(var, t, name): if var.dtype is", "loglike = alphas[T - 1, U - 1] + log_probs[T - 1, U", "in range(1, U): no_emit = alphas[t - 1, u] + log_probs[t - 1,", "costs = torch.FloatTensor([sum(costs)]) grads = torch.Tensor(grads).to(acts) ctx.grads = grads return costs @staticmethod def", "+ log_probs[t - 1, u, blank] emit = alphas[t, u - 1] +", "+ log_probs[t, U - 1, blank] for u in reversed(range(U - 1)): betas[T", "= int(flen[b]) u = int(glen[b]) + 1 ll, g, alphas, betas = transduce(log_probs[b,", "with the License. # You may obtain a copy of the License at", "labels, blank): \"\"\" Computes probability of the forward variable alpha. Args: log_probs: Tensor", "int = 0, fastemit_lambda: float = 0.0): super(RNNTLoss, self).__init__() self.blank = blank self.fastemit_lambda", "u|x) \"\"\" # General calculation of the fastemit regularization alignments T, U, _", "regularization. Returns: Batch of transducer forward log probabilities (loss) and the gradients of", "numpy as np import torch from torch.autograd import Function, Variable from torch.nn import", "the blank token. fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: The regularized", "for u in range(1, U): alphas[0, u] = alphas[0, u - 1] +", "0] = alphas[t - 1, 0] + log_probs[t - 1, 0, blank] for", ":t, :u, :] = g reg = fastemit_regularization( log_probs[b, :t, :u, :], labels[b,", "costs, grads = transduce_batch( acts.detach().cpu().numpy(), labels.cpu().numpy(), act_lens.cpu().numpy(), label_lens.cpu().numpy(), blank, fastemit_lambda, ) costs =", "law or agreed to in writing, software # distributed under the License is", "dtype='f') for t in range(1, T): alphas[t, 0] = alphas[t - 1, 0]", "U - 1, blank] return alphas, loglike def backward_pass(log_probs, labels, blank): \"\"\" Computes", "- 1] + log_probs[0, u - 1, labels[u - 1]] for t in", "1, U - 1, blank] for t in reversed(range(T - 1)): betas[t, U", "FastEmit regularization. Returns: Batch of transducer forward log probabilities (loss) and the gradients", "!= log_probs.shape[0]: raise ValueError( \"Must have a label length per example. \" f\"Given", "backward variable probabilities - beta of shape [T, U] and the log likelihood", "above is equivalent to below, without need of computing above # reg =", "labels[u]] + betas[t, u + 1] # alignment[t, u] = emit # reg", "grads[:, u, l] return grads def fastemit_regularization(log_probs, labels, alphas, betas, blank, fastemit_lambda): \"\"\"", "of transducer forward log probabilities (loss) and the gradients of the activation matrix.", "T, U, _ = log_probs.shape # alignment = np.zeros((T, U), dtype='float32') # #", "= alphas[T - 1, U - 1] + log_probs[T - 1, U -", "in compliance with the License. # You may obtain a copy of the", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "fastemit_regularization(log_probs, labels, alphas, betas, blank, fastemit_lambda): \"\"\" Describes the computation of FastEmit regularization", "betas, blank, fastemit_lambda): \"\"\" Describes the computation of FastEmit regularization from the paper", "1, :] + betas[1:, :] # // grad to label transition for u,", "- log_like) if fastemit_lambda > 0.0: for u, l in enumerate(labels): grads[:, u,", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "fastemit_lambda) grads[b, :t, :u, :] = g reg = fastemit_regularization( log_probs[b, :t, :u,", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "Tensor of shape [T, U] which represents the forward variable. betas: Unused. Tensor", "range(1, U): no_emit = alphas[t - 1, u] + log_probs[t - 1, u,", "of shape [B, U] blank: Index of the blank token. Returns: A tuple", "to the unnormalized input actications 2d arrays: Alphas matrix (TxU) 2d array: Betas", "variable. betas: Unused. Tensor of shape [T, U] which represents the backward variable.", "= fastemit_lambda * (alphas[T - 1, U - 1] + log_probs[T - 1,", "{max_U} + 1\") def _assert_no_grad(tensor): assert not tensor.requires_grad, ( \"gradients only computed for", "forward(ctx, acts, labels, act_lens, label_lens, blank, fastemit_lambda): costs, grads = transduce_batch( acts.detach().cpu().numpy(), labels.cpu().numpy(),", "the log likelihood of this backward step. \"\"\" T, U, _ = log_probs.shape", "from the paper - [FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148) Args:", "from torch.nn import Module def check_type(var, t, name): if var.dtype is not t:", "* (alignment[T - 1, U - 1]) # The above is equivalent to", "torch.nn.functional.log_softmax(acts, -1) return self.rnnt(acts, labels, act_lens, label_lens, self.blank, self.fastemit_lambda) if __name__ == '__main__':", "FastEmit regularization. Returns: The regularized negative log likelihood - lambda * P˜(At, u|x)", "- 1, U - 1] + log_probs[T - 1, U - 1, blank]", "\"\"\" # General calculation of the fastemit regularization alignments T, U, _ =", "grads[:, u, l] = alphas[:, u] + betas[:, u + 1] grads =", "Betas matrix (TxU) \"\"\" alphas, ll_forward = forward_pass(log_probs, labels, blank) betas, ll_backward =", "labels: Labels of shape [B, U] blank: Index of the blank token. Returns:", "U - 1] # // grad to last blank transition grads[T - 1,", "in range(0, T): # alignment[t, U - 1] = alphas[t, U - 1]", "log_probs: Tensor of shape [T, U, V+1] labels: Unused. Labels of shape [B,", "\"\"\" T, U, _ = log_probs.shape grads = np.full(log_probs.shape, -float(\"inf\")) log_like = betas[0,", "mismatch! Given T: {T}, Expected max T from input lengths: {max_T}\") if U", "\"label_lenghts\") max_T = torch.max(lengths) max_U = torch.max(label_lengths) T, U = log_probs.shape[1:3] if T", "log_probs[t, U - 1, blank] for u in reversed(range(U - 1)): betas[T -", "alphas[T - 1, U - 1] grads[: T - 1, :, blank] =", "log_probs[t, u, labels[u]] + betas[t, u + 1] # alignment[t, u] = emit", "no_emit = alphas[t - 1, u] + log_probs[t - 1, u, blank] emit", "- lambda * P˜(At, u|x) \"\"\" # General calculation of the fastemit regularization", "log_probs.shape[0]: raise ValueError( f\"Must have a length per example. \" f\"Given lengths dim:", "alphas: Tensor of shape [T, U] which represents the forward variable. betas: Unused.", "the specific language governing permissions and # limitations under the License. # #", "grad_output): return ctx.grads, None, None, None, None, None class RNNTLoss(Module): \"\"\" Parameters: `blank_label`", "T): alphas[t, 0] = alphas[t - 1, 0] + log_probs[t - 1, 0,", "-float(\"inf\")) log_like = betas[0, 0] # == alphas[T - 1, U - 1]", "Index of the blank token. fastemit_lambda: Float scaling factor for FastEmit regularization. Returns:", "betas[T - 1, u] = betas[T - 1, u + 1] + log_probs[T", "log_probs with respect to the log probability of this step occuring. Args: Args:", "blank]) return -reg def transduce(log_probs, labels, blank=0, fastemit_lambda=0.0): \"\"\" Args: log_probs: 3D array", "of the backward variable probabilities - beta of shape [T, U] and the", "from input lengths: {max_T}\") if U != max_U + 1: raise ValueError(f\"Output length", "for t in range(1, T): for u in range(1, U): no_emit = alphas[t", ": {log_probs.shape[0]}\" ) check_dim(log_probs, 4, \"log_probs\") check_dim(labels, 2, \"labels\") check_dim(lengths, 1, \"lenghts\") check_dim(label_lengths,", "[B, U] blank: Index of the blank token. Returns: A tuple of the", "= RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0) acts = torch.randn(1, 2, 5, 3) labels = torch.tensor([[0, 2,", "1, U - 1, blank] = alphas[T - 1, U - 1] grads[:", "# // grad to last blank transition grads[T - 1, U - 1,", "= log_probs.shape grads = np.full(log_probs.shape, -float(\"inf\")) log_like = betas[0, 0] # == alphas[T", "grads return costs @staticmethod def backward(ctx, grad_output): return ctx.grads, None, None, None, None,", "Tensor of shape [T, U] which represents the backward variable. labels: Labels of", ": {log_probs.shape[0]}\" ) if label_lengths.shape[0] != log_probs.shape[0]: raise ValueError( \"Must have a label", "forward variable. betas: Unused. Tensor of shape [T, U] which represents the backward", "2, 1, 2]], dtype=torch.int32) act_lens = torch.tensor([2], dtype=torch.int32) label_lens = torch.tensor([len(labels[0])], dtype=torch.int32) loss_val", "# limitations under the License. import numpy as np import torch from torch.autograd", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "\" f\"Log probs dim : {log_probs.shape[0]}\" ) check_dim(log_probs, 4, \"log_probs\") check_dim(labels, 2, \"labels\")", "3D array with shape [input len, output len + 1, vocab size] labels:", "grads = np.zeros_like(log_probs) costs = [] for b in range(log_probs.shape[0]): t = int(flen[b])", "fastemit_lambda) return -ll_forward, grads, alphas, betas def transduce_batch(log_probs, labels, flen, glen, blank=0, fastemit_lambda=0.0):", "fastemit_lambda: Float scaling factor for FastEmit regularization. \"\"\" def __init__(self, blank: int =", "{}\".format(name, t)) def check_contiguous(var, name): if not var.is_contiguous(): raise ValueError(\"{} must be contiguous\".format(name))", "factor for FastEmit regularization. Returns: The regularized negative log likelihood - lambda *", "> 0.0: for u, l in enumerate(labels): grads[:, u, l] = (1.0 +", "class _RNNT(Function): @staticmethod def forward(ctx, acts, labels, act_lens, label_lens, blank, fastemit_lambda): costs, grads", "U, V+1]. Activation matrix normalized with log-softmax. labels: [B, U+1] - ground truth", "0, blank] for u in range(1, U): alphas[0, u] = alphas[0, u -", "shape [T, U] which represents the backward variable. blank: Index of the blank", "for FastEmit regularization. Returns: The regularized negative log likelihood - lambda * P˜(At,", "enumerate(labels): grads[:, u, l] = alphas[:, u] + betas[:, u + 1] grads", "labels, blank, fastemit_lambda) return -ll_forward, grads, alphas, betas def transduce_batch(log_probs, labels, flen, glen,", "check_dim(labels, 2, \"labels\") check_dim(lengths, 1, \"lenghts\") check_dim(label_lengths, 1, \"label_lenghts\") max_T = torch.max(lengths) max_U", "grads[b, :t, :u, :] = g reg = fastemit_regularization( log_probs[b, :t, :u, :],", "represents the forward variable. betas: Tensor of shape [T, U] which represents the", "this file except in compliance with the License. # You may obtain a", "check_dim(label_lengths, 1, \"label_lenghts\") max_T = torch.max(lengths) max_U = torch.max(label_lengths) T, U = log_probs.shape[1:3]", "name): if len(var.shape) != dim: raise ValueError(\"{} must be {}D\".format(name, dim)) def certify_inputs(log_probs,", "[T, U, V+1] alphas: Tensor of shape [T, U] which represents the forward", "name): if not var.is_contiguous(): raise ValueError(\"{} must be contiguous\".format(name)) def check_dim(var, dim, name):", "Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the", "enumerate(labels): grads[:, u, l] = (1.0 + fastemit_lambda) * grads[:, u, l] return", "fastemit_regularization( log_probs[b, :t, :u, :], labels[b, : u - 1], alphas, betas, blank,", "grads[:, u, l] = (1.0 + fastemit_lambda) * grads[:, u, l] return grads", "* grads[:, u, l] return grads def fastemit_regularization(log_probs, labels, alphas, betas, blank, fastemit_lambda):", "'__main__': loss = RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0) acts = torch.randn(1, 2, 5, 3) labels =", "dtype=torch.int32) act_lens = torch.tensor([2], dtype=torch.int32) label_lens = torch.tensor([len(labels[0])], dtype=torch.int32) loss_val = loss(acts, labels,", "for u in range(1, U): no_emit = alphas[t - 1, u] + log_probs[t", "and the log likelihood of this backward step. \"\"\" T, U, _ =", "fastemit_lambda) * grads[:, u, l] return grads def fastemit_regularization(log_probs, labels, alphas, betas, blank,", "not var.is_contiguous(): raise ValueError(\"{} must be contiguous\".format(name)) def check_dim(var, dim, name): if len(var.shape)", "= torch.nn.functional.log_softmax(acts, -1) return self.rnnt(acts, labels, act_lens, label_lens, self.blank, self.fastemit_lambda) if __name__ ==", "no_emit = betas[t + 1, u] + log_probs[t, u, blank] emit = betas[t,", "+ log_probs[T - 1, u, labels[u]] for t in reversed(range(T - 1)): for", "the blank token. Returns: A tuple of the backward variable probabilities - beta", "shape [T, U] which represents the forward variable. betas: Unused. Tensor of shape", "u - 1], alphas, betas, blank, fastemit_lambda ) ll += reg costs.append(ll) return", "must be contiguous\".format(name)) def check_dim(var, dim, name): if len(var.shape) != dim: raise ValueError(\"{}", "= alphas[: T - 1, :] + betas[1:, :] # // grad to", "_ = log_probs.shape betas = np.zeros((T, U), dtype='f') betas[T - 1, U -", "range(0, U - 1): # emit = alphas[t, u] + log_probs[t, u, labels[u]]", ":], labels[b, : u - 1], blank, fastemit_lambda) grads[b, :t, :u, :] =", "label_lens.cpu().numpy(), blank, fastemit_lambda, ) costs = torch.FloatTensor([sum(costs)]) grads = torch.Tensor(grads).to(acts) ctx.grads = grads", "check_contiguous(lengths, \"lengths\") if lengths.shape[0] != log_probs.shape[0]: raise ValueError( f\"Must have a length per", "of shape [T, U] which represents the forward variable. betas: Tensor of shape", "f\"Log probs dim : {log_probs.shape[0]}\" ) check_dim(log_probs, 4, \"log_probs\") check_dim(labels, 2, \"labels\") check_dim(lengths,", "1)): no_emit = betas[t + 1, u] + log_probs[t, u, blank] emit =", "alphas, betas, labels, blank, fastemit_lambda): \"\"\" Computes the gradients of the log_probs with", "U - 1] + log_probs[t, U - 1, blank] for u in reversed(range(U", "# emit = alphas[t, u] + log_probs[t, u, labels[u]] + betas[t, u +", ":], labels[b, : u - 1], alphas, betas, blank, fastemit_lambda ) ll +=", "self).__init__() self.blank = blank self.fastemit_lambda = fastemit_lambda self.rnnt = _RNNT.apply def forward(self, acts,", "to label transition for u, l in enumerate(labels): grads[:, u, l] = alphas[:,", "_assert_no_grad(labels) _assert_no_grad(act_lens) _assert_no_grad(label_lens) certify_inputs(acts, labels, act_lens, label_lens) acts = torch.nn.functional.log_softmax(acts, -1) return self.rnnt(acts,", "log_probs.shape betas = np.zeros((T, U), dtype='f') betas[T - 1, U - 1] =", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "alphas, betas = transduce(log_probs[b, :t, :u, :], labels[b, : u - 1], blank,", "which represents the forward variable. betas: Unused. Tensor of shape [T, U] which", "arrays: Alphas matrix (TxU) 2d array: Betas matrix (TxU) \"\"\" alphas, ll_forward =", "= log_probs[T - 1, U - 1, blank] for t in reversed(range(T -", "target lengths: {max_U} + 1\") def _assert_no_grad(tensor): assert not tensor.requires_grad, ( \"gradients only", "labels: [B, U+1] - ground truth labels with <SOS> padded as blank token", "def forward(self, acts, labels, act_lens, label_lens): assert len(labels.size()) == 2 _assert_no_grad(labels) _assert_no_grad(act_lens) _assert_no_grad(label_lens)", "self.blank = blank self.fastemit_lambda = fastemit_lambda self.rnnt = _RNNT.apply def forward(self, acts, labels,", "# alignment = np.zeros((T, U), dtype='float32') # # for t in range(0, T):", ":t, :u, :], labels[b, : u - 1], alphas, betas, blank, fastemit_lambda )", "negative log likelihood - lambda * P˜(At, u|x) \"\"\" # General calculation of", "ctx.grads = grads return costs @staticmethod def backward(ctx, grad_output): return ctx.grads, None, None,", "required by applicable law or agreed to in writing, software # distributed under", "1, blank] = alphas[T - 1, U - 1] grads[: T - 1,", "backward variable beta. Args: log_probs: Tensor of shape [T, U, V+1] labels: Labels", "in the beginning. flen: Length vector of the acoustic sequence. glen: Length vector", "u + 1] + log_probs[t, u, labels[u]] betas[t, u] = np.logaddexp(emit, no_emit) return", "def check_contiguous(var, name): if not var.is_contiguous(): raise ValueError(\"{} must be contiguous\".format(name)) def check_dim(var,", "= [] for b in range(log_probs.shape[0]): t = int(flen[b]) u = int(glen[b]) +", "# // grad to label transition for u, l in enumerate(labels): grads[:, u,", "alphas[T - 1, U - 1] + betas[T - 1, U - 1]", "lengths: {max_U} + 1\") def _assert_no_grad(tensor): assert not tensor.requires_grad, ( \"gradients only computed", "the blank token. fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: Batch of", "1, 0, blank] for u in range(1, U): alphas[0, u] = alphas[0, u", "reg = fastemit_regularization( log_probs[b, :t, :u, :], labels[b, : u - 1], alphas,", "U - 1] = betas[t + 1, U - 1] + log_probs[t, U", "negative log-likelihood 3D array: Gradients with respect to the unnormalized input actications 2d", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "in range(log_probs.shape[0]): t = int(flen[b]) u = int(glen[b]) + 1 ll, g, alphas,", "1, labels[u - 1]] alphas[t, u] = np.logaddexp(emit, no_emit) loglike = alphas[T -", "act_lens, label_lens): assert len(labels.size()) == 2 _assert_no_grad(labels) _assert_no_grad(act_lens) _assert_no_grad(label_lens) certify_inputs(acts, labels, act_lens, label_lens)", "_ = log_probs.shape alphas = np.zeros((T, U), dtype='f') for t in range(1, T):", "specific language governing permissions and # limitations under the License. # # Copyright", "of shape [T, U] and the log likelihood of this backward step. \"\"\"", "Tensor of shape [T, U, V+1] labels: Unused. Labels of shape [B, U]", "labels, lengths, label_lengths): # check_type(log_probs, torch.float32, \"log_probs\") check_type(labels, torch.int32, \"labels\") check_type(label_lengths, torch.int32, \"label_lengths\")", "import Function, Variable from torch.nn import Module def check_type(var, t, name): if var.dtype", "truth labels with <SOS> padded as blank token in the beginning. flen: Length", "[] for b in range(log_probs.shape[0]): t = int(flen[b]) u = int(glen[b]) + 1", "check_type(log_probs, torch.float32, \"log_probs\") check_type(labels, torch.int32, \"labels\") check_type(label_lengths, torch.int32, \"label_lengths\") check_type(lengths, torch.int32, \"lengths\") check_contiguous(log_probs,", "blank) grads = compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda) return -ll_forward, grads, alphas,", "- 1)): betas[T - 1, u] = betas[T - 1, u + 1]", "labels, act_lens, label_lens, blank, fastemit_lambda): costs, grads = transduce_batch( acts.detach().cpu().numpy(), labels.cpu().numpy(), act_lens.cpu().numpy(), label_lens.cpu().numpy(),", "= transduce_batch( acts.detach().cpu().numpy(), labels.cpu().numpy(), act_lens.cpu().numpy(), label_lens.cpu().numpy(), blank, fastemit_lambda, ) costs = torch.FloatTensor([sum(costs)]) grads", "# for t in range(0, T): # for u in range(0, U -", "Expected max T from input lengths: {max_T}\") if U != max_U + 1:", "blank: Index of the blank token. Returns: Gradients of shape [T, U, V+1]", "U, V+1] with respect to the forward log probability \"\"\" T, U, _", "U, _ = log_probs.shape alphas = np.zeros((T, U), dtype='f') for t in range(1,", "= torch.max(label_lengths) T, U = log_probs.shape[1:3] if T != max_T: raise ValueError(f\"Input length", "computation of FastEmit regularization from the paper - [FastEmit: Low-latency Streaming ASR with", "__init__(self, blank: int = 0, fastemit_lambda: float = 0.0): super(RNNTLoss, self).__init__() self.blank =", "u - 1] + log_probs[t, u - 1, labels[u - 1]] alphas[t, u]", "computing the betas alignment matrix reg = fastemit_lambda * (alphas[T - 1, U", "costs.append(ll) return costs, grads class _RNNT(Function): @staticmethod def forward(ctx, acts, labels, act_lens, label_lens,", "(TxU) 2d array: Betas matrix (TxU) \"\"\" alphas, ll_forward = forward_pass(log_probs, labels, blank)", "log_probs[t - 1, u, blank] emit = alphas[t, u - 1] + log_probs[t,", ":] # // grad to label transition for u, l in enumerate(labels): grads[:,", "# you may not use this file except in compliance with the License.", "U] and the log likelihood of this forward step. \"\"\" T, U, _", "= np.full(log_probs.shape, -float(\"inf\")) log_like = betas[0, 0] # == alphas[T - 1, U", "__name__ == '__main__': loss = RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0) acts = torch.randn(1, 2, 5, 3)", "U, _ = log_probs.shape betas = np.zeros((T, U), dtype='f') betas[T - 1, U", "2d arrays: Alphas matrix (TxU) 2d array: Betas matrix (TxU) \"\"\" alphas, ll_forward", "with respect to the log probability of this step occuring. Args: Args: log_probs:", "def backward(ctx, grad_output): return ctx.grads, None, None, None, None, None class RNNTLoss(Module): \"\"\"", "U), dtype='f') for t in range(1, T): alphas[t, 0] = alphas[t - 1,", "return costs, grads class _RNNT(Function): @staticmethod def forward(ctx, acts, labels, act_lens, label_lens, blank,", "raise ValueError(\"{} must be {}D\".format(name, dim)) def certify_inputs(log_probs, labels, lengths, label_lengths): # check_type(log_probs,", "per example. \" f\"Given label lengths dim : {label_lengths.shape[0]}, \" f\"Log probs dim", "Args: log_probs: Tensor of shape [T, U, V+1] labels: Labels of shape [B,", "1, 0] + log_probs[t - 1, 0, blank] for u in range(1, U):", "variable beta. Args: log_probs: Tensor of shape [T, U, V+1] labels: Labels of", "act_lens, label_lens, self.blank, self.fastemit_lambda) if __name__ == '__main__': loss = RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0) acts", "for t in range(0, T): # for u in range(0, U - 1):", "probabilities - beta of shape [T, U] and the log likelihood of this", "alphas[:, u] + betas[:, u + 1] grads = -np.exp(grads + log_probs -", "max_U + 1: raise ValueError(f\"Output length mismatch! Given U: {U}, Expected max U", "= compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda) return -ll_forward, grads, alphas, betas def", "blank] = alphas[T - 1, U - 1] grads[: T - 1, :,", "log_probs[T - 1, U - 1, blank] return alphas, loglike def backward_pass(log_probs, labels,", "None, None, None, None class RNNTLoss(Module): \"\"\" Parameters: `blank_label` (int): default 0 -", "blank] emit = betas[t, u + 1] + log_probs[t, u, labels[u]] betas[t, u]", "if lengths.shape[0] != log_probs.shape[0]: raise ValueError( f\"Must have a length per example. \"", "torch.max(lengths) max_U = torch.max(label_lengths) T, U = log_probs.shape[1:3] if T != max_T: raise", "betas[T - 1, U - 1] = log_probs[T - 1, U - 1,", "V+1] labels: Labels of shape [B, U] blank: Index of the blank token.", "1, U - 1]) # The above is equivalent to below, without need", "np.logaddexp(emit, no_emit) return betas, betas[0, 0] def compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda):", "specific language governing permissions and # limitations under the License. import numpy as", "under the License. # # Copyright 2018-2019, <NAME> # # Licensed under the", "= transduce(log_probs[b, :t, :u, :], labels[b, : u - 1], blank, fastemit_lambda) grads[b,", "[T, U] which represents the backward variable. blank: Index of the blank token.", "{label_lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\" ) check_dim(log_probs, 4, \"log_probs\") check_dim(labels, 2,", "under the License. import numpy as np import torch from torch.autograd import Function,", "License for the specific language governing permissions and # limitations under the License.", "Float scaling factor for FastEmit regularization. Returns: Batch of transducer forward log probabilities", "= -np.exp(grads + log_probs - log_like) if fastemit_lambda > 0.0: for u, l", "u in reversed(range(U - 1)): no_emit = betas[t + 1, u] + log_probs[t,", "dtype='f') betas[T - 1, U - 1] = log_probs[T - 1, U -", "u in reversed(range(U - 1)): betas[T - 1, u] = betas[T - 1,", "1, U - 1] # // grad to last blank transition grads[T -", "\"License\"); # you may not use this file except in compliance with the", "forward variable alpha. Args: log_probs: Tensor of shape [T, U, V+1] labels: Labels", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "TypeError(\"{} must be {}\".format(name, t)) def check_contiguous(var, name): if not var.is_contiguous(): raise ValueError(\"{}", "- 1, u] = betas[T - 1, u + 1] + log_probs[T -", "t in reversed(range(T - 1)): betas[t, U - 1] = betas[t + 1,", "betas[t + 1, U - 1] + log_probs[t, U - 1, blank] for", "respect to the forward log probability \"\"\" T, U, _ = log_probs.shape grads", "- 1, U - 1, blank] for t in reversed(range(T - 1)): betas[t,", "V+1] labels: Unused. Labels of shape [B, U] alphas: Tensor of shape [T,", "log_probs: 3D array with shape [input len, output len + 1, vocab size]", "in reversed(range(U - 1)): betas[T - 1, u] = betas[T - 1, u", "= grads return costs @staticmethod def backward(ctx, grad_output): return ctx.grads, None, None, None,", "variable probabilities - alpha of shape [T, U] and the log likelihood of", "Computes the gradients of the log_probs with respect to the log probability of", "t in range(0, T): # for u in range(0, U - 1): #", "= blank self.fastemit_lambda = fastemit_lambda self.rnnt = _RNNT.apply def forward(self, acts, labels, act_lens,", "as np import torch from torch.autograd import Function, Variable from torch.nn import Module", "sequence. glen: Length vector of the target sequence. blank: Id of the blank", "likelihood - lambda * P˜(At, u|x) \"\"\" # General calculation of the fastemit", ") def forward_pass(log_probs, labels, blank): \"\"\" Computes probability of the forward variable alpha.", "- 1)): betas[t, U - 1] = betas[t + 1, U - 1]", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "U - 1, blank]) return -reg def transduce(log_probs, labels, blank=0, fastemit_lambda=0.0): \"\"\" Args:", "in writing, software # distributed under the License is distributed on an \"AS", "Unused. Labels of shape [B, U] alphas: Tensor of shape [T, U] which", "act_lens, label_lens, blank, fastemit_lambda): costs, grads = transduce_batch( acts.detach().cpu().numpy(), labels.cpu().numpy(), act_lens.cpu().numpy(), label_lens.cpu().numpy(), blank,", "raise ValueError(\"{} must be contiguous\".format(name)) def check_dim(var, dim, name): if len(var.shape) != dim:", "= torch.max(lengths) max_U = torch.max(label_lengths) T, U = log_probs.shape[1:3] if T != max_T:", "tensor.requires_grad, ( \"gradients only computed for log_probs - please \" \"mark other tensors", "betas = transduce(log_probs[b, :t, :u, :], labels[b, : u - 1], blank, fastemit_lambda)", "of shape [T, U, V+1] alphas: Tensor of shape [T, U] which represents", "0.0: for u, l in enumerate(labels): grads[:, u, l] = (1.0 + fastemit_lambda)", "alphas[t - 1, u] + log_probs[t - 1, u, blank] emit = alphas[t,", "token. fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: float: The negative log-likelihood", "u, labels[u]] + betas[t, u + 1] # alignment[t, u] = emit #", "the blank token. fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: float: The", "1, blank] return alphas, loglike def backward_pass(log_probs, labels, blank): \"\"\" Computes probability of", "this step occuring. Args: Args: log_probs: Tensor of shape [T, U, V+1] alphas:", "the gradients of the log_probs with respect to the log probability of this", "to below, without need of computing the betas alignment matrix reg = fastemit_lambda", "def compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda): \"\"\" Computes the gradients of the", "// grad to last blank transition grads[T - 1, U - 1, blank]", "- 1, 0] + log_probs[t - 1, 0, blank] for u in range(1,", "1], blank, fastemit_lambda) grads[b, :t, :u, :] = g reg = fastemit_regularization( log_probs[b,", "if __name__ == '__main__': loss = RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0) acts = torch.randn(1, 2, 5,", "Tensor of shape [T, U, V+1] labels: Labels of shape [B, U] blank:", "= alphas[t - 1, u] + log_probs[t - 1, u, blank] emit =", "f\"Must have a length per example. \" f\"Given lengths dim: {lengths.shape[0]}, \" f\"Log", "A tuple of the backward variable probabilities - beta of shape [T, U]", "flen, glen, blank=0, fastemit_lambda=0.0): \"\"\" Compute the transducer loss of the batch. Args:", "raise ValueError( f\"Must have a length per example. \" f\"Given lengths dim: {lengths.shape[0]},", "scaling factor for FastEmit regularization. \"\"\" def __init__(self, blank: int = 0, fastemit_lambda:", "grads[T - 1, U - 1, blank] = alphas[T - 1, U -", "def forward_pass(log_probs, labels, blank): \"\"\" Computes probability of the forward variable alpha. Args:", "1, :, blank] = alphas[: T - 1, :] + betas[1:, :] #", "to the log probability of this step occuring. Args: Args: log_probs: Tensor of", "2.0 (the \"License\"); # you may not use this file except in compliance", "U - 1] = alphas[t, U - 1] + betas[t, U - 1]", "# # for t in range(0, T): # for u in range(0, U", "= betas[t, u + 1] + log_probs[t, u, labels[u]] betas[t, u] = np.logaddexp(emit,", "+ 1: raise ValueError(f\"Output length mismatch! Given U: {U}, Expected max U from", "U] which represents the forward variable. betas: Unused. Tensor of shape [T, U]", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "blank): \"\"\" Computes probability of the forward variable alpha. Args: log_probs: Tensor of", "+ betas[t, U - 1] # # for t in range(0, T): #", "u] + betas[:, u + 1] grads = -np.exp(grads + log_probs - log_like)", "= np.zeros((T, U), dtype='f') for t in range(1, T): alphas[t, 0] = alphas[t", "# # Unless required by applicable law or agreed to in writing, software", "a label length per example. \" f\"Given label lengths dim : {label_lengths.shape[0]}, \"", "express or implied. # See the License for the specific language governing permissions", "+ log_probs[T - 1, U - 1, blank]) return -reg def transduce(log_probs, labels,", "ll += reg costs.append(ll) return costs, grads class _RNNT(Function): @staticmethod def forward(ctx, acts,", "the fastemit regularization alignments T, U, _ = log_probs.shape # alignment = np.zeros((T,", "== '__main__': loss = RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0) acts = torch.randn(1, 2, 5, 3) labels", "in reversed(range(T - 1)): betas[t, U - 1] = betas[t + 1, U", "either express or implied. # See the License for the specific language governing", "u - 1] + log_probs[0, u - 1, labels[u - 1]] for t", "# limitations under the License. # # Copyright 2018-2019, <NAME> # # Licensed", "1] # # for t in range(0, T): # for u in range(0,", "token. fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: Batch of transducer forward", "labels, blank): \"\"\" Computes probability of the backward variable beta. Args: log_probs: Tensor", "loss of the batch. Args: log_probs: [B, T, U, V+1]. Activation matrix normalized", "label lengths dim : {label_lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\" ) check_dim(log_probs,", "the forward variable. betas: Unused. Tensor of shape [T, U] which represents the", "permissions and # limitations under the License. # # Copyright 2018-2019, <NAME> #", "- 1, blank] = alphas[T - 1, U - 1] grads[: T -", "token. fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: The regularized negative log", "no_emit) return betas, betas[0, 0] def compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda): \"\"\"", "the License. # You may obtain a copy of the License at #", "betas[T - 1, U - 1]) # The above is also equivalent to", "\"lengths\") if lengths.shape[0] != log_probs.shape[0]: raise ValueError( f\"Must have a length per example.", "import torch from torch.autograd import Function, Variable from torch.nn import Module def check_type(var,", "for t in range(1, T): alphas[t, 0] = alphas[t - 1, 0] +", "- 1, U - 1, blank] = alphas[T - 1, U - 1]", "1)): betas[T - 1, u] = betas[T - 1, u + 1] +", "torch.max(label_lengths) T, U = log_probs.shape[1:3] if T != max_T: raise ValueError(f\"Input length mismatch!", "blank self.fastemit_lambda = fastemit_lambda self.rnnt = _RNNT.apply def forward(self, acts, labels, act_lens, label_lens):", "the batch. Args: log_probs: [B, T, U, V+1]. Activation matrix normalized with log-softmax.", "U] blank: Index of the blank token. Returns: A tuple of the forward", "transduce_batch( acts.detach().cpu().numpy(), labels.cpu().numpy(), act_lens.cpu().numpy(), label_lens.cpu().numpy(), blank, fastemit_lambda, ) costs = torch.FloatTensor([sum(costs)]) grads =", "the log_probs with respect to the log probability of this step occuring. Args:", "Module def check_type(var, t, name): if var.dtype is not t: raise TypeError(\"{} must", "blank token in the beginning. flen: Length vector of the acoustic sequence. glen:", "Returns: The regularized negative log likelihood - lambda * P˜(At, u|x) \"\"\" #", "of the blank token. fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: Batch", "!= max_U + 1: raise ValueError(f\"Output length mismatch! Given U: {U}, Expected max", "\"labels\") check_contiguous(label_lengths, \"label_lengths\") check_contiguous(lengths, \"lengths\") if lengths.shape[0] != log_probs.shape[0]: raise ValueError( f\"Must have", "np.zeros_like(log_probs) costs = [] for b in range(log_probs.shape[0]): t = int(flen[b]) u =", "have a label length per example. \" f\"Given label lengths dim : {label_lengths.shape[0]},", "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", ": u - 1], alphas, betas, blank, fastemit_lambda ) ll += reg costs.append(ll)", "1, U - 1] + log_probs[t, U - 1, blank] for u in", "g reg = fastemit_regularization( log_probs[b, :t, :u, :], labels[b, : u - 1],", "equivalent to below, without need of computing the betas alignment matrix reg =", "reg = fastemit_lambda * (alphas[T - 1, U - 1] + log_probs[T -", "log_probs[T - 1, u, labels[u]] for t in reversed(range(T - 1)): for u", "represents the backward variable. labels: Labels of shape [B, U] blank: Index of", "= np.zeros((T, U), dtype='float32') # # for t in range(0, T): # alignment[t,", "= np.zeros((T, U), dtype='f') betas[T - 1, U - 1] = log_probs[T -", "grads = np.full(log_probs.shape, -float(\"inf\")) log_like = betas[0, 0] # == alphas[T - 1,", "T): # for u in range(0, U - 1): # emit = alphas[t,", "1, u, labels[u]] for t in reversed(range(T - 1)): for u in reversed(range(U", "log probabilities (loss) and the gradients of the activation matrix. \"\"\" grads =", "= alphas[t, U - 1] + betas[t, U - 1] # # for", "FastEmit regularization. Returns: float: The negative log-likelihood 3D array: Gradients with respect to", "shape [T, U] and the log likelihood of this backward step. \"\"\" T,", "range(0, T): # for u in range(0, U - 1): # emit =", "blank, fastemit_lambda, ) costs = torch.FloatTensor([sum(costs)]) grads = torch.Tensor(grads).to(acts) ctx.grads = grads return", "token in the beginning. flen: Length vector of the acoustic sequence. glen: Length", "u, l] = (1.0 + fastemit_lambda) * grads[:, u, l] return grads def", "grads = torch.Tensor(grads).to(acts) ctx.grads = grads return costs @staticmethod def backward(ctx, grad_output): return", "labels: 1D array with shape [output time steps] blank: Index of the blank", "if var.dtype is not t: raise TypeError(\"{} must be {}\".format(name, t)) def check_contiguous(var,", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "blank=0, fastemit_lambda=0.0): \"\"\" Args: log_probs: 3D array with shape [input len, output len", "acts = torch.randn(1, 2, 5, 3) labels = torch.tensor([[0, 2, 1, 2]], dtype=torch.int32)", "Expected max U from target lengths: {max_U} + 1\") def _assert_no_grad(tensor): assert not", "ground truth labels with <SOS> padded as blank token in the beginning. flen:", "of the activation matrix. \"\"\" grads = np.zeros_like(log_probs) costs = [] for b", "the blank token. Returns: Gradients of shape [T, U, V+1] with respect to", "matrix. \"\"\" grads = np.zeros_like(log_probs) costs = [] for b in range(log_probs.shape[0]): t", "+ 1\") def _assert_no_grad(tensor): assert not tensor.requires_grad, ( \"gradients only computed for log_probs", "- 1] = alphas[t, U - 1] + betas[t, U - 1] #", "if label_lengths.shape[0] != log_probs.shape[0]: raise ValueError( \"Must have a label length per example.", "1, U - 1] = log_probs[T - 1, U - 1, blank] for", "name): if var.dtype is not t: raise TypeError(\"{} must be {}\".format(name, t)) def", "U - 1] + betas[T - 1, U - 1] # // grad", "Args: Args: log_probs: Tensor of shape [T, U, V+1] alphas: Tensor of shape", "except in compliance with the License. # You may obtain a copy of", "+ log_probs[t, u, labels[u]] betas[t, u] = np.logaddexp(emit, no_emit) return betas, betas[0, 0]", "+ log_probs - log_like) if fastemit_lambda > 0.0: for u, l in enumerate(labels):", "time steps] blank: Index of the blank token. fastemit_lambda: Float scaling factor for", "factor for FastEmit regularization. Returns: Batch of transducer forward log probabilities (loss) and", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "occuring. Args: Args: log_probs: Tensor of shape [T, U, V+1] alphas: Tensor of", "blank] = alphas[: T - 1, :] + betas[1:, :] # // grad", "`blank_label` (int): default 0 - label index of blank token fastemit_lambda: Float scaling", "of shape [T, U] and the log likelihood of this forward step. \"\"\"", "matrix (TxU) \"\"\" alphas, ll_forward = forward_pass(log_probs, labels, blank) betas, ll_backward = backward_pass(log_probs,", "ctx.grads, None, None, None, None, None class RNNTLoss(Module): \"\"\" Parameters: `blank_label` (int): default", "fastemit_lambda, ) costs = torch.FloatTensor([sum(costs)]) grads = torch.Tensor(grads).to(acts) ctx.grads = grads return costs", "+ betas[T - 1, U - 1] # // grad to last blank", "alphas[t, u] + log_probs[t, u, labels[u]] + betas[t, u + 1] # alignment[t,", "the blank token. Returns: A tuple of the forward variable probabilities - alpha", "Labels of shape [B, U] alphas: Tensor of shape [T, U] which represents", "betas, labels, blank, fastemit_lambda) return -ll_forward, grads, alphas, betas def transduce_batch(log_probs, labels, flen,", "probs dim : {log_probs.shape[0]}\" ) if label_lengths.shape[0] != log_probs.shape[0]: raise ValueError( \"Must have", "labels[u]] for t in reversed(range(T - 1)): for u in reversed(range(U - 1)):", "(alphas[T - 1, U - 1] + betas[T - 1, U - 1])", "below, without need of computing above # reg = fastemit_lambda * (alphas[T -", "None, None, None, None, None class RNNTLoss(Module): \"\"\" Parameters: `blank_label` (int): default 0", "acoustic sequence. glen: Length vector of the target sequence. blank: Id of the", "t in range(1, T): alphas[t, 0] = alphas[t - 1, 0] + log_probs[t", "t = int(flen[b]) u = int(glen[b]) + 1 ll, g, alphas, betas =", "Parameters: `blank_label` (int): default 0 - label index of blank token fastemit_lambda: Float", "!= log_probs.shape[0]: raise ValueError( f\"Must have a length per example. \" f\"Given lengths", "P˜(At, u|x) \"\"\" # General calculation of the fastemit regularization alignments T, U,", "torch.autograd import Function, Variable from torch.nn import Module def check_type(var, t, name): if", "if not var.is_contiguous(): raise ValueError(\"{} must be contiguous\".format(name)) def check_dim(var, dim, name): if", "blank] for u in reversed(range(U - 1)): betas[T - 1, u] = betas[T", "alphas[0, u - 1] + log_probs[0, u - 1, labels[u - 1]] for", "Returns: Gradients of shape [T, U, V+1] with respect to the forward log" ]
[ "as np import math from dataset_specifications.dataset import Dataset class SwirlsSet(Dataset): def __init__(self): super().__init__()", "= means + std*noise return ys def sample(self, n): xs = np.random.uniform(low=0., high=2.,", "math from dataset_specifications.dataset import Dataset class SwirlsSet(Dataset): def __init__(self): super().__init__() self.name = \"swirls\"", "self.n_samples = { \"train\": 2000, \"val\": 1000, \"test\": 1000, } self.y_dim = 2", "n): xs = np.random.uniform(low=0., high=2., size=(n,1)) ys = self.sample_ys(xs) return np.concatenate((xs, ys), axis=1)", "= np.random.randn(n, 2) # samples form 2d gaussian std = 0.3 - 0.2*np.abs(xs-1.)", "np.sin(angles)), axis=1) noise = np.random.randn(n, 2) # samples form 2d gaussian std =", "# Angles to centers means = np.stack((np.cos(angles), np.sin(angles)), axis=1) noise = np.random.randn(n, 2)", "+ std*noise return ys def sample(self, n): xs = np.random.uniform(low=0., high=2., size=(n,1)) ys", "__init__(self): super().__init__() self.name = \"swirls\" self.n_samples = { \"train\": 2000, \"val\": 1000, \"test\":", "1000, \"test\": 1000, } self.y_dim = 2 # 2D heteroskedastic Gaussian mixture model", "dataset_specifications.dataset import Dataset class SwirlsSet(Dataset): def __init__(self): super().__init__() self.name = \"swirls\" self.n_samples =", "# samples form 2d gaussian std = 0.3 - 0.2*np.abs(xs-1.) ys = means", "self.y_dim = 2 # 2D heteroskedastic Gaussian mixture model with 2 components def", "import numpy as np import math from dataset_specifications.dataset import Dataset class SwirlsSet(Dataset): def", "# uniform 0,1 angles = math.pi*components + (math.pi/2.)*xs[:,0] # Angles to centers means", "def __init__(self): super().__init__() self.name = \"swirls\" self.n_samples = { \"train\": 2000, \"val\": 1000,", "2000, \"val\": 1000, \"test\": 1000, } self.y_dim = 2 # 2D heteroskedastic Gaussian", "} self.y_dim = 2 # 2D heteroskedastic Gaussian mixture model with 2 components", "components def sample_ys(self, xs): n = xs.shape[0] components = np.random.randint(2, size=n) # uniform", "Gaussian mixture model with 2 components def sample_ys(self, xs): n = xs.shape[0] components", "= np.random.randint(2, size=n) # uniform 0,1 angles = math.pi*components + (math.pi/2.)*xs[:,0] # Angles", "return ys def sample(self, n): xs = np.random.uniform(low=0., high=2., size=(n,1)) ys = self.sample_ys(xs)", "= np.stack((np.cos(angles), np.sin(angles)), axis=1) noise = np.random.randn(n, 2) # samples form 2d gaussian", "ys = means + std*noise return ys def sample(self, n): xs = np.random.uniform(low=0.,", "SwirlsSet(Dataset): def __init__(self): super().__init__() self.name = \"swirls\" self.n_samples = { \"train\": 2000, \"val\":", "heteroskedastic Gaussian mixture model with 2 components def sample_ys(self, xs): n = xs.shape[0]", "= math.pi*components + (math.pi/2.)*xs[:,0] # Angles to centers means = np.stack((np.cos(angles), np.sin(angles)), axis=1)", "def sample_ys(self, xs): n = xs.shape[0] components = np.random.randint(2, size=n) # uniform 0,1", "= 2 # 2D heteroskedastic Gaussian mixture model with 2 components def sample_ys(self,", "- 0.2*np.abs(xs-1.) ys = means + std*noise return ys def sample(self, n): xs", "\"test\": 1000, } self.y_dim = 2 # 2D heteroskedastic Gaussian mixture model with", "Dataset class SwirlsSet(Dataset): def __init__(self): super().__init__() self.name = \"swirls\" self.n_samples = { \"train\":", "xs.shape[0] components = np.random.randint(2, size=n) # uniform 0,1 angles = math.pi*components + (math.pi/2.)*xs[:,0]", "std = 0.3 - 0.2*np.abs(xs-1.) ys = means + std*noise return ys def", "\"train\": 2000, \"val\": 1000, \"test\": 1000, } self.y_dim = 2 # 2D heteroskedastic", "class SwirlsSet(Dataset): def __init__(self): super().__init__() self.name = \"swirls\" self.n_samples = { \"train\": 2000,", "Angles to centers means = np.stack((np.cos(angles), np.sin(angles)), axis=1) noise = np.random.randn(n, 2) #", "axis=1) noise = np.random.randn(n, 2) # samples form 2d gaussian std = 0.3", "0,1 angles = math.pi*components + (math.pi/2.)*xs[:,0] # Angles to centers means = np.stack((np.cos(angles),", "0.3 - 0.2*np.abs(xs-1.) ys = means + std*noise return ys def sample(self, n):", "0.2*np.abs(xs-1.) ys = means + std*noise return ys def sample(self, n): xs =", "np.random.randint(2, size=n) # uniform 0,1 angles = math.pi*components + (math.pi/2.)*xs[:,0] # Angles to", "= \"swirls\" self.n_samples = { \"train\": 2000, \"val\": 1000, \"test\": 1000, } self.y_dim", "xs): n = xs.shape[0] components = np.random.randint(2, size=n) # uniform 0,1 angles =", "noise = np.random.randn(n, 2) # samples form 2d gaussian std = 0.3 -", "2D heteroskedastic Gaussian mixture model with 2 components def sample_ys(self, xs): n =", "super().__init__() self.name = \"swirls\" self.n_samples = { \"train\": 2000, \"val\": 1000, \"test\": 1000,", "components = np.random.randint(2, size=n) # uniform 0,1 angles = math.pi*components + (math.pi/2.)*xs[:,0] #", "mixture model with 2 components def sample_ys(self, xs): n = xs.shape[0] components =", "# 2D heteroskedastic Gaussian mixture model with 2 components def sample_ys(self, xs): n", "gaussian std = 0.3 - 0.2*np.abs(xs-1.) ys = means + std*noise return ys", "sample_ys(self, xs): n = xs.shape[0] components = np.random.randint(2, size=n) # uniform 0,1 angles", "def sample(self, n): xs = np.random.uniform(low=0., high=2., size=(n,1)) ys = self.sample_ys(xs) return np.concatenate((xs,", "means + std*noise return ys def sample(self, n): xs = np.random.uniform(low=0., high=2., size=(n,1))", "{ \"train\": 2000, \"val\": 1000, \"test\": 1000, } self.y_dim = 2 # 2D", "np.stack((np.cos(angles), np.sin(angles)), axis=1) noise = np.random.randn(n, 2) # samples form 2d gaussian std", "from dataset_specifications.dataset import Dataset class SwirlsSet(Dataset): def __init__(self): super().__init__() self.name = \"swirls\" self.n_samples", "import Dataset class SwirlsSet(Dataset): def __init__(self): super().__init__() self.name = \"swirls\" self.n_samples = {", "2 # 2D heteroskedastic Gaussian mixture model with 2 components def sample_ys(self, xs):", "2d gaussian std = 0.3 - 0.2*np.abs(xs-1.) ys = means + std*noise return", "model with 2 components def sample_ys(self, xs): n = xs.shape[0] components = np.random.randint(2,", "self.name = \"swirls\" self.n_samples = { \"train\": 2000, \"val\": 1000, \"test\": 1000, }", "np.random.randn(n, 2) # samples form 2d gaussian std = 0.3 - 0.2*np.abs(xs-1.) ys", "sample(self, n): xs = np.random.uniform(low=0., high=2., size=(n,1)) ys = self.sample_ys(xs) return np.concatenate((xs, ys),", "np import math from dataset_specifications.dataset import Dataset class SwirlsSet(Dataset): def __init__(self): super().__init__() self.name", "= 0.3 - 0.2*np.abs(xs-1.) ys = means + std*noise return ys def sample(self,", "\"swirls\" self.n_samples = { \"train\": 2000, \"val\": 1000, \"test\": 1000, } self.y_dim =", "means = np.stack((np.cos(angles), np.sin(angles)), axis=1) noise = np.random.randn(n, 2) # samples form 2d", "std*noise return ys def sample(self, n): xs = np.random.uniform(low=0., high=2., size=(n,1)) ys =", "import math from dataset_specifications.dataset import Dataset class SwirlsSet(Dataset): def __init__(self): super().__init__() self.name =", "samples form 2d gaussian std = 0.3 - 0.2*np.abs(xs-1.) ys = means +", "centers means = np.stack((np.cos(angles), np.sin(angles)), axis=1) noise = np.random.randn(n, 2) # samples form", "ys def sample(self, n): xs = np.random.uniform(low=0., high=2., size=(n,1)) ys = self.sample_ys(xs) return", "1000, } self.y_dim = 2 # 2D heteroskedastic Gaussian mixture model with 2", "with 2 components def sample_ys(self, xs): n = xs.shape[0] components = np.random.randint(2, size=n)", "n = xs.shape[0] components = np.random.randint(2, size=n) # uniform 0,1 angles = math.pi*components", "size=n) # uniform 0,1 angles = math.pi*components + (math.pi/2.)*xs[:,0] # Angles to centers", "angles = math.pi*components + (math.pi/2.)*xs[:,0] # Angles to centers means = np.stack((np.cos(angles), np.sin(angles)),", "(math.pi/2.)*xs[:,0] # Angles to centers means = np.stack((np.cos(angles), np.sin(angles)), axis=1) noise = np.random.randn(n,", "to centers means = np.stack((np.cos(angles), np.sin(angles)), axis=1) noise = np.random.randn(n, 2) # samples", "<reponame>joeloskarsson/CGAN-regression import numpy as np import math from dataset_specifications.dataset import Dataset class SwirlsSet(Dataset):", "numpy as np import math from dataset_specifications.dataset import Dataset class SwirlsSet(Dataset): def __init__(self):", "math.pi*components + (math.pi/2.)*xs[:,0] # Angles to centers means = np.stack((np.cos(angles), np.sin(angles)), axis=1) noise", "form 2d gaussian std = 0.3 - 0.2*np.abs(xs-1.) ys = means + std*noise", "\"val\": 1000, \"test\": 1000, } self.y_dim = 2 # 2D heteroskedastic Gaussian mixture", "+ (math.pi/2.)*xs[:,0] # Angles to centers means = np.stack((np.cos(angles), np.sin(angles)), axis=1) noise =", "= { \"train\": 2000, \"val\": 1000, \"test\": 1000, } self.y_dim = 2 #", "= xs.shape[0] components = np.random.randint(2, size=n) # uniform 0,1 angles = math.pi*components +", "2) # samples form 2d gaussian std = 0.3 - 0.2*np.abs(xs-1.) ys =", "2 components def sample_ys(self, xs): n = xs.shape[0] components = np.random.randint(2, size=n) #", "uniform 0,1 angles = math.pi*components + (math.pi/2.)*xs[:,0] # Angles to centers means =" ]
[ "initialization() # run cpp tests get_json_report(test_list, options) # collect coverage data from json", "run cpp tests get_json_report(test_list, options) # collect coverage data from json profiles if", "= time.time() (options, test_list, interested_folders) = initialization() # run cpp tests get_json_report(test_list, options)", "None: start_time = time.time() (options, test_list, interested_folders) = initialization() # run cpp tests", "cpp tests get_json_report(test_list, options) # collect coverage data from json profiles if options.need_summary:", "import initialization from package.tool.summarize_jsons import summarize_jsons from package.util.setting import TestPlatform def report_coverage() ->", "= initialization() # run cpp tests get_json_report(test_list, options) # collect coverage data from", "import summarize_jsons from package.util.setting import TestPlatform def report_coverage() -> None: start_time = time.time()", "data from json profiles if options.need_summary: summarize_jsons( test_list, interested_folders, [\"\"], TestPlatform.OSS, start_time )", "from package.oss.cov_json import get_json_report from package.oss.init import initialization from package.tool.summarize_jsons import summarize_jsons from", "time.time() (options, test_list, interested_folders) = initialization() # run cpp tests get_json_report(test_list, options) #", "# run cpp tests get_json_report(test_list, options) # collect coverage data from json profiles", "json profiles if options.need_summary: summarize_jsons( test_list, interested_folders, [\"\"], TestPlatform.OSS, start_time ) if __name__", "options.need_summary: summarize_jsons( test_list, interested_folders, [\"\"], TestPlatform.OSS, start_time ) if __name__ == \"__main__\": report_coverage()", "package.oss.cov_json import get_json_report from package.oss.init import initialization from package.tool.summarize_jsons import summarize_jsons from package.util.setting", "summarize_jsons from package.util.setting import TestPlatform def report_coverage() -> None: start_time = time.time() (options,", "from json profiles if options.need_summary: summarize_jsons( test_list, interested_folders, [\"\"], TestPlatform.OSS, start_time ) if", "package.oss.init import initialization from package.tool.summarize_jsons import summarize_jsons from package.util.setting import TestPlatform def report_coverage()", "get_json_report(test_list, options) # collect coverage data from json profiles if options.need_summary: summarize_jsons( test_list,", "tests get_json_report(test_list, options) # collect coverage data from json profiles if options.need_summary: summarize_jsons(", "interested_folders) = initialization() # run cpp tests get_json_report(test_list, options) # collect coverage data", "# collect coverage data from json profiles if options.need_summary: summarize_jsons( test_list, interested_folders, [\"\"],", "coverage data from json profiles if options.need_summary: summarize_jsons( test_list, interested_folders, [\"\"], TestPlatform.OSS, start_time", "import time from package.oss.cov_json import get_json_report from package.oss.init import initialization from package.tool.summarize_jsons import", "TestPlatform def report_coverage() -> None: start_time = time.time() (options, test_list, interested_folders) = initialization()", "test_list, interested_folders) = initialization() # run cpp tests get_json_report(test_list, options) # collect coverage", "get_json_report from package.oss.init import initialization from package.tool.summarize_jsons import summarize_jsons from package.util.setting import TestPlatform", "-> None: start_time = time.time() (options, test_list, interested_folders) = initialization() # run cpp", "<gh_stars>10-100 #!/usr/bin/env python import time from package.oss.cov_json import get_json_report from package.oss.init import initialization", "package.tool.summarize_jsons import summarize_jsons from package.util.setting import TestPlatform def report_coverage() -> None: start_time =", "import TestPlatform def report_coverage() -> None: start_time = time.time() (options, test_list, interested_folders) =", "start_time = time.time() (options, test_list, interested_folders) = initialization() # run cpp tests get_json_report(test_list,", "(options, test_list, interested_folders) = initialization() # run cpp tests get_json_report(test_list, options) # collect", "collect coverage data from json profiles if options.need_summary: summarize_jsons( test_list, interested_folders, [\"\"], TestPlatform.OSS,", "import get_json_report from package.oss.init import initialization from package.tool.summarize_jsons import summarize_jsons from package.util.setting import", "time from package.oss.cov_json import get_json_report from package.oss.init import initialization from package.tool.summarize_jsons import summarize_jsons", "profiles if options.need_summary: summarize_jsons( test_list, interested_folders, [\"\"], TestPlatform.OSS, start_time ) if __name__ ==", "from package.util.setting import TestPlatform def report_coverage() -> None: start_time = time.time() (options, test_list,", "#!/usr/bin/env python import time from package.oss.cov_json import get_json_report from package.oss.init import initialization from", "initialization from package.tool.summarize_jsons import summarize_jsons from package.util.setting import TestPlatform def report_coverage() -> None:", "package.util.setting import TestPlatform def report_coverage() -> None: start_time = time.time() (options, test_list, interested_folders)", "from package.tool.summarize_jsons import summarize_jsons from package.util.setting import TestPlatform def report_coverage() -> None: start_time", "python import time from package.oss.cov_json import get_json_report from package.oss.init import initialization from package.tool.summarize_jsons", "options) # collect coverage data from json profiles if options.need_summary: summarize_jsons( test_list, interested_folders,", "if options.need_summary: summarize_jsons( test_list, interested_folders, [\"\"], TestPlatform.OSS, start_time ) if __name__ == \"__main__\":", "def report_coverage() -> None: start_time = time.time() (options, test_list, interested_folders) = initialization() #", "report_coverage() -> None: start_time = time.time() (options, test_list, interested_folders) = initialization() # run", "from package.oss.init import initialization from package.tool.summarize_jsons import summarize_jsons from package.util.setting import TestPlatform def" ]
[ "a given Tweet. Example: predict_user('ausen', 'elonmusk', 'Lambda School Rocks!') Returns 1 corresponding to", "'elonmusk', 'Lambda School Rocks!') Returns 1 corresponding to 1st user passed in, or", "to 1st user passed in, or 0 for second. \"\"\" user1 = User.query.filter(User.name", "np from sklearn.linear_model import LogisticRegression from .models import User from .twitter import vectorize_tweet", "labels) # We've done the model fitting, now to predict... hypo_tweet_vect = vectorize_tweet(tweet_text)", "from .twitter import vectorize_tweet def predict_user(user1_name, user2_name, tweet_text): \"\"\" Determine and return which", "np.vstack([user1_vect, user2_vect]) labels = np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))]) log_reg = LogisticRegression().fit(vects, labels) # We've done", "from .models import User from .twitter import vectorize_tweet def predict_user(user1_name, user2_name, tweet_text): \"\"\"", "log_reg = LogisticRegression().fit(vects, labels) # We've done the model fitting, now to predict...", "predict_user(user1_name, user2_name, tweet_text): \"\"\" Determine and return which user is more likely to", "user1_vect = np.array([tweet.vect for tweet in user1.tweets]) user2_vect = np.array([tweet.vect for tweet in", "for tweet in user2.tweets]) vects = np.vstack([user1_vect, user2_vect]) labels = np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))]) log_reg", "\"\"\" Determine and return which user is more likely to say a given", "Example: predict_user('ausen', 'elonmusk', 'Lambda School Rocks!') Returns 1 corresponding to 1st user passed", "user2_vect]) labels = np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))]) log_reg = LogisticRegression().fit(vects, labels) # We've done the", "def predict_user(user1_name, user2_name, tweet_text): \"\"\" Determine and return which user is more likely", "LogisticRegression from .models import User from .twitter import vectorize_tweet def predict_user(user1_name, user2_name, tweet_text):", "import LogisticRegression from .models import User from .twitter import vectorize_tweet def predict_user(user1_name, user2_name,", "User from .twitter import vectorize_tweet def predict_user(user1_name, user2_name, tweet_text): \"\"\" Determine and return", "= np.array([tweet.vect for tweet in user2.tweets]) vects = np.vstack([user1_vect, user2_vect]) labels = np.concatenate([np.ones(len(user1.tweets)),", "user2_name, tweet_text): \"\"\" Determine and return which user is more likely to say", "likely to say a given Tweet. Example: predict_user('ausen', 'elonmusk', 'Lambda School Rocks!') Returns", "== user1_name).one() user2 = User.query.filter(User.name == user2_name).one() user1_vect = np.array([tweet.vect for tweet in", "We've done the model fitting, now to predict... hypo_tweet_vect = vectorize_tweet(tweet_text) return log_reg.predict(np.array(hypo_tweet_vect).reshape(1,-1))", "np.array([tweet.vect for tweet in user2.tweets]) vects = np.vstack([user1_vect, user2_vect]) labels = np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))])", "vectorize_tweet def predict_user(user1_name, user2_name, tweet_text): \"\"\" Determine and return which user is more", "User.query.filter(User.name == user1_name).one() user2 = User.query.filter(User.name == user2_name).one() user1_vect = np.array([tweet.vect for tweet", "labels = np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))]) log_reg = LogisticRegression().fit(vects, labels) # We've done the model", "or 0 for second. \"\"\" user1 = User.query.filter(User.name == user1_name).one() user2 = User.query.filter(User.name", "user is more likely to say a given Tweet. Example: predict_user('ausen', 'elonmusk', 'Lambda", "Returns 1 corresponding to 1st user passed in, or 0 for second. \"\"\"", "more likely to say a given Tweet. Example: predict_user('ausen', 'elonmusk', 'Lambda School Rocks!')", "say a given Tweet. Example: predict_user('ausen', 'elonmusk', 'Lambda School Rocks!') Returns 1 corresponding", "is more likely to say a given Tweet. Example: predict_user('ausen', 'elonmusk', 'Lambda School", "== user2_name).one() user1_vect = np.array([tweet.vect for tweet in user1.tweets]) user2_vect = np.array([tweet.vect for", "user1.tweets]) user2_vect = np.array([tweet.vect for tweet in user2.tweets]) vects = np.vstack([user1_vect, user2_vect]) labels", "given Tweet. Example: predict_user('ausen', 'elonmusk', 'Lambda School Rocks!') Returns 1 corresponding to 1st", "user2.tweets]) vects = np.vstack([user1_vect, user2_vect]) labels = np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))]) log_reg = LogisticRegression().fit(vects, labels)", "School Rocks!') Returns 1 corresponding to 1st user passed in, or 0 for", "Determine and return which user is more likely to say a given Tweet.", "tweet in user2.tweets]) vects = np.vstack([user1_vect, user2_vect]) labels = np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))]) log_reg =", "= np.vstack([user1_vect, user2_vect]) labels = np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))]) log_reg = LogisticRegression().fit(vects, labels) # We've", "in user1.tweets]) user2_vect = np.array([tweet.vect for tweet in user2.tweets]) vects = np.vstack([user1_vect, user2_vect])", "= LogisticRegression().fit(vects, labels) # We've done the model fitting, now to predict... hypo_tweet_vect", "1 corresponding to 1st user passed in, or 0 for second. \"\"\" user1", "from sklearn.linear_model import LogisticRegression from .models import User from .twitter import vectorize_tweet def", "corresponding to 1st user passed in, or 0 for second. \"\"\" user1 =", "tweet_text): \"\"\" Determine and return which user is more likely to say a", "user1_name).one() user2 = User.query.filter(User.name == user2_name).one() user1_vect = np.array([tweet.vect for tweet in user1.tweets])", "for second. \"\"\" user1 = User.query.filter(User.name == user1_name).one() user2 = User.query.filter(User.name == user2_name).one()", "= User.query.filter(User.name == user2_name).one() user1_vect = np.array([tweet.vect for tweet in user1.tweets]) user2_vect =", "LogisticRegression().fit(vects, labels) # We've done the model fitting, now to predict... hypo_tweet_vect =", ".models import User from .twitter import vectorize_tweet def predict_user(user1_name, user2_name, tweet_text): \"\"\" Determine", "Rocks!') Returns 1 corresponding to 1st user passed in, or 0 for second.", "0 for second. \"\"\" user1 = User.query.filter(User.name == user1_name).one() user2 = User.query.filter(User.name ==", "= np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))]) log_reg = LogisticRegression().fit(vects, labels) # We've done the model fitting,", "to say a given Tweet. Example: predict_user('ausen', 'elonmusk', 'Lambda School Rocks!') Returns 1", "user2_name).one() user1_vect = np.array([tweet.vect for tweet in user1.tweets]) user2_vect = np.array([tweet.vect for tweet", "return which user is more likely to say a given Tweet. Example: predict_user('ausen',", "np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))]) log_reg = LogisticRegression().fit(vects, labels) # We've done the model fitting, now", "= User.query.filter(User.name == user1_name).one() user2 = User.query.filter(User.name == user2_name).one() user1_vect = np.array([tweet.vect for", ".twitter import vectorize_tweet def predict_user(user1_name, user2_name, tweet_text): \"\"\" Determine and return which user", "and return which user is more likely to say a given Tweet. Example:", "numpy as np from sklearn.linear_model import LogisticRegression from .models import User from .twitter", "np.array([tweet.vect for tweet in user1.tweets]) user2_vect = np.array([tweet.vect for tweet in user2.tweets]) vects", "second. \"\"\" user1 = User.query.filter(User.name == user1_name).one() user2 = User.query.filter(User.name == user2_name).one() user1_vect", "user1 = User.query.filter(User.name == user1_name).one() user2 = User.query.filter(User.name == user2_name).one() user1_vect = np.array([tweet.vect", "which user is more likely to say a given Tweet. Example: predict_user('ausen', 'elonmusk',", "vects = np.vstack([user1_vect, user2_vect]) labels = np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))]) log_reg = LogisticRegression().fit(vects, labels) #", "import User from .twitter import vectorize_tweet def predict_user(user1_name, user2_name, tweet_text): \"\"\" Determine and", "as np from sklearn.linear_model import LogisticRegression from .models import User from .twitter import", "user passed in, or 0 for second. \"\"\" user1 = User.query.filter(User.name == user1_name).one()", "'Lambda School Rocks!') Returns 1 corresponding to 1st user passed in, or 0", "1st user passed in, or 0 for second. \"\"\" user1 = User.query.filter(User.name ==", "# We've done the model fitting, now to predict... hypo_tweet_vect = vectorize_tweet(tweet_text) return", "\"\"\" user1 = User.query.filter(User.name == user1_name).one() user2 = User.query.filter(User.name == user2_name).one() user1_vect =", "in, or 0 for second. \"\"\" user1 = User.query.filter(User.name == user1_name).one() user2 =", "in user2.tweets]) vects = np.vstack([user1_vect, user2_vect]) labels = np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))]) log_reg = LogisticRegression().fit(vects,", "= np.array([tweet.vect for tweet in user1.tweets]) user2_vect = np.array([tweet.vect for tweet in user2.tweets])", "passed in, or 0 for second. \"\"\" user1 = User.query.filter(User.name == user1_name).one() user2", "import numpy as np from sklearn.linear_model import LogisticRegression from .models import User from", "Tweet. Example: predict_user('ausen', 'elonmusk', 'Lambda School Rocks!') Returns 1 corresponding to 1st user", "User.query.filter(User.name == user2_name).one() user1_vect = np.array([tweet.vect for tweet in user1.tweets]) user2_vect = np.array([tweet.vect", "np.zeros(len(user2.tweets))]) log_reg = LogisticRegression().fit(vects, labels) # We've done the model fitting, now to", "tweet in user1.tweets]) user2_vect = np.array([tweet.vect for tweet in user2.tweets]) vects = np.vstack([user1_vect,", "for tweet in user1.tweets]) user2_vect = np.array([tweet.vect for tweet in user2.tweets]) vects =", "sklearn.linear_model import LogisticRegression from .models import User from .twitter import vectorize_tweet def predict_user(user1_name,", "predict_user('ausen', 'elonmusk', 'Lambda School Rocks!') Returns 1 corresponding to 1st user passed in,", "import vectorize_tweet def predict_user(user1_name, user2_name, tweet_text): \"\"\" Determine and return which user is", "user2_vect = np.array([tweet.vect for tweet in user2.tweets]) vects = np.vstack([user1_vect, user2_vect]) labels =", "user2 = User.query.filter(User.name == user2_name).one() user1_vect = np.array([tweet.vect for tweet in user1.tweets]) user2_vect" ]
[ "States. # Additionally, the Government of the District of Columbia waives # copyright", "worldwide through the CC0 1.0 # Universal public domain dedication. __version__ = '1.0.0'", "python # -*- coding: utf-8 -*- # This file is part of groupthink.", "-*- coding: utf-8 -*- # This file is part of groupthink. # https://github.com/emanuelfeld/groupthink", "groupthink. # https://github.com/emanuelfeld/groupthink # This project is in the public domain within the", "the Government of the District of Columbia waives # copyright and related rights", "and related rights in the work worldwide through the CC0 1.0 # Universal", "This file is part of groupthink. # https://github.com/emanuelfeld/groupthink # This project is in", "of Columbia waives # copyright and related rights in the work worldwide through", "# copyright and related rights in the work worldwide through the CC0 1.0", "United States. # Additionally, the Government of the District of Columbia waives #", "is in the public domain within the United States. # Additionally, the Government", "copyright and related rights in the work worldwide through the CC0 1.0 #", "# https://github.com/emanuelfeld/groupthink # This project is in the public domain within the United", "the public domain within the United States. # Additionally, the Government of the", "Government of the District of Columbia waives # copyright and related rights in", "https://github.com/emanuelfeld/groupthink # This project is in the public domain within the United States.", "waives # copyright and related rights in the work worldwide through the CC0", "through the CC0 1.0 # Universal public domain dedication. __version__ = '1.0.0' #", "the work worldwide through the CC0 1.0 # Universal public domain dedication. __version__", "the CC0 1.0 # Universal public domain dedication. __version__ = '1.0.0' # NOQA", "domain within the United States. # Additionally, the Government of the District of", "Additionally, the Government of the District of Columbia waives # copyright and related", "utf-8 -*- # This file is part of groupthink. # https://github.com/emanuelfeld/groupthink # This", "the District of Columbia waives # copyright and related rights in the work", "work worldwide through the CC0 1.0 # Universal public domain dedication. __version__ =", "# -*- coding: utf-8 -*- # This file is part of groupthink. #", "is part of groupthink. # https://github.com/emanuelfeld/groupthink # This project is in the public", "District of Columbia waives # copyright and related rights in the work worldwide", "related rights in the work worldwide through the CC0 1.0 # Universal public", "rights in the work worldwide through the CC0 1.0 # Universal public domain", "This project is in the public domain within the United States. # Additionally,", "# This file is part of groupthink. # https://github.com/emanuelfeld/groupthink # This project is", "within the United States. # Additionally, the Government of the District of Columbia", "part of groupthink. # https://github.com/emanuelfeld/groupthink # This project is in the public domain", "in the work worldwide through the CC0 1.0 # Universal public domain dedication.", "# This project is in the public domain within the United States. #", "project is in the public domain within the United States. # Additionally, the", "of groupthink. # https://github.com/emanuelfeld/groupthink # This project is in the public domain within", "#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of", "coding: utf-8 -*- # This file is part of groupthink. # https://github.com/emanuelfeld/groupthink #", "the United States. # Additionally, the Government of the District of Columbia waives", "Columbia waives # copyright and related rights in the work worldwide through the", "in the public domain within the United States. # Additionally, the Government of", "# Additionally, the Government of the District of Columbia waives # copyright and", "public domain within the United States. # Additionally, the Government of the District", "-*- # This file is part of groupthink. # https://github.com/emanuelfeld/groupthink # This project", "file is part of groupthink. # https://github.com/emanuelfeld/groupthink # This project is in the", "of the District of Columbia waives # copyright and related rights in the" ]
[ "[l in rank[i, -top_k:] for i, l in enumerate(self.label)] return sum(hit_top_k) * 1.0", "= score.argsort() hit_top_k = [l in rank[i, -top_k:] for i, l in enumerate(self.label)]", "self.sample_name = os.listdir(self.data_path) if self.debug: self.sample_name = self.sample_name[0:2] # load label label_path =", "frame_index, :, m] = pose[1::2] data_numpy[2, frame_index, :, m] = score # count", "self.sample_name = self.sample_name[0:2] # load label label_path = self.label_path with open(label_path) as f:", "label_info = json.load(f) sample_id = [name.split('.')[0] for name in self.sample_name] self.label = np.array(", "data_numpy = tools.auto_pading(data_numpy, self.window_size) if self.random_move: data_numpy = tools.random_move(data_numpy) # sort by score", "import tools class Feeder_UCF(torch.utils.data.Dataset): \"\"\" Feeder for skeleton-based action recognition in kinetics-skeleton dataset", "self.random_shift = random_shift self.random_move = random_move self.window_size = window_size self.num_person_in = num_person_in self.num_person_out", "output sequence debug: If true, only use the first 100 samples \"\"\" def", "#person def __len__(self): return len(self.sample_name) def __iter__(self): return self def __getitem__(self, index): #", "self.window_size = window_size self.num_person_in = num_person_in self.num_person_out = num_person_out self.pose_matching = pose_matching self.ignore_empty_sample", "= json.load(f) # fill data_numpy data_numpy = np.zeros((self.C, self.T, self.V, self.num_person_in)) count =", ":, m] = pose[1::2] data_numpy[2, frame_index, :, m] = score # count +=", "100 samples \"\"\" def __init__(self, data_path, label_path, ignore_empty_sample=True, random_choose=False, random_shift=False, random_move=False, window_size=-1, pose_matching=False,", "to '.npy' data, the shape of data should be (N, C, T, V,", "data_numpy = tools.random_shift(data_numpy) if self.random_choose: data_numpy = tools.random_choose(data_numpy, self.window_size) elif self.window_size > 0:", "& check label index label = video_info['label_index'] assert (self.label[index] == label) # data", "= tools.auto_pading(data_numpy, self.window_size) if self.random_move: data_numpy = tools.random_move(data_numpy) # sort by score sort_index", "augmentation if self.random_shift: data_numpy = tools.random_shift(data_numpy) if self.random_choose: data_numpy = tools.random_choose(data_numpy, self.window_size) elif", "'r') as f: video_info = json.load(f) # fill data_numpy data_numpy = np.zeros((self.C, self.T,", "index): # output shape (C, T, V, M) # get data sample_name =", "window_size=-1, pose_matching=False, num_person_in=5, num_person_out=2, debug=False): self.debug = debug self.data_path = data_path self.label_path =", "num_person_out: The number of people the feeder in the output sequence debug: If", "open(sample_path, 'r') as f: video_info = json.load(f) # fill data_numpy data_numpy = np.zeros((self.C,", "input sequence num_person_out: The number of people the feeder in the output sequence", "sequence num_person_out: The number of people the feeder in the output sequence debug:", "= 0 # get & check label index label = video_info['label_index'] assert (self.label[index]", "data_numpy, label def top_k(self, score, top_k): assert (all(self.label >= 0)) rank = score.argsort()", "= pose[0::2] data_numpy[1, frame_index, :, m] = pose[1::2] data_numpy[2, frame_index, :, m] =", "of the input sequence random_shift: If true, randomly pad zeros at the begining", "#channel self.T = 90000 #frame self.V = 18 #joint self.M = self.num_person_out #person", "should be (N, C, T, V, M) label_path: the path to label random_choose:", "= (-data_numpy[2, :, :, :].sum(axis=1)).argsort(axis=1) for t, s in enumerate(sort_index): data_numpy[:, t, :,", "0] = 0 # get & check label index label = video_info['label_index'] assert", "self.sample_name = [ s for h, s in zip(has_skeleton, self.sample_name) if h ]", "transformation to input sequence window_size: The length of the output sequence pose_matching: If", "0 data_numpy[1][data_numpy[2] == 0] = 0 # get & check label index label", "= np.array( [label_info[id]['has_skeleton'] for id in sample_id]) # ignore the samples which does", "label = video_info['label_index'] assert (self.label[index] == label) # data augmentation if self.random_shift: data_numpy", "0 for frame_info in video_info['data']: frame_index = frame_info['frame_index'] for m, skeleton_info in enumerate(frame_info[\"skeleton\"]):", "samples which does not has skeleton sequence if self.ignore_empty_sample: self.sample_name = [ s", "frames if self.pose_matching: data_numpy = tools.openpose_match(data_numpy) return data_numpy, label def top_k(self, score, top_k):", "rank[i, -top_k:] for i, l in enumerate(self.label)] return sum(hit_top_k) * 1.0 / len(hit_top_k)", "random_choose=False, random_shift=False, random_move=False, window_size=-1, pose_matching=False, num_person_in=5, num_person_out=2, debug=False): self.debug = debug self.data_path =", "score = skeleton_info['score'] frame_index = int(frame_index) # print(frame_index) data_numpy[0, frame_index, :, m] =", "= np.zeros((self.C, self.T, self.V, self.num_person_in)) count = 0 for frame_info in video_info['data']: frame_index", "for name in self.sample_name] self.label = np.array( [label_info[id]['label_index'] for id in sample_id]) has_skeleton", "from . import tools class Feeder_UCF(torch.utils.data.Dataset): \"\"\" Feeder for skeleton-based action recognition in", "#frame self.V = 18 #joint self.M = self.num_person_out #person def __len__(self): return len(self.sample_name)", "input sequence random_shift: If true, randomly pad zeros at the begining or end", "top_k_by_category(self, score, top_k): assert (all(self.label >= 0)) return tools.top_k_by_category(self.label, score, top_k) def calculate_recall_precision(self,", "tools.top_k_by_category(self.label, score, top_k) def calculate_recall_precision(self, score): assert (all(self.label >= 0)) return tools.calculate_recall_precision(self.label, score)", "to input sequence window_size: The length of the output sequence pose_matching: If ture,", "data_numpy[0:2] - 0.5 data_numpy[0][data_numpy[2] == 0] = 0 data_numpy[1][data_numpy[2] == 0] = 0", "index label = video_info['label_index'] assert (self.label[index] == label) # data augmentation if self.random_shift:", "if self.pose_matching: data_numpy = tools.openpose_match(data_numpy) return data_numpy, label def top_k(self, score, top_k): assert", "count += 1 # print(\" \",count, \" \") # centralization data_numpy[0:2] = data_numpy[0:2]", "for i, l in enumerate(self.label)] return sum(hit_top_k) * 1.0 / len(hit_top_k) def top_k_by_category(self,", "data sample_name = self.sample_name[index] sample_path = os.path.join(self.data_path, sample_name) with open(sample_path, 'r') as f:", "ture, match the pose between two frames num_person_in: The number of people the", "of the output sequence pose_matching: If ture, match the pose between two frames", "= 0 data_numpy[1][data_numpy[2] == 0] = 0 # get & check label index", "def top_k(self, score, top_k): assert (all(self.label >= 0)) rank = score.argsort() hit_top_k =", "def load_data(self): # load file list self.sample_name = os.listdir(self.data_path) if self.debug: self.sample_name =", "import sys import numpy as np import random import pickle import json #", "for frame_info in video_info['data']: frame_index = frame_info['frame_index'] for m, skeleton_info in enumerate(frame_info[\"skeleton\"]): if", "s in enumerate(sort_index): data_numpy[:, t, :, :] = data_numpy[:, t, :, s].transpose((1, 2,", "frame_info['frame_index'] for m, skeleton_info in enumerate(frame_info[\"skeleton\"]): if m >= self.num_person_in: break pose =", "num_person_in: The number of people the feeder can observe in the input sequence", "num_person_in=5, num_person_out=2, debug=False): self.debug = debug self.data_path = data_path self.label_path = label_path self.random_choose", "2, 0)) data_numpy = data_numpy[:, :, :, 0:self.num_person_out] # match poses between 2", "= json.load(f) sample_id = [name.split('.')[0] for name in self.sample_name] self.label = np.array( [label_info[id]['label_index']", "the input sequence random_shift: If true, randomly pad zeros at the begining or", "= ignore_empty_sample self.load_data() def load_data(self): # load file list self.sample_name = os.listdir(self.data_path) if", "h ] self.label = self.label[has_skeleton] # output data shape (N, C, T, V,", "data_numpy[1, frame_index, :, m] = pose[1::2] data_numpy[2, frame_index, :, m] = score #", "data augmentation if self.random_shift: data_numpy = tools.random_shift(data_numpy) if self.random_choose: data_numpy = tools.random_choose(data_numpy, self.window_size)", "skeleton sequence if self.ignore_empty_sample: self.sample_name = [ s for h, s in zip(has_skeleton,", "ignore the samples which does not has skeleton sequence if self.ignore_empty_sample: self.sample_name =", "for m, skeleton_info in enumerate(frame_info[\"skeleton\"]): if m >= self.num_person_in: break pose = skeleton_info['pose']", "print(frame_index) data_numpy[0, frame_index, :, m] = pose[0::2] data_numpy[1, frame_index, :, m] = pose[1::2]", "0: data_numpy = tools.auto_pading(data_numpy, self.window_size) if self.random_move: data_numpy = tools.random_move(data_numpy) # sort by", "= data_numpy[:, t, :, s].transpose((1, 2, 0)) data_numpy = data_numpy[:, :, :, 0:self.num_person_out]", "self.label_path with open(label_path) as f: label_info = json.load(f) sample_id = [name.split('.')[0] for name", "in enumerate(self.label)] return sum(hit_top_k) * 1.0 / len(hit_top_k) def top_k_by_category(self, score, top_k): assert", "label_path, ignore_empty_sample=True, random_choose=False, random_shift=False, random_move=False, window_size=-1, pose_matching=False, num_person_in=5, num_person_out=2, debug=False): self.debug = debug", "shape (C, T, V, M) # get data sample_name = self.sample_name[index] sample_path =", "skeleton-based action recognition in kinetics-skeleton dataset Arguments: data_path: the path to '.npy' data,", "observe in the input sequence num_person_out: The number of people the feeder in", "in the output sequence debug: If true, only use the first 100 samples", "random_move=False, window_size=-1, pose_matching=False, num_person_in=5, num_person_out=2, debug=False): self.debug = debug self.data_path = data_path self.label_path", "self.debug = debug self.data_path = data_path self.label_path = label_path self.random_choose = random_choose self.random_shift", "# centralization data_numpy[0:2] = data_numpy[0:2] - 0.5 data_numpy[0][data_numpy[2] == 0] = 0 data_numpy[1][data_numpy[2]", "self.num_person_in = num_person_in self.num_person_out = num_person_out self.pose_matching = pose_matching self.ignore_empty_sample = ignore_empty_sample self.load_data()", "random_move self.window_size = window_size self.num_person_in = num_person_in self.num_person_out = num_person_out self.pose_matching = pose_matching", "sequence random_shift: If true, randomly pad zeros at the begining or end of", "def top_k_by_category(self, score, top_k): assert (all(self.label >= 0)) return tools.top_k_by_category(self.label, score, top_k) def", "import datasets, transforms # operation from . import tools class Feeder_UCF(torch.utils.data.Dataset): \"\"\" Feeder", "= data_path self.label_path = label_path self.random_choose = random_choose self.random_shift = random_shift self.random_move =", "[label_info[id]['label_index'] for id in sample_id]) has_skeleton = np.array( [label_info[id]['has_skeleton'] for id in sample_id])", "self.sample_name) if h ] self.label = self.label[has_skeleton] # output data shape (N, C,", "frame_index = int(frame_index) # print(frame_index) data_numpy[0, frame_index, :, m] = pose[0::2] data_numpy[1, frame_index,", "self.random_move: data_numpy = tools.random_move(data_numpy) # sort by score sort_index = (-data_numpy[2, :, :,", "top_k(self, score, top_k): assert (all(self.label >= 0)) rank = score.argsort() hit_top_k = [l", "random_move: If true, perform randomly but continuously changed transformation to input sequence window_size:", "num_person_in self.num_person_out = num_person_out self.pose_matching = pose_matching self.ignore_empty_sample = ignore_empty_sample self.load_data() def load_data(self):", "random_shift: If true, randomly pad zeros at the begining or end of sequence", ">= self.num_person_in: break pose = skeleton_info['pose'] score = skeleton_info['score'] frame_index = int(frame_index) #", "feeder in the output sequence debug: If true, only use the first 100", "data_numpy = data_numpy[:, :, :, 0:self.num_person_out] # match poses between 2 frames if", "label_path: the path to label random_choose: If true, randomly choose a portion of", "T, V, M) self.N = len(self.sample_name) #sample self.C = 3 #channel self.T =", "if m >= self.num_person_in: break pose = skeleton_info['pose'] score = skeleton_info['score'] frame_index =", "only use the first 100 samples \"\"\" def __init__(self, data_path, label_path, ignore_empty_sample=True, random_choose=False,", "self def __getitem__(self, index): # output shape (C, T, V, M) # get", "= random_shift self.random_move = random_move self.window_size = window_size self.num_person_in = num_person_in self.num_person_out =", "datasets, transforms # operation from . import tools class Feeder_UCF(torch.utils.data.Dataset): \"\"\" Feeder for", "get & check label index label = video_info['label_index'] assert (self.label[index] == label) #", "count = 0 for frame_info in video_info['data']: frame_index = frame_info['frame_index'] for m, skeleton_info", "assert (all(self.label >= 0)) return tools.top_k_by_category(self.label, score, top_k) def calculate_recall_precision(self, score): assert (all(self.label", "shape of data should be (N, C, T, V, M) label_path: the path", "in kinetics-skeleton dataset Arguments: data_path: the path to '.npy' data, the shape of", "# print(\" \",count, \" \") # centralization data_numpy[0:2] = data_numpy[0:2] - 0.5 data_numpy[0][data_numpy[2]", "tools.random_choose(data_numpy, self.window_size) elif self.window_size > 0: data_numpy = tools.auto_pading(data_numpy, self.window_size) if self.random_move: data_numpy", "self.label[has_skeleton] # output data shape (N, C, T, V, M) self.N = len(self.sample_name)", "label random_choose: If true, randomly choose a portion of the input sequence random_shift:", "video_info['data']: frame_index = frame_info['frame_index'] for m, skeleton_info in enumerate(frame_info[\"skeleton\"]): if m >= self.num_person_in:", "continuously changed transformation to input sequence window_size: The length of the output sequence", "sample_id]) # ignore the samples which does not has skeleton sequence if self.ignore_empty_sample:", "match the pose between two frames num_person_in: The number of people the feeder", "= tools.openpose_match(data_numpy) return data_numpy, label def top_k(self, score, top_k): assert (all(self.label >= 0))", "# data augmentation if self.random_shift: data_numpy = tools.random_shift(data_numpy) if self.random_choose: data_numpy = tools.random_choose(data_numpy,", "== label) # data augmentation if self.random_shift: data_numpy = tools.random_shift(data_numpy) if self.random_choose: data_numpy", "window_size self.num_person_in = num_person_in self.num_person_out = num_person_out self.pose_matching = pose_matching self.ignore_empty_sample = ignore_empty_sample", "self.ignore_empty_sample: self.sample_name = [ s for h, s in zip(has_skeleton, self.sample_name) if h", "label_path = self.label_path with open(label_path) as f: label_info = json.load(f) sample_id = [name.split('.')[0]", "load file list self.sample_name = os.listdir(self.data_path) if self.debug: self.sample_name = self.sample_name[0:2] # load", "frames num_person_in: The number of people the feeder can observe in the input", "= num_person_in self.num_person_out = num_person_out self.pose_matching = pose_matching self.ignore_empty_sample = ignore_empty_sample self.load_data() def", "= len(self.sample_name) #sample self.C = 3 #channel self.T = 90000 #frame self.V =", "# fill data_numpy data_numpy = np.zeros((self.C, self.T, self.V, self.num_person_in)) count = 0 for", "= [name.split('.')[0] for name in self.sample_name] self.label = np.array( [label_info[id]['label_index'] for id in", "nn from torchvision import datasets, transforms # operation from . import tools class", "in sample_id]) # ignore the samples which does not has skeleton sequence if", "__iter__(self): return self def __getitem__(self, index): # output shape (C, T, V, M)", "(-data_numpy[2, :, :, :].sum(axis=1)).argsort(axis=1) for t, s in enumerate(sort_index): data_numpy[:, t, :, :]", "# get & check label index label = video_info['label_index'] assert (self.label[index] == label)", "as nn from torchvision import datasets, transforms # operation from . import tools", "pose[0::2] data_numpy[1, frame_index, :, m] = pose[1::2] data_numpy[2, frame_index, :, m] = score", "name in self.sample_name] self.label = np.array( [label_info[id]['label_index'] for id in sample_id]) has_skeleton =", "sample_id = [name.split('.')[0] for name in self.sample_name] self.label = np.array( [label_info[id]['label_index'] for id", "number of people the feeder can observe in the input sequence num_person_out: The", "self.M = self.num_person_out #person def __len__(self): return len(self.sample_name) def __iter__(self): return self def", "90000 #frame self.V = 18 #joint self.M = self.num_person_out #person def __len__(self): return", "h, s in zip(has_skeleton, self.sample_name) if h ] self.label = self.label[has_skeleton] # output", "V, M) self.N = len(self.sample_name) #sample self.C = 3 #channel self.T = 90000", "== 0] = 0 # get & check label index label = video_info['label_index']", "self.label = np.array( [label_info[id]['label_index'] for id in sample_id]) has_skeleton = np.array( [label_info[id]['has_skeleton'] for", "(all(self.label >= 0)) return tools.top_k_by_category(self.label, score, top_k) def calculate_recall_precision(self, score): assert (all(self.label >=", "check label index label = video_info['label_index'] assert (self.label[index] == label) # data augmentation", "self.label = self.label[has_skeleton] # output data shape (N, C, T, V, M) self.N", "data_numpy = tools.random_choose(data_numpy, self.window_size) elif self.window_size > 0: data_numpy = tools.auto_pading(data_numpy, self.window_size) if", "# load label label_path = self.label_path with open(label_path) as f: label_info = json.load(f)", "label def top_k(self, score, top_k): assert (all(self.label >= 0)) rank = score.argsort() hit_top_k", "self.random_choose = random_choose self.random_shift = random_shift self.random_move = random_move self.window_size = window_size self.num_person_in", "label_path self.random_choose = random_choose self.random_shift = random_shift self.random_move = random_move self.window_size = window_size", "but continuously changed transformation to input sequence window_size: The length of the output", "+= 1 # print(\" \",count, \" \") # centralization data_numpy[0:2] = data_numpy[0:2] -", "end of sequence random_move: If true, perform randomly but continuously changed transformation to", "# sort by score sort_index = (-data_numpy[2, :, :, :].sum(axis=1)).argsort(axis=1) for t, s", "pose_matching: If ture, match the pose between two frames num_person_in: The number of", "import torch.nn as nn from torchvision import datasets, transforms # operation from .", "if self.random_shift: data_numpy = tools.random_shift(data_numpy) if self.random_choose: data_numpy = tools.random_choose(data_numpy, self.window_size) elif self.window_size", "output sequence pose_matching: If ture, match the pose between two frames num_person_in: The", "self.V = 18 #joint self.M = self.num_person_out #person def __len__(self): return len(self.sample_name) def", "data_numpy[0:2] = data_numpy[0:2] - 0.5 data_numpy[0][data_numpy[2] == 0] = 0 data_numpy[1][data_numpy[2] == 0]", "self.random_choose: data_numpy = tools.random_choose(data_numpy, self.window_size) elif self.window_size > 0: data_numpy = tools.auto_pading(data_numpy, self.window_size)", "label index label = video_info['label_index'] assert (self.label[index] == label) # data augmentation if", "path to '.npy' data, the shape of data should be (N, C, T,", "data_numpy[:, :, :, 0:self.num_person_out] # match poses between 2 frames if self.pose_matching: data_numpy", "skeleton_info['pose'] score = skeleton_info['score'] frame_index = int(frame_index) # print(frame_index) data_numpy[0, frame_index, :, m]", "the output sequence debug: If true, only use the first 100 samples \"\"\"", "self.pose_matching = pose_matching self.ignore_empty_sample = ignore_empty_sample self.load_data() def load_data(self): # load file list", "has skeleton sequence if self.ignore_empty_sample: self.sample_name = [ s for h, s in", "frame_index = frame_info['frame_index'] for m, skeleton_info in enumerate(frame_info[\"skeleton\"]): if m >= self.num_person_in: break", "If ture, match the pose between two frames num_person_in: The number of people", "torch.nn as nn from torchvision import datasets, transforms # operation from . import", "\"\"\" Feeder for skeleton-based action recognition in kinetics-skeleton dataset Arguments: data_path: the path", "can observe in the input sequence num_person_out: The number of people the feeder", "pose[1::2] data_numpy[2, frame_index, :, m] = score # count += 1 # print(\"", "data_numpy = tools.openpose_match(data_numpy) return data_numpy, label def top_k(self, score, top_k): assert (all(self.label >=", "= skeleton_info['pose'] score = skeleton_info['score'] frame_index = int(frame_index) # print(frame_index) data_numpy[0, frame_index, :,", "video_info['label_index'] assert (self.label[index] == label) # data augmentation if self.random_shift: data_numpy = tools.random_shift(data_numpy)", "return sum(hit_top_k) * 1.0 / len(hit_top_k) def top_k_by_category(self, score, top_k): assert (all(self.label >=", "18 #joint self.M = self.num_person_out #person def __len__(self): return len(self.sample_name) def __iter__(self): return", "ignore_empty_sample self.load_data() def load_data(self): # load file list self.sample_name = os.listdir(self.data_path) if self.debug:", "self.window_size > 0: data_numpy = tools.auto_pading(data_numpy, self.window_size) if self.random_move: data_numpy = tools.random_move(data_numpy) #", "import numpy as np import random import pickle import json # torch import", "for skeleton-based action recognition in kinetics-skeleton dataset Arguments: data_path: the path to '.npy'", "list self.sample_name = os.listdir(self.data_path) if self.debug: self.sample_name = self.sample_name[0:2] # load label label_path", "sample_path = os.path.join(self.data_path, sample_name) with open(sample_path, 'r') as f: video_info = json.load(f) #", "rank = score.argsort() hit_top_k = [l in rank[i, -top_k:] for i, l in", "which does not has skeleton sequence if self.ignore_empty_sample: self.sample_name = [ s for", "[label_info[id]['has_skeleton'] for id in sample_id]) # ignore the samples which does not has", "= self.label_path with open(label_path) as f: label_info = json.load(f) sample_id = [name.split('.')[0] for", "f: video_info = json.load(f) # fill data_numpy data_numpy = np.zeros((self.C, self.T, self.V, self.num_person_in))", "score.argsort() hit_top_k = [l in rank[i, -top_k:] for i, l in enumerate(self.label)] return", "action recognition in kinetics-skeleton dataset Arguments: data_path: the path to '.npy' data, the", "data_path, label_path, ignore_empty_sample=True, random_choose=False, random_shift=False, random_move=False, window_size=-1, pose_matching=False, num_person_in=5, num_person_out=2, debug=False): self.debug =", "self.random_move = random_move self.window_size = window_size self.num_person_in = num_person_in self.num_person_out = num_person_out self.pose_matching", "== 0] = 0 data_numpy[1][data_numpy[2] == 0] = 0 # get & check", "> 0: data_numpy = tools.auto_pading(data_numpy, self.window_size) if self.random_move: data_numpy = tools.random_move(data_numpy) # sort", "#sample self.C = 3 #channel self.T = 90000 #frame self.V = 18 #joint", "m, skeleton_info in enumerate(frame_info[\"skeleton\"]): if m >= self.num_person_in: break pose = skeleton_info['pose'] score", "sum(hit_top_k) * 1.0 / len(hit_top_k) def top_k_by_category(self, score, top_k): assert (all(self.label >= 0))", "C, T, V, M) self.N = len(self.sample_name) #sample self.C = 3 #channel self.T", "the pose between two frames num_person_in: The number of people the feeder can", "frame_index, :, m] = score # count += 1 # print(\" \",count, \"", "json # torch import torch import torch.nn as nn from torchvision import datasets,", "the begining or end of sequence random_move: If true, perform randomly but continuously", "in sample_id]) has_skeleton = np.array( [label_info[id]['has_skeleton'] for id in sample_id]) # ignore the", "self.sample_name[index] sample_path = os.path.join(self.data_path, sample_name) with open(sample_path, 'r') as f: video_info = json.load(f)", "frame_info in video_info['data']: frame_index = frame_info['frame_index'] for m, skeleton_info in enumerate(frame_info[\"skeleton\"]): if m", "i, l in enumerate(self.label)] return sum(hit_top_k) * 1.0 / len(hit_top_k) def top_k_by_category(self, score,", "the feeder can observe in the input sequence num_person_out: The number of people", "score sort_index = (-data_numpy[2, :, :, :].sum(axis=1)).argsort(axis=1) for t, s in enumerate(sort_index): data_numpy[:,", "self.sample_name[0:2] # load label label_path = self.label_path with open(label_path) as f: label_info =", "zip(has_skeleton, self.sample_name) if h ] self.label = self.label[has_skeleton] # output data shape (N,", "does not has skeleton sequence if self.ignore_empty_sample: self.sample_name = [ s for h,", ":, :, 0:self.num_person_out] # match poses between 2 frames if self.pose_matching: data_numpy =", "(self.label[index] == label) # data augmentation if self.random_shift: data_numpy = tools.random_shift(data_numpy) if self.random_choose:", "] self.label = self.label[has_skeleton] # output data shape (N, C, T, V, M)", "data_path self.label_path = label_path self.random_choose = random_choose self.random_shift = random_shift self.random_move = random_move", "s in zip(has_skeleton, self.sample_name) if h ] self.label = self.label[has_skeleton] # output data", ":, :].sum(axis=1)).argsort(axis=1) for t, s in enumerate(sort_index): data_numpy[:, t, :, :] = data_numpy[:,", "= self.sample_name[0:2] # load label label_path = self.label_path with open(label_path) as f: label_info", "be (N, C, T, V, M) label_path: the path to label random_choose: If", "= int(frame_index) # print(frame_index) data_numpy[0, frame_index, :, m] = pose[0::2] data_numpy[1, frame_index, :,", "If true, perform randomly but continuously changed transformation to input sequence window_size: The", "pad zeros at the begining or end of sequence random_move: If true, perform", "randomly choose a portion of the input sequence random_shift: If true, randomly pad", "= self.label[has_skeleton] # output data shape (N, C, T, V, M) self.N =", "# match poses between 2 frames if self.pose_matching: data_numpy = tools.openpose_match(data_numpy) return data_numpy,", "= num_person_out self.pose_matching = pose_matching self.ignore_empty_sample = ignore_empty_sample self.load_data() def load_data(self): # load", "= self.num_person_out #person def __len__(self): return len(self.sample_name) def __iter__(self): return self def __getitem__(self,", "between 2 frames if self.pose_matching: data_numpy = tools.openpose_match(data_numpy) return data_numpy, label def top_k(self,", "1 # print(\" \",count, \" \") # centralization data_numpy[0:2] = data_numpy[0:2] - 0.5", "0] = 0 data_numpy[1][data_numpy[2] == 0] = 0 # get & check label", "poses between 2 frames if self.pose_matching: data_numpy = tools.openpose_match(data_numpy) return data_numpy, label def", "def __len__(self): return len(self.sample_name) def __iter__(self): return self def __getitem__(self, index): # output", ":, :, :].sum(axis=1)).argsort(axis=1) for t, s in enumerate(sort_index): data_numpy[:, t, :, :] =", ":, m] = score # count += 1 # print(\" \",count, \" \")", "= label_path self.random_choose = random_choose self.random_shift = random_shift self.random_move = random_move self.window_size =", "sample_name) with open(sample_path, 'r') as f: video_info = json.load(f) # fill data_numpy data_numpy", "in zip(has_skeleton, self.sample_name) if h ] self.label = self.label[has_skeleton] # output data shape", "for id in sample_id]) has_skeleton = np.array( [label_info[id]['has_skeleton'] for id in sample_id]) #", "# print(frame_index) data_numpy[0, frame_index, :, m] = pose[0::2] data_numpy[1, frame_index, :, m] =", "choose a portion of the input sequence random_shift: If true, randomly pad zeros", "- 0.5 data_numpy[0][data_numpy[2] == 0] = 0 data_numpy[1][data_numpy[2] == 0] = 0 #", "break pose = skeleton_info['pose'] score = skeleton_info['score'] frame_index = int(frame_index) # print(frame_index) data_numpy[0,", "tools.auto_pading(data_numpy, self.window_size) if self.random_move: data_numpy = tools.random_move(data_numpy) # sort by score sort_index =", "skeleton_info in enumerate(frame_info[\"skeleton\"]): if m >= self.num_person_in: break pose = skeleton_info['pose'] score =", "random_shift=False, random_move=False, window_size=-1, pose_matching=False, num_person_in=5, num_person_out=2, debug=False): self.debug = debug self.data_path = data_path", "shape (N, C, T, V, M) self.N = len(self.sample_name) #sample self.C = 3", ":, :] = data_numpy[:, t, :, s].transpose((1, 2, 0)) data_numpy = data_numpy[:, :,", "1.0 / len(hit_top_k) def top_k_by_category(self, score, top_k): assert (all(self.label >= 0)) return tools.top_k_by_category(self.label,", "sort by score sort_index = (-data_numpy[2, :, :, :].sum(axis=1)).argsort(axis=1) for t, s in", "to label random_choose: If true, randomly choose a portion of the input sequence", "= skeleton_info['score'] frame_index = int(frame_index) # print(frame_index) data_numpy[0, frame_index, :, m] = pose[0::2]", "frame_index, :, m] = pose[0::2] data_numpy[1, frame_index, :, m] = pose[1::2] data_numpy[2, frame_index,", "assert (all(self.label >= 0)) rank = score.argsort() hit_top_k = [l in rank[i, -top_k:]", "of people the feeder in the output sequence debug: If true, only use", "file list self.sample_name = os.listdir(self.data_path) if self.debug: self.sample_name = self.sample_name[0:2] # load label", "sequence if self.ignore_empty_sample: self.sample_name = [ s for h, s in zip(has_skeleton, self.sample_name)", "self.num_person_out = num_person_out self.pose_matching = pose_matching self.ignore_empty_sample = ignore_empty_sample self.load_data() def load_data(self): #", "The length of the output sequence pose_matching: If ture, match the pose between", "import random import pickle import json # torch import torch import torch.nn as", "the first 100 samples \"\"\" def __init__(self, data_path, label_path, ignore_empty_sample=True, random_choose=False, random_shift=False, random_move=False,", "between two frames num_person_in: The number of people the feeder can observe in", "(all(self.label >= 0)) rank = score.argsort() hit_top_k = [l in rank[i, -top_k:] for", "sys import os import sys import numpy as np import random import pickle", "return tools.top_k_by_category(self.label, score, top_k) def calculate_recall_precision(self, score): assert (all(self.label >= 0)) return tools.calculate_recall_precision(self.label,", "\",count, \" \") # centralization data_numpy[0:2] = data_numpy[0:2] - 0.5 data_numpy[0][data_numpy[2] == 0]", "the feeder in the output sequence debug: If true, only use the first", "sequence debug: If true, only use the first 100 samples \"\"\" def __init__(self,", "the path to '.npy' data, the shape of data should be (N, C,", "/ len(hit_top_k) def top_k_by_category(self, score, top_k): assert (all(self.label >= 0)) return tools.top_k_by_category(self.label, score,", "self.data_path = data_path self.label_path = label_path self.random_choose = random_choose self.random_shift = random_shift self.random_move", "__init__(self, data_path, label_path, ignore_empty_sample=True, random_choose=False, random_shift=False, random_move=False, window_size=-1, pose_matching=False, num_person_in=5, num_person_out=2, debug=False): self.debug", "\") # centralization data_numpy[0:2] = data_numpy[0:2] - 0.5 data_numpy[0][data_numpy[2] == 0] = 0", "tools.random_move(data_numpy) # sort by score sort_index = (-data_numpy[2, :, :, :].sum(axis=1)).argsort(axis=1) for t,", "output shape (C, T, V, M) # get data sample_name = self.sample_name[index] sample_path", "len(self.sample_name) def __iter__(self): return self def __getitem__(self, index): # output shape (C, T,", "[name.split('.')[0] for name in self.sample_name] self.label = np.array( [label_info[id]['label_index'] for id in sample_id])", "length of the output sequence pose_matching: If ture, match the pose between two", "in the input sequence num_person_out: The number of people the feeder in the", "# operation from . import tools class Feeder_UCF(torch.utils.data.Dataset): \"\"\" Feeder for skeleton-based action", "The number of people the feeder can observe in the input sequence num_person_out:", ":] = data_numpy[:, t, :, s].transpose((1, 2, 0)) data_numpy = data_numpy[:, :, :,", "'.npy' data, the shape of data should be (N, C, T, V, M)", ":, 0:self.num_person_out] # match poses between 2 frames if self.pose_matching: data_numpy = tools.openpose_match(data_numpy)", "os.listdir(self.data_path) if self.debug: self.sample_name = self.sample_name[0:2] # load label label_path = self.label_path with", "the shape of data should be (N, C, T, V, M) label_path: the", "(N, C, T, V, M) label_path: the path to label random_choose: If true,", "enumerate(sort_index): data_numpy[:, t, :, :] = data_numpy[:, t, :, s].transpose((1, 2, 0)) data_numpy", "people the feeder in the output sequence debug: If true, only use the", "get data sample_name = self.sample_name[index] sample_path = os.path.join(self.data_path, sample_name) with open(sample_path, 'r') as", "if self.random_move: data_numpy = tools.random_move(data_numpy) # sort by score sort_index = (-data_numpy[2, :,", "(N, C, T, V, M) self.N = len(self.sample_name) #sample self.C = 3 #channel", "# count += 1 # print(\" \",count, \" \") # centralization data_numpy[0:2] =", "debug=False): self.debug = debug self.data_path = data_path self.label_path = label_path self.random_choose = random_choose", "in self.sample_name] self.label = np.array( [label_info[id]['label_index'] for id in sample_id]) has_skeleton = np.array(", "= self.sample_name[index] sample_path = os.path.join(self.data_path, sample_name) with open(sample_path, 'r') as f: video_info =", "or end of sequence random_move: If true, perform randomly but continuously changed transformation", "data_path: the path to '.npy' data, the shape of data should be (N,", "with open(sample_path, 'r') as f: video_info = json.load(f) # fill data_numpy data_numpy =", "json.load(f) sample_id = [name.split('.')[0] for name in self.sample_name] self.label = np.array( [label_info[id]['label_index'] for", ">= 0)) rank = score.argsort() hit_top_k = [l in rank[i, -top_k:] for i,", "def __iter__(self): return self def __getitem__(self, index): # output shape (C, T, V,", "skeleton_info['score'] frame_index = int(frame_index) # print(frame_index) data_numpy[0, frame_index, :, m] = pose[0::2] data_numpy[1,", "in video_info['data']: frame_index = frame_info['frame_index'] for m, skeleton_info in enumerate(frame_info[\"skeleton\"]): if m >=", "data shape (N, C, T, V, M) self.N = len(self.sample_name) #sample self.C =", "number of people the feeder in the output sequence debug: If true, only", "= os.path.join(self.data_path, sample_name) with open(sample_path, 'r') as f: video_info = json.load(f) # fill", "fill data_numpy data_numpy = np.zeros((self.C, self.T, self.V, self.num_person_in)) count = 0 for frame_info", "t, :, s].transpose((1, 2, 0)) data_numpy = data_numpy[:, :, :, 0:self.num_person_out] # match", "= debug self.data_path = data_path self.label_path = label_path self.random_choose = random_choose self.random_shift =", "self.num_person_in: break pose = skeleton_info['pose'] score = skeleton_info['score'] frame_index = int(frame_index) # print(frame_index)", "[ s for h, s in zip(has_skeleton, self.sample_name) if h ] self.label =", "__len__(self): return len(self.sample_name) def __iter__(self): return self def __getitem__(self, index): # output shape", "if h ] self.label = self.label[has_skeleton] # output data shape (N, C, T,", "import os import sys import numpy as np import random import pickle import", "input sequence window_size: The length of the output sequence pose_matching: If ture, match", "score # count += 1 # print(\" \",count, \" \") # centralization data_numpy[0:2]", "= tools.random_move(data_numpy) # sort by score sort_index = (-data_numpy[2, :, :, :].sum(axis=1)).argsort(axis=1) for", "m] = score # count += 1 # print(\" \",count, \" \") #", "score, top_k): assert (all(self.label >= 0)) return tools.top_k_by_category(self.label, score, top_k) def calculate_recall_precision(self, score):", "sequence window_size: The length of the output sequence pose_matching: If ture, match the", "data_numpy data_numpy = np.zeros((self.C, self.T, self.V, self.num_person_in)) count = 0 for frame_info in", "tools class Feeder_UCF(torch.utils.data.Dataset): \"\"\" Feeder for skeleton-based action recognition in kinetics-skeleton dataset Arguments:", "a portion of the input sequence random_shift: If true, randomly pad zeros at", "enumerate(frame_info[\"skeleton\"]): if m >= self.num_person_in: break pose = skeleton_info['pose'] score = skeleton_info['score'] frame_index", "the input sequence num_person_out: The number of people the feeder in the output", "C, T, V, M) label_path: the path to label random_choose: If true, randomly", "label) # data augmentation if self.random_shift: data_numpy = tools.random_shift(data_numpy) if self.random_choose: data_numpy =", "changed transformation to input sequence window_size: The length of the output sequence pose_matching:", "as np import random import pickle import json # torch import torch import", "top_k): assert (all(self.label >= 0)) return tools.top_k_by_category(self.label, score, top_k) def calculate_recall_precision(self, score): assert", "# output data shape (N, C, T, V, M) self.N = len(self.sample_name) #sample", "score, top_k): assert (all(self.label >= 0)) rank = score.argsort() hit_top_k = [l in", "elif self.window_size > 0: data_numpy = tools.auto_pading(data_numpy, self.window_size) if self.random_move: data_numpy = tools.random_move(data_numpy)", "dataset Arguments: data_path: the path to '.npy' data, the shape of data should", "= np.array( [label_info[id]['label_index'] for id in sample_id]) has_skeleton = np.array( [label_info[id]['has_skeleton'] for id", "= random_move self.window_size = window_size self.num_person_in = num_person_in self.num_person_out = num_person_out self.pose_matching =", "m] = pose[0::2] data_numpy[1, frame_index, :, m] = pose[1::2] data_numpy[2, frame_index, :, m]", "not has skeleton sequence if self.ignore_empty_sample: self.sample_name = [ s for h, s", "self.window_size) elif self.window_size > 0: data_numpy = tools.auto_pading(data_numpy, self.window_size) if self.random_move: data_numpy =", "(C, T, V, M) # get data sample_name = self.sample_name[index] sample_path = os.path.join(self.data_path,", "torchvision import datasets, transforms # operation from . import tools class Feeder_UCF(torch.utils.data.Dataset): \"\"\"", "= pose[1::2] data_numpy[2, frame_index, :, m] = score # count += 1 #", "Arguments: data_path: the path to '.npy' data, the shape of data should be", "= 18 #joint self.M = self.num_person_out #person def __len__(self): return len(self.sample_name) def __iter__(self):", "transforms # operation from . import tools class Feeder_UCF(torch.utils.data.Dataset): \"\"\" Feeder for skeleton-based", "self.T, self.V, self.num_person_in)) count = 0 for frame_info in video_info['data']: frame_index = frame_info['frame_index']", "video_info = json.load(f) # fill data_numpy data_numpy = np.zeros((self.C, self.T, self.V, self.num_person_in)) count", "recognition in kinetics-skeleton dataset Arguments: data_path: the path to '.npy' data, the shape", "The number of people the feeder in the output sequence debug: If true,", "2 frames if self.pose_matching: data_numpy = tools.openpose_match(data_numpy) return data_numpy, label def top_k(self, score,", "t, :, :] = data_numpy[:, t, :, s].transpose((1, 2, 0)) data_numpy = data_numpy[:,", "for t, s in enumerate(sort_index): data_numpy[:, t, :, :] = data_numpy[:, t, :,", "T, V, M) label_path: the path to label random_choose: If true, randomly choose", "len(self.sample_name) #sample self.C = 3 #channel self.T = 90000 #frame self.V = 18", "0:self.num_person_out] # match poses between 2 frames if self.pose_matching: data_numpy = tools.openpose_match(data_numpy) return", "def __init__(self, data_path, label_path, ignore_empty_sample=True, random_choose=False, random_shift=False, random_move=False, window_size=-1, pose_matching=False, num_person_in=5, num_person_out=2, debug=False):", "pose_matching self.ignore_empty_sample = ignore_empty_sample self.load_data() def load_data(self): # load file list self.sample_name =", ":].sum(axis=1)).argsort(axis=1) for t, s in enumerate(sort_index): data_numpy[:, t, :, :] = data_numpy[:, t,", "by score sort_index = (-data_numpy[2, :, :, :].sum(axis=1)).argsort(axis=1) for t, s in enumerate(sort_index):", "= video_info['label_index'] assert (self.label[index] == label) # data augmentation if self.random_shift: data_numpy =", "data should be (N, C, T, V, M) label_path: the path to label", "for h, s in zip(has_skeleton, self.sample_name) if h ] self.label = self.label[has_skeleton] #", "ignore_empty_sample=True, random_choose=False, random_shift=False, random_move=False, window_size=-1, pose_matching=False, num_person_in=5, num_person_out=2, debug=False): self.debug = debug self.data_path", "random_choose self.random_shift = random_shift self.random_move = random_move self.window_size = window_size self.num_person_in = num_person_in", "path to label random_choose: If true, randomly choose a portion of the input", "self.pose_matching: data_numpy = tools.openpose_match(data_numpy) return data_numpy, label def top_k(self, score, top_k): assert (all(self.label", "of people the feeder can observe in the input sequence num_person_out: The number", "the path to label random_choose: If true, randomly choose a portion of the", "V, M) label_path: the path to label random_choose: If true, randomly choose a", "random_choose: If true, randomly choose a portion of the input sequence random_shift: If", "= tools.random_choose(data_numpy, self.window_size) elif self.window_size > 0: data_numpy = tools.auto_pading(data_numpy, self.window_size) if self.random_move:", "os import sys import numpy as np import random import pickle import json", "randomly pad zeros at the begining or end of sequence random_move: If true,", "use the first 100 samples \"\"\" def __init__(self, data_path, label_path, ignore_empty_sample=True, random_choose=False, random_shift=False,", "self.label_path = label_path self.random_choose = random_choose self.random_shift = random_shift self.random_move = random_move self.window_size", "two frames num_person_in: The number of people the feeder can observe in the", "random_shift self.random_move = random_move self.window_size = window_size self.num_person_in = num_person_in self.num_person_out = num_person_out", "sample_name = self.sample_name[index] sample_path = os.path.join(self.data_path, sample_name) with open(sample_path, 'r') as f: video_info", "portion of the input sequence random_shift: If true, randomly pad zeros at the", "operation from . import tools class Feeder_UCF(torch.utils.data.Dataset): \"\"\" Feeder for skeleton-based action recognition", "len(hit_top_k) def top_k_by_category(self, score, top_k): assert (all(self.label >= 0)) return tools.top_k_by_category(self.label, score, top_k)", "label label_path = self.label_path with open(label_path) as f: label_info = json.load(f) sample_id =", "# load file list self.sample_name = os.listdir(self.data_path) if self.debug: self.sample_name = self.sample_name[0:2] #", "json.load(f) # fill data_numpy data_numpy = np.zeros((self.C, self.T, self.V, self.num_person_in)) count = 0", "# output shape (C, T, V, M) # get data sample_name = self.sample_name[index]", "data_numpy[:, t, :, s].transpose((1, 2, 0)) data_numpy = data_numpy[:, :, :, 0:self.num_person_out] #", "from torchvision import datasets, transforms # operation from . import tools class Feeder_UCF(torch.utils.data.Dataset):", "if self.debug: self.sample_name = self.sample_name[0:2] # load label label_path = self.label_path with open(label_path)", "pose = skeleton_info['pose'] score = skeleton_info['score'] frame_index = int(frame_index) # print(frame_index) data_numpy[0, frame_index,", "begining or end of sequence random_move: If true, perform randomly but continuously changed", "hit_top_k = [l in rank[i, -top_k:] for i, l in enumerate(self.label)] return sum(hit_top_k)", "zeros at the begining or end of sequence random_move: If true, perform randomly", "self.num_person_in)) count = 0 for frame_info in video_info['data']: frame_index = frame_info['frame_index'] for m,", "If true, only use the first 100 samples \"\"\" def __init__(self, data_path, label_path,", "num_person_out self.pose_matching = pose_matching self.ignore_empty_sample = ignore_empty_sample self.load_data() def load_data(self): # load file", "np.array( [label_info[id]['has_skeleton'] for id in sample_id]) # ignore the samples which does not", "self.C = 3 #channel self.T = 90000 #frame self.V = 18 #joint self.M", "self.load_data() def load_data(self): # load file list self.sample_name = os.listdir(self.data_path) if self.debug: self.sample_name", "top_k): assert (all(self.label >= 0)) rank = score.argsort() hit_top_k = [l in rank[i,", "= 90000 #frame self.V = 18 #joint self.M = self.num_person_out #person def __len__(self):", "pose_matching=False, num_person_in=5, num_person_out=2, debug=False): self.debug = debug self.data_path = data_path self.label_path = label_path", "the output sequence pose_matching: If ture, match the pose between two frames num_person_in:", "= data_numpy[:, :, :, 0:self.num_person_out] # match poses between 2 frames if self.pose_matching:", "# sys import os import sys import numpy as np import random import", "assert (self.label[index] == label) # data augmentation if self.random_shift: data_numpy = tools.random_shift(data_numpy) if", "load label label_path = self.label_path with open(label_path) as f: label_info = json.load(f) sample_id", "tools.openpose_match(data_numpy) return data_numpy, label def top_k(self, score, top_k): assert (all(self.label >= 0)) rank", "0)) rank = score.argsort() hit_top_k = [l in rank[i, -top_k:] for i, l", "self.ignore_empty_sample = ignore_empty_sample self.load_data() def load_data(self): # load file list self.sample_name = os.listdir(self.data_path)", "load_data(self): # load file list self.sample_name = os.listdir(self.data_path) if self.debug: self.sample_name = self.sample_name[0:2]", "true, randomly choose a portion of the input sequence random_shift: If true, randomly", "= tools.random_shift(data_numpy) if self.random_choose: data_numpy = tools.random_choose(data_numpy, self.window_size) elif self.window_size > 0: data_numpy", "true, only use the first 100 samples \"\"\" def __init__(self, data_path, label_path, ignore_empty_sample=True,", "f: label_info = json.load(f) sample_id = [name.split('.')[0] for name in self.sample_name] self.label =", "data, the shape of data should be (N, C, T, V, M) label_path:", "id in sample_id]) has_skeleton = np.array( [label_info[id]['has_skeleton'] for id in sample_id]) # ignore", "0.5 data_numpy[0][data_numpy[2] == 0] = 0 data_numpy[1][data_numpy[2] == 0] = 0 # get", "numpy as np import random import pickle import json # torch import torch", "sequence random_move: If true, perform randomly but continuously changed transformation to input sequence", "self.debug: self.sample_name = self.sample_name[0:2] # load label label_path = self.label_path with open(label_path) as", "= frame_info['frame_index'] for m, skeleton_info in enumerate(frame_info[\"skeleton\"]): if m >= self.num_person_in: break pose", "def __getitem__(self, index): # output shape (C, T, V, M) # get data", "random import pickle import json # torch import torch import torch.nn as nn", "= data_numpy[0:2] - 0.5 data_numpy[0][data_numpy[2] == 0] = 0 data_numpy[1][data_numpy[2] == 0] =", "np.zeros((self.C, self.T, self.V, self.num_person_in)) count = 0 for frame_info in video_info['data']: frame_index =", "data_numpy[:, t, :, :] = data_numpy[:, t, :, s].transpose((1, 2, 0)) data_numpy =", "true, perform randomly but continuously changed transformation to input sequence window_size: The length", ". import tools class Feeder_UCF(torch.utils.data.Dataset): \"\"\" Feeder for skeleton-based action recognition in kinetics-skeleton", "data_numpy[0][data_numpy[2] == 0] = 0 data_numpy[1][data_numpy[2] == 0] = 0 # get &", "int(frame_index) # print(frame_index) data_numpy[0, frame_index, :, m] = pose[0::2] data_numpy[1, frame_index, :, m]", "kinetics-skeleton dataset Arguments: data_path: the path to '.npy' data, the shape of data", "at the begining or end of sequence random_move: If true, perform randomly but", "= score # count += 1 # print(\" \",count, \" \") # centralization", "in rank[i, -top_k:] for i, l in enumerate(self.label)] return sum(hit_top_k) * 1.0 /", "has_skeleton = np.array( [label_info[id]['has_skeleton'] for id in sample_id]) # ignore the samples which", "M) # get data sample_name = self.sample_name[index] sample_path = os.path.join(self.data_path, sample_name) with open(sample_path,", "self.num_person_out #person def __len__(self): return len(self.sample_name) def __iter__(self): return self def __getitem__(self, index):", ":, m] = pose[0::2] data_numpy[1, frame_index, :, m] = pose[1::2] data_numpy[2, frame_index, :,", "= random_choose self.random_shift = random_shift self.random_move = random_move self.window_size = window_size self.num_person_in =", "pickle import json # torch import torch import torch.nn as nn from torchvision", "enumerate(self.label)] return sum(hit_top_k) * 1.0 / len(hit_top_k) def top_k_by_category(self, score, top_k): assert (all(self.label", "of data should be (N, C, T, V, M) label_path: the path to", "return self def __getitem__(self, index): # output shape (C, T, V, M) #", "return len(self.sample_name) def __iter__(self): return self def __getitem__(self, index): # output shape (C,", "data_numpy = np.zeros((self.C, self.T, self.V, self.num_person_in)) count = 0 for frame_info in video_info['data']:", "= pose_matching self.ignore_empty_sample = ignore_empty_sample self.load_data() def load_data(self): # load file list self.sample_name", "If true, randomly pad zeros at the begining or end of sequence random_move:", "sort_index = (-data_numpy[2, :, :, :].sum(axis=1)).argsort(axis=1) for t, s in enumerate(sort_index): data_numpy[:, t,", "debug self.data_path = data_path self.label_path = label_path self.random_choose = random_choose self.random_shift = random_shift", "samples \"\"\" def __init__(self, data_path, label_path, ignore_empty_sample=True, random_choose=False, random_shift=False, random_move=False, window_size=-1, pose_matching=False, num_person_in=5,", "= 3 #channel self.T = 90000 #frame self.V = 18 #joint self.M =", "# ignore the samples which does not has skeleton sequence if self.ignore_empty_sample: self.sample_name", "open(label_path) as f: label_info = json.load(f) sample_id = [name.split('.')[0] for name in self.sample_name]", "= window_size self.num_person_in = num_person_in self.num_person_out = num_person_out self.pose_matching = pose_matching self.ignore_empty_sample =", "\" \") # centralization data_numpy[0:2] = data_numpy[0:2] - 0.5 data_numpy[0][data_numpy[2] == 0] =", "self.T = 90000 #frame self.V = 18 #joint self.M = self.num_person_out #person def", "as f: label_info = json.load(f) sample_id = [name.split('.')[0] for name in self.sample_name] self.label", "import torch import torch.nn as nn from torchvision import datasets, transforms # operation", "M) self.N = len(self.sample_name) #sample self.C = 3 #channel self.T = 90000 #frame", "tools.random_shift(data_numpy) if self.random_choose: data_numpy = tools.random_choose(data_numpy, self.window_size) elif self.window_size > 0: data_numpy =", "for id in sample_id]) # ignore the samples which does not has skeleton", "match poses between 2 frames if self.pose_matching: data_numpy = tools.openpose_match(data_numpy) return data_numpy, label", "class Feeder_UCF(torch.utils.data.Dataset): \"\"\" Feeder for skeleton-based action recognition in kinetics-skeleton dataset Arguments: data_path:", "# torch import torch import torch.nn as nn from torchvision import datasets, transforms", "data_numpy[2, frame_index, :, m] = score # count += 1 # print(\" \",count,", "pose between two frames num_person_in: The number of people the feeder can observe", "true, randomly pad zeros at the begining or end of sequence random_move: If", "= os.listdir(self.data_path) if self.debug: self.sample_name = self.sample_name[0:2] # load label label_path = self.label_path", "first 100 samples \"\"\" def __init__(self, data_path, label_path, ignore_empty_sample=True, random_choose=False, random_shift=False, random_move=False, window_size=-1,", "= [ s for h, s in zip(has_skeleton, self.sample_name) if h ] self.label", "0)) data_numpy = data_numpy[:, :, :, 0:self.num_person_out] # match poses between 2 frames", "# get data sample_name = self.sample_name[index] sample_path = os.path.join(self.data_path, sample_name) with open(sample_path, 'r')", "self.window_size) if self.random_move: data_numpy = tools.random_move(data_numpy) # sort by score sort_index = (-data_numpy[2,", ":, s].transpose((1, 2, 0)) data_numpy = data_numpy[:, :, :, 0:self.num_person_out] # match poses", "Feeder for skeleton-based action recognition in kinetics-skeleton dataset Arguments: data_path: the path to", "num_person_out=2, debug=False): self.debug = debug self.data_path = data_path self.label_path = label_path self.random_choose =", "sequence pose_matching: If ture, match the pose between two frames num_person_in: The number", "#joint self.M = self.num_person_out #person def __len__(self): return len(self.sample_name) def __iter__(self): return self", "m >= self.num_person_in: break pose = skeleton_info['pose'] score = skeleton_info['score'] frame_index = int(frame_index)", "sample_id]) has_skeleton = np.array( [label_info[id]['has_skeleton'] for id in sample_id]) # ignore the samples", "Feeder_UCF(torch.utils.data.Dataset): \"\"\" Feeder for skeleton-based action recognition in kinetics-skeleton dataset Arguments: data_path: the", "__getitem__(self, index): # output shape (C, T, V, M) # get data sample_name", "-top_k:] for i, l in enumerate(self.label)] return sum(hit_top_k) * 1.0 / len(hit_top_k) def", "m] = pose[1::2] data_numpy[2, frame_index, :, m] = score # count += 1", "data_numpy = tools.random_move(data_numpy) # sort by score sort_index = (-data_numpy[2, :, :, :].sum(axis=1)).argsort(axis=1)", ">= 0)) return tools.top_k_by_category(self.label, score, top_k) def calculate_recall_precision(self, score): assert (all(self.label >= 0))", "0)) return tools.top_k_by_category(self.label, score, top_k) def calculate_recall_precision(self, score): assert (all(self.label >= 0)) return", "M) label_path: the path to label random_choose: If true, randomly choose a portion", "self.N = len(self.sample_name) #sample self.C = 3 #channel self.T = 90000 #frame self.V", "t, s in enumerate(sort_index): data_numpy[:, t, :, :] = data_numpy[:, t, :, s].transpose((1,", "if self.random_choose: data_numpy = tools.random_choose(data_numpy, self.window_size) elif self.window_size > 0: data_numpy = tools.auto_pading(data_numpy,", "as f: video_info = json.load(f) # fill data_numpy data_numpy = np.zeros((self.C, self.T, self.V,", "of sequence random_move: If true, perform randomly but continuously changed transformation to input", "np.array( [label_info[id]['label_index'] for id in sample_id]) has_skeleton = np.array( [label_info[id]['has_skeleton'] for id in", "output data shape (N, C, T, V, M) self.N = len(self.sample_name) #sample self.C", "os.path.join(self.data_path, sample_name) with open(sample_path, 'r') as f: video_info = json.load(f) # fill data_numpy", "in enumerate(sort_index): data_numpy[:, t, :, :] = data_numpy[:, t, :, s].transpose((1, 2, 0))", "\"\"\" def __init__(self, data_path, label_path, ignore_empty_sample=True, random_choose=False, random_shift=False, random_move=False, window_size=-1, pose_matching=False, num_person_in=5, num_person_out=2,", "s for h, s in zip(has_skeleton, self.sample_name) if h ] self.label = self.label[has_skeleton]", "if self.ignore_empty_sample: self.sample_name = [ s for h, s in zip(has_skeleton, self.sample_name) if", "self.V, self.num_person_in)) count = 0 for frame_info in video_info['data']: frame_index = frame_info['frame_index'] for", "self.sample_name] self.label = np.array( [label_info[id]['label_index'] for id in sample_id]) has_skeleton = np.array( [label_info[id]['has_skeleton']", "data_numpy[0, frame_index, :, m] = pose[0::2] data_numpy[1, frame_index, :, m] = pose[1::2] data_numpy[2,", "randomly but continuously changed transformation to input sequence window_size: The length of the", "data_numpy[1][data_numpy[2] == 0] = 0 # get & check label index label =", "in enumerate(frame_info[\"skeleton\"]): if m >= self.num_person_in: break pose = skeleton_info['pose'] score = skeleton_info['score']", "print(\" \",count, \" \") # centralization data_numpy[0:2] = data_numpy[0:2] - 0.5 data_numpy[0][data_numpy[2] ==", "import pickle import json # torch import torch import torch.nn as nn from", "sys import numpy as np import random import pickle import json # torch", "3 #channel self.T = 90000 #frame self.V = 18 #joint self.M = self.num_person_out", "T, V, M) # get data sample_name = self.sample_name[index] sample_path = os.path.join(self.data_path, sample_name)", "np import random import pickle import json # torch import torch import torch.nn", "id in sample_id]) # ignore the samples which does not has skeleton sequence", "centralization data_numpy[0:2] = data_numpy[0:2] - 0.5 data_numpy[0][data_numpy[2] == 0] = 0 data_numpy[1][data_numpy[2] ==", "return data_numpy, label def top_k(self, score, top_k): assert (all(self.label >= 0)) rank =", "If true, randomly choose a portion of the input sequence random_shift: If true,", "= 0 for frame_info in video_info['data']: frame_index = frame_info['frame_index'] for m, skeleton_info in", "= [l in rank[i, -top_k:] for i, l in enumerate(self.label)] return sum(hit_top_k) *", "people the feeder can observe in the input sequence num_person_out: The number of", "torch import torch.nn as nn from torchvision import datasets, transforms # operation from", "torch import torch import torch.nn as nn from torchvision import datasets, transforms #", "debug: If true, only use the first 100 samples \"\"\" def __init__(self, data_path,", "perform randomly but continuously changed transformation to input sequence window_size: The length of", "V, M) # get data sample_name = self.sample_name[index] sample_path = os.path.join(self.data_path, sample_name) with", "s].transpose((1, 2, 0)) data_numpy = data_numpy[:, :, :, 0:self.num_person_out] # match poses between", "the samples which does not has skeleton sequence if self.ignore_empty_sample: self.sample_name = [", "import json # torch import torch import torch.nn as nn from torchvision import", "feeder can observe in the input sequence num_person_out: The number of people the", "window_size: The length of the output sequence pose_matching: If ture, match the pose", "0 # get & check label index label = video_info['label_index'] assert (self.label[index] ==", "with open(label_path) as f: label_info = json.load(f) sample_id = [name.split('.')[0] for name in", "l in enumerate(self.label)] return sum(hit_top_k) * 1.0 / len(hit_top_k) def top_k_by_category(self, score, top_k):", "* 1.0 / len(hit_top_k) def top_k_by_category(self, score, top_k): assert (all(self.label >= 0)) return", "self.random_shift: data_numpy = tools.random_shift(data_numpy) if self.random_choose: data_numpy = tools.random_choose(data_numpy, self.window_size) elif self.window_size >" ]
[ "'Sexual Content'), ('OTHER', 'Other')], max_length=50)), ('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user',", "options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Abuse', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),", "('SEXUAL_CONTENT', 'Sexual Content'), ('OTHER', 'Other')], max_length=50)), ('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')),", "max_length=50)), ('special', models.BooleanField(default=False)), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Requirments', fields=[ ('id',", "('name', models.CharField(max_length=50)), ('description', models.TextField()), ('color', models.CharField(choices=[('success', 'Green'), ('info', 'Blue'), ('link', 'Purple'), ('primary', 'Turquoise'),", "] operations = [ migrations.CreateModel( name='Badge', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name',", "import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'),", "'Abuse'), ('INAPPROPRIATE', 'Inappropriate'), ('SPAM', 'Spam'), ('BULLYING', 'Bullying'), ('SEXUAL_CONTENT', 'Sexual Content'), ('OTHER', 'Other')], max_length=50)),", "], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Requirments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False,", "migrations.CreateModel( name='Abuse', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE', 'Inappropriate'),", "= [ migrations.CreateModel( name='Badge', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description',", "('danger', 'Red'), ('dark', 'Black'), ('white', 'White')], max_length=50)), ('special', models.BooleanField(default=False)), ], options={ 'ordering': ['name'],", "['name'], }, ), migrations.CreateModel( name='Requirments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)),", "django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'), ]", "('warning', 'Yellow'), ('danger', 'Red'), ('dark', 'Black'), ('white', 'White')], max_length=50)), ('special', models.BooleanField(default=False)), ], options={", "('special', models.BooleanField(default=False)), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Requirments', fields=[ ('id', models.BigAutoField(auto_created=True,", "<gh_stars>1-10 # Generated by Django 4.0.2 on 2022-03-02 03:29 from django.conf import settings", "}, ), migrations.CreateModel( name='Abuse', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'),", "'Turquoise'), ('warning', 'Yellow'), ('danger', 'Red'), ('dark', 'Black'), ('white', 'White')], max_length=50)), ('special', models.BooleanField(default=False)), ],", "to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name_plural': 'Abuses', 'ordering': ['-date'], }, ), ]", "True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'), ] operations = [ migrations.CreateModel( name='Badge',", "), migrations.CreateModel( name='Requirments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()),", "models.CharField(choices=[('success', 'Green'), ('info', 'Blue'), ('link', 'Purple'), ('primary', 'Turquoise'), ('warning', 'Yellow'), ('danger', 'Red'), ('dark',", "('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE', 'Inappropriate'), ('SPAM', 'Spam'), ('BULLYING',", "primary_key=True, serialize=False, verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE', 'Inappropriate'), ('SPAM', 'Spam'), ('BULLYING', 'Bullying'), ('SEXUAL_CONTENT',", "[ migrations.CreateModel( name='Badge', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()),", "name='Badge', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('color', models.CharField(choices=[('success',", "('INAPPROPRIATE', 'Inappropriate'), ('SPAM', 'Spam'), ('BULLYING', 'Bullying'), ('SEXUAL_CONTENT', 'Sexual Content'), ('OTHER', 'Other')], max_length=50)), ('description',", "2022-03-02 03:29 from django.conf import settings from django.db import migrations, models import django.db.models.deletion", "migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL),", "4.0.2 on 2022-03-02 03:29 from django.conf import settings from django.db import migrations, models", "serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ], options={ 'ordering': ['name'],", "models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name_plural': 'Abuses', 'ordering': ['-date'], }, ),", "models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name_plural': 'Abuses',", "primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('color', models.CharField(choices=[('success', 'Green'), ('info', 'Blue'), ('link',", "('vit', '0001_initial'), ] operations = [ migrations.CreateModel( name='Badge', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False,", "), migrations.CreateModel( name='Abuse', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE',", "dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'), ] operations = [ migrations.CreateModel( name='Badge', fields=[", "('SPAM', 'Spam'), ('BULLYING', 'Bullying'), ('SEXUAL_CONTENT', 'Sexual Content'), ('OTHER', 'Other')], max_length=50)), ('description', models.TextField()), ('date',", "Content'), ('OTHER', 'Other')], max_length=50)), ('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,", "# Generated by Django 4.0.2 on 2022-03-02 03:29 from django.conf import settings from", "[ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'), ] operations = [ migrations.CreateModel( name='Badge', fields=[ ('id', models.BigAutoField(auto_created=True,", "verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE', 'Inappropriate'), ('SPAM', 'Spam'), ('BULLYING', 'Bullying'), ('SEXUAL_CONTENT', 'Sexual Content'),", "'White')], max_length=50)), ('special', models.BooleanField(default=False)), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Requirments', fields=[", "'Black'), ('white', 'White')], max_length=50)), ('special', models.BooleanField(default=False)), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel(", "('name', models.CharField(max_length=50)), ('description', models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ], options={ 'ordering': ['name'], }, ),", "migrations.CreateModel( name='Badge', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('color',", "verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('color', models.CharField(choices=[('success', 'Green'), ('info', 'Blue'), ('link', 'Purple'), ('primary',", "django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial", "('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name_plural': 'Abuses', 'ordering': ['-date'], },", "('description', models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Abuse',", "operations = [ migrations.CreateModel( name='Badge', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)),", "'Spam'), ('BULLYING', 'Bullying'), ('SEXUAL_CONTENT', 'Sexual Content'), ('OTHER', 'Other')], max_length=50)), ('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)),", "Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'), ] operations =", "('info', 'Blue'), ('link', 'Purple'), ('primary', 'Turquoise'), ('warning', 'Yellow'), ('danger', 'Red'), ('dark', 'Black'), ('white',", "= [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'), ] operations = [ migrations.CreateModel( name='Badge', fields=[ ('id',", "max_length=50)), ('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={", "models.TextField()), ('color', models.CharField(choices=[('success', 'Green'), ('info', 'Blue'), ('link', 'Purple'), ('primary', 'Turquoise'), ('warning', 'Yellow'), ('danger',", "= True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'), ] operations = [ migrations.CreateModel(", "'Purple'), ('primary', 'Turquoise'), ('warning', 'Yellow'), ('danger', 'Red'), ('dark', 'Black'), ('white', 'White')], max_length=50)), ('special',", "('date', models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name_plural': 'Abuses', 'ordering':", "from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies", "by Django 4.0.2 on 2022-03-02 03:29 from django.conf import settings from django.db import", "models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ], options={", "('link', 'Purple'), ('primary', 'Turquoise'), ('warning', 'Yellow'), ('danger', 'Red'), ('dark', 'Black'), ('white', 'White')], max_length=50)),", "'Other')], max_length=50)), ('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ],", "('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ],", "('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name_plural':", "('dark', 'Black'), ('white', 'White')], max_length=50)), ('special', models.BooleanField(default=False)), ], options={ 'ordering': ['name'], }, ),", "('description', models.TextField()), ('color', models.CharField(choices=[('success', 'Green'), ('info', 'Blue'), ('link', 'Purple'), ('primary', 'Turquoise'), ('warning', 'Yellow'),", "'0001_initial'), ] operations = [ migrations.CreateModel( name='Badge', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),", "name='Requirments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,", "models.CharField(max_length=50)), ('description', models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel(", "'Bullying'), ('SEXUAL_CONTENT', 'Sexual Content'), ('OTHER', 'Other')], max_length=50)), ('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,", "import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [", "models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Abuse', fields=[", "models.BooleanField(default=False)), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Requirments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True,", "('color', models.CharField(choices=[('success', 'Green'), ('info', 'Blue'), ('link', 'Purple'), ('primary', 'Turquoise'), ('warning', 'Yellow'), ('danger', 'Red'),", "fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('color', models.CharField(choices=[('success', 'Green'),", "], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Abuse', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False,", "'ordering': ['name'], }, ), migrations.CreateModel( name='Requirments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name',", "fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE', 'Inappropriate'), ('SPAM', 'Spam'),", "'Green'), ('info', 'Blue'), ('link', 'Purple'), ('primary', 'Turquoise'), ('warning', 'Yellow'), ('danger', 'Red'), ('dark', 'Black'),", "('primary', 'Turquoise'), ('warning', 'Yellow'), ('danger', 'Red'), ('dark', 'Black'), ('white', 'White')], max_length=50)), ('special', models.BooleanField(default=False)),", "models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit',", "03:29 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class", "serialize=False, verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE', 'Inappropriate'), ('SPAM', 'Spam'), ('BULLYING', 'Bullying'), ('SEXUAL_CONTENT', 'Sexual", "django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies =", "migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'), ] operations = [ migrations.CreateModel( name='Badge', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True,", "'Yellow'), ('danger', 'Red'), ('dark', 'Black'), ('white', 'White')], max_length=50)), ('special', models.BooleanField(default=False)), ], options={ 'ordering':", "models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Abuse', fields=[ ('id', models.BigAutoField(auto_created=True,", "migrations.CreateModel( name='Requirments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('badge',", "import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial =", "fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')),", "primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ], options={ 'ordering':", "('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Abuse', fields=[ ('id',", "('BULLYING', 'Bullying'), ('SEXUAL_CONTENT', 'Sexual Content'), ('OTHER', 'Other')], max_length=50)), ('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit',", "'Red'), ('dark', 'Black'), ('white', 'White')], max_length=50)), ('special', models.BooleanField(default=False)), ], options={ 'ordering': ['name'], },", "verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ], options={ 'ordering': ['name'], },", "class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'), ] operations", "on 2022-03-02 03:29 from django.conf import settings from django.db import migrations, models import", "initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'), ] operations = [", "('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('color', models.CharField(choices=[('success', 'Green'), ('info',", "from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):", "}, ), migrations.CreateModel( name='Requirments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description',", "models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE', 'Inappropriate'), ('SPAM', 'Spam'), ('BULLYING', 'Bullying'),", "options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Requirments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),", "models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name_plural': 'Abuses', 'ordering': ['-date'],", "['name'], }, ), migrations.CreateModel( name='Abuse', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE',", "'Blue'), ('link', 'Purple'), ('primary', 'Turquoise'), ('warning', 'Yellow'), ('danger', 'Red'), ('dark', 'Black'), ('white', 'White')],", "'Inappropriate'), ('SPAM', 'Spam'), ('BULLYING', 'Bullying'), ('SEXUAL_CONTENT', 'Sexual Content'), ('OTHER', 'Other')], max_length=50)), ('description', models.TextField()),", "name='Abuse', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE', 'Inappropriate'), ('SPAM',", "models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('color', models.CharField(choices=[('success', 'Green'), ('info', 'Blue'),", "'ordering': ['name'], }, ), migrations.CreateModel( name='Abuse', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('abuse_type',", "('white', 'White')], max_length=50)), ('special', models.BooleanField(default=False)), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Requirments',", "('OTHER', 'Other')], max_length=50)), ('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),", "('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE', 'Inappropriate'), ('SPAM', 'Spam'), ('BULLYING', 'Bullying'), ('SEXUAL_CONTENT', 'Sexual Content'), ('OTHER',", "Generated by Django 4.0.2 on 2022-03-02 03:29 from django.conf import settings from django.db", "settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True", "models.CharField(max_length=50)), ('description', models.TextField()), ('color', models.CharField(choices=[('success', 'Green'), ('info', 'Blue'), ('link', 'Purple'), ('primary', 'Turquoise'), ('warning',", "models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE', 'Inappropriate'), ('SPAM', 'Spam'), ('BULLYING', 'Bullying'), ('SEXUAL_CONTENT', 'Sexual Content'), ('OTHER', 'Other')],", "to='core.badge')), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Abuse', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True,", "serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('color', models.CharField(choices=[('success', 'Green'), ('info', 'Blue'), ('link', 'Purple'),", "Django 4.0.2 on 2022-03-02 03:29 from django.conf import settings from django.db import migrations," ]
[ "schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel: stub = pb2_grpc.SchemaRegistryStub(channel) resp = stub.AddSchema( pb2.NewSchema( definition=bytes(body,", "if self.initial_schema is not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc = subprocess.Popen([EXE], env=env) time.sleep(3) return self", "destination, query, body, schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel: stub = pb2_grpc.SchemaRegistryStub(channel) resp =", "__init__(self, edge_registry_addr, kafka_brokers, postgres_config: PostgresConfig, kafka_group_id='schema_registry', input_port='50101', initial_schema=None): self.edge_registry_addr = edge_registry_addr self.kafka_brokers =", "= edge_registry_addr self.kafka_brokers = kafka_brokers self.kafka_group_id = kafka_group_id self.input_port = input_port self.postgres_config =", "\"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") } if", "edge_registry_addr self.kafka_brokers = kafka_brokers self.kafka_group_id = kafka_group_id self.input_port = input_port self.postgres_config = postgres_config", "self.svc = None def start(self): env = { \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\":", "not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc = subprocess.Popen([EXE], env=env) time.sleep(3) return self def stop(self): self.svc.kill()", "import tests.rpc.proto.schema_registry_pb2_grpc as pb2_grpc from tests.common.postgres import PostgresConfig EXE = os.getenv('SCHEMA_REGISTRY_EXE') or 'schema-registry'", "as channel: stub = pb2_grpc.SchemaRegistryStub(channel) resp = stub.AddSchema( pb2.NewSchema( definition=bytes(body, 'utf-8'), name=name, insert_destination=destination,", "'0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") } if self.initial_schema is not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc =", "= kafka_brokers self.kafka_group_id = kafka_group_id self.input_port = input_port self.postgres_config = postgres_config self.initial_schema =", "self.postgres_config = postgres_config self.initial_schema = initial_schema self.svc = None def start(self): env =", "\"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") } if self.initial_schema is", "def __init__(self, edge_registry_addr, kafka_brokers, postgres_config: PostgresConfig, kafka_group_id='schema_registry', input_port='50101', initial_schema=None): self.edge_registry_addr = edge_registry_addr self.kafka_brokers", "self.svc = subprocess.Popen([EXE], env=env) time.sleep(3) return self def stop(self): self.svc.kill() def create_schema(self, name,", "channel: stub = pb2_grpc.SchemaRegistryStub(channel) resp = stub.AddSchema( pb2.NewSchema( definition=bytes(body, 'utf-8'), name=name, insert_destination=destination, query_address=query,", "= { \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\":", "= os.getenv('SCHEMA_REGISTRY_EXE') or 'schema-registry' class SchemaRegistry: def __init__(self, edge_registry_addr, kafka_brokers, postgres_config: PostgresConfig, kafka_group_id='schema_registry',", "time.sleep(3) return self def stop(self): self.svc.kill() def create_schema(self, name, destination, query, body, schema_type):", "as pb2_grpc from tests.common.postgres import PostgresConfig EXE = os.getenv('SCHEMA_REGISTRY_EXE') or 'schema-registry' class SchemaRegistry:", "class SchemaRegistry: def __init__(self, edge_registry_addr, kafka_brokers, postgres_config: PostgresConfig, kafka_group_id='schema_registry', input_port='50101', initial_schema=None): self.edge_registry_addr =", "= input_port self.postgres_config = postgres_config self.initial_schema = initial_schema self.svc = None def start(self):", "self def stop(self): self.svc.kill() def create_schema(self, name, destination, query, body, schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\")", "{ \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0',", "def start(self): env = { \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port,", "initial_schema=None): self.edge_registry_addr = edge_registry_addr self.kafka_brokers = kafka_brokers self.kafka_group_id = kafka_group_id self.input_port = input_port", "kafka_group_id='schema_registry', input_port='50101', initial_schema=None): self.edge_registry_addr = edge_registry_addr self.kafka_brokers = kafka_brokers self.kafka_group_id = kafka_group_id self.input_port", "name, destination, query, body, schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel: stub = pb2_grpc.SchemaRegistryStub(channel) resp", "return self def stop(self): self.svc.kill() def create_schema(self, name, destination, query, body, schema_type): with", "= kafka_group_id self.input_port = input_port self.postgres_config = postgres_config self.initial_schema = initial_schema self.svc =", "\"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\":", "create_schema(self, name, destination, query, body, schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel: stub = pb2_grpc.SchemaRegistryStub(channel)", "import os import subprocess import time import grpc import tests.rpc.proto.schema_registry_pb2 as pb2 import", "pb2 import tests.rpc.proto.schema_registry_pb2_grpc as pb2_grpc from tests.common.postgres import PostgresConfig EXE = os.getenv('SCHEMA_REGISTRY_EXE') or", "self.initial_schema = initial_schema self.svc = None def start(self): env = { \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka',", "start(self): env = { \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\":", "\"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") } if self.initial_schema is not None:", "tests.common.postgres import PostgresConfig EXE = os.getenv('SCHEMA_REGISTRY_EXE') or 'schema-registry' class SchemaRegistry: def __init__(self, edge_registry_addr,", "self.kafka_group_id = kafka_group_id self.input_port = input_port self.postgres_config = postgres_config self.initial_schema = initial_schema self.svc", "self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") }", "'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr,", "tests.rpc.proto.schema_registry_pb2 as pb2 import tests.rpc.proto.schema_registry_pb2_grpc as pb2_grpc from tests.common.postgres import PostgresConfig EXE =", "= None def start(self): env = { \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id,", "= subprocess.Popen([EXE], env=env) time.sleep(3) return self def stop(self): self.svc.kill() def create_schema(self, name, destination,", "stop(self): self.svc.kill() def create_schema(self, name, destination, query, body, schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel:", "os.getenv('SCHEMA_REGISTRY_EXE') or 'schema-registry' class SchemaRegistry: def __init__(self, edge_registry_addr, kafka_brokers, postgres_config: PostgresConfig, kafka_group_id='schema_registry', input_port='50101',", "body, schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel: stub = pb2_grpc.SchemaRegistryStub(channel) resp = stub.AddSchema( pb2.NewSchema(", "postgres_config self.initial_schema = initial_schema self.svc = None def start(self): env = { \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\":", "with grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel: stub = pb2_grpc.SchemaRegistryStub(channel) resp = stub.AddSchema( pb2.NewSchema( definition=bytes(body, 'utf-8'),", "input_port='50101', initial_schema=None): self.edge_registry_addr = edge_registry_addr self.kafka_brokers = kafka_brokers self.kafka_group_id = kafka_group_id self.input_port =", "subprocess import time import grpc import tests.rpc.proto.schema_registry_pb2 as pb2 import tests.rpc.proto.schema_registry_pb2_grpc as pb2_grpc", "self.input_port = input_port self.postgres_config = postgres_config self.initial_schema = initial_schema self.svc = None def", "os import subprocess import time import grpc import tests.rpc.proto.schema_registry_pb2 as pb2 import tests.rpc.proto.schema_registry_pb2_grpc", "\"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\")", "def create_schema(self, name, destination, query, body, schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel: stub =", "kafka_group_id self.input_port = input_port self.postgres_config = postgres_config self.initial_schema = initial_schema self.svc = None", "'schema-registry' class SchemaRegistry: def __init__(self, edge_registry_addr, kafka_brokers, postgres_config: PostgresConfig, kafka_group_id='schema_registry', input_port='50101', initial_schema=None): self.edge_registry_addr", "self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") } if self.initial_schema", "initial_schema self.svc = None def start(self): env = { \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers,", "stub = pb2_grpc.SchemaRegistryStub(channel) resp = stub.AddSchema( pb2.NewSchema( definition=bytes(body, 'utf-8'), name=name, insert_destination=destination, query_address=query, schema_type=pb2.SchemaType(schema_type=schema_type)))", "env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc = subprocess.Popen([EXE], env=env) time.sleep(3) return self def stop(self): self.svc.kill() def create_schema(self,", "self.svc.kill() def create_schema(self, name, destination, query, body, schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel: stub", "env=env) time.sleep(3) return self def stop(self): self.svc.kill() def create_schema(self, name, destination, query, body,", "\"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") } if self.initial_schema is not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc = subprocess.Popen([EXE],", "import tests.rpc.proto.schema_registry_pb2 as pb2 import tests.rpc.proto.schema_registry_pb2_grpc as pb2_grpc from tests.common.postgres import PostgresConfig EXE", "import PostgresConfig EXE = os.getenv('SCHEMA_REGISTRY_EXE') or 'schema-registry' class SchemaRegistry: def __init__(self, edge_registry_addr, kafka_brokers,", "self.kafka_brokers = kafka_brokers self.kafka_group_id = kafka_group_id self.input_port = input_port self.postgres_config = postgres_config self.initial_schema", "import time import grpc import tests.rpc.proto.schema_registry_pb2 as pb2 import tests.rpc.proto.schema_registry_pb2_grpc as pb2_grpc from", "kafka_brokers, postgres_config: PostgresConfig, kafka_group_id='schema_registry', input_port='50101', initial_schema=None): self.edge_registry_addr = edge_registry_addr self.kafka_brokers = kafka_brokers self.kafka_group_id", "env = { \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry',", "= pb2_grpc.SchemaRegistryStub(channel) resp = stub.AddSchema( pb2.NewSchema( definition=bytes(body, 'utf-8'), name=name, insert_destination=destination, query_address=query, schema_type=pb2.SchemaType(schema_type=schema_type))) return", "grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel: stub = pb2_grpc.SchemaRegistryStub(channel) resp = stub.AddSchema( pb2.NewSchema( definition=bytes(body, 'utf-8'), name=name,", "None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc = subprocess.Popen([EXE], env=env) time.sleep(3) return self def stop(self): self.svc.kill() def", "grpc import tests.rpc.proto.schema_registry_pb2 as pb2 import tests.rpc.proto.schema_registry_pb2_grpc as pb2_grpc from tests.common.postgres import PostgresConfig", "pb2_grpc from tests.common.postgres import PostgresConfig EXE = os.getenv('SCHEMA_REGISTRY_EXE') or 'schema-registry' class SchemaRegistry: def", "None def start(self): env = { \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\":", "kafka_brokers self.kafka_group_id = kafka_group_id self.input_port = input_port self.postgres_config = postgres_config self.initial_schema = initial_schema", "tests.rpc.proto.schema_registry_pb2_grpc as pb2_grpc from tests.common.postgres import PostgresConfig EXE = os.getenv('SCHEMA_REGISTRY_EXE') or 'schema-registry' class", "time import grpc import tests.rpc.proto.schema_registry_pb2 as pb2 import tests.rpc.proto.schema_registry_pb2_grpc as pb2_grpc from tests.common.postgres", "or 'schema-registry' class SchemaRegistry: def __init__(self, edge_registry_addr, kafka_brokers, postgres_config: PostgresConfig, kafka_group_id='schema_registry', input_port='50101', initial_schema=None):", "input_port self.postgres_config = postgres_config self.initial_schema = initial_schema self.svc = None def start(self): env", "\"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") } if self.initial_schema is not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc", "is not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc = subprocess.Popen([EXE], env=env) time.sleep(3) return self def stop(self):", "import grpc import tests.rpc.proto.schema_registry_pb2 as pb2 import tests.rpc.proto.schema_registry_pb2_grpc as pb2_grpc from tests.common.postgres import", "self.edge_registry_addr = edge_registry_addr self.kafka_brokers = kafka_brokers self.kafka_group_id = kafka_group_id self.input_port = input_port self.postgres_config", "= postgres_config self.initial_schema = initial_schema self.svc = None def start(self): env = {", "self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") } if self.initial_schema is not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc = subprocess.Popen([EXE], env=env)", "SchemaRegistry: def __init__(self, edge_registry_addr, kafka_brokers, postgres_config: PostgresConfig, kafka_group_id='schema_registry', input_port='50101', initial_schema=None): self.edge_registry_addr = edge_registry_addr", "edge_registry_addr, kafka_brokers, postgres_config: PostgresConfig, kafka_group_id='schema_registry', input_port='50101', initial_schema=None): self.edge_registry_addr = edge_registry_addr self.kafka_brokers = kafka_brokers", "EXE = os.getenv('SCHEMA_REGISTRY_EXE') or 'schema-registry' class SchemaRegistry: def __init__(self, edge_registry_addr, kafka_brokers, postgres_config: PostgresConfig,", "} if self.initial_schema is not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc = subprocess.Popen([EXE], env=env) time.sleep(3) return", "as pb2 import tests.rpc.proto.schema_registry_pb2_grpc as pb2_grpc from tests.common.postgres import PostgresConfig EXE = os.getenv('SCHEMA_REGISTRY_EXE')", "import subprocess import time import grpc import tests.rpc.proto.schema_registry_pb2 as pb2 import tests.rpc.proto.schema_registry_pb2_grpc as", "self.initial_schema is not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc = subprocess.Popen([EXE], env=env) time.sleep(3) return self def", "PostgresConfig, kafka_group_id='schema_registry', input_port='50101', initial_schema=None): self.edge_registry_addr = edge_registry_addr self.kafka_brokers = kafka_brokers self.kafka_group_id = kafka_group_id", "from tests.common.postgres import PostgresConfig EXE = os.getenv('SCHEMA_REGISTRY_EXE') or 'schema-registry' class SchemaRegistry: def __init__(self,", "PostgresConfig EXE = os.getenv('SCHEMA_REGISTRY_EXE') or 'schema-registry' class SchemaRegistry: def __init__(self, edge_registry_addr, kafka_brokers, postgres_config:", "self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") } if self.initial_schema is not", "query, body, schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel: stub = pb2_grpc.SchemaRegistryStub(channel) resp = stub.AddSchema(", "pb2_grpc.SchemaRegistryStub(channel) resp = stub.AddSchema( pb2.NewSchema( definition=bytes(body, 'utf-8'), name=name, insert_destination=destination, query_address=query, schema_type=pb2.SchemaType(schema_type=schema_type))) return resp.id", "'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") } if self.initial_schema is not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema)", "postgres_config: PostgresConfig, kafka_group_id='schema_registry', input_port='50101', initial_schema=None): self.edge_registry_addr = edge_registry_addr self.kafka_brokers = kafka_brokers self.kafka_group_id =", "= initial_schema self.svc = None def start(self): env = { \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\":", "def stop(self): self.svc.kill() def create_schema(self, name, destination, query, body, schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\") as", "**self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") } if self.initial_schema is not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc = subprocess.Popen([EXE], env=env) time.sleep(3)", "subprocess.Popen([EXE], env=env) time.sleep(3) return self def stop(self): self.svc.kill() def create_schema(self, name, destination, query," ]
[ "a routing policy is set with an empty condition, it should be loaded", "EchoedRequest pytestmark = [ pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url): \"\"\" Asserts,", "as a catch all rule) \"\"\" proxy = service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig( \"routing\", {", "\"\"\" When a routing policy is set with an empty condition, it should", "correct backend (httpbin) \"\"\" parsed_url = urlparse(private_base_url(\"httpbin\")) response = api_client().get(\"/get\") assert response.status_code ==", "backend \"\"\" return rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\") def service(service, private_base_url): \"\"\" Set the routing policy", "condition should act as a catch all rule) \"\"\" proxy = service.proxy.list() proxy.policies.insert(0,", "test_routing_policy_without_header(api_client, private_base_url): \"\"\" Sends a request and asserts, that the routing policy is", "empty condition, it should be loaded correctly and should route all the requests", "and the requests is routed to the correct backend (httpbin) \"\"\" parsed_url =", "from packaging.version import Version # noqa # pylint: disable=unused-import from testsuite import TESTED_VERSION,", "testsuite import TESTED_VERSION, rawobj # noqa # pylint: disable=unused-import from testsuite.echoed_request import EchoedRequest", "\"\"\" Asserts, that echo api is used as the default backend \"\"\" return", "noqa # pylint: disable=unused-import from testsuite import TESTED_VERSION, rawobj # noqa # pylint:", "with an empty condition, it should be loaded correctly and should route all", "the requests to a correct backend. \"\"\" from urllib.parse import urlparse import pytest", "logic that an empty condition should act as a catch all rule) \"\"\"", "pytestmark = [ pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url): \"\"\" Asserts, that", "a correct backend. \"\"\" from urllib.parse import urlparse import pytest from packaging.version import", "rule) \"\"\" proxy = service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig( \"routing\", { \"rules\": [ { \"url\":", "private_base_url(\"httpbin\"), \"condition\": {}, }]})) return service def test_routing_policy_without_header(api_client, private_base_url): \"\"\" Sends a request", "import EchoedRequest pytestmark = [ pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url): \"\"\"", "that the routing policy is active and the requests is routed to the", "urlparse(private_base_url(\"httpbin\")) response = api_client().get(\"/get\") assert response.status_code == 200 echoed_request = EchoedRequest.create(response) assert echoed_request.headers[\"Host\"]", "used as the default backend \"\"\" return rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\") def service(service, private_base_url): \"\"\"", "correctly and should route all the requests to a correct backend. \"\"\" from", "\"rules\": [ { \"url\": private_base_url(\"httpbin\"), \"condition\": {}, }]})) return service def test_routing_policy_without_header(api_client, private_base_url):", "to httpbin. (Using the logic that an empty condition should act as a", "import Version # noqa # pylint: disable=unused-import from testsuite import TESTED_VERSION, rawobj #", "= urlparse(private_base_url(\"httpbin\")) response = api_client().get(\"/get\") assert response.status_code == 200 echoed_request = EchoedRequest.create(response) assert", "(httpbin) \"\"\" parsed_url = urlparse(private_base_url(\"httpbin\")) response = api_client().get(\"/get\") assert response.status_code == 200 echoed_request", "the requests is routed to the correct backend (httpbin) \"\"\" parsed_url = urlparse(private_base_url(\"httpbin\"))", "that an empty condition should act as a catch all rule) \"\"\" proxy", "empty condition should act as a catch all rule) \"\"\" proxy = service.proxy.list()", "be loaded correctly and should route all the requests to a correct backend.", "Sends a request and asserts, that the routing policy is active and the", "from testsuite import TESTED_VERSION, rawobj # noqa # pylint: disable=unused-import from testsuite.echoed_request import", "the default backend \"\"\" return rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\") def service(service, private_base_url): \"\"\" Set the", "an empty condition, it should be loaded correctly and should route all the", "is routed to the correct backend (httpbin) \"\"\" parsed_url = urlparse(private_base_url(\"httpbin\")) response =", "as the default backend \"\"\" return rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\") def service(service, private_base_url): \"\"\" Set", "return rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\") def service(service, private_base_url): \"\"\" Set the routing policy to route", "pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url): \"\"\" Asserts, that echo api is", "a catch all rule) \"\"\" proxy = service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig( \"routing\", { \"rules\":", "# pylint: disable=unused-import from testsuite import TESTED_VERSION, rawobj # noqa # pylint: disable=unused-import", "\"condition\": {}, }]})) return service def test_routing_policy_without_header(api_client, private_base_url): \"\"\" Sends a request and", "to the correct backend (httpbin) \"\"\" parsed_url = urlparse(private_base_url(\"httpbin\")) response = api_client().get(\"/get\") assert", "asserts, that the routing policy is active and the requests is routed to", "{ \"url\": private_base_url(\"httpbin\"), \"condition\": {}, }]})) return service def test_routing_policy_without_header(api_client, private_base_url): \"\"\" Sends", "from testsuite.echoed_request import EchoedRequest pytestmark = [ pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def", "Version # noqa # pylint: disable=unused-import from testsuite import TESTED_VERSION, rawobj # noqa", "an empty condition should act as a catch all rule) \"\"\" proxy =", "[ { \"url\": private_base_url(\"httpbin\"), \"condition\": {}, }]})) return service def test_routing_policy_without_header(api_client, private_base_url): \"\"\"", "default backend \"\"\" return rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\") def service(service, private_base_url): \"\"\" Set the routing", "\"\"\" proxy = service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig( \"routing\", { \"rules\": [ { \"url\": private_base_url(\"httpbin\"),", "active and the requests is routed to the correct backend (httpbin) \"\"\" parsed_url", "should be loaded correctly and should route all the requests to a correct", "api is used as the default backend \"\"\" return rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\") def service(service,", "requests is routed to the correct backend (httpbin) \"\"\" parsed_url = urlparse(private_base_url(\"httpbin\")) response", "from urllib.parse import urlparse import pytest from packaging.version import Version # noqa #", "\"\"\" parsed_url = urlparse(private_base_url(\"httpbin\")) response = api_client().get(\"/get\") assert response.status_code == 200 echoed_request =", "testsuite.echoed_request import EchoedRequest pytestmark = [ pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url):", "requests to httpbin. (Using the logic that an empty condition should act as", "}]})) return service def test_routing_policy_without_header(api_client, private_base_url): \"\"\" Sends a request and asserts, that", "routed to the correct backend (httpbin) \"\"\" parsed_url = urlparse(private_base_url(\"httpbin\")) response = api_client().get(\"/get\")", "routing policy to route all requests to httpbin. (Using the logic that an", "< Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url): \"\"\" Asserts, that echo api is used", "urllib.parse import urlparse import pytest from packaging.version import Version # noqa # pylint:", "policy to route all requests to httpbin. (Using the logic that an empty", "parsed_url = urlparse(private_base_url(\"httpbin\")) response = api_client().get(\"/get\") assert response.status_code == 200 echoed_request = EchoedRequest.create(response)", "\"routing\", { \"rules\": [ { \"url\": private_base_url(\"httpbin\"), \"condition\": {}, }]})) return service def", "should route all the requests to a correct backend. \"\"\" from urllib.parse import", "noqa # pylint: disable=unused-import from testsuite.echoed_request import EchoedRequest pytestmark = [ pytest.mark.skipif(\"TESTED_VERSION <", "When a routing policy is set with an empty condition, it should be", "and should route all the requests to a correct backend. \"\"\" from urllib.parse", "to route all requests to httpbin. (Using the logic that an empty condition", "set with an empty condition, it should be loaded correctly and should route", "(Using the logic that an empty condition should act as a catch all", "\"\"\" Set the routing policy to route all requests to httpbin. (Using the", "\"\"\" Sends a request and asserts, that the routing policy is active and", "request and asserts, that the routing policy is active and the requests is", "{ \"rules\": [ { \"url\": private_base_url(\"httpbin\"), \"condition\": {}, }]})) return service def test_routing_policy_without_header(api_client,", "the routing policy is active and the requests is routed to the correct", "urlparse import pytest from packaging.version import Version # noqa # pylint: disable=unused-import from", "a request and asserts, that the routing policy is active and the requests", "service_proxy_settings(private_base_url): \"\"\" Asserts, that echo api is used as the default backend \"\"\"", "backend. \"\"\" from urllib.parse import urlparse import pytest from packaging.version import Version #", "httpbin. (Using the logic that an empty condition should act as a catch", "proxy.policies.insert(0, rawobj.PolicyConfig( \"routing\", { \"rules\": [ { \"url\": private_base_url(\"httpbin\"), \"condition\": {}, }]})) return", "all requests to httpbin. (Using the logic that an empty condition should act", "the routing policy to route all requests to httpbin. (Using the logic that", "import urlparse import pytest from packaging.version import Version # noqa # pylint: disable=unused-import", "Set the routing policy to route all requests to httpbin. (Using the logic", "def service_proxy_settings(private_base_url): \"\"\" Asserts, that echo api is used as the default backend", "it should be loaded correctly and should route all the requests to a", "act as a catch all rule) \"\"\" proxy = service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig( \"routing\",", "disable=unused-import from testsuite import TESTED_VERSION, rawobj # noqa # pylint: disable=unused-import from testsuite.echoed_request", "all rule) \"\"\" proxy = service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig( \"routing\", { \"rules\": [ {", "\"url\": private_base_url(\"httpbin\"), \"condition\": {}, }]})) return service def test_routing_policy_without_header(api_client, private_base_url): \"\"\" Sends a", "\"\"\" return rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\") def service(service, private_base_url): \"\"\" Set the routing policy to", "import pytest from packaging.version import Version # noqa # pylint: disable=unused-import from testsuite", "backend (httpbin) \"\"\" parsed_url = urlparse(private_base_url(\"httpbin\")) response = api_client().get(\"/get\") assert response.status_code == 200", "pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url): \"\"\" Asserts, that echo api is used as the", "pylint: disable=unused-import from testsuite.echoed_request import EchoedRequest pytestmark = [ pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")]", "import TESTED_VERSION, rawobj # noqa # pylint: disable=unused-import from testsuite.echoed_request import EchoedRequest pytestmark", "TESTED_VERSION, rawobj # noqa # pylint: disable=unused-import from testsuite.echoed_request import EchoedRequest pytestmark =", "= [ pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url): \"\"\" Asserts, that echo", "and asserts, that the routing policy is active and the requests is routed", "response = api_client().get(\"/get\") assert response.status_code == 200 echoed_request = EchoedRequest.create(response) assert echoed_request.headers[\"Host\"] ==", "all the requests to a correct backend. \"\"\" from urllib.parse import urlparse import", "[ pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url): \"\"\" Asserts, that echo api", "private_base_url): \"\"\" Set the routing policy to route all requests to httpbin. (Using", "private_base_url): \"\"\" Sends a request and asserts, that the routing policy is active", "condition, it should be loaded correctly and should route all the requests to", "{}, }]})) return service def test_routing_policy_without_header(api_client, private_base_url): \"\"\" Sends a request and asserts,", "is set with an empty condition, it should be loaded correctly and should", "that echo api is used as the default backend \"\"\" return rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\")", "pytest from packaging.version import Version # noqa # pylint: disable=unused-import from testsuite import", "packaging.version import Version # noqa # pylint: disable=unused-import from testsuite import TESTED_VERSION, rawobj", "rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\") def service(service, private_base_url): \"\"\" Set the routing policy to route all", "service def test_routing_policy_without_header(api_client, private_base_url): \"\"\" Sends a request and asserts, that the routing", "Asserts, that echo api is used as the default backend \"\"\" return rawobj.Proxy(private_base_url(\"echo_api\"))", "proxy = service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig( \"routing\", { \"rules\": [ { \"url\": private_base_url(\"httpbin\"), \"condition\":", "catch all rule) \"\"\" proxy = service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig( \"routing\", { \"rules\": [", "should act as a catch all rule) \"\"\" proxy = service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig(", "= api_client().get(\"/get\") assert response.status_code == 200 echoed_request = EchoedRequest.create(response) assert echoed_request.headers[\"Host\"] == parsed_url.hostname", "# noqa # pylint: disable=unused-import from testsuite import TESTED_VERSION, rawobj # noqa #", "service(service, private_base_url): \"\"\" Set the routing policy to route all requests to httpbin.", "rawobj.PolicyConfig( \"routing\", { \"rules\": [ { \"url\": private_base_url(\"httpbin\"), \"condition\": {}, }]})) return service", "\"\"\" from urllib.parse import urlparse import pytest from packaging.version import Version # noqa", "loaded correctly and should route all the requests to a correct backend. \"\"\"", "requests to a correct backend. \"\"\" from urllib.parse import urlparse import pytest from", "# pylint: disable=unused-import from testsuite.echoed_request import EchoedRequest pytestmark = [ pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"),", "the correct backend (httpbin) \"\"\" parsed_url = urlparse(private_base_url(\"httpbin\")) response = api_client().get(\"/get\") assert response.status_code", "# noqa # pylint: disable=unused-import from testsuite.echoed_request import EchoedRequest pytestmark = [ pytest.mark.skipif(\"TESTED_VERSION", "route all the requests to a correct backend. \"\"\" from urllib.parse import urlparse", "echo api is used as the default backend \"\"\" return rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\") def", "def test_routing_policy_without_header(api_client, private_base_url): \"\"\" Sends a request and asserts, that the routing policy", "Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url): \"\"\" Asserts, that echo api is used as", "= service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig( \"routing\", { \"rules\": [ { \"url\": private_base_url(\"httpbin\"), \"condition\": {},", "@pytest.fixture(scope=\"module\") def service(service, private_base_url): \"\"\" Set the routing policy to route all requests", "the logic that an empty condition should act as a catch all rule)", "to a correct backend. \"\"\" from urllib.parse import urlparse import pytest from packaging.version", "is active and the requests is routed to the correct backend (httpbin) \"\"\"", "@pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url): \"\"\" Asserts, that echo api is used as the default", "route all requests to httpbin. (Using the logic that an empty condition should", "routing policy is set with an empty condition, it should be loaded correctly", "correct backend. \"\"\" from urllib.parse import urlparse import pytest from packaging.version import Version", "pylint: disable=unused-import from testsuite import TESTED_VERSION, rawobj # noqa # pylint: disable=unused-import from", "return service def test_routing_policy_without_header(api_client, private_base_url): \"\"\" Sends a request and asserts, that the", "def service(service, private_base_url): \"\"\" Set the routing policy to route all requests to", "routing policy is active and the requests is routed to the correct backend", "policy is active and the requests is routed to the correct backend (httpbin)", "policy is set with an empty condition, it should be loaded correctly and", "service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig( \"routing\", { \"rules\": [ { \"url\": private_base_url(\"httpbin\"), \"condition\": {}, }]}))", "is used as the default backend \"\"\" return rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\") def service(service, private_base_url):", "rawobj # noqa # pylint: disable=unused-import from testsuite.echoed_request import EchoedRequest pytestmark = [", "disable=unused-import from testsuite.echoed_request import EchoedRequest pytestmark = [ pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\")" ]
[ "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "writing, software # distributed under the License is distributed on an \"AS IS\"", "[ '%s.create' % self.resource_name, '%s.update' % self.resource_name, '%s.delete' % self.resource_name, ] @staticmethod def", "or # implied. # See the License for the specific language governing permissions", "OR CONDITIONS OF ANY KIND, either express or # implied. # See the", "Unless required by applicable law or agreed to in writing, software # distributed", "in conf.notification_topics] def process_notification(self, message): name = message['event_type'].replace(self.resource_name, 'cluster') project_id = message['payload']['project_id'] user_id", "return [ '%s.create' % self.resource_name, '%s.update' % self.resource_name, '%s.delete' % self.resource_name, ] @staticmethod", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "# See the License for the specific language governing permissions and # limitations", "'%s.update' % self.resource_name, '%s.delete' % self.resource_name, ] @staticmethod def get_targets(conf): \"\"\"Return a sequence", "Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the \"License\");", "License. # You may obtain a copy of the License at # #", "= message['payload']['project_id'] user_id = message['_context_user_id'] yield sample.Sample.from_notification( name=name, type=sample.TYPE_DELTA, unit='cluster', volume=1, resource_id=message['payload']['cluster_id'], user_id=user_id,", "self.resource_name, '%s.update' % self.resource_name, '%s.delete' % self.resource_name, ] @staticmethod def get_targets(conf): \"\"\"Return a", "def process_notification(self, message): name = message['event_type'].replace(self.resource_name, 'cluster') project_id = message['payload']['project_id'] user_id = message['_context_user_id']", "% self.resource_name, '%s.delete' % self.resource_name, ] @staticmethod def get_targets(conf): \"\"\"Return a sequence of", "\"\"\" return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for topic in conf.notification_topics] def process_notification(self, message): name =", "law or agreed to in writing, software # distributed under the License is", "2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the", "def get_targets(conf): \"\"\"Return a sequence of oslo.messaging.Target It is defining the exchange and", "the License for the specific language governing permissions and # limitations under the", "from ceilometer import plugin from ceilometer import sample OPTS = [ cfg.StrOpt('sahara_control_exchange', default='sahara',", "name = message['event_type'].replace(self.resource_name, 'cluster') project_id = message['payload']['project_id'] user_id = message['_context_user_id'] yield sample.Sample.from_notification( name=name,", "compliance with the License. # You may obtain a copy of the License", "the License. from oslo.config import cfg import oslo.messaging from ceilometer import plugin from", "message['event_type'].replace(self.resource_name, 'cluster') project_id = message['payload']['project_id'] user_id = message['_context_user_id'] yield sample.Sample.from_notification( name=name, type=sample.TYPE_DELTA, unit='cluster',", "cfg import oslo.messaging from ceilometer import plugin from ceilometer import sample OPTS =", "import oslo.messaging from ceilometer import plugin from ceilometer import sample OPTS = [", "user_id = message['_context_user_id'] yield sample.Sample.from_notification( name=name, type=sample.TYPE_DELTA, unit='cluster', volume=1, resource_id=message['payload']['cluster_id'], user_id=user_id, project_id=project_id, message=message)", "ceilometer import sample OPTS = [ cfg.StrOpt('sahara_control_exchange', default='sahara', help=\"Exchange name for Data Processing", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "oslo.messaging from ceilometer import plugin from ceilometer import sample OPTS = [ cfg.StrOpt('sahara_control_exchange',", "this file except in compliance with the License. # You may obtain a", "'%s.cluster' % SERVICE @property def event_types(self): return [ '%s.create' % self.resource_name, '%s.update' %", "Data Processing notifications.\"), ] cfg.CONF.register_opts(OPTS) SERVICE = 'sahara' class DataProcessing(plugin.NotificationBase): resource_name = '%s.cluster'", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "you may not use this file except in compliance with the License. #", "@staticmethod def get_targets(conf): \"\"\"Return a sequence of oslo.messaging.Target It is defining the exchange", "self.resource_name, '%s.delete' % self.resource_name, ] @staticmethod def get_targets(conf): \"\"\"Return a sequence of oslo.messaging.Target", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "sequence of oslo.messaging.Target It is defining the exchange and topics to be connected", "topics to be connected for this plugin. \"\"\" return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for topic", "governing permissions and # limitations under the License. from oslo.config import cfg import", "ANY KIND, either express or # implied. # See the License for the", "% SERVICE @property def event_types(self): return [ '%s.create' % self.resource_name, '%s.update' % self.resource_name,", "\"\"\"Return a sequence of oslo.messaging.Target It is defining the exchange and topics to", "exchange=conf.sahara_control_exchange) for topic in conf.notification_topics] def process_notification(self, message): name = message['event_type'].replace(self.resource_name, 'cluster') project_id", "event_types(self): return [ '%s.create' % self.resource_name, '%s.update' % self.resource_name, '%s.delete' % self.resource_name, ]", "import plugin from ceilometer import sample OPTS = [ cfg.StrOpt('sahara_control_exchange', default='sahara', help=\"Exchange name", "def event_types(self): return [ '%s.create' % self.resource_name, '%s.update' % self.resource_name, '%s.delete' % self.resource_name,", "defining the exchange and topics to be connected for this plugin. \"\"\" return", "get_targets(conf): \"\"\"Return a sequence of oslo.messaging.Target It is defining the exchange and topics", "default='sahara', help=\"Exchange name for Data Processing notifications.\"), ] cfg.CONF.register_opts(OPTS) SERVICE = 'sahara' class", "in compliance with the License. # You may obtain a copy of the", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "the exchange and topics to be connected for this plugin. \"\"\" return [oslo.messaging.Target(topic=topic,", "oslo.messaging.Target It is defining the exchange and topics to be connected for this", "use this file except in compliance with the License. # You may obtain", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "plugin. \"\"\" return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for topic in conf.notification_topics] def process_notification(self, message): name", "not use this file except in compliance with the License. # You may", "<gh_stars>0 # Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache", "of oslo.messaging.Target It is defining the exchange and topics to be connected for", "See the License for the specific language governing permissions and # limitations under", "KIND, either express or # implied. # See the License for the specific", "License, Version 2.0 (the \"License\"); # you may not use this file except", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "the specific language governing permissions and # limitations under the License. from oslo.config", "# limitations under the License. from oslo.config import cfg import oslo.messaging from ceilometer", "conf.notification_topics] def process_notification(self, message): name = message['event_type'].replace(self.resource_name, 'cluster') project_id = message['payload']['project_id'] user_id =", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "import sample OPTS = [ cfg.StrOpt('sahara_control_exchange', default='sahara', help=\"Exchange name for Data Processing notifications.\"),", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "plugin from ceilometer import sample OPTS = [ cfg.StrOpt('sahara_control_exchange', default='sahara', help=\"Exchange name for", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "@property def event_types(self): return [ '%s.create' % self.resource_name, '%s.update' % self.resource_name, '%s.delete' %", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or #", "Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version", "= [ cfg.StrOpt('sahara_control_exchange', default='sahara', help=\"Exchange name for Data Processing notifications.\"), ] cfg.CONF.register_opts(OPTS) SERVICE", "name for Data Processing notifications.\"), ] cfg.CONF.register_opts(OPTS) SERVICE = 'sahara' class DataProcessing(plugin.NotificationBase): resource_name", "self.resource_name, ] @staticmethod def get_targets(conf): \"\"\"Return a sequence of oslo.messaging.Target It is defining", "2.0 (the \"License\"); # you may not use this file except in compliance", "permissions and # limitations under the License. from oslo.config import cfg import oslo.messaging", "# you may not use this file except in compliance with the License.", "topic in conf.notification_topics] def process_notification(self, message): name = message['event_type'].replace(self.resource_name, 'cluster') project_id = message['payload']['project_id']", "[ cfg.StrOpt('sahara_control_exchange', default='sahara', help=\"Exchange name for Data Processing notifications.\"), ] cfg.CONF.register_opts(OPTS) SERVICE =", "agreed to in writing, software # distributed under the License is distributed on", "from oslo.config import cfg import oslo.messaging from ceilometer import plugin from ceilometer import", "OPTS = [ cfg.StrOpt('sahara_control_exchange', default='sahara', help=\"Exchange name for Data Processing notifications.\"), ] cfg.CONF.register_opts(OPTS)", "It is defining the exchange and topics to be connected for this plugin.", "(the \"License\"); # you may not use this file except in compliance with", "for topic in conf.notification_topics] def process_notification(self, message): name = message['event_type'].replace(self.resource_name, 'cluster') project_id =", "specific language governing permissions and # limitations under the License. from oslo.config import", "project_id = message['payload']['project_id'] user_id = message['_context_user_id'] yield sample.Sample.from_notification( name=name, type=sample.TYPE_DELTA, unit='cluster', volume=1, resource_id=message['payload']['cluster_id'],", "notifications.\"), ] cfg.CONF.register_opts(OPTS) SERVICE = 'sahara' class DataProcessing(plugin.NotificationBase): resource_name = '%s.cluster' % SERVICE", "DataProcessing(plugin.NotificationBase): resource_name = '%s.cluster' % SERVICE @property def event_types(self): return [ '%s.create' %", "# # Unless required by applicable law or agreed to in writing, software", "exchange and topics to be connected for this plugin. \"\"\" return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange)", "this plugin. \"\"\" return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for topic in conf.notification_topics] def process_notification(self, message):", "return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for topic in conf.notification_topics] def process_notification(self, message): name = message['event_type'].replace(self.resource_name,", "Version 2.0 (the \"License\"); # you may not use this file except in", "# Unless required by applicable law or agreed to in writing, software #", "for the specific language governing permissions and # limitations under the License. from", "except in compliance with the License. # You may obtain a copy of", "express or # implied. # See the License for the specific language governing", "cfg.CONF.register_opts(OPTS) SERVICE = 'sahara' class DataProcessing(plugin.NotificationBase): resource_name = '%s.cluster' % SERVICE @property def", "by applicable law or agreed to in writing, software # distributed under the", "'%s.create' % self.resource_name, '%s.update' % self.resource_name, '%s.delete' % self.resource_name, ] @staticmethod def get_targets(conf):", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "for this plugin. \"\"\" return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for topic in conf.notification_topics] def process_notification(self,", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "Inc. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "% self.resource_name, ] @staticmethod def get_targets(conf): \"\"\"Return a sequence of oslo.messaging.Target It is", "] @staticmethod def get_targets(conf): \"\"\"Return a sequence of oslo.messaging.Target It is defining the", "be connected for this plugin. \"\"\" return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for topic in conf.notification_topics]", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "'%s.delete' % self.resource_name, ] @staticmethod def get_targets(conf): \"\"\"Return a sequence of oslo.messaging.Target It", "'cluster') project_id = message['payload']['project_id'] user_id = message['_context_user_id'] yield sample.Sample.from_notification( name=name, type=sample.TYPE_DELTA, unit='cluster', volume=1,", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "resource_name = '%s.cluster' % SERVICE @property def event_types(self): return [ '%s.create' % self.resource_name,", "message): name = message['event_type'].replace(self.resource_name, 'cluster') project_id = message['payload']['project_id'] user_id = message['_context_user_id'] yield sample.Sample.from_notification(", "file except in compliance with the License. # You may obtain a copy", "connected for this plugin. \"\"\" return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for topic in conf.notification_topics] def", "= message['event_type'].replace(self.resource_name, 'cluster') project_id = message['payload']['project_id'] user_id = message['_context_user_id'] yield sample.Sample.from_notification( name=name, type=sample.TYPE_DELTA,", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "License for the specific language governing permissions and # limitations under the License.", "CONDITIONS OF ANY KIND, either express or # implied. # See the License", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "OF ANY KIND, either express or # implied. # See the License for", "a sequence of oslo.messaging.Target It is defining the exchange and topics to be", "for Data Processing notifications.\"), ] cfg.CONF.register_opts(OPTS) SERVICE = 'sahara' class DataProcessing(plugin.NotificationBase): resource_name =", "either express or # implied. # See the License for the specific language", "SERVICE @property def event_types(self): return [ '%s.create' % self.resource_name, '%s.update' % self.resource_name, '%s.delete'", "[oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for topic in conf.notification_topics] def process_notification(self, message): name = message['event_type'].replace(self.resource_name, 'cluster')", "the License. # You may obtain a copy of the License at #", "to in writing, software # distributed under the License is distributed on an", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "process_notification(self, message): name = message['event_type'].replace(self.resource_name, 'cluster') project_id = message['payload']['project_id'] user_id = message['_context_user_id'] yield", "and # limitations under the License. from oslo.config import cfg import oslo.messaging from", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "implied. # See the License for the specific language governing permissions and #", "cfg.StrOpt('sahara_control_exchange', default='sahara', help=\"Exchange name for Data Processing notifications.\"), ] cfg.CONF.register_opts(OPTS) SERVICE = 'sahara'", "\"License\"); # you may not use this file except in compliance with the", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. #", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "required by applicable law or agreed to in writing, software # distributed under", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied.", "Processing notifications.\"), ] cfg.CONF.register_opts(OPTS) SERVICE = 'sahara' class DataProcessing(plugin.NotificationBase): resource_name = '%s.cluster' %", "language governing permissions and # limitations under the License. from oslo.config import cfg", "'sahara' class DataProcessing(plugin.NotificationBase): resource_name = '%s.cluster' % SERVICE @property def event_types(self): return [", "= 'sahara' class DataProcessing(plugin.NotificationBase): resource_name = '%s.cluster' % SERVICE @property def event_types(self): return", "is defining the exchange and topics to be connected for this plugin. \"\"\"", "applicable law or agreed to in writing, software # distributed under the License", "limitations under the License. from oslo.config import cfg import oslo.messaging from ceilometer import", "# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License,", "SERVICE = 'sahara' class DataProcessing(plugin.NotificationBase): resource_name = '%s.cluster' % SERVICE @property def event_types(self):", "(c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0", "import cfg import oslo.messaging from ceilometer import plugin from ceilometer import sample OPTS", "ceilometer import plugin from ceilometer import sample OPTS = [ cfg.StrOpt('sahara_control_exchange', default='sahara', help=\"Exchange", "= '%s.cluster' % SERVICE @property def event_types(self): return [ '%s.create' % self.resource_name, '%s.update'", "% self.resource_name, '%s.update' % self.resource_name, '%s.delete' % self.resource_name, ] @staticmethod def get_targets(conf): \"\"\"Return", "or agreed to in writing, software # distributed under the License is distributed", "class DataProcessing(plugin.NotificationBase): resource_name = '%s.cluster' % SERVICE @property def event_types(self): return [ '%s.create'", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See", "and topics to be connected for this plugin. \"\"\" return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for", "License. from oslo.config import cfg import oslo.messaging from ceilometer import plugin from ceilometer", "to be connected for this plugin. \"\"\" return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for topic in", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "under the License. from oslo.config import cfg import oslo.messaging from ceilometer import plugin", "oslo.config import cfg import oslo.messaging from ceilometer import plugin from ceilometer import sample", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "] cfg.CONF.register_opts(OPTS) SERVICE = 'sahara' class DataProcessing(plugin.NotificationBase): resource_name = '%s.cluster' % SERVICE @property", "sample OPTS = [ cfg.StrOpt('sahara_control_exchange', default='sahara', help=\"Exchange name for Data Processing notifications.\"), ]", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "from ceilometer import sample OPTS = [ cfg.StrOpt('sahara_control_exchange', default='sahara', help=\"Exchange name for Data", "help=\"Exchange name for Data Processing notifications.\"), ] cfg.CONF.register_opts(OPTS) SERVICE = 'sahara' class DataProcessing(plugin.NotificationBase):", "# implied. # See the License for the specific language governing permissions and", "with the License. # You may obtain a copy of the License at", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "in writing, software # distributed under the License is distributed on an \"AS", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "message['payload']['project_id'] user_id = message['_context_user_id'] yield sample.Sample.from_notification( name=name, type=sample.TYPE_DELTA, unit='cluster', volume=1, resource_id=message['payload']['cluster_id'], user_id=user_id, project_id=project_id," ]
[ "Select from Data.parameters import Data from get_dir import pwd from reuse_func import GetData", "def __init__(self,driver): self.driver = driver self.filename ='' def test_download_csv(self): self.data = GetData() self.p", "import Data from get_dir import pwd from reuse_func import GetData class All_records_download(): def", "='' def test_download_csv(self): self.data = GetData() self.p = pwd() self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver) colltype =", "self.data.page_loading(self.driver) colltype = Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text(' Overall ') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename = self.p.get_download_dir()", "All_records_download(): def __init__(self,driver): self.driver = driver self.filename ='' def test_download_csv(self): self.data = GetData()", "pwd from reuse_func import GetData class All_records_download(): def __init__(self,driver): self.driver = driver self.filename", "self.driver = driver self.filename ='' def test_download_csv(self): self.data = GetData() self.p = pwd()", "test_download_csv(self): self.data = GetData() self.p = pwd() self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver) colltype = Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text('", "<gh_stars>0 import os import time from selenium.webdriver.support.select import Select from Data.parameters import Data", "class All_records_download(): def __init__(self,driver): self.driver = driver self.filename ='' def test_download_csv(self): self.data =", "def test_download_csv(self): self.data = GetData() self.p = pwd() self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver) colltype = Select(self.driver.find_element_by_name('collection_type'))", "from selenium.webdriver.support.select import Select from Data.parameters import Data from get_dir import pwd from", "from Data.parameters import Data from get_dir import pwd from reuse_func import GetData class", "__init__(self,driver): self.driver = driver self.filename ='' def test_download_csv(self): self.data = GetData() self.p =", "driver self.filename ='' def test_download_csv(self): self.data = GetData() self.p = pwd() self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver)", "pwd() self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver) colltype = Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text(' Overall ') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename", "import time from selenium.webdriver.support.select import Select from Data.parameters import Data from get_dir import", "self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename = self.p.get_download_dir() + '/collectionType_all_data.csv' time.sleep(2) file = os.path.isfile(self.filename) os.remove(self.filename) return", "= GetData() self.p = pwd() self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver) colltype = Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text(' Overall ')", "= Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text(' Overall ') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename = self.p.get_download_dir() + '/collectionType_all_data.csv'", "self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename = self.p.get_download_dir() + '/collectionType_all_data.csv' time.sleep(2) file = os.path.isfile(self.filename) os.remove(self.filename)", "Overall ') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename = self.p.get_download_dir() + '/collectionType_all_data.csv' time.sleep(2) file =", "from get_dir import pwd from reuse_func import GetData class All_records_download(): def __init__(self,driver): self.driver", "colltype.select_by_visible_text(' Overall ') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename = self.p.get_download_dir() + '/collectionType_all_data.csv' time.sleep(2) file", "self.data = GetData() self.p = pwd() self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver) colltype = Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text(' Overall", "os import time from selenium.webdriver.support.select import Select from Data.parameters import Data from get_dir", "reuse_func import GetData class All_records_download(): def __init__(self,driver): self.driver = driver self.filename ='' def", "Data from get_dir import pwd from reuse_func import GetData class All_records_download(): def __init__(self,driver):", "from reuse_func import GetData class All_records_download(): def __init__(self,driver): self.driver = driver self.filename =''", "self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver) colltype = Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text(' Overall ') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename =", "colltype = Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text(' Overall ') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename = self.p.get_download_dir() +", "Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text(' Overall ') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename = self.p.get_download_dir() + '/collectionType_all_data.csv' time.sleep(2)", "GetData() self.p = pwd() self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver) colltype = Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text(' Overall ') self.data.page_loading(self.driver)", "time from selenium.webdriver.support.select import Select from Data.parameters import Data from get_dir import pwd", "import GetData class All_records_download(): def __init__(self,driver): self.driver = driver self.filename ='' def test_download_csv(self):", "') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename = self.p.get_download_dir() + '/collectionType_all_data.csv' time.sleep(2) file = os.path.isfile(self.filename)", "self.filename ='' def test_download_csv(self): self.data = GetData() self.p = pwd() self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver) colltype", "import pwd from reuse_func import GetData class All_records_download(): def __init__(self,driver): self.driver = driver", "Data.parameters import Data from get_dir import pwd from reuse_func import GetData class All_records_download():", "import os import time from selenium.webdriver.support.select import Select from Data.parameters import Data from", "get_dir import pwd from reuse_func import GetData class All_records_download(): def __init__(self,driver): self.driver =", "GetData class All_records_download(): def __init__(self,driver): self.driver = driver self.filename ='' def test_download_csv(self): self.data", "time.sleep(4) self.filename = self.p.get_download_dir() + '/collectionType_all_data.csv' time.sleep(2) file = os.path.isfile(self.filename) os.remove(self.filename) return file", "import Select from Data.parameters import Data from get_dir import pwd from reuse_func import", "self.p = pwd() self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver) colltype = Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text(' Overall ') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click()", "= pwd() self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver) colltype = Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text(' Overall ') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4)", "= driver self.filename ='' def test_download_csv(self): self.data = GetData() self.p = pwd() self.driver.find_element_by_xpath(Data.hyper_link).click()", "selenium.webdriver.support.select import Select from Data.parameters import Data from get_dir import pwd from reuse_func" ]
[ "= compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path), secure=is_secure,", "--enable-logging=stderr --v=1 2>&1 | grep key_storage_ # Chromium supports a flag: --password-store=<basic|gnome|kwallet> so", "e: logger.warning(f'exception while obtaining NetworkWallet: {e}') return default_wallet def _get_kwallet_password(browser_keyring_name, logger): logger.debug('using kwallet-query", "= self.cursor + num_bytes if end > len(self._data): raise ParserError('reached end of input')", "state file at \"{path}\"') with open(path, encoding='utf8') as f: data = json.load(f) try:", "extract cookies from {browser_name} without sqlite3 support. ' 'Please use a python interpreter", "tmpdir: cursor = None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.execute('SELECT host, name, value,", "UTF-8 decoding failed', only_once=True) return record_size p.skip_to(record_size, 'space at the end of the", "data, logger): self._data = data self.cursor = 0 self._logger = logger def read_bytes(self,", "[row[1].decode('utf-8') for row in table_info] def _find_most_recently_used_file(root, filename, logger): # if there are", "{len(jar)} cookies from safari') return jar class ParserError(Exception): pass class DataParser: def __init__(self,", "elif 'KDE_FULL_SESSION' in env: return _LinuxDesktopEnvironment.KDE return _LinuxDesktopEnvironment.OTHER def _choose_linux_keyring(logger): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend", "tries to read the value (which kwallet returns \"\") whereas kwallet-query # checks", "discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) return record_size def parse_safari_cookies(data, jar=None, logger=YDLLogger()): \"\"\" References:", "search_root = os.path.join(config['browser_dir'], profile) else: logger.error(f'{browser_name} does not support profiles') search_root = config['browser_dir']", "is to generate a random password and store # it, but that doesn't", "= env.get('XDG_CURRENT_DESKTOP', None) desktop_session = env.get('DESKTOP_SESSION', None) if xdg_current_desktop is not None: xdg_current_desktop", "= ydl def debug(self, message): if self._ydl: self._ydl.write_debug(message) def info(self, message): if self._ydl:", "consult ' 'the kwallet-query man page for details') return b'' else: if stdout.lower().startswith(b'failed", "Using empty string instead') # this sometimes occurs in KDE because chrome does", "'firefox': return _extract_firefox_cookies(profile, logger) elif browser_name == 'safari': return _extract_safari_cookies(profile, logger) elif browser_name", "self._ydl: self._ydl.write_debug(message) def info(self, message): if self._ydl: self._ydl.to_screen(f'[Cookies] {message}') def warning(self, message, only_once=False):", "1 if self._v10_key is None: self._logger.warning('cannot decrypt v10 cookies: no key found', only_once=True)", "if cursor is not None: cursor.connection.close() def _firefox_browser_dir(): if sys.platform in ('linux', 'linux2'):", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return _decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8') def _extract_safari_cookies(profile, logger): if profile is not None: logger.error('safari", "0: raise ParserError(f'invalid read of {num_bytes} bytes') end = self.cursor + num_bytes if", "_parse_safari_cookies_header(data, logger) p = DataParser(data[body_start:], logger) for page_size in page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger)", "parse_safari_cookies(data, jar=None, logger=YDLLogger()): \"\"\" References: - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc - this data appears to be", "OS protected key (keyring) and more key derivation iterations than linux - not", "https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init()) as con: col = secretstorage.get_default_collection(con) for item in col.get_all_items(): if", "'vivaldi'} SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'} class YDLLogger: def __init__(self, ydl=None): self._ydl", "lambda _: None return printer def load_cookies(cookie_file, browser_specification, ydl): cookie_jars = [] if", "b'v10': self._cookie_counts['v10'] += 1 return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) elif version == b'v11': self._cookie_counts['v11']", "key which is encrypted with DPAPI - not v10: encrypted with DPAPI Sources:", "decrypt cookie (AES-GCM) because the MAC check failed. Possibly the key is wrong?',", "*, keyring=None): if browser_name == 'firefox': return _extract_firefox_cookies(profile, logger) elif browser_name == 'safari':", "return default_wallet def _get_kwallet_password(browser_keyring_name, logger): logger.debug('using kwallet-query to obtain password from kwallet') if", "pPromptStruct: information about prompts to display 0, # dwFlags ctypes.byref(blob_out) # pDataOut )", "return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) def pbkdf2_sha1(password, salt, iterations, key_length): return pbkdf2_hmac('sha1', password, salt, iterations,", "proc = Popen( ['security', 'find-generic-password', '-w', # write password to stdout '-a', browser_keyring_name,", "// 8 # boringssl # EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length = 16 raw_ciphertext = ciphertext nonce", "are either v10 or not v10 - v10: AES-CBC encrypted with an OS", "records') record_length = _parse_safari_cookies_record(data[record_offset:], jar, logger) p.read_bytes(record_length) p.skip_to_end('space in between pages') def _parse_safari_cookies_record(data,", "self._v10_key = _get_windows_v10_key(browser_root, logger) self._cookie_counts = {'v10': 0, 'other': 0} @property def cookie_counts(self):", "'opera'), 'vivaldi': os.path.join(config, 'vivaldi'), }[browser_name] elif sys.platform == 'win32': appdata_local = os.path.expandvars('%LOCALAPPDATA%') appdata_roaming", "p.skip_to(record_offset, 'space between records') record_length = _parse_safari_cookies_record(data[record_offset:], jar, logger) p.read_bytes(record_length) p.skip_to_end('space in between", "def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, logger): try: plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce)", "return b'' else: if stdout.lower().startswith(b'failed to read'): logger.debug('failed to read password from kwallet.", "else 'Chrome', }[browser_name] browsers_without_profiles = {'opera'} return { 'browser_dir': browser_dir, 'keyring_name': keyring_name, 'supports_profiles':", "(AES-CBC) because UTF-8 decoding failed. Possibly the key is wrong?', only_once=True) return None", "the same way as KWallet, # using `dbus-monitor` during startup, it can be", "in KDE: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" keyring_name = { 'brave': 'Brave', 'chrome': 'Chrome',", "raw_ciphertext[-authentication_tag_length:] return _decrypt_aes_gcm(ciphertext, self._v10_key, nonce, authentication_tag, self._logger) else: self._cookie_counts['other'] += 1 # any", "not find firefox cookies database in {search_root}') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') with tempfile.TemporaryDirectory(prefix='yt_dlp')", "which were stored as plaintext # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return encrypted_value class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self,", "ydl def debug(self, message): if self._ydl: self._ydl.write_debug(message) def info(self, message): if self._ydl: self._ydl.to_screen(f'[Cookies]", "in column_names else 'secure' cursor.execute(f'SELECT host_key, name, value, encrypted_value, path, expires_utc, {secure_column} FROM", "port_specified=False, domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False, comment=None, comment_url=None, rest={}) class", "+= 1 progress_bar.print(f'Searching for \"{filename}\": {i: 6d} files searched') if file == filename:", "'service' stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if stdout[-1:] == b'\\n': stdout =", "expected_value, message): value = self.read_bytes(len(expected_value)) if value != expected_value: raise ParserError(f'unexpected value: {value}", "--password-store=<basic|gnome|kwallet> so the automatic detection # will not be sufficient in all cases.", "value, encrypted_value, path, expires_utc, {secure_column} FROM cookies') jar = YoutubeDLCookieJar() failed_cookies = 0", "elif version == b'v11': self._cookie_counts['v11'] += 1 if self._v11_key is None: self._logger.warning('cannot decrypt", "ydl): cookie_jars = [] if browser_specification is not None: browser_name, profile, keyring =", "None assert False, f'Unknown keyring {keyring}' def _get_mac_keyring_password(browser_keyring_name, logger): logger.debug('using find-generic-password to obtain", "self._ydl.params.get('logger'): return file = self._ydl._out_files['error'] try: if not file.isatty(): return except BaseException: return", "stdout, stderr = proc.communicate_or_kill() if stdout[-1:] == b'\\n': stdout = stdout[:-1] return stdout", "domain_offset = p.read_uint() name_offset = p.read_uint() path_offset = p.read_uint() value_offset = p.read_uint() p.skip(8,", "if self._ydl: self._ydl.report_warning(message, only_once) def error(self, message): if self._ydl: self._ydl.report_error(message) def progress_bar(self): \"\"\"Return", "raise ParserError(f'invalid skip of {num_bytes} bytes') def skip_to(self, offset, description='unknown'): self.skip(offset - self.cursor,", "= unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector)) try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie", "'edge', 'opera', 'vivaldi'} SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'} class YDLLogger: def __init__(self,", "except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-CBC) because UTF-8 decoding failed. Possibly the", "description) def skip_to_end(self, description='unknown'): self.skip_to(len(self._data), description) def _mac_absolute_time_to_posix(timestamp): return int((datetime(2001, 1, 1, 0,", "def progress_bar(self): \"\"\"Return a context manager with a print method. (Optional)\"\"\" # Do", "browser_dir = { 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(appdata, 'Google/Chrome'), 'chromium': os.path.join(appdata, 'Chromium'), 'edge':", "Popen([ 'dbus-send', '--session', '--print-reply=literal', '--dest=org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet.networkWallet' ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr =", "logger): try: plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce) except ValueError: logger.warning('failed to decrypt", "_decrypt_windows_dpapi(ciphertext, logger): \"\"\" References: - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\" from ctypes.wintypes import DWORD class DATA_BLOB(ctypes.Structure):", "files: i += 1 progress_bar.print(f'Searching for \"{filename}\": {i: 6d} files searched') if file", "len(table) for i, line in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') is_encrypted, cookie", "'kdewallet' try: proc = Popen([ 'dbus-send', '--session', '--print-reply=literal', '--dest=org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet.networkWallet' ], stdout=subprocess.PIPE,", "with return code {proc.returncode}. Please consult ' 'the kwallet-query man page for details')", "- v11: AES-CBC encrypted with an OS protected key (keyring) - v11 keys", "ignore_expires=True) cookie_jars.append(jar) return _merge_cookie_jars(cookie_jars) def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *, keyring=None): if browser_name ==", "profile is not None and _is_path(profile): profile = os.path.expanduser(profile) return browser_name, profile, keyring", "i, line in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') is_encrypted, cookie = _process_chrome_cookie(decryptor,", "os.path.isfile(cookies_path): logger.debug('Trying secondary cookie location') cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): raise FileNotFoundError('could", "skip of {num_bytes} bytes') def skip_to(self, offset, description='unknown'): self.skip(offset - self.cursor, description) def", "\"type=method_return\" keyring_name = { 'brave': 'Brave', 'chrome': 'Chrome', 'chromium': 'Chromium', 'edge': 'Microsoft Edge'", "classes') @property def cookie_counts(self): raise NotImplementedError('Must be implemented by sub classes') def get_cookie_decryptor(browser_root,", "keyring_name = { 'brave': 'Brave', 'chrome': 'Chrome', 'chromium': 'Chromium', 'edge': 'Microsoft Edge' if", "[p.read_uint() for _ in range(number_of_cookies)] if number_of_cookies == 0: logger.debug(f'a cookies page of", "else: raise NotImplementedError(f'Chrome cookie decryption is not supported on this platform: {sys.platform}') class", "b'v10': self._cookie_counts['v10'] += 1 if self._v10_key is None: self._logger.warning('cannot decrypt v10 cookies: no", "None: search_root = config['browser_dir'] elif _is_path(profile): search_root = profile config['browser_dir'] = os.path.dirname(profile) if", "'is_secure' in column_names else 'secure' cursor.execute(f'SELECT host_key, name, value, encrypted_value, path, expires_utc, {secure_column}", "\"interface='org.kde.KWallet'\" \"type=method_return\" # while starting chrome. # this may be a bug as", "1 if self._v11_key is None: self._logger.warning('cannot decrypt v11 cookies: no key found', only_once=True)", "self._ydl: self._ydl.to_screen(f'[Cookies] {message}') def warning(self, message, only_once=False): if self._ydl: self._ydl.report_warning(message, only_once) def error(self,", "= p.read_uint(big_endian=True) page_sizes = [p.read_uint(big_endian=True) for _ in range(number_of_pages)] return page_sizes, p.cursor def", "get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger, keyring=keyring) with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try: cursor", "raise FileNotFoundError(f'could not find firefox cookies database in {search_root}') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"')", "' 'Please use a python interpreter compiled with sqlite3 support') return YoutubeDLCookieJar() if", "_decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) def pbkdf2_sha1(password, salt, iterations, key_length): return pbkdf2_hmac('sha1', password, salt, iterations, key_length)", "KWALLET = auto() GNOMEKEYRING = auto() BASICTEXT = auto() SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys() def", "else '<I' return struct.unpack(data_format, self.read_bytes(4))[0] def read_double(self, big_endian=False): data_format = '>d' if big_endian", "'temporary.sqlite') shutil.copy(database_path, database_copy_path) conn = sqlite3.connect(database_copy_path) return conn.cursor() def _get_column_names(cursor, table_name): table_info =", "= None if password is None else self.derive_key(password) self._cookie_counts = {'v10': 0, 'v11':", "message): if self._ydl: self._ydl.to_screen(f'[Cookies] {message}') def warning(self, message, only_once=False): if self._ydl: self._ydl.report_warning(message, only_once)", "your distribution') return b'' network_wallet = _get_kwallet_network_wallet(logger) try: proc = Popen([ 'kwallet-query', '--read-password',", "be implemented by sub classes') def get_cookie_decryptor(browser_root, browser_keyring_name, logger, *, keyring=None): if sys.platform", "as con: col = secretstorage.get_default_collection(con) for item in col.get_all_items(): if item.get_label() == f'{browser_keyring_name}", "is part of the standard library, it is possible to compile python without", "< 0: raise ParserError(f'invalid read of {num_bytes} bytes') end = self.cursor + num_bytes", "os.access(cookie_file, os.R_OK): jar.load(ignore_discard=True, ignore_expires=True) cookie_jars.append(jar) return _merge_cookie_jars(cookie_jars) def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *, keyring=None):", "SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage not available {SECRETSTORAGE_UNAVAILABLE_REASON}') return b'' # the Gnome keyring does not", "return jar finally: if cursor is not None: cursor.connection.close() def _process_chrome_cookie(decryptor, host_key, name,", "are considered 'old data' which were stored as plaintext # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return encrypted_value", "self._v11_key is None: self._logger.warning('cannot decrypt v11 cookies: no key found', only_once=True) return None", "unencrypted_cookies logger.debug(f'cookie version breakdown: {counts}') return jar finally: if cursor is not None:", "= QuietMultilinePrinter() printer.print = lambda _: None return printer def load_cookies(cookie_file, browser_specification, ydl):", "enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None,", "{ 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(appdata, 'Google/Chrome'), 'chromium': os.path.join(appdata, 'Chromium'), 'edge': os.path.join(appdata, 'Microsoft", "cursor.execute(f'PRAGMA table_info({table_name})').fetchall() return [row[1].decode('utf-8') for row in table_info] def _find_most_recently_used_file(root, filename, logger): #", "{'opera'} return { 'browser_dir': browser_dir, 'keyring_name': keyring_name, 'supports_profiles': browser_name not in browsers_without_profiles }", "sqlite support. See: https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE = False try: import secretstorage SECRETSTORAGE_AVAILABLE = True", "_get_windows_v10_key(browser_root, logger) self._cookie_counts = {'v10': 0, 'other': 0} @property def cookie_counts(self): return self._cookie_counts", "self._cookie_counts['other'] += 1 # any other prefix means the data is DPAPI encrypted", "auto() KDE = auto() PANTHEON = auto() UNITY = auto() XFCE = auto()", "which does a dbus call to the following function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet \"\"\" default_wallet", "cookie_database_path = _find_most_recently_used_file(search_root, 'Cookies', logger) if cookie_database_path is None: raise FileNotFoundError(f'could not find", "finally: if cursor is not None: cursor.connection.close() def _firefox_browser_dir(): if sys.platform in ('linux',", "prefixes are considered 'old data' which were stored as plaintext # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return", "= p.read_cstring() p.skip_to(value_offset) value = p.read_cstring() except UnicodeDecodeError: logger.warning('failed to parse Safari cookie", "no key found', only_once=True) return None # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc # kNonceLength nonce_length = 96", "== _LinuxDesktopEnvironment.OTHER: linux_keyring = _LinuxKeyring.BASICTEXT else: linux_keyring = _LinuxKeyring.GNOMEKEYRING return linux_keyring def _get_kwallet_network_wallet(logger):", "return b'' else: logger.debug('password found') if stdout[-1:] == b'\\n': stdout = stdout[:-1] return", "None: self._logger.warning('cannot decrypt v11 cookies: no key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext,", "\"\"\" References: - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\" from ctypes.wintypes import DWORD class DATA_BLOB(ctypes.Structure): _fields_ =", "failed', only_once=True) return record_size p.skip_to(record_size, 'space at the end of the record') cookie", "chrome does not check hasEntry and instead # just tries to read the", "to obtain password from kwallet') if shutil.which('kwallet-query') is None: logger.error('kwallet-query command not found.", "or not v10 - v10: AES-GCM encrypted with a key which is encrypted", "except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-GCM) because UTF-8 decoding failed. Possibly the", "v10: AES-GCM encrypted with a key which is encrypted with DPAPI - not", "authentication_tag, logger): try: plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce) except ValueError: logger.warning('failed to", "desktop_session: return _LinuxDesktopEnvironment.KDE elif 'xfce' in desktop_session: return _LinuxDesktopEnvironment.XFCE else: if 'GNOME_DESKTOP_SESSION_ID' in", "else: if 'GNOME_DESKTOP_SESSION_ID' in env: return _LinuxDesktopEnvironment.GNOME elif 'KDE_FULL_SESSION' in env: return _LinuxDesktopEnvironment.KDE", "as progress_bar: table = cursor.fetchall() total_cookie_count = len(table) for i, (host, name, value,", "= None if password is None else self.derive_key(password) self._cookie_counts = {'v10': 0, 'other':", "to use # chromium --enable-logging=stderr --v=1 2>&1 | grep key_storage_ # Chromium supports", "os.path.join(tmpdir, 'temporary.sqlite') shutil.copy(database_path, database_copy_path) conn = sqlite3.connect(database_copy_path) return conn.cursor() def _get_column_names(cursor, table_name): table_info", "'xfce' in desktop_session: return _LinuxDesktopEnvironment.XFCE else: if 'GNOME_DESKTOP_SESSION_ID' in env: return _LinuxDesktopEnvironment.GNOME elif", "from hashlib import pbkdf2_hmac from .aes import ( aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7, ) from", "p.read_uint() name_offset = p.read_uint() path_offset = p.read_uint() value_offset = p.read_uint() p.skip(8, 'unknown record", "keyring = _LinuxKeyring[keyring] if keyring else _choose_linux_keyring(logger) logger.debug(f'Chosen keyring: {keyring.name}') if keyring ==", "= p.read_uint() record_offsets = [p.read_uint() for _ in range(number_of_cookies)] if number_of_cookies == 0:", "None logger.debug(f'Found local state file at \"{path}\"') with open(path, encoding='utf8') as f: data", "# Do not print to files/pipes, loggers, or when --no-progress is used if", "= encrypted_value[:3] ciphertext = encrypted_value[3:] if version == b'v10': self._cookie_counts['v10'] += 1 if", "raw_ciphertext = ciphertext nonce = raw_ciphertext[:nonce_length] ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag = raw_ciphertext[-authentication_tag_length:] return", "module is not installed. ' 'Please install by running `python3 -m pip install", "while True: c = self.read_bytes(1) if c == b'\\x00': return b''.join(buffer).decode('utf-8') else: buffer.append(c)", "printer printer = QuietMultilinePrinter() printer.print = lambda _: None return printer def load_cookies(cookie_file,", "data' which were stored as plaintext # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return encrypted_value class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def", "initialization_vector)) try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-CBC) because UTF-8", "if end > len(self._data): raise ParserError('reached end of input') data = self._data[self.cursor:end] self.cursor", "data = json.load(f) try: base64_key = data['os_crypt']['encrypted_key'] except KeyError: logger.error('no encrypted key in", "!= 0: logger.error(f'kwallet-query failed with return code {proc.returncode}. Please consult ' 'the kwallet-query", "nonce = raw_ciphertext[:nonce_length] ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag = raw_ciphertext[-authentication_tag_length:] return _decrypt_aes_gcm(ciphertext, self._v10_key, nonce,", "- v10: AES-CBC encrypted with an OS protected key (keyring) and more key", "{sys.platform}') class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger, *, keyring=None): self._logger = logger self._v10_key", "keyring, logger): # note: chrome/chromium can be run with the following flags to", "keyring_name, 'supports_profiles': browser_name not in browsers_without_profiles } def _extract_chrome_cookies(browser_name, profile, keyring, logger): logger.info(f'Extracting", "('linux', 'linux2'): return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring) elif sys.platform == 'darwin': return MacChromeCookieDecryptor(browser_keyring_name, logger)", "in (None, *SUPPORTED_KEYRINGS): raise ValueError(f'unsupported keyring: \"{keyring}\"') if profile is not None and", "self._v11_key, self._logger) else: self._cookie_counts['other'] += 1 return None class MacChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name,", "secure=is_secure, expires=expires_utc, discard=False, comment=None, comment_url=None, rest={}) class ChromeCookieDecryptor: \"\"\" Overview: Linux: - cookies", "https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE = False try: import secretstorage SECRETSTORAGE_AVAILABLE = True except ImportError: SECRETSTORAGE_AVAILABLE", "self._v10_key, nonce, authentication_tag, self._logger) else: self._cookie_counts['other'] += 1 # any other prefix means", "Support') browser_dir = { 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(appdata, 'Google/Chrome'), 'chromium': os.path.join(appdata, 'Chromium'),", "in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') is_encrypted, cookie = _process_chrome_cookie(decryptor, *line) if", "except BaseException: return printer = MultilinePrinter(file, preserve_output=False) printer.print = lambda message: printer.print_at_line(f'[Cookies] {message}',", "_extract_chrome_cookies(browser_name, profile, keyring, logger) else: raise ValueError(f'unknown browser: {browser_name}') def _extract_firefox_cookies(profile, logger): logger.info('Extracting", "except ValueError: logger.warning('failed to decrypt cookie (AES-GCM) because the MAC check failed. Possibly", "only_once=True) return record_size p.skip_to(record_size, 'space at the end of the record') cookie =", "already in use (e.g. by the browser) database_copy_path = os.path.join(tmpdir, 'temporary.sqlite') shutil.copy(database_path, database_copy_path)", "body_start = _parse_safari_cookies_header(data, logger) p = DataParser(data[body_start:], logger) for page_size in page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size),", "is the same - there are a few bytes here and there which", "Data'), }[browser_name] elif sys.platform == 'darwin': appdata = os.path.expanduser('~/Library/Application Support') browser_dir = {", "auto() UNITY = auto() XFCE = auto() class _LinuxKeyring(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend \"\"\"", "ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in), # pDataIn None, # ppszDataDescr: human readable description of pDataIn None,", "# using `dbus-monitor` during startup, it can be observed that chromium lists all", "if self._v11_key is None: self._logger.warning('cannot decrypt v11 cookies: no key found', only_once=True) return", "in value def _parse_browser_specification(browser_name, profile=None, keyring=None): if browser_name not in SUPPORTED_BROWSERS: raise ValueError(f'unsupported", "record_offsets = [p.read_uint() for _ in range(number_of_cookies)] if number_of_cookies == 0: logger.debug(f'a cookies", "record_size = p.read_uint() p.skip(4, 'unknown record field 1') flags = p.read_uint() is_secure =", "0, [] with _create_progress_bar(logger) as progress_bar: for curr_root, dirs, files in os.walk(root): for", "item.get_secret() else: logger.error('failed to read from keyring') return b'' def _get_linux_keyring_password(browser_keyring_name, keyring, logger):", "browser_keyring_name, logger, *, keyring=None): self._logger = logger self._v10_key = self.derive_key(b'peanuts') password = _get_linux_keyring_password(browser_keyring_name,", "keyring backend # it has chosen to use # chromium --enable-logging=stderr --v=1 2>&1", "cookies are either v10 or not v10 - v10: AES-GCM encrypted with a", "data appears to be out of date but the important parts of the", "stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode != 0: logger.warning('failed to read NetworkWallet')", "= ( 'as the `secretstorage` module is not installed. ' 'Please install by", "logger): logger.info('Extracting cookies from firefox') if not SQLITE_AVAILABLE: logger.warning('Cannot extract cookies from firefox", "= profile else: search_root = os.path.join(_firefox_browser_dir(), profile) cookie_database_path = _find_most_recently_used_file(search_root, 'cookies.sqlite', logger) if", "not in SUPPORTED_BROWSERS: raise ValueError(f'unsupported browser: \"{browser_name}\"') if keyring not in (None, *SUPPORTED_KEYRINGS):", "by sub classes') @property def cookie_counts(self): raise NotImplementedError('Must be implemented by sub classes')", "comment_url=None, rest={}) jar.set_cookie(cookie) return record_size def parse_safari_cookies(data, jar=None, logger=YDLLogger()): \"\"\" References: - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc", "failed. Possibly the key is wrong?', only_once=True) return None def _decrypt_aes_gcm(ciphertext, key, nonce,", "password and store # it, but that doesn't matter here. return b'' else:", "progress_bar: for i, record_offset in enumerate(record_offsets): progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies: 6d}') p.skip_to(record_offset, 'space", "{i: 6d}/{total_cookie_count: 6d}') is_encrypted, cookie = _process_chrome_cookie(decryptor, *line) if not cookie: failed_cookies +=", "data_format = '>d' if big_endian else '<d' return struct.unpack(data_format, self.read_bytes(8))[0] def read_cstring(self): buffer", "keyring=keyring) elif sys.platform == 'darwin': return MacChromeCookieDecryptor(browser_keyring_name, logger) elif sys.platform == 'win32': return", "profile) cookie_database_path = _find_most_recently_used_file(search_root, 'cookies.sqlite', logger) if cookie_database_path is None: raise FileNotFoundError(f'could not", "to display 0, # dwFlags ctypes.byref(blob_out) # pDataOut ) if not ret: logger.warning('failed", "description of pDataIn None, # pOptionalEntropy: salt? None, # pvReserved: must be NULL", "platform: {sys.platform}') # Linux keyring names can be determined by snooping on dbus", "- v10: AES-CBC encrypted with a fixed key - v11: AES-CBC encrypted with", "from .aes import ( aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7, ) from .compat import compat_b64decode, compat_cookiejar_Cookie", "proc.communicate_or_kill() if stdout[-1:] == b'\\n': stdout = stdout[:-1] return stdout except Exception as", "os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): raise FileNotFoundError('could not find safari cookies database') with open(cookies_path,", "with an OS protected key (keyring) - v11 keys can be stored in", "as KWallet, # using `dbus-monitor` during startup, it can be observed that chromium", "os.path.join(config, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(config, 'google-chrome'), 'chromium': os.path.join(config, 'chromium'), 'edge': os.path.join(config, 'microsoft-edge'), 'opera': os.path.join(config,", "jar, logger): p = DataParser(data, logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page signature') number_of_cookies = p.read_uint() record_offsets", "not None: cursor.connection.close() def _firefox_browser_dir(): if sys.platform in ('linux', 'linux2'): return os.path.expanduser('~/.mozilla/firefox') elif", "module could not be initialized. {_err}' CHROMIUM_BASED_BROWSERS = {'brave', 'chrome', 'chromium', 'edge', 'opera',", "in use (e.g. by the browser) database_copy_path = os.path.join(tmpdir, 'temporary.sqlite') shutil.copy(database_path, database_copy_path) conn", "= [] while True: c = self.read_bytes(1) if c == b'\\x00': return b''.join(buffer).decode('utf-8')", "printer def _create_progress_bar(logger): if hasattr(logger, 'progress_bar'): printer = logger.progress_bar() if printer: return printer", "browser_keyring_name, logger): self._logger = logger password = _get_mac_keyring_password(browser_keyring_name, logger) self._v10_key = None if", "stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode != 0: logger.warning('failed to read", "keyring: {keyring.name}') if keyring == _LinuxKeyring.KWALLET: return _get_kwallet_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.GNOMEKEYRING:", "of the wallet used to store network passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet which does a", "stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode != 0: logger.error(f'kwallet-query failed with", "installed to read from KWallet. kwallet-query should be' 'included in the kwallet package", "paths.append(os.path.join(curr_root, file)) return None if not paths else max(paths, key=lambda path: os.lstat(path).st_mtime) def", "safari') return jar class ParserError(Exception): pass class DataParser: def __init__(self, data, logger): self._data", "search_root = profile config['browser_dir'] = os.path.dirname(profile) if config['supports_profiles'] else profile else: if config['supports_profiles']:", "ImportError: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = ( 'as the `secretstorage` module is not", "== 'X-Cinnamon': return _LinuxDesktopEnvironment.CINNAMON elif xdg_current_desktop == 'KDE': return _LinuxDesktopEnvironment.KDE elif xdg_current_desktop ==", "in between pages') def _parse_safari_cookies_record(data, jar, logger): p = DataParser(data, logger) record_size =", "def warning(self, message, only_once=False): if self._ydl: self._ydl.report_warning(message, only_once) def error(self, message): if self._ydl:", "lambda message: printer.print_at_line(f'[Cookies] {message}', 0) return printer def _create_progress_bar(logger): if hasattr(logger, 'progress_bar'): printer", "record') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), path=path,", "few bytes here and there which are skipped during parsing \"\"\" if jar", "encrypted with DPAPI Sources: - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc - KeyStorageLinux::CreateService \"\"\"", "browser) database_copy_path = os.path.join(tmpdir, 'temporary.sqlite') shutil.copy(database_path, database_copy_path) conn = sqlite3.connect(database_copy_path) return conn.cursor() def", "_decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8') def _extract_safari_cookies(profile, logger): if profile is not None: logger.error('safari does not", "None: logger.error('kwallet-query command not found. KWallet and kwallet-query ' 'must be installed to", "= data['os_crypt']['encrypted_key'] except KeyError: logger.error('no encrypted key in Local State') return None encrypted_key", "if desktop_session is not None and 'gnome-fallback' in desktop_session: return _LinuxDesktopEnvironment.GNOME else: return", "return None # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc # kNonceLength nonce_length = 96 // 8 # boringssl", "message): if self._ydl: self._ydl.write_debug(message) def info(self, message): if self._ydl: self._ydl.to_screen(f'[Cookies] {message}') def warning(self,", "KWallet. kwallet-query should be' 'included in the kwallet package for your distribution') return", "_open_database_copy(database_path, tmpdir): # cannot open sqlite databases if they are already in use", "same way as KWallet, # using `dbus-monitor` during startup, it can be observed", "ctypes.POINTER(ctypes.c_char))] buffer = ctypes.create_string_buffer(ciphertext) blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer) blob_out = DATA_BLOB() ret =", "of pDataIn None, # pOptionalEntropy: salt? None, # pvReserved: must be NULL None,", "plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce) except ValueError: logger.warning('failed to decrypt cookie (AES-GCM)", "if sys.platform != 'darwin': raise ValueError(f'unsupported platform: {sys.platform}') cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if not", "return pbkdf2_hmac('sha1', password, salt, iterations, key_length) def _decrypt_aes_cbc(ciphertext, key, logger, initialization_vector=b' ' *", "GNOMEKEYRING = auto() BASICTEXT = auto() SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys() def _get_linux_desktop_environment(env): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc", "\"{network_wallet}\"') return network_wallet except Exception as e: logger.warning(f'exception while obtaining NetworkWallet: {e}') return", "check failed. Possibly the key is wrong?', only_once=True) return None try: return plaintext.decode('utf-8')", "if 'GNOME_DESKTOP_SESSION_ID' in env: return _LinuxDesktopEnvironment.GNOME elif 'KDE_FULL_SESSION' in env: return _LinuxDesktopEnvironment.KDE return", "{SECRETSTORAGE_UNAVAILABLE_REASON}') return b'' # the Gnome keyring does not seem to organise keys", "= lambda _: None return printer def load_cookies(cookie_file, browser_specification, ydl): cookie_jars = []", "nonce) except ValueError: logger.warning('failed to decrypt cookie (AES-GCM) because the MAC check failed.", "def error(self, message): if self._ydl: self._ydl.report_error(message) def progress_bar(self): \"\"\"Return a context manager with", "def _decrypt_windows_dpapi(ciphertext, logger): \"\"\" References: - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\" from ctypes.wintypes import DWORD class", "ctypes.byref(blob_in), # pDataIn None, # ppszDataDescr: human readable description of pDataIn None, #", "logger.warning('failed to decrypt cookie (AES-GCM) because the MAC check failed. Possibly the key", "either v10 or not v10 - v10: AES-GCM encrypted with a key which", "or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'): return file = self._ydl._out_files['error'] try: if not file.isatty(): return", "in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value,", "= YoutubeDLCookieJar() page_sizes, body_start = _parse_safari_cookies_header(data, logger) p = DataParser(data[body_start:], logger) for page_size", "False try: import secretstorage SECRETSTORAGE_AVAILABLE = True except ImportError: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON", "this: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" # while starting chrome. # this may be", "AES-CBC encrypted with a fixed key - v11: AES-CBC encrypted with an OS", "key_length): return pbkdf2_hmac('sha1', password, salt, iterations, key_length) def _decrypt_aes_cbc(ciphertext, key, logger, initialization_vector=b' '", "import MultilinePrinter, QuietMultilinePrinter from .utils import Popen, YoutubeDLCookieJar, error_to_str, expand_path try: import sqlite3", "return None return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) else: self._cookie_counts['other'] += 1 # other prefixes", "to parse Safari cookie because UTF-8 decoding failed', only_once=True) return record_size p.skip_to(record_size, 'space", "self._logger) elif version == b'v11': self._cookie_counts['v11'] += 1 if self._v11_key is None: self._logger.warning('cannot", "self._logger) else: self._cookie_counts['other'] += 1 return None class MacChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger):", "logger password = _get_mac_keyring_password(browser_keyring_name, logger) self._v10_key = None if password is None else", "{i: 6d}/{number_of_cookies: 6d}') p.skip_to(record_offset, 'space between records') record_length = _parse_safari_cookies_record(data[record_offset:], jar, logger) p.read_bytes(record_length)", "key is wrong?', only_once=True) return None def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, logger): try:", "dwFlags ctypes.byref(blob_out) # pDataOut ) if not ret: logger.warning('failed to decrypt with DPAPI',", "# will not be sufficient in all cases. keyring = _LinuxKeyring[keyring] if keyring", "page header field') with _create_progress_bar(logger) as progress_bar: for i, record_offset in enumerate(record_offsets): progress_bar.print(f'Loading", "class MacChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger): self._logger = logger password = _get_mac_keyring_password(browser_keyring_name, logger)", "= auto() PANTHEON = auto() UNITY = auto() XFCE = auto() class _LinuxKeyring(Enum):", "search_root = profile else: search_root = os.path.join(_firefox_browser_dir(), profile) cookie_database_path = _find_most_recently_used_file(search_root, 'cookies.sqlite', logger)", "cookie_jars.append(jar) return _merge_cookie_jars(cookie_jars) def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *, keyring=None): if browser_name == 'firefox':", "self.read_bytes(8))[0] def read_cstring(self): buffer = [] while True: c = self.read_bytes(1) if c", "KeyStorageLinux::CreateService \"\"\" def decrypt(self, encrypted_value): raise NotImplementedError('Must be implemented by sub classes') @property", "unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector)) try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-CBC)", "None, # pPromptStruct: information about prompts to display 0, # dwFlags ctypes.byref(blob_out) #", "os.path.expandvars('%APPDATA%') browser_dir = { 'brave': os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User Data'), 'chrome': os.path.join(appdata_local, R'Google\\Chrome\\User Data'), 'chromium':", "\"{search_root}\"') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') decryptor = get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger, keyring=keyring) with tempfile.TemporaryDirectory(prefix='yt_dlp')", "decrypt(self, encrypted_value): version = encrypted_value[:3] ciphertext = encrypted_value[3:] if version == b'v10': self._cookie_counts['v10']", "record field 3') expiration_date = _mac_absolute_time_to_posix(p.read_double()) _creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa: F841 try:", "= os.path.join(_firefox_browser_dir(), profile) cookie_database_path = _find_most_recently_used_file(search_root, 'cookies.sqlite', logger) if cookie_database_path is None: raise", "but that doesn't matter here. return b'' else: logger.debug('password found') if stdout[-1:] ==", "None: return is_encrypted, None return is_encrypted, compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host_key,", "kwallet-query should be' 'included in the kwallet package for your distribution') return b''", "behaviour is to generate a random password and store # it, but that", "YoutubeDLCookieJar() with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count = len(table) for i,", "_create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count = len(table) for i, (host, name,", "= { 'brave': os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User Data'), 'chrome': os.path.join(appdata_local, R'Google\\Chrome\\User Data'), 'chromium': os.path.join(appdata_local, R'Chromium\\User", "derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1, key_length=16) @property def", "f.read() jar = parse_safari_cookies(cookies_data, logger=logger) logger.info(f'Extracted {len(jar)} cookies from safari') return jar class", "sqlite3 SQLITE_AVAILABLE = True except ImportError: # although sqlite3 is part of the", "import contextlib import ctypes import json import os import shutil import struct import", "in desktop_session: return _LinuxDesktopEnvironment.XFCE else: if 'GNOME_DESKTOP_SESSION_ID' in env: return _LinuxDesktopEnvironment.GNOME elif 'KDE_FULL_SESSION'", "value, encrypted_value, path, expires_utc, is_secure): host_key = host_key.decode('utf-8') name = name.decode('utf-8') value =", "discard=False, comment=None, comment_url=None, rest={}) class ChromeCookieDecryptor: \"\"\" Overview: Linux: - cookies are either", "== b'\\n': stdout = stdout[:-1] return stdout except Exception as e: logger.warning(f'exception running", "passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet which does a dbus call to the following function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html", "data['os_crypt']['encrypted_key'] except KeyError: logger.error('no encrypted key in Local State') return None encrypted_key =", "domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiry, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) logger.info(f'Extracted {len(jar)}", "with a print method. (Optional)\"\"\" # Do not print to files/pipes, loggers, or", "not SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage not available {SECRETSTORAGE_UNAVAILABLE_REASON}') return b'' # the Gnome keyring does", "return network_wallet except Exception as e: logger.warning(f'exception while obtaining NetworkWallet: {e}') return default_wallet", "obtain password from kwallet') if shutil.which('kwallet-query') is None: logger.error('kwallet-query command not found. KWallet", "key - v11: AES-CBC encrypted with an OS protected key (keyring) - v11", "the same - there are a few bytes here and there which are", "logger) if path is None: logger.error('could not find local state file') return None", "6d}/{total_cookie_count: 6d}') is_encrypted, cookie = _process_chrome_cookie(decryptor, *line) if not cookie: failed_cookies += 1", "name = name.decode('utf-8') value = value.decode('utf-8') path = path.decode('utf-8') is_encrypted = not value", "== 'XFCE': return _LinuxDesktopEnvironment.XFCE elif desktop_session is not None: if desktop_session in ('mate',", "' 'the kwallet-query man page for details') return b'' else: if stdout.lower().startswith(b'failed to", "# ppszDataDescr: human readable description of pDataIn None, # pOptionalEntropy: salt? None, #", "values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1, key_length=16) @property def cookie_counts(self): return", "{secure_column} FROM cookies') jar = YoutubeDLCookieJar() failed_cookies = 0 unencrypted_cookies = 0 with", "not ret: logger.warning('failed to decrypt with DPAPI', only_once=True) return None result = ctypes.string_at(blob_out.pbData,", "return _LinuxDesktopEnvironment.PANTHEON elif xdg_current_desktop == 'XFCE': return _LinuxDesktopEnvironment.XFCE elif desktop_session is not None:", "'keyring_name': keyring_name, 'supports_profiles': browser_name not in browsers_without_profiles } def _extract_chrome_cookies(browser_name, profile, keyring, logger):", "Popen, YoutubeDLCookieJar, error_to_str, expand_path try: import sqlite3 SQLITE_AVAILABLE = True except ImportError: #", "logger.error(f'kwallet-query failed with return code {proc.returncode}. Please consult ' 'the kwallet-query man page", "nonce, authentication_tag, logger): try: plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce) except ValueError: logger.warning('failed", "command not found. KWallet and kwallet-query ' 'must be installed to read from", "logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try: cursor", "'darwin' else 'Chrome', }[browser_name] browsers_without_profiles = {'opera'} return { 'browser_dir': browser_dir, 'keyring_name': keyring_name,", "considered 'old data' which were stored as plaintext # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return encrypted_value class", "__init__(self, browser_root, logger): self._logger = logger self._v10_key = _get_windows_v10_key(browser_root, logger) self._cookie_counts = {'v10':", "self._logger.debug(f'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}') elif num_bytes < 0: raise ParserError(f'invalid skip of", "return int((datetime(2001, 1, 1, 0, 0, tzinfo=timezone.utc) + timedelta(seconds=timestamp)).timestamp()) def _parse_safari_cookies_header(data, logger): p", "compiled with sqlite3 support') return YoutubeDLCookieJar() if profile is None: search_root = _firefox_browser_dir()", "ParserError(f'invalid skip of {num_bytes} bytes') def skip_to(self, offset, description='unknown'): self.skip(offset - self.cursor, description)", "is not None: browser_name, profile, keyring = _parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring)) if", "= { 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(config, 'google-chrome'), 'chromium': os.path.join(config, 'chromium'), 'edge': os.path.join(config,", "call to the following function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet \"\"\" default_wallet = 'kdewallet' try: proc", "p = DataParser(data, logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page signature') number_of_cookies = p.read_uint() record_offsets = [p.read_uint()", "cookies from {browser_name} without sqlite3 support. ' 'Please use a python interpreter compiled", "does not check hasEntry and instead # just tries to read the value", "R'Chromium\\User Data'), 'edge': os.path.join(appdata_local, R'Microsoft\\Edge\\User Data'), 'opera': os.path.join(appdata_roaming, R'Opera Software\\Opera Stable'), 'vivaldi': os.path.join(appdata_local,", "elif _is_path(profile): search_root = profile else: search_root = os.path.join(_firefox_browser_dir(), profile) cookie_database_path = _find_most_recently_used_file(search_root,", "jar, logger) p.skip_to_end('footer') return jar class _LinuxDesktopEnvironment(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment \"\"\" OTHER =", "= Popen([ 'dbus-send', '--session', '--print-reply=literal', '--dest=org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet.networkWallet' ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr", "Overview: Linux: - cookies are either v10 or v11 - v10: AES-CBC encrypted", "the following flags to determine which keyring backend # it has chosen to", "= 0 unencrypted_cookies = 0 with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count", "from datetime import datetime, timedelta, timezone from enum import Enum, auto from hashlib", "to store network passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet which does a dbus call to the", "Exception as e: logger.warning(f'exception while obtaining NetworkWallet: {e}') return default_wallet def _get_kwallet_password(browser_keyring_name, logger):", "i, paths = 0, [] with _create_progress_bar(logger) as progress_bar: for curr_root, dirs, files", "XFCE = auto() class _LinuxKeyring(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend \"\"\" KWALLET = auto() GNOMEKEYRING", "try: proc = Popen([ 'kwallet-query', '--read-password', f'{browser_keyring_name} Safe Storage', '--folder', f'{browser_keyring_name} Keys', network_wallet", "pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1003, key_length=16) @property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value): version", "proc.returncode != 0: logger.error(f'kwallet-query failed with return code {proc.returncode}. Please consult ' 'the", "_parse_safari_cookies_header(data, logger): p = DataParser(data, logger) p.expect_bytes(b'cook', 'database signature') number_of_pages = p.read_uint(big_endian=True) page_sizes", "'edge': 'Microsoft Edge' if sys.platform == 'darwin' else 'Chromium', 'opera': 'Opera' if sys.platform", "(so no keyring password is required) return None assert False, f'Unknown keyring {keyring}'", "- [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc - KeyStorageLinux::CreateService \"\"\" def decrypt(self, encrypted_value): raise NotImplementedError('Must be implemented", "except KeyError: logger.error('no encrypted key in Local State') return None encrypted_key = compat_b64decode(base64_key)", "\"\"\" OTHER = auto() CINNAMON = auto() GNOME = auto() KDE = auto()", "= _open_database_copy(cookie_database_path, tmpdir) cursor.execute('SELECT host, name, value, path, expiry, isSecure FROM moz_cookies') jar", "self._ydl = ydl def debug(self, message): if self._ydl: self._ydl.write_debug(message) def info(self, message): if", "print method. (Optional)\"\"\" # Do not print to files/pipes, loggers, or when --no-progress", "https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if sys.platform in ('linux', 'linux2'): config = _config_home() browser_dir = { 'brave':", "= 0, [] with _create_progress_bar(logger) as progress_bar: for curr_root, dirs, files in os.walk(root):", "self._v10_key = None if password is None else self.derive_key(password) self._cookie_counts = {'v10': 0,", "description='unknown'): self.skip_to(len(self._data), description) def _mac_absolute_time_to_posix(timestamp): return int((datetime(2001, 1, 1, 0, 0, tzinfo=timezone.utc) +", "key is wrong?', only_once=True) return None def _decrypt_windows_dpapi(ciphertext, logger): \"\"\" References: - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata", "try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-CBC) because UTF-8 decoding", "= parse_safari_cookies(cookies_data, logger=logger) logger.info(f'Extracted {len(jar)} cookies from safari') return jar class ParserError(Exception): pass", "ctypes.windll.kernel32.LocalFree(blob_out.pbData) return result def _config_home(): return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) def _open_database_copy(database_path, tmpdir): # cannot", "shutil.copy(database_path, database_copy_path) conn = sqlite3.connect(database_copy_path) return conn.cursor() def _get_column_names(cursor, table_name): table_info = cursor.execute(f'PRAGMA", "_decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) else: self._cookie_counts['other'] += 1 # other prefixes are considered 'old", "def _firefox_browser_dir(): if sys.platform in ('linux', 'linux2'): return os.path.expanduser('~/.mozilla/firefox') elif sys.platform == 'win32':", "'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(appdata, 'Google/Chrome'), 'chromium': os.path.join(appdata, 'Chromium'), 'edge': os.path.join(appdata, 'Microsoft Edge'),", "SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys() def _get_linux_desktop_environment(env): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment \"\"\" xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None)", "to read password from kwallet. Using empty string instead') # this sometimes occurs", "= _process_chrome_cookie(decryptor, *line) if not cookie: failed_cookies += 1 continue elif not is_encrypted:", "match 'account' '-s', f'{browser_keyring_name} Safe Storage'], # match 'service' stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr", "= ciphertext nonce = raw_ciphertext[:nonce_length] ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag = raw_ciphertext[-authentication_tag_length:] return _decrypt_aes_gcm(ciphertext,", "keyring, logger): logger.info(f'Extracting cookies from {browser_name}') if not SQLITE_AVAILABLE: logger.warning(f'Cannot extract cookies from", "return _LinuxDesktopEnvironment.KDE return _LinuxDesktopEnvironment.OTHER def _choose_linux_keyring(logger): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend \"\"\" desktop_environment = _get_linux_desktop_environment(os.environ)", "signature') number_of_pages = p.read_uint(big_endian=True) page_sizes = [p.read_uint(big_endian=True) for _ in range(number_of_pages)] return page_sizes,", "None, # ppszDataDescr: human readable description of pDataIn None, # pOptionalEntropy: salt? None,", "end of input') data = self._data[self.cursor:end] self.cursor = end return data def expect_bytes(self,", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet which does a dbus call to the following function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet", "lists all keys # and presumably searches for its key in the list.", "not find local state file') return None logger.debug(f'Found local state file at \"{path}\"')", "= p.read_cstring() except UnicodeDecodeError: logger.warning('failed to parse Safari cookie because UTF-8 decoding failed',", "== 'win32': return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif sys.platform == 'darwin': return os.path.expanduser('~/Library/Application Support/Firefox') else: raise", "keyring, logger) self._v11_key = None if password is None else self.derive_key(password) self._cookie_counts =", "databases if they are already in use (e.g. by the browser) database_copy_path =", "UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-CBC) because UTF-8 decoding failed. Possibly the key", "database') with open(cookies_path, 'rb') as f: cookies_data = f.read() jar = parse_safari_cookies(cookies_data, logger=logger)", "if printer: return printer printer = QuietMultilinePrinter() printer.print = lambda _: None return", "+ num_bytes if end > len(self._data): raise ParserError('reached end of input') data =", "# https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1, key_length=16) @property def cookie_counts(self): return self._cookie_counts def", "progress_bar.print(f'Searching for \"{filename}\": {i: 6d} files searched') if file == filename: paths.append(os.path.join(curr_root, file))", "printer = QuietMultilinePrinter() printer.print = lambda _: None return printer def load_cookies(cookie_file, browser_specification,", "wrong?', only_once=True) return None def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, logger): try: plaintext =", "if self._ydl: self._ydl.to_screen(f'[Cookies] {message}') def warning(self, message, only_once=False): if self._ydl: self._ydl.report_warning(message, only_once) def", "hasEntry and instead # just tries to read the value (which kwallet returns", ") from .compat import compat_b64decode, compat_cookiejar_Cookie from .minicurses import MultilinePrinter, QuietMultilinePrinter from .utils", "p.skip_to_end('footer') return jar class _LinuxDesktopEnvironment(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment \"\"\" OTHER = auto() CINNAMON", "pvReserved: must be NULL None, # pPromptStruct: information about prompts to display 0,", "return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif sys.platform == 'darwin': return os.path.expanduser('~/Library/Application Support/Firefox') else: raise ValueError(f'unsupported platform:", "details') return b'' else: if stdout.lower().startswith(b'failed to read'): logger.debug('failed to read password from", "decoding failed. Possibly the key is wrong?', only_once=True) return None def _decrypt_aes_gcm(ciphertext, key,", "seem to organise keys in the same way as KWallet, # using `dbus-monitor`", "stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if stdout[-1:] == b'\\n': stdout = stdout[:-1] return", "all cases. keyring = _LinuxKeyring[keyring] if keyring else _choose_linux_keyring(logger) logger.debug(f'Chosen keyring: {keyring.name}') if", "sqlite3.connect(database_copy_path) return conn.cursor() def _get_column_names(cursor, table_name): table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall() return [row[1].decode('utf-8') for", "if jar.filename is not None: output_jar.filename = jar.filename return output_jar def _is_path(value): return", "'--read-password', f'{browser_keyring_name} Safe Storage', '--folder', f'{browser_keyring_name} Keys', network_wallet ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr", "means the data is DPAPI encrypted # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return _decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8') def _extract_safari_cookies(profile,", "return None logger.debug(f'Found local state file at \"{path}\"') with open(path, encoding='utf8') as f:", "readable description of pDataIn None, # pOptionalEntropy: salt? None, # pvReserved: must be", "f: cookies_data = f.read() jar = parse_safari_cookies(cookies_data, logger=logger) logger.info(f'Extracted {len(jar)} cookies from safari')", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc - KeyStorageLinux::CreateService \"\"\" def decrypt(self, encrypted_value): raise NotImplementedError('Must be implemented by sub", "{browser_name} without sqlite3 support. ' 'Please use a python interpreter compiled with sqlite3", "flags to determine which keyring backend # it has chosen to use #", "1') flags = p.read_uint() is_secure = bool(flags & 0x0001) p.skip(4, 'unknown record field", "default_wallet else: network_wallet = stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet = \"{network_wallet}\"') return network_wallet except Exception as", "UnicodeDecodeError: logger.warning('failed to parse Safari cookie because UTF-8 decoding failed', only_once=True) return record_size", "key is wrong?', only_once=True) return None try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to", "distribution') return b'' network_wallet = _get_kwallet_network_wallet(logger) try: proc = Popen([ 'kwallet-query', '--read-password', f'{browser_keyring_name}", "else: failed_message = '' logger.info(f'Extracted {len(jar)} cookies from {browser_name}{failed_message}') counts = decryptor.cookie_counts.copy() counts['unencrypted']", "'Brave', 'chrome': 'Chrome', 'chromium': 'Chromium', 'edge': 'Microsoft Edge' if sys.platform == 'darwin' else", "browser_dir, 'keyring_name': keyring_name, 'supports_profiles': browser_name not in browsers_without_profiles } def _extract_chrome_cookies(browser_name, profile, keyring,", "None: self._logger.warning('cannot decrypt v10 cookies: no key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext,", "cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.connection.text_factory = bytes column_names = _get_column_names(cursor, 'cookies') secure_column =", "_decrypt_aes_gcm(ciphertext, self._v10_key, nonce, authentication_tag, self._logger) else: self._cookie_counts['other'] += 1 # any other prefix", "'darwin': appdata = os.path.expanduser('~/Library/Application Support') browser_dir = { 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(appdata,", "in various places depending on the activate desktop environment [2] Mac: - cookies", "_choose_linux_keyring(logger): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend \"\"\" desktop_environment = _get_linux_desktop_environment(os.environ) logger.debug(f'detected desktop environment: {desktop_environment.name}') if", "logger): self._logger = logger self._v10_key = _get_windows_v10_key(browser_root, logger) self._cookie_counts = {'v10': 0, 'other':", "jar, logger): p = DataParser(data, logger) record_size = p.read_uint() p.skip(4, 'unknown record field", "cookie because UTF-8 decoding failed', only_once=True) return record_size p.skip_to(record_size, 'space at the end", "nonce, authentication_tag, self._logger) else: self._cookie_counts['other'] += 1 # any other prefix means the", "= _find_most_recently_used_file(browser_root, 'Local State', logger) if path is None: logger.error('could not find local", "profile=None, keyring=None): if browser_name not in SUPPORTED_BROWSERS: raise ValueError(f'unsupported browser: \"{browser_name}\"') if keyring", "path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False, comment=None, comment_url=None, rest={}) class ChromeCookieDecryptor: \"\"\" Overview: Linux:", "in col.get_all_items(): if item.get_label() == f'{browser_keyring_name} Safe Storage': return item.get_secret() else: logger.error('failed to", "self.skip_to(len(self._data), description) def _mac_absolute_time_to_posix(timestamp): return int((datetime(2001, 1, 1, 0, 0, tzinfo=timezone.utc) + timedelta(seconds=timestamp)).timestamp())", "method. (Optional)\"\"\" # Do not print to files/pipes, loggers, or when --no-progress is", "if profile is not None: logger.error('safari does not support profiles') if sys.platform !=", "FileNotFoundError('could not find safari cookies database') with open(cookies_path, 'rb') as f: cookies_data =", "YoutubeDLCookieJar() if profile is None: search_root = _firefox_browser_dir() elif _is_path(profile): search_root = profile", "found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v11_key, self._logger) else: self._cookie_counts['other'] += 1 return", "cursor.execute(f'SELECT host_key, name, value, encrypted_value, path, expires_utc, {secure_column} FROM cookies') jar = YoutubeDLCookieJar()", "class DATA_BLOB(ctypes.Structure): _fields_ = [('cbData', DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))] buffer = ctypes.create_string_buffer(ciphertext) blob_in =", "DesktopEnvironment \"\"\" OTHER = auto() CINNAMON = auto() GNOME = auto() KDE =", "self._logger = logger self._v10_key = self.derive_key(b'peanuts') password = _get_linux_keyring_password(browser_keyring_name, keyring, logger) self._v11_key =", "self._ydl: self._ydl.report_error(message) def progress_bar(self): \"\"\"Return a context manager with a print method. (Optional)\"\"\"", "key, logger, initialization_vector=b' ' * 16): plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector)) try: return", "= self.read_bytes(len(expected_value)) if value != expected_value: raise ParserError(f'unexpected value: {value} != {expected_value} ({message})')", "return None encrypted_key = compat_b64decode(base64_key) prefix = b'DPAPI' if not encrypted_key.startswith(prefix): logger.error('invalid key')", "= _LinuxKeyring.GNOMEKEYRING return linux_keyring def _get_kwallet_network_wallet(logger): \"\"\" The name of the wallet used", "logger): self._logger = logger password = _get_mac_keyring_password(browser_keyring_name, logger) self._v10_key = None if password", "elif 'kde' in desktop_session: return _LinuxDesktopEnvironment.KDE elif 'xfce' in desktop_session: return _LinuxDesktopEnvironment.XFCE else:", "logger=logger) logger.info(f'Extracted {len(jar)} cookies from safari') return jar class ParserError(Exception): pass class DataParser:", "__init__(self, browser_keyring_name, logger): self._logger = logger password = _get_mac_keyring_password(browser_keyring_name, logger) self._v10_key = None", "pbkdf2_hmac('sha1', password, salt, iterations, key_length) def _decrypt_aes_cbc(ciphertext, key, logger, initialization_vector=b' ' * 16):", "cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), path=path, path_specified=bool(path),", "as the intended behaviour is to generate a random password and store #", "port=None, port_specified=False, domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False, comment=None, comment_url=None, rest={})", "\"{path}\"') with open(path, encoding='utf8') as f: data = json.load(f) try: base64_key = data['os_crypt']['encrypted_key']", "v10: AES-CBC encrypted with an OS protected key (keyring) and more key derivation", "jar is None: jar = YoutubeDLCookieJar() page_sizes, body_start = _parse_safari_cookies_header(data, logger) p =", "expires_utc, is_secure): host_key = host_key.decode('utf-8') name = name.decode('utf-8') value = value.decode('utf-8') path =", "else: logger.debug('password found') if stdout[-1:] == b'\\n': stdout = stdout[:-1] return stdout except", "path = p.read_cstring() p.skip_to(value_offset) value = p.read_cstring() except UnicodeDecodeError: logger.warning('failed to parse Safari", "profiles, take the most recently used one i, paths = 0, [] with", "= aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce) except ValueError: logger.warning('failed to decrypt cookie (AES-GCM) because", "value != expected_value: raise ParserError(f'unexpected value: {value} != {expected_value} ({message})') def read_uint(self, big_endian=False):", "return YoutubeDLCookieJar() if profile is None: search_root = _firefox_browser_dir() elif _is_path(profile): search_root =", "expiry, is_secure) in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') cookie = compat_cookiejar_Cookie( version=0,", "keychain') try: proc = Popen( ['security', 'find-generic-password', '-w', # write password to stdout", "\"{cookie_database_path}\"') decryptor = get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger, keyring=keyring) with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor =", "instead') # this sometimes occurs in KDE because chrome does not check hasEntry", "import ctypes import json import os import shutil import struct import subprocess import", "keyring {keyring}' def _get_mac_keyring_password(browser_keyring_name, logger): logger.debug('using find-generic-password to obtain password from OSX keychain')", "!= 0: logger.warning('failed to read NetworkWallet') return default_wallet else: network_wallet = stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet", "must be NULL None, # pPromptStruct: information about prompts to display 0, #", "logger) self._v11_key = None if password is None else self.derive_key(password) self._cookie_counts = {'v10':", "DPAPI', only_once=True) return None result = ctypes.string_at(blob_out.pbData, blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData) return result def _config_home():", "the key is wrong?', only_once=True) return None def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, logger):", "if self._v10_key is None: self._logger.warning('cannot decrypt v10 cookies: no key found', only_once=True) return", "'unknown page header field') with _create_progress_bar(logger) as progress_bar: for i, record_offset in enumerate(record_offsets):", "try: import secretstorage SECRETSTORAGE_AVAILABLE = True except ImportError: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON =", "v11 keys can be stored in various places depending on the activate desktop", "logger.info(f'Extracted {len(jar)} cookies from firefox') return jar finally: if cursor is not None:", "keyring = _parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring)) if cookie_file is not None: cookie_file", "{_err}' CHROMIUM_BASED_BROWSERS = {'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi'} SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS |", "keyring names can be determined by snooping on dbus while opening the browser", "as e: logger.warning(f'exception running find-generic-password: {error_to_str(e)}') return None def _get_windows_v10_key(browser_root, logger): path =", "only_once=True) return None def _decrypt_windows_dpapi(ciphertext, logger): \"\"\" References: - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\" from ctypes.wintypes", "bytes ({description}): {self.read_bytes(num_bytes)!r}') elif num_bytes < 0: raise ParserError(f'invalid skip of {num_bytes} bytes')", "stdout except Exception as e: logger.warning(f'exception running kwallet-query: {error_to_str(e)}') return b'' def _get_gnome_keyring_password(browser_keyring_name,", "= True except ImportError: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = ( 'as the `secretstorage`", "+= 1 jar.set_cookie(cookie) if failed_cookies > 0: failed_message = f' ({failed_cookies} could not", "if keyring not in (None, *SUPPORTED_KEYRINGS): raise ValueError(f'unsupported keyring: \"{keyring}\"') if profile is", "| {'firefox', 'safari'} class YDLLogger: def __init__(self, ydl=None): self._ydl = ydl def debug(self,", "sub classes') @property def cookie_counts(self): raise NotImplementedError('Must be implemented by sub classes') def", "if num_bytes < 0: raise ParserError(f'invalid read of {num_bytes} bytes') end = self.cursor", "if proc.returncode != 0: logger.warning('failed to read NetworkWallet') return default_wallet else: network_wallet =", "keyring=None): if sys.platform in ('linux', 'linux2'): return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring) elif sys.platform ==", "= logger password = _get_mac_keyring_password(browser_keyring_name, logger) self._v10_key = None if password is None", "password is None else self.derive_key(password) self._cookie_counts = {'v10': 0, 'other': 0} @staticmethod def", "Storage', '--folder', f'{browser_keyring_name} Keys', network_wallet ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if", "to determine which keyring backend # it has chosen to use # chromium", "bug as the intended behaviour is to generate a random password and store", "support') return YoutubeDLCookieJar() config = _get_chromium_based_browser_settings(browser_name) if profile is None: search_root = config['browser_dir']", "= host_key.decode('utf-8') name = name.decode('utf-8') value = value.decode('utf-8') path = path.decode('utf-8') is_encrypted =", "linux_keyring = _LinuxKeyring.KWALLET elif desktop_environment == _LinuxDesktopEnvironment.OTHER: linux_keyring = _LinuxKeyring.BASICTEXT else: linux_keyring =", "None if not paths else max(paths, key=lambda path: os.lstat(path).st_mtime) def _merge_cookie_jars(jars): output_jar =", "def __init__(self, ydl=None): self._ydl = ydl def debug(self, message): if self._ydl: self._ydl.write_debug(message) def", "_is_path(value): return os.path.sep in value def _parse_browser_specification(browser_name, profile=None, keyring=None): if browser_name not in", "logger.debug('password found') if stdout[-1:] == b'\\n': stdout = stdout[:-1] return stdout except Exception", "failed_cookies += 1 continue elif not is_encrypted: unencrypted_cookies += 1 jar.set_cookie(cookie) if failed_cookies", "get_cookie_decryptor(browser_root, browser_keyring_name, logger, *, keyring=None): if sys.platform in ('linux', 'linux2'): return LinuxChromeCookieDecryptor(browser_keyring_name, logger,", "num_bytes < 0: raise ParserError(f'invalid read of {num_bytes} bytes') end = self.cursor +", "def skip(self, num_bytes, description='unknown'): if num_bytes > 0: self._logger.debug(f'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}')", "only_once=True) return None try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-GCM)", "('pbData', ctypes.POINTER(ctypes.c_char))] buffer = ctypes.create_string_buffer(ciphertext) blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer) blob_out = DATA_BLOB() ret", "text is chosen, all cookies are stored as v10 (so no keyring password", "compiled with sqlite3 support') return YoutubeDLCookieJar() config = _get_chromium_based_browser_settings(browser_name) if profile is None:", "moz_cookies') jar = YoutubeDLCookieJar() with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count =", "_get_linux_desktop_environment(os.environ) logger.debug(f'detected desktop environment: {desktop_environment.name}') if desktop_environment == _LinuxDesktopEnvironment.KDE: linux_keyring = _LinuxKeyring.KWALLET elif", "from safari') return jar class ParserError(Exception): pass class DataParser: def __init__(self, data, logger):", "is None: search_root = _firefox_browser_dir() elif _is_path(profile): search_root = profile else: search_root =", "not find safari cookies database') with open(cookies_path, 'rb') as f: cookies_data = f.read()", "f'{browser_keyring_name} Keys', network_wallet ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode !=", "== _LinuxKeyring.GNOMEKEYRING: return _get_gnome_keyring_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.BASICTEXT: # when basic text", "firefox cookies database in {search_root}') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir:", "def _get_linux_desktop_environment(env): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment \"\"\" xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None) desktop_session = env.get('DESKTOP_SESSION',", "authentication_tag, nonce) except ValueError: logger.warning('failed to decrypt cookie (AES-GCM) because the MAC check", "_open_database_copy(cookie_database_path, tmpdir) cursor.execute('SELECT host, name, value, path, expiry, isSecure FROM moz_cookies') jar =", "_LinuxKeyring.KWALLET elif desktop_environment == _LinuxDesktopEnvironment.OTHER: linux_keyring = _LinuxKeyring.BASICTEXT else: linux_keyring = _LinuxKeyring.GNOMEKEYRING return", "('mate', 'gnome'): return _LinuxDesktopEnvironment.GNOME elif 'kde' in desktop_session: return _LinuxDesktopEnvironment.KDE elif 'xfce' in", "with the following flags to determine which keyring backend # it has chosen", "def pbkdf2_sha1(password, salt, iterations, key_length): return pbkdf2_hmac('sha1', password, salt, iterations, key_length) def _decrypt_aes_cbc(ciphertext,", "jar class _LinuxDesktopEnvironment(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment \"\"\" OTHER = auto() CINNAMON = auto()", "in ('mate', 'gnome'): return _LinuxDesktopEnvironment.GNOME elif 'kde' in desktop_session: return _LinuxDesktopEnvironment.KDE elif 'xfce'", "encoding='utf8') as f: data = json.load(f) try: base64_key = data['os_crypt']['encrypted_key'] except KeyError: logger.error('no", "= False SECRETSTORAGE_UNAVAILABLE_REASON = f'as the `secretstorage` module could not be initialized. {_err}'", "encrypted_value, path, expires_utc, is_secure): host_key = host_key.decode('utf-8') name = name.decode('utf-8') value = value.decode('utf-8')", "6d}') p.skip_to(record_offset, 'space between records') record_length = _parse_safari_cookies_record(data[record_offset:], jar, logger) p.read_bytes(record_length) p.skip_to_end('space in", "0, 'v11': 0, 'other': 0} @staticmethod def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc", "{'v10': 0, 'other': 0} @property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value): version", "if browser_specification is not None: browser_name, profile, keyring = _parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl),", "logger) elif browser_name in CHROMIUM_BASED_BROWSERS: return _extract_chrome_cookies(browser_name, profile, keyring, logger) else: raise ValueError(f'unknown", "= profile config['browser_dir'] = os.path.dirname(profile) if config['supports_profiles'] else profile else: if config['supports_profiles']: search_root", "comment_url=None, rest={}) class ChromeCookieDecryptor: \"\"\" Overview: Linux: - cookies are either v10 or", "cookies database in {search_root}') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor", "used if not self._ydl or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'): return file = self._ydl._out_files['error'] try:", "logger) else: raise ValueError(f'unknown browser: {browser_name}') def _extract_firefox_cookies(profile, logger): logger.info('Extracting cookies from firefox')", "None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.execute('SELECT host, name, value, path, expiry, isSecure", "None return printer def load_cookies(cookie_file, browser_specification, ydl): cookie_jars = [] if browser_specification is", "| grep key_storage_ # Chromium supports a flag: --password-store=<basic|gnome|kwallet> so the automatic detection", "== 'firefox': return _extract_firefox_cookies(profile, logger) elif browser_name == 'safari': return _extract_safari_cookies(profile, logger) elif", "for \"{filename}\": {i: 6d} files searched') if file == filename: paths.append(os.path.join(curr_root, file)) return", "range(number_of_cookies)] if number_of_cookies == 0: logger.debug(f'a cookies page of size {len(data)} has no", "# note: chrome/chromium can be run with the following flags to determine which", "path, expires_utc, is_secure): host_key = host_key.decode('utf-8') name = name.decode('utf-8') value = value.decode('utf-8') path", "else: logger.error(f'{browser_name} does not support profiles') search_root = config['browser_dir'] cookie_database_path = _find_most_recently_used_file(search_root, 'Cookies',", "not v10: 'old data' stored as plaintext Windows: - cookies are either v10", "False, f'Unknown keyring {keyring}' def _get_mac_keyring_password(browser_keyring_name, logger): logger.debug('using find-generic-password to obtain password from", "'--dest=org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet.networkWallet' ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode !=", "failed_cookies = 0 unencrypted_cookies = 0 with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall()", "= {'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi'} SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'}", "logger.warning('failed to decrypt cookie (AES-CBC) because UTF-8 decoding failed. Possibly the key is", "struct.unpack(data_format, self.read_bytes(4))[0] def read_double(self, big_endian=False): data_format = '>d' if big_endian else '<d' return", "self.cursor = 0 self._logger = logger def read_bytes(self, num_bytes): if num_bytes < 0:", "return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) elif version == b'v11': self._cookie_counts['v11'] += 1 if self._v11_key", "browser_root, logger): self._logger = logger self._v10_key = _get_windows_v10_key(browser_root, logger) self._cookie_counts = {'v10': 0,", "as progress_bar: for curr_root, dirs, files in os.walk(root): for file in files: i", "['security', 'find-generic-password', '-w', # write password to stdout '-a', browser_keyring_name, # match 'account'", "_: None return printer def load_cookies(cookie_file, browser_specification, ydl): cookie_jars = [] if browser_specification", "the Gnome keyring does not seem to organise keys in the same way", "domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False, comment=None, comment_url=None, rest={}) class ChromeCookieDecryptor:", "stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode != 0: logger.error(f'kwallet-query failed with return", "cookies are stored as v10 (so no keyring password is required) return None", "xdg_current_desktop == 'X-Cinnamon': return _LinuxDesktopEnvironment.CINNAMON elif xdg_current_desktop == 'KDE': return _LinuxDesktopEnvironment.KDE elif xdg_current_desktop", "# https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init()) as con: col = secretstorage.get_default_collection(con) for item in col.get_all_items():", "_LinuxDesktopEnvironment.UNITY elif xdg_current_desktop == 'GNOME': return _LinuxDesktopEnvironment.GNOME elif xdg_current_desktop == 'X-Cinnamon': return _LinuxDesktopEnvironment.CINNAMON", "decrypt cookie (AES-GCM) because UTF-8 decoding failed. Possibly the key is wrong?', only_once=True)", "0} @property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value): version = encrypted_value[:3] ciphertext", "kwallet-query # checks hasEntry. To verify this: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" # while", "cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): logger.debug('Trying secondary cookie location') cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies')", "curr_root, dirs, files in os.walk(root): for file in files: i += 1 progress_bar.print(f'Searching", "= logger def read_bytes(self, num_bytes): if num_bytes < 0: raise ParserError(f'invalid read of", "len(self._data): raise ParserError('reached end of input') data = self._data[self.cursor:end] self.cursor = end return", "f: data = json.load(f) try: base64_key = data['os_crypt']['encrypted_key'] except KeyError: logger.error('no encrypted key", "from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1, key_length=16) @property def cookie_counts(self): return self._cookie_counts", "discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) logger.info(f'Extracted {len(jar)} cookies from firefox') return jar finally:", "message): if self._ydl: self._ydl.report_error(message) def progress_bar(self): \"\"\"Return a context manager with a print", "auto from hashlib import pbkdf2_hmac from .aes import ( aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7, )", "unpad_pkcs7, ) from .compat import compat_b64decode, compat_cookiejar_Cookie from .minicurses import MultilinePrinter, QuietMultilinePrinter from", "returns \"\") whereas kwallet-query # checks hasEntry. To verify this: # dbus-monitor \"interface='org.kde.KWallet'\"", "as e: logger.warning(f'exception running kwallet-query: {error_to_str(e)}') return b'' def _get_gnome_keyring_password(browser_keyring_name, logger): if not", "file') return None logger.debug(f'Found local state file at \"{path}\"') with open(path, encoding='utf8') as", "found', only_once=True) return None # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc # kNonceLength nonce_length = 96 // 8", "in os.walk(root): for file in files: i += 1 progress_bar.print(f'Searching for \"{filename}\": {i:", "python without # sqlite support. See: https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE = False try: import secretstorage", "p.read_cstring() p.skip_to(path_offset) path = p.read_cstring() p.skip_to(value_offset) value = p.read_cstring() except UnicodeDecodeError: logger.warning('failed to", "is_secure): host_key = host_key.decode('utf-8') name = name.decode('utf-8') value = value.decode('utf-8') path = path.decode('utf-8')", "logger) self._v10_key = None if password is None else self.derive_key(password) self._cookie_counts = {'v10':", "raise FileNotFoundError(f'could not find {browser_name} cookies database in \"{search_root}\"') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"')", "= decryptor.decrypt(encrypted_value) if value is None: return is_encrypted, None return is_encrypted, compat_cookiejar_Cookie( version=0,", "Data'), 'chromium': os.path.join(appdata_local, R'Chromium\\User Data'), 'edge': os.path.join(appdata_local, R'Microsoft\\Edge\\User Data'), 'opera': os.path.join(appdata_roaming, R'Opera Software\\Opera", "read from KWallet. kwallet-query should be' 'included in the kwallet package for your", "None: logger.error('could not find local state file') return None logger.debug(f'Found local state file", "in browsers_without_profiles } def _extract_chrome_cookies(browser_name, profile, keyring, logger): logger.info(f'Extracting cookies from {browser_name}') if", "progress_bar(self): \"\"\"Return a context manager with a print method. (Optional)\"\"\" # Do not", "os.path.join(appdata, 'Chromium'), 'edge': os.path.join(appdata, 'Microsoft Edge'), 'opera': os.path.join(appdata, 'com.operasoftware.Opera'), 'vivaldi': os.path.join(appdata, 'Vivaldi'), }[browser_name]", "'chrome', 'chromium', 'edge', 'opera', 'vivaldi'} SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'} class YDLLogger:", "(keyring) - v11 keys can be stored in various places depending on the", "CHROMIUM_BASED_BROWSERS: return _extract_chrome_cookies(browser_name, profile, keyring, logger) else: raise ValueError(f'unknown browser: {browser_name}') def _extract_firefox_cookies(profile,", "progress_bar: table = cursor.fetchall() total_cookie_count = len(table) for i, (host, name, value, path,", "is possible to compile python without # sqlite support. See: https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE =", "only_once=False): if self._ydl: self._ydl.report_warning(message, only_once) def error(self, message): if self._ydl: self._ydl.report_error(message) def progress_bar(self):", "if hasattr(logger, 'progress_bar'): printer = logger.progress_bar() if printer: return printer printer = QuietMultilinePrinter()", "MultilinePrinter(file, preserve_output=False) printer.print = lambda message: printer.print_at_line(f'[Cookies] {message}', 0) return printer def _create_progress_bar(logger):", "logger): if not SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage not available {SECRETSTORAGE_UNAVAILABLE_REASON}') return b'' # the Gnome", "FileNotFoundError(f'could not find {browser_name} cookies database in \"{search_root}\"') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') decryptor", "noqa: F841 try: p.skip_to(domain_offset) domain = p.read_cstring() p.skip_to(name_offset) name = p.read_cstring() p.skip_to(path_offset) path", "'--folder', f'{browser_keyring_name} Keys', network_wallet ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode", "self._cookie_counts['v10'] += 1 return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) elif version == b'v11': self._cookie_counts['v11'] +=", "path = path.decode('utf-8') is_encrypted = not value and encrypted_value if is_encrypted: value =", "ret: logger.warning('failed to decrypt with DPAPI', only_once=True) return None result = ctypes.string_at(blob_out.pbData, blob_out.cbData)", "cookie {i: 6d}/{total_cookie_count: 6d}') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host,", "FROM moz_cookies') jar = YoutubeDLCookieJar() with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count", "data = self._data[self.cursor:end] self.cursor = end return data def expect_bytes(self, expected_value, message): value", "file = self._ydl._out_files['error'] try: if not file.isatty(): return except BaseException: return printer =", "return None def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, logger): try: plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key,", "be implemented by sub classes') @property def cookie_counts(self): raise NotImplementedError('Must be implemented by", "\"{cookie_database_path}\"') with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try: cursor = _open_database_copy(cookie_database_path, tmpdir)", "keyring=keyring)) if cookie_file is not None: cookie_file = expand_path(cookie_file) jar = YoutubeDLCookieJar(cookie_file) if", "os.path.join(appdata_local, R'Microsoft\\Edge\\User Data'), 'opera': os.path.join(appdata_roaming, R'Opera Software\\Opera Stable'), 'vivaldi': os.path.join(appdata_local, R'Vivaldi\\User Data'), }[browser_name]", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return encrypted_value class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_root, logger): self._logger = logger self._v10_key", "p.read_cstring() p.skip_to(value_offset) value = p.read_cstring() except UnicodeDecodeError: logger.warning('failed to parse Safari cookie because", "_get_kwallet_password(browser_keyring_name, logger): logger.debug('using kwallet-query to obtain password from kwallet') if shutil.which('kwallet-query') is None:", "search_root = os.path.join(_firefox_browser_dir(), profile) cookie_database_path = _find_most_recently_used_file(search_root, 'cookies.sqlite', logger) if cookie_database_path is None:", "# it, but that doesn't matter here. return b'' else: logger.debug('password found') if", "'>d' if big_endian else '<d' return struct.unpack(data_format, self.read_bytes(8))[0] def read_cstring(self): buffer = []", "= b'DPAPI' if not encrypted_key.startswith(prefix): logger.error('invalid key') return None return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) def", "return _extract_safari_cookies(profile, logger) elif browser_name in CHROMIUM_BASED_BROWSERS: return _extract_chrome_cookies(browser_name, profile, keyring, logger) else:", "cookie_file = expand_path(cookie_file) jar = YoutubeDLCookieJar(cookie_file) if os.access(cookie_file, os.R_OK): jar.load(ignore_discard=True, ignore_expires=True) cookie_jars.append(jar) return", "if profile is None: search_root = _firefox_browser_dir() elif _is_path(profile): search_root = profile else:", "except UnicodeDecodeError: logger.warning('failed to parse Safari cookie because UTF-8 decoding failed', only_once=True) return", "rest={}) jar.set_cookie(cookie) logger.info(f'Extracted {len(jar)} cookies from firefox') return jar finally: if cursor is", "elif not is_encrypted: unencrypted_cookies += 1 jar.set_cookie(cookie) if failed_cookies > 0: failed_message =", "_LinuxKeyring.BASICTEXT: # when basic text is chosen, all cookies are stored as v10", "cookie (AES-CBC) because UTF-8 decoding failed. Possibly the key is wrong?', only_once=True) return", "desktop_environment = _get_linux_desktop_environment(os.environ) logger.debug(f'detected desktop environment: {desktop_environment.name}') if desktop_environment == _LinuxDesktopEnvironment.KDE: linux_keyring =", "_LinuxKeyring[keyring] if keyring else _choose_linux_keyring(logger) logger.debug(f'Chosen keyring: {keyring.name}') if keyring == _LinuxKeyring.KWALLET: return", "cookies from firefox without sqlite3 support. ' 'Please use a python interpreter compiled", "'chromium': 'Chromium', 'edge': 'Microsoft Edge' if sys.platform == 'darwin' else 'Chromium', 'opera': 'Opera'", "logger.warning('failed to read NetworkWallet') return default_wallet else: network_wallet = stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet = \"{network_wallet}\"')", "= _parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring)) if cookie_file is not None: cookie_file =", "logger) elif browser_name == 'safari': return _extract_safari_cookies(profile, logger) elif browser_name in CHROMIUM_BASED_BROWSERS: return", "== b'v11': self._cookie_counts['v11'] += 1 if self._v11_key is None: self._logger.warning('cannot decrypt v11 cookies:", "the most recently used one i, paths = 0, [] with _create_progress_bar(logger) as", "None if password is None else self.derive_key(password) self._cookie_counts = {'v10': 0, 'other': 0}", "elif sys.platform == 'darwin': return MacChromeCookieDecryptor(browser_keyring_name, logger) elif sys.platform == 'win32': return WindowsChromeCookieDecryptor(browser_root,", "= _get_mac_keyring_password(browser_keyring_name, logger) self._v10_key = None if password is None else self.derive_key(password) self._cookie_counts", "def skip_to_end(self, description='unknown'): self.skip_to(len(self._data), description) def _mac_absolute_time_to_posix(timestamp): return int((datetime(2001, 1, 1, 0, 0,", "_get_kwallet_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.GNOMEKEYRING: return _get_gnome_keyring_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.BASICTEXT:", "pages') def _parse_safari_cookies_record(data, jar, logger): p = DataParser(data, logger) record_size = p.read_uint() p.skip(4,", "linux_keyring = _LinuxKeyring.GNOMEKEYRING return linux_keyring def _get_kwallet_network_wallet(logger): \"\"\" The name of the wallet", "config = _get_chromium_based_browser_settings(browser_name) if profile is None: search_root = config['browser_dir'] elif _is_path(profile): search_root", "return os.path.sep in value def _parse_browser_specification(browser_name, profile=None, keyring=None): if browser_name not in SUPPORTED_BROWSERS:", "https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet \"\"\" default_wallet = 'kdewallet' try: proc = Popen([ 'dbus-send', '--session', '--print-reply=literal',", "if value is None: return is_encrypted, None return is_encrypted, compat_cookiejar_Cookie( version=0, name=name, value=value,", "Storage'], # match 'service' stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if stdout[-1:] ==", "stored in various places depending on the activate desktop environment [2] Mac: -", "- v10: AES-GCM encrypted with a key which is encrypted with DPAPI -", "os.path.join(config, 'chromium'), 'edge': os.path.join(config, 'microsoft-edge'), 'opera': os.path.join(config, 'opera'), 'vivaldi': os.path.join(config, 'vivaldi'), }[browser_name] elif", "path = _find_most_recently_used_file(browser_root, 'Local State', logger) if path is None: logger.error('could not find", "config['browser_dir'] elif _is_path(profile): search_root = profile config['browser_dir'] = os.path.dirname(profile) if config['supports_profiles'] else profile", "table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall() return [row[1].decode('utf-8') for row in table_info] def _find_most_recently_used_file(root, filename,", "hashlib import pbkdf2_hmac from .aes import ( aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7, ) from .compat", "> 0: self._logger.debug(f'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}') elif num_bytes < 0: raise ParserError(f'invalid", "derivation iterations than linux - not v10: 'old data' stored as plaintext Windows:", "keyring == _LinuxKeyring.BASICTEXT: # when basic text is chosen, all cookies are stored", "'brave': os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User Data'), 'chrome': os.path.join(appdata_local, R'Google\\Chrome\\User Data'), 'chromium': os.path.join(appdata_local, R'Chromium\\User Data'), 'edge':", "# it has chosen to use # chromium --enable-logging=stderr --v=1 2>&1 | grep", "0, 0, tzinfo=timezone.utc) + timedelta(seconds=timestamp)).timestamp()) def _parse_safari_cookies_header(data, logger): p = DataParser(data, logger) p.expect_bytes(b'cook',", "elif sys.platform == 'win32': return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif sys.platform == 'darwin': return os.path.expanduser('~/Library/Application Support/Firefox')", "failed_message = '' logger.info(f'Extracted {len(jar)} cookies from {browser_name}{failed_message}') counts = decryptor.cookie_counts.copy() counts['unencrypted'] =", "cookies') return p.skip_to(record_offsets[0], 'unknown page header field') with _create_progress_bar(logger) as progress_bar: for i,", "== 'darwin': appdata = os.path.expanduser('~/Library/Application Support') browser_dir = { 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'), 'chrome':", "@staticmethod def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1, key_length=16)", "following function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet \"\"\" default_wallet = 'kdewallet' try: proc = Popen([ 'dbus-send',", "stdout '-a', browser_keyring_name, # match 'account' '-s', f'{browser_keyring_name} Safe Storage'], # match 'service'", "os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): logger.debug('Trying secondary cookie location') cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if not", "= compat_b64decode(base64_key) prefix = b'DPAPI' if not encrypted_key.startswith(prefix): logger.error('invalid key') return None return", "else: self._cookie_counts['other'] += 1 return None class MacChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger): self._logger", "iterations, key_length) def _decrypt_aes_cbc(ciphertext, key, logger, initialization_vector=b' ' * 16): plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext,", "failed. Possibly the key is wrong?', only_once=True) return None try: return plaintext.decode('utf-8') except", "between pages') def _parse_safari_cookies_record(data, jar, logger): p = DataParser(data, logger) record_size = p.read_uint()", "CHROMIUM_BASED_BROWSERS = {'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi'} SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS | {'firefox',", "os.R_OK): jar.load(ignore_discard=True, ignore_expires=True) cookie_jars.append(jar) return _merge_cookie_jars(cookie_jars) def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *, keyring=None): if", "num_bytes > 0: self._logger.debug(f'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}') elif num_bytes < 0: raise", "== 'win32': appdata_local = os.path.expandvars('%LOCALAPPDATA%') appdata_roaming = os.path.expandvars('%APPDATA%') browser_dir = { 'brave': os.path.join(appdata_local,", "page_sizes = [p.read_uint(big_endian=True) for _ in range(number_of_pages)] return page_sizes, p.cursor def _parse_safari_cookies_page(data, jar,", "con: col = secretstorage.get_default_collection(con) for item in col.get_all_items(): if item.get_label() == f'{browser_keyring_name} Safe", "c == b'\\x00': return b''.join(buffer).decode('utf-8') else: buffer.append(c) def skip(self, num_bytes, description='unknown'): if num_bytes", "supported on this platform: {sys.platform}') class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger, *, keyring=None):", "DATA_BLOB() ret = ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in), # pDataIn None, # ppszDataDescr: human readable description", "not None: if desktop_session in ('mate', 'gnome'): return _LinuxDesktopEnvironment.GNOME elif 'kde' in desktop_session:", "def _get_column_names(cursor, table_name): table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall() return [row[1].decode('utf-8') for row in table_info]", "return _get_gnome_keyring_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.BASICTEXT: # when basic text is chosen,", "config = _config_home() browser_dir = { 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(config, 'google-chrome'), 'chromium':", "skip_to_end(self, description='unknown'): self.skip_to(len(self._data), description) def _mac_absolute_time_to_posix(timestamp): return int((datetime(2001, 1, 1, 0, 0, tzinfo=timezone.utc)", "{counts}') return jar finally: if cursor is not None: cursor.connection.close() def _process_chrome_cookie(decryptor, host_key,", "self._ydl.to_screen(f'[Cookies] {message}') def warning(self, message, only_once=False): if self._ydl: self._ydl.report_warning(message, only_once) def error(self, message):", "# Chromium supports a flag: --password-store=<basic|gnome|kwallet> so the automatic detection # will not", "try: p.skip_to(domain_offset) domain = p.read_cstring() p.skip_to(name_offset) name = p.read_cstring() p.skip_to(path_offset) path = p.read_cstring()", "logger self._v10_key = self.derive_key(b'peanuts') password = _get_linux_keyring_password(browser_keyring_name, keyring, logger) self._v11_key = None if", "== b'v10': self._cookie_counts['v10'] += 1 return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) elif version == b'v11':", "read the value (which kwallet returns \"\") whereas kwallet-query # checks hasEntry. To", "_mac_absolute_time_to_posix(p.read_double()) _creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa: F841 try: p.skip_to(domain_offset) domain = p.read_cstring() p.skip_to(name_offset)", "YDLLogger: def __init__(self, ydl=None): self._ydl = ydl def debug(self, message): if self._ydl: self._ydl.write_debug(message)", "b'DPAPI' if not encrypted_key.startswith(prefix): logger.error('invalid key') return None return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) def pbkdf2_sha1(password,", "b'\\x00': return b''.join(buffer).decode('utf-8') else: buffer.append(c) def skip(self, num_bytes, description='unknown'): if num_bytes > 0:", "cookies from: \"{cookie_database_path}\"') with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try: cursor =", "os.path.join(config, 'microsoft-edge'), 'opera': os.path.join(config, 'opera'), 'vivaldi': os.path.join(config, 'vivaldi'), }[browser_name] elif sys.platform == 'win32':", "manager with a print method. (Optional)\"\"\" # Do not print to files/pipes, loggers,", "\"\"\" default_wallet = 'kdewallet' try: proc = Popen([ 'dbus-send', '--session', '--print-reply=literal', '--dest=org.kde.kwalletd5', '/modules/kwalletd5',", "'vivaldi': os.path.join(appdata, 'Vivaldi'), }[browser_name] else: raise ValueError(f'unsupported platform: {sys.platform}') # Linux keyring names", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1, key_length=16) @property def cookie_counts(self): return self._cookie_counts def decrypt(self,", "- there are a few bytes here and there which are skipped during", "during startup, it can be observed that chromium lists all keys # and", "# sqlite support. See: https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE = False try: import secretstorage SECRETSTORAGE_AVAILABLE =", "of the standard library, it is possible to compile python without # sqlite", "browser_name, profile, keyring = _parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring)) if cookie_file is not", "return b'' network_wallet = _get_kwallet_network_wallet(logger) try: proc = Popen([ 'kwallet-query', '--read-password', f'{browser_keyring_name} Safe", "this data appears to be out of date but the important parts of", "to read'): logger.debug('failed to read password from kwallet. Using empty string instead') #", "SelectBackend \"\"\" desktop_environment = _get_linux_desktop_environment(os.environ) logger.debug(f'detected desktop environment: {desktop_environment.name}') if desktop_environment == _LinuxDesktopEnvironment.KDE:", "sufficient in all cases. keyring = _LinuxKeyring[keyring] if keyring else _choose_linux_keyring(logger) logger.debug(f'Chosen keyring:", "False SECRETSTORAGE_UNAVAILABLE_REASON = f'as the `secretstorage` module could not be initialized. {_err}' CHROMIUM_BASED_BROWSERS", "be run with the following flags to determine which keyring backend # it", "in env: return _LinuxDesktopEnvironment.KDE return _LinuxDesktopEnvironment.OTHER def _choose_linux_keyring(logger): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend \"\"\" desktop_environment", "# while starting chrome. # this may be a bug as the intended", "@property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value): version = encrypted_value[:3] ciphertext =", "not SQLITE_AVAILABLE: logger.warning('Cannot extract cookies from firefox without sqlite3 support. ' 'Please use", "\"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend \"\"\" KWALLET = auto() GNOMEKEYRING = auto() BASICTEXT = auto()", "a python interpreter compiled with sqlite3 support') return YoutubeDLCookieJar() if profile is None:", "domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False, comment=None, comment_url=None, rest={}) class ChromeCookieDecryptor: \"\"\"", "= YoutubeDLCookieJar() for jar in jars: for cookie in jar: output_jar.set_cookie(cookie) if jar.filename", "not v10: encrypted with DPAPI Sources: - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc -", "p.skip(4, 'unknown record field 1') flags = p.read_uint() is_secure = bool(flags & 0x0001)", "= compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), path=path, path_specified=bool(path), secure=is_secure,", "appdata_roaming = os.path.expandvars('%APPDATA%') browser_dir = { 'brave': os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User Data'), 'chrome': os.path.join(appdata_local, R'Google\\Chrome\\User", "os.path.join(config, 'google-chrome'), 'chromium': os.path.join(config, 'chromium'), 'edge': os.path.join(config, 'microsoft-edge'), 'opera': os.path.join(config, 'opera'), 'vivaldi': os.path.join(config,", "# values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1, key_length=16) @property def cookie_counts(self):", "safari cookies database') with open(cookies_path, 'rb') as f: cookies_data = f.read() jar =", "when --no-progress is used if not self._ydl or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'): return file", "try: proc = Popen( ['security', 'find-generic-password', '-w', # write password to stdout '-a',", "= YoutubeDLCookieJar(cookie_file) if os.access(cookie_file, os.R_OK): jar.load(ignore_discard=True, ignore_expires=True) cookie_jars.append(jar) return _merge_cookie_jars(cookie_jars) def extract_cookies_from_browser(browser_name, profile=None,", "any other prefix means the data is DPAPI encrypted # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return _decrypt_windows_dpapi(encrypted_value,", "[] while True: c = self.read_bytes(1) if c == b'\\x00': return b''.join(buffer).decode('utf-8') else:", "'>I' if big_endian else '<I' return struct.unpack(data_format, self.read_bytes(4))[0] def read_double(self, big_endian=False): data_format =", "write password to stdout '-a', browser_keyring_name, # match 'account' '-s', f'{browser_keyring_name} Safe Storage'],", "import tempfile from datetime import datetime, timedelta, timezone from enum import Enum, auto", "which is encrypted with DPAPI - not v10: encrypted with DPAPI Sources: -", "b'' def _get_gnome_keyring_password(browser_keyring_name, logger): if not SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage not available {SECRETSTORAGE_UNAVAILABLE_REASON}') return b''", "p.read_uint() value_offset = p.read_uint() p.skip(8, 'unknown record field 3') expiration_date = _mac_absolute_time_to_posix(p.read_double()) _creation_date", "= ctypes.string_at(blob_out.pbData, blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData) return result def _config_home(): return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) def _open_database_copy(database_path,", "data' stored as plaintext Windows: - cookies are either v10 or not v10", "it has chosen to use # chromium --enable-logging=stderr --v=1 2>&1 | grep key_storage_", "SQLITE_AVAILABLE: logger.warning(f'Cannot extract cookies from {browser_name} without sqlite3 support. ' 'Please use a", "v10 - v10: AES-CBC encrypted with an OS protected key (keyring) and more", "value and encrypted_value if is_encrypted: value = decryptor.decrypt(encrypted_value) if value is None: return", "EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length = 16 raw_ciphertext = ciphertext nonce = raw_ciphertext[:nonce_length] ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length]", "not file.isatty(): return except BaseException: return printer = MultilinePrinter(file, preserve_output=False) printer.print = lambda", "cookie {i: 6d}/{number_of_cookies: 6d}') p.skip_to(record_offset, 'space between records') record_length = _parse_safari_cookies_record(data[record_offset:], jar, logger)", "version=0, name=name, value=value, port=None, port_specified=False, domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False,", "xdg_current_desktop == 'Unity': if desktop_session is not None and 'gnome-fallback' in desktop_session: return", "classes') def get_cookie_decryptor(browser_root, browser_keyring_name, logger, *, keyring=None): if sys.platform in ('linux', 'linux2'): return", "password, salt, iterations, key_length) def _decrypt_aes_cbc(ciphertext, key, logger, initialization_vector=b' ' * 16): plaintext", "0: logger.error(f'kwallet-query failed with return code {proc.returncode}. Please consult ' 'the kwallet-query man", "if cursor is not None: cursor.connection.close() def _process_chrome_cookie(decryptor, host_key, name, value, encrypted_value, path,", "Do not print to files/pipes, loggers, or when --no-progress is used if not", "header field') with _create_progress_bar(logger) as progress_bar: for i, record_offset in enumerate(record_offsets): progress_bar.print(f'Loading cookie", "logger.warning('failed to decrypt with DPAPI', only_once=True) return None result = ctypes.string_at(blob_out.pbData, blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData)", "do the same. # https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init()) as con: col = secretstorage.get_default_collection(con) for", "v10 cookies: no key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) else:", "'darwin': return MacChromeCookieDecryptor(browser_keyring_name, logger) elif sys.platform == 'win32': return WindowsChromeCookieDecryptor(browser_root, logger) else: raise", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1003, key_length=16) @property def cookie_counts(self): return self._cookie_counts def decrypt(self,", "raise ValueError(f'unsupported platform: {sys.platform}') # Linux keyring names can be determined by snooping", "== 'darwin': return os.path.expanduser('~/Library/Application Support/Firefox') else: raise ValueError(f'unsupported platform: {sys.platform}') def _get_chromium_based_browser_settings(browser_name): #", "description='unknown'): if num_bytes > 0: self._logger.debug(f'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}') elif num_bytes <", "+ timedelta(seconds=timestamp)).timestamp()) def _parse_safari_cookies_header(data, logger): p = DataParser(data, logger) p.expect_bytes(b'cook', 'database signature') number_of_pages", "== 'safari': return _extract_safari_cookies(profile, logger) elif browser_name in CHROMIUM_BASED_BROWSERS: return _extract_chrome_cookies(browser_name, profile, keyring,", "stderr = proc.communicate_or_kill() if proc.returncode != 0: logger.warning('failed to read NetworkWallet') return default_wallet", "os.path.expanduser('~/Library/Application Support/Firefox') else: raise ValueError(f'unsupported platform: {sys.platform}') def _get_chromium_based_browser_settings(browser_name): # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if sys.platform", "in env: return _LinuxDesktopEnvironment.GNOME elif 'KDE_FULL_SESSION' in env: return _LinuxDesktopEnvironment.KDE return _LinuxDesktopEnvironment.OTHER def", "+= 1 # other prefixes are considered 'old data' which were stored as", "f'{browser_keyring_name} Safe Storage': return item.get_secret() else: logger.error('failed to read from keyring') return b''", "v10 or v11 - v10: AES-CBC encrypted with a fixed key - v11:", "path: os.lstat(path).st_mtime) def _merge_cookie_jars(jars): output_jar = YoutubeDLCookieJar() for jar in jars: for cookie", "# values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1003, key_length=16) @property def cookie_counts(self):", "backend # it has chosen to use # chromium --enable-logging=stderr --v=1 2>&1 |", "True except ImportError: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = ( 'as the `secretstorage` module", "*SUPPORTED_KEYRINGS): raise ValueError(f'unsupported keyring: \"{keyring}\"') if profile is not None and _is_path(profile): profile", "be NULL None, # pPromptStruct: information about prompts to display 0, # dwFlags", "stdout.lower().startswith(b'failed to read'): logger.debug('failed to read password from kwallet. Using empty string instead')", "= raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag = raw_ciphertext[-authentication_tag_length:] return _decrypt_aes_gcm(ciphertext, self._v10_key, nonce, authentication_tag, self._logger) else: self._cookie_counts['other']", "way as KWallet, # using `dbus-monitor` during startup, it can be observed that", "Edge'), 'opera': os.path.join(appdata, 'com.operasoftware.Opera'), 'vivaldi': os.path.join(appdata, 'Vivaldi'), }[browser_name] else: raise ValueError(f'unsupported platform: {sys.platform}')", "'opera': os.path.join(appdata, 'com.operasoftware.Opera'), 'vivaldi': os.path.join(appdata, 'Vivaldi'), }[browser_name] else: raise ValueError(f'unsupported platform: {sys.platform}') #", "FileNotFoundError(f'could not find firefox cookies database in {search_root}') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') with", "= [] if browser_specification is not None: browser_name, profile, keyring = _parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name,", "def _decrypt_aes_cbc(ciphertext, key, logger, initialization_vector=b' ' * 16): plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector))", "# and presumably searches for its key in the list. It appears that", "stored as plaintext Windows: - cookies are either v10 or not v10 -", "iterations than linux - not v10: 'old data' stored as plaintext Windows: -", "printer = MultilinePrinter(file, preserve_output=False) printer.print = lambda message: printer.print_at_line(f'[Cookies] {message}', 0) return printer", "self.read_bytes(4))[0] def read_double(self, big_endian=False): data_format = '>d' if big_endian else '<d' return struct.unpack(data_format,", "self._v10_key, self._logger) else: self._cookie_counts['other'] += 1 # other prefixes are considered 'old data'", "WindowsChromeCookieDecryptor(browser_root, logger) else: raise NotImplementedError(f'Chrome cookie decryption is not supported on this platform:", "firefox') return jar finally: if cursor is not None: cursor.connection.close() def _firefox_browser_dir(): if", "logger, *, keyring=None): self._logger = logger self._v10_key = self.derive_key(b'peanuts') password = _get_linux_keyring_password(browser_keyring_name, keyring,", "= auto() SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys() def _get_linux_desktop_environment(env): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment \"\"\" xdg_current_desktop =", "domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiry, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) logger.info(f'Extracted {len(jar)} cookies", "cookie (AES-GCM) because the MAC check failed. Possibly the key is wrong?', only_once=True)", "References: - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\" from ctypes.wintypes import DWORD class DATA_BLOB(ctypes.Structure): _fields_ = [('cbData',", "jar, logger) p.read_bytes(record_length) p.skip_to_end('space in between pages') def _parse_safari_cookies_record(data, jar, logger): p =", "p.read_uint() is_secure = bool(flags & 0x0001) p.skip(4, 'unknown record field 2') domain_offset =", "= json.load(f) try: base64_key = data['os_crypt']['encrypted_key'] except KeyError: logger.error('no encrypted key in Local", "keyring else _choose_linux_keyring(logger) logger.debug(f'Chosen keyring: {keyring.name}') if keyring == _LinuxKeyring.KWALLET: return _get_kwallet_password(browser_keyring_name, logger)", "stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet = \"{network_wallet}\"') return network_wallet except Exception as e: logger.warning(f'exception while obtaining", "can be observed that chromium lists all keys # and presumably searches for", "= _firefox_browser_dir() elif _is_path(profile): search_root = profile else: search_root = os.path.join(_firefox_browser_dir(), profile) cookie_database_path", "is not None: logger.error('safari does not support profiles') if sys.platform != 'darwin': raise", "YDLLogger(ydl), keyring=keyring)) if cookie_file is not None: cookie_file = expand_path(cookie_file) jar = YoutubeDLCookieJar(cookie_file)", "at \"{path}\"') with open(path, encoding='utf8') as f: data = json.load(f) try: base64_key =", "as f: cookies_data = f.read() jar = parse_safari_cookies(cookies_data, logger=logger) logger.info(f'Extracted {len(jar)} cookies from", "open sqlite databases if they are already in use (e.g. by the browser)", "Data'), 'chrome': os.path.join(appdata_local, R'Google\\Chrome\\User Data'), 'chromium': os.path.join(appdata_local, R'Chromium\\User Data'), 'edge': os.path.join(appdata_local, R'Microsoft\\Edge\\User Data'),", "json import os import shutil import struct import subprocess import sys import tempfile", "'vivaldi': os.path.join(config, 'vivaldi'), }[browser_name] elif sys.platform == 'win32': appdata_local = os.path.expandvars('%LOCALAPPDATA%') appdata_roaming =", "is_encrypted: value = decryptor.decrypt(encrypted_value) if value is None: return is_encrypted, None return is_encrypted,", "compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiry,", "jar.filename return output_jar def _is_path(value): return os.path.sep in value def _parse_browser_specification(browser_name, profile=None, keyring=None):", "compile python without # sqlite support. See: https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE = False try: import", "is not supported on this platform: {sys.platform}') class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger,", "cursor.fetchall() total_cookie_count = len(table) for i, (host, name, value, path, expiry, is_secure) in", "logger) self._cookie_counts = {'v10': 0, 'other': 0} @property def cookie_counts(self): return self._cookie_counts def", "to read from keyring') return b'' def _get_linux_keyring_password(browser_keyring_name, keyring, logger): # note: chrome/chromium", "_LinuxDesktopEnvironment.PANTHEON elif xdg_current_desktop == 'XFCE': return _LinuxDesktopEnvironment.XFCE elif desktop_session is not None: if", "_get_linux_desktop_environment(env): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment \"\"\" xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None) desktop_session = env.get('DESKTOP_SESSION', None)", "cookies from firefox') if not SQLITE_AVAILABLE: logger.warning('Cannot extract cookies from firefox without sqlite3", "secretstorage SECRETSTORAGE_AVAILABLE = True except ImportError: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = ( 'as", "path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False, comment=None, comment_url=None, rest={}) class ChromeCookieDecryptor: \"\"\" Overview: Linux: -", "proc.communicate_or_kill() if proc.returncode != 0: logger.warning('failed to read NetworkWallet') return default_wallet else: network_wallet", "salt, iterations, key_length) def _decrypt_aes_cbc(ciphertext, key, logger, initialization_vector=b' ' * 16): plaintext =", "enumerate(record_offsets): progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies: 6d}') p.skip_to(record_offset, 'space between records') record_length = _parse_safari_cookies_record(data[record_offset:],", "does not support profiles') search_root = config['browser_dir'] cookie_database_path = _find_most_recently_used_file(search_root, 'Cookies', logger) if", "cookies page of size {len(data)} has no cookies') return p.skip_to(record_offsets[0], 'unknown page header", "class DataParser: def __init__(self, data, logger): self._data = data self.cursor = 0 self._logger", "desktop_session in ('mate', 'gnome'): return _LinuxDesktopEnvironment.GNOME elif 'kde' in desktop_session: return _LinuxDesktopEnvironment.KDE elif", "}[browser_name] elif sys.platform == 'win32': appdata_local = os.path.expandvars('%LOCALAPPDATA%') appdata_roaming = os.path.expandvars('%APPDATA%') browser_dir =", "_LinuxKeyring.BASICTEXT else: linux_keyring = _LinuxKeyring.GNOMEKEYRING return linux_keyring def _get_kwallet_network_wallet(logger): \"\"\" The name of", "to files/pipes, loggers, or when --no-progress is used if not self._ydl or self._ydl.params.get('noprogress')", "{keyring.name}') if keyring == _LinuxKeyring.KWALLET: return _get_kwallet_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.GNOMEKEYRING: return", "return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1003, key_length=16) @property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value):", "not None: logger.error('safari does not support profiles') if sys.platform != 'darwin': raise ValueError(f'unsupported", "enum import Enum, auto from hashlib import pbkdf2_hmac from .aes import ( aes_cbc_decrypt_bytes,", "if not file.isatty(): return except BaseException: return printer = MultilinePrinter(file, preserve_output=False) printer.print =", "({failed_cookies} could not be decrypted)' else: failed_message = '' logger.info(f'Extracted {len(jar)} cookies from", "cookie_file is not None: cookie_file = expand_path(cookie_file) jar = YoutubeDLCookieJar(cookie_file) if os.access(cookie_file, os.R_OK):", "key, authentication_tag, nonce) except ValueError: logger.warning('failed to decrypt cookie (AES-GCM) because the MAC", "return jar class _LinuxDesktopEnvironment(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment \"\"\" OTHER = auto() CINNAMON =", "automatic detection # will not be sufficient in all cases. keyring = _LinuxKeyring[keyring]", "= cursor.execute(f'PRAGMA table_info({table_name})').fetchall() return [row[1].decode('utf-8') for row in table_info] def _find_most_recently_used_file(root, filename, logger):", "in range(number_of_pages)] return page_sizes, p.cursor def _parse_safari_cookies_page(data, jar, logger): p = DataParser(data, logger)", "to the following function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet \"\"\" default_wallet = 'kdewallet' try: proc =", "- https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\" from ctypes.wintypes import DWORD class DATA_BLOB(ctypes.Structure): _fields_ = [('cbData', DWORD),", "0 with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count = len(table) for i,", "description='unknown'): self.skip(offset - self.cursor, description) def skip_to_end(self, description='unknown'): self.skip_to(len(self._data), description) def _mac_absolute_time_to_posix(timestamp): return", "location') cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): raise FileNotFoundError('could not find safari cookies", "extract cookies from firefox without sqlite3 support. ' 'Please use a python interpreter", "else '<d' return struct.unpack(data_format, self.read_bytes(8))[0] def read_cstring(self): buffer = [] while True: c", "field 3') expiration_date = _mac_absolute_time_to_posix(p.read_double()) _creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa: F841 try: p.skip_to(domain_offset)", "_ in range(number_of_pages)] return page_sizes, p.cursor def _parse_safari_cookies_page(data, jar, logger): p = DataParser(data,", "an OS protected key (keyring) - v11 keys can be stored in various", "_parse_safari_cookies_record(data[record_offset:], jar, logger) p.read_bytes(record_length) p.skip_to_end('space in between pages') def _parse_safari_cookies_record(data, jar, logger): p", "unencrypted_cookies += 1 jar.set_cookie(cookie) if failed_cookies > 0: failed_message = f' ({failed_cookies} could", "parse Safari cookie because UTF-8 decoding failed', only_once=True) return record_size p.skip_to(record_size, 'space at", "database structure is the same - there are a few bytes here and", "= _LinuxKeyring.__members__.keys() def _get_linux_desktop_environment(env): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment \"\"\" xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None) desktop_session", "encrypted_value): raise NotImplementedError('Must be implemented by sub classes') @property def cookie_counts(self): raise NotImplementedError('Must", "in the kwallet package for your distribution') return b'' network_wallet = _get_kwallet_network_wallet(logger) try:", "desktop_session is not None: if desktop_session in ('mate', 'gnome'): return _LinuxDesktopEnvironment.GNOME elif 'kde'", "logger, initialization_vector=b' ' * 16): plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector)) try: return plaintext.decode('utf-8')", "os.path.join(_firefox_browser_dir(), profile) cookie_database_path = _find_most_recently_used_file(search_root, 'cookies.sqlite', logger) if cookie_database_path is None: raise FileNotFoundError(f'could", "cursor is not None: cursor.connection.close() def _firefox_browser_dir(): if sys.platform in ('linux', 'linux2'): return", "0, 'other': 0} @property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value): version =", "self._v10_key is None: self._logger.warning('cannot decrypt v10 cookies: no key found', only_once=True) return None", "NotImplementedError(f'Chrome cookie decryption is not supported on this platform: {sys.platform}') class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def", "DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))] buffer = ctypes.create_string_buffer(ciphertext) blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer) blob_out = DATA_BLOB()", "'chrome': os.path.join(config, 'google-chrome'), 'chromium': os.path.join(config, 'chromium'), 'edge': os.path.join(config, 'microsoft-edge'), 'opera': os.path.join(config, 'opera'), 'vivaldi':", "firefox without sqlite3 support. ' 'Please use a python interpreter compiled with sqlite3", "try: proc = Popen([ 'dbus-send', '--session', '--print-reply=literal', '--dest=org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet.networkWallet' ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)", "keyring not in (None, *SUPPORTED_KEYRINGS): raise ValueError(f'unsupported keyring: \"{keyring}\"') if profile is not", "initialization_vector=b' ' * 16): plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector)) try: return plaintext.decode('utf-8') except", "v10 or not v10 - v10: AES-CBC encrypted with an OS protected key", "be' 'included in the kwallet package for your distribution') return b'' network_wallet =", "tzinfo=timezone.utc) + timedelta(seconds=timestamp)).timestamp()) def _parse_safari_cookies_header(data, logger): p = DataParser(data, logger) p.expect_bytes(b'cook', 'database signature')", "is None: raise FileNotFoundError(f'could not find firefox cookies database in {search_root}') logger.debug(f'Extracting cookies", "= config['browser_dir'] cookie_database_path = _find_most_recently_used_file(search_root, 'Cookies', logger) if cookie_database_path is None: raise FileNotFoundError(f'could", "'edge': os.path.join(config, 'microsoft-edge'), 'opera': os.path.join(config, 'opera'), 'vivaldi': os.path.join(config, 'vivaldi'), }[browser_name] elif sys.platform ==", "whereas kwallet-query # checks hasEntry. To verify this: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" #", "if not self._ydl or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'): return file = self._ydl._out_files['error'] try: if", "ValueError(f'unsupported platform: {sys.platform}') # Linux keyring names can be determined by snooping on", "os.path.join(appdata_local, R'Vivaldi\\User Data'), }[browser_name] elif sys.platform == 'darwin': appdata = os.path.expanduser('~/Library/Application Support') browser_dir", "sqlite3 is part of the standard library, it is possible to compile python", "snooping on dbus while opening the browser in KDE: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\"", "keys in the same way as KWallet, # using `dbus-monitor` during startup, it", "logger) elif keyring == _LinuxKeyring.BASICTEXT: # when basic text is chosen, all cookies", "_parse_safari_cookies_record(data, jar, logger): p = DataParser(data, logger) record_size = p.read_uint() p.skip(4, 'unknown record", "only_once=True) return None result = ctypes.string_at(blob_out.pbData, blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData) return result def _config_home(): return", "p.read_uint() path_offset = p.read_uint() value_offset = p.read_uint() p.skip(8, 'unknown record field 3') expiration_date", "0: logger.debug(f'a cookies page of size {len(data)} has no cookies') return p.skip_to(record_offsets[0], 'unknown", "in the list. It appears that we must do the same. # https://github.com/jaraco/keyring/issues/556", "\"\"\"Return a context manager with a print method. (Optional)\"\"\" # Do not print", "import pbkdf2_hmac from .aes import ( aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7, ) from .compat import", "if they are already in use (e.g. by the browser) database_copy_path = os.path.join(tmpdir,", "= os.path.expandvars('%APPDATA%') browser_dir = { 'brave': os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User Data'), 'chrome': os.path.join(appdata_local, R'Google\\Chrome\\User Data'),", "def skip_to(self, offset, description='unknown'): self.skip(offset - self.cursor, description) def skip_to_end(self, description='unknown'): self.skip_to(len(self._data), description)", "stdout[:-1] return stdout except Exception as e: logger.warning(f'exception running find-generic-password: {error_to_str(e)}') return None", "ValueError(f'unsupported platform: {sys.platform}') cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): logger.debug('Trying secondary cookie location')", "0, 'other': 0} @staticmethod def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return pbkdf2_sha1(password,", "failed with return code {proc.returncode}. Please consult ' 'the kwallet-query man page for", "except Exception as _err: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = f'as the `secretstorage` module", "= sqlite3.connect(database_copy_path) return conn.cursor() def _get_column_names(cursor, table_name): table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall() return [row[1].decode('utf-8')", "== 'darwin' else 'Chrome', }[browser_name] browsers_without_profiles = {'opera'} return { 'browser_dir': browser_dir, 'keyring_name':", "from ctypes.wintypes import DWORD class DATA_BLOB(ctypes.Structure): _fields_ = [('cbData', DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))] buffer", "kwallet-query: {error_to_str(e)}') return b'' def _get_gnome_keyring_password(browser_keyring_name, logger): if not SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage not available", "'-a', browser_keyring_name, # match 'account' '-s', f'{browser_keyring_name} Safe Storage'], # match 'service' stdout=subprocess.PIPE,", "== 'GNOME': return _LinuxDesktopEnvironment.GNOME elif xdg_current_desktop == 'X-Cinnamon': return _LinuxDesktopEnvironment.CINNAMON elif xdg_current_desktop ==", "self._logger) else: self._cookie_counts['other'] += 1 # other prefixes are considered 'old data' which", "b'' else: logger.debug('password found') if stdout[-1:] == b'\\n': stdout = stdout[:-1] return stdout", "[('cbData', DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))] buffer = ctypes.create_string_buffer(ciphertext) blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer) blob_out =", "== 'Unity': if desktop_session is not None and 'gnome-fallback' in desktop_session: return _LinuxDesktopEnvironment.GNOME", "from keyring') return b'' def _get_linux_keyring_password(browser_keyring_name, keyring, logger): # note: chrome/chromium can be", "0) return printer def _create_progress_bar(logger): if hasattr(logger, 'progress_bar'): printer = logger.progress_bar() if printer:", "# although sqlite3 is part of the standard library, it is possible to", "Linux: - cookies are either v10 or v11 - v10: AES-CBC encrypted with", "parsing \"\"\" if jar is None: jar = YoutubeDLCookieJar() page_sizes, body_start = _parse_safari_cookies_header(data,", "auto() XFCE = auto() class _LinuxKeyring(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend \"\"\" KWALLET = auto()", "'Cookies', logger) if cookie_database_path is None: raise FileNotFoundError(f'could not find {browser_name} cookies database", "the end of the record') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False,", "{keyring}' def _get_mac_keyring_password(browser_keyring_name, logger): logger.debug('using find-generic-password to obtain password from OSX keychain') try:", "wallet used to store network passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet which does a dbus call", "else: buffer.append(c) def skip(self, num_bytes, description='unknown'): if num_bytes > 0: self._logger.debug(f'skipping {num_bytes} bytes", "raise ValueError(f'unsupported platform: {sys.platform}') def _get_chromium_based_browser_settings(browser_name): # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if sys.platform in ('linux', 'linux2'):", "wrong?', only_once=True) return None try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie", "the value (which kwallet returns \"\") whereas kwallet-query # checks hasEntry. To verify", "logger.warning('Cannot extract cookies from firefox without sqlite3 support. ' 'Please use a python", "aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce) except ValueError: logger.warning('failed to decrypt cookie (AES-GCM) because the", "support. See: https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE = False try: import secretstorage SECRETSTORAGE_AVAILABLE = True except", "= _get_linux_desktop_environment(os.environ) logger.debug(f'detected desktop environment: {desktop_environment.name}') if desktop_environment == _LinuxDesktopEnvironment.KDE: linux_keyring = _LinuxKeyring.KWALLET", "{e}') return default_wallet def _get_kwallet_password(browser_keyring_name, logger): logger.debug('using kwallet-query to obtain password from kwallet')", "domain_initial_dot=host_key.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False, comment=None, comment_url=None, rest={}) class ChromeCookieDecryptor: \"\"\" Overview:", "p = DataParser(data, logger) record_size = p.read_uint() p.skip(4, 'unknown record field 1') flags", "_create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count = len(table) for i, line in", "places depending on the activate desktop environment [2] Mac: - cookies are either", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc # kNonceLength nonce_length = 96 // 8 # boringssl # EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length", "cookies: no key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v11_key, self._logger) else: self._cookie_counts['other']", "_mac_absolute_time_to_posix(timestamp): return int((datetime(2001, 1, 1, 0, 0, tzinfo=timezone.utc) + timedelta(seconds=timestamp)).timestamp()) def _parse_safari_cookies_header(data, logger):", "expires=expiration_date, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) return record_size def parse_safari_cookies(data, jar=None, logger=YDLLogger()): \"\"\"", "GetDesktopEnvironment \"\"\" xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None) desktop_session = env.get('DESKTOP_SESSION', None) if xdg_current_desktop is", "iterations=1003, key_length=16) @property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value): version = encrypted_value[:3]", "= [('cbData', DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))] buffer = ctypes.create_string_buffer(ciphertext) blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer) blob_out", "printer.print = lambda _: None return printer def load_cookies(cookie_file, browser_specification, ydl): cookie_jars =", "import Enum, auto from hashlib import pbkdf2_hmac from .aes import ( aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes,", "struct.unpack(data_format, self.read_bytes(8))[0] def read_cstring(self): buffer = [] while True: c = self.read_bytes(1) if", "p.read_uint() p.skip(4, 'unknown record field 1') flags = p.read_uint() is_secure = bool(flags &", "expiration_date = _mac_absolute_time_to_posix(p.read_double()) _creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa: F841 try: p.skip_to(domain_offset) domain =", "= stdout[:-1] return stdout except Exception as e: logger.warning(f'exception running find-generic-password: {error_to_str(e)}') return", "is not None: cookie_file = expand_path(cookie_file) jar = YoutubeDLCookieJar(cookie_file) if os.access(cookie_file, os.R_OK): jar.load(ignore_discard=True,", "{ 'browser_dir': browser_dir, 'keyring_name': keyring_name, 'supports_profiles': browser_name not in browsers_without_profiles } def _extract_chrome_cookies(browser_name,", "else self.derive_key(password) self._cookie_counts = {'v10': 0, 'other': 0} @staticmethod def derive_key(password): # values", "value=value, port=None, port_specified=False, domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False, comment=None, comment_url=None,", "the automatic detection # will not be sufficient in all cases. keyring =", "initialized. {_err}' CHROMIUM_BASED_BROWSERS = {'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi'} SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS", "this sometimes occurs in KDE because chrome does not check hasEntry and instead", "self._logger).decode('utf-8') def _extract_safari_cookies(profile, logger): if profile is not None: logger.error('safari does not support", "else: network_wallet = stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet = \"{network_wallet}\"') return network_wallet except Exception as e:", "if not os.path.isfile(cookies_path): raise FileNotFoundError('could not find safari cookies database') with open(cookies_path, 'rb')", "item.get_label() == f'{browser_keyring_name} Safe Storage': return item.get_secret() else: logger.error('failed to read from keyring')", "decryptor.cookie_counts.copy() counts['unencrypted'] = unencrypted_cookies logger.debug(f'cookie version breakdown: {counts}') return jar finally: if cursor", "verify this: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" # while starting chrome. # this may", "keyring == _LinuxKeyring.KWALLET: return _get_kwallet_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.GNOMEKEYRING: return _get_gnome_keyring_password(browser_keyring_name, logger)", "stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if stdout[-1:] == b'\\n': stdout = stdout[:-1]", "logger) p = DataParser(data[body_start:], logger) for page_size in page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger) p.skip_to_end('footer')", "True except ImportError: # although sqlite3 is part of the standard library, it", "not paths else max(paths, key=lambda path: os.lstat(path).st_mtime) def _merge_cookie_jars(jars): output_jar = YoutubeDLCookieJar() for", "logger.warning('failed to parse Safari cookie because UTF-8 decoding failed', only_once=True) return record_size p.skip_to(record_size,", "blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData) return result def _config_home(): return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) def _open_database_copy(database_path, tmpdir): #", "'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(config, 'google-chrome'), 'chromium': os.path.join(config, 'chromium'), 'edge': os.path.join(config, 'microsoft-edge'), 'opera': os.path.join(config, 'opera'),", "os.path.isfile(cookies_path): raise FileNotFoundError('could not find safari cookies database') with open(cookies_path, 'rb') as f:", "encrypted_value[3:] if version == b'v10': self._cookie_counts['v10'] += 1 if self._v10_key is None: self._logger.warning('cannot", "os.lstat(path).st_mtime) def _merge_cookie_jars(jars): output_jar = YoutubeDLCookieJar() for jar in jars: for cookie in", "else: if config['supports_profiles']: search_root = os.path.join(config['browser_dir'], profile) else: logger.error(f'{browser_name} does not support profiles')", "logger.progress_bar() if printer: return printer printer = QuietMultilinePrinter() printer.print = lambda _: None", "NotImplementedError('Must be implemented by sub classes') def get_cookie_decryptor(browser_root, browser_keyring_name, logger, *, keyring=None): if", "find-generic-password to obtain password from OSX keychain') try: proc = Popen( ['security', 'find-generic-password',", "profile else: search_root = os.path.join(_firefox_browser_dir(), profile) cookie_database_path = _find_most_recently_used_file(search_root, 'cookies.sqlite', logger) if cookie_database_path", "+= 1 # any other prefix means the data is DPAPI encrypted #", "take the most recently used one i, paths = 0, [] with _create_progress_bar(logger)", "jar.load(ignore_discard=True, ignore_expires=True) cookie_jars.append(jar) return _merge_cookie_jars(cookie_jars) def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *, keyring=None): if browser_name", "6d}/{number_of_cookies: 6d}') p.skip_to(record_offset, 'space between records') record_length = _parse_safari_cookies_record(data[record_offset:], jar, logger) p.read_bytes(record_length) p.skip_to_end('space", "cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): raise FileNotFoundError('could not find safari cookies database')", "use a python interpreter compiled with sqlite3 support') return YoutubeDLCookieJar() if profile is", "Software\\Opera Stable'), 'vivaldi': os.path.join(appdata_local, R'Vivaldi\\User Data'), }[browser_name] elif sys.platform == 'darwin': appdata =", "by sub classes') def get_cookie_decryptor(browser_root, browser_keyring_name, logger, *, keyring=None): if sys.platform in ('linux',", "if not os.path.isfile(cookies_path): logger.debug('Trying secondary cookie location') cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path):", "network_wallet = _get_kwallet_network_wallet(logger) try: proc = Popen([ 'kwallet-query', '--read-password', f'{browser_keyring_name} Safe Storage', '--folder',", "p.skip_to(record_offsets[0], 'unknown page header field') with _create_progress_bar(logger) as progress_bar: for i, record_offset in", "if self._ydl: self._ydl.report_error(message) def progress_bar(self): \"\"\"Return a context manager with a print method.", "raise ValueError(f'unknown browser: {browser_name}') def _extract_firefox_cookies(profile, logger): logger.info('Extracting cookies from firefox') if not", "BaseException: return printer = MultilinePrinter(file, preserve_output=False) printer.print = lambda message: printer.print_at_line(f'[Cookies] {message}', 0)", "dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" keyring_name = { 'brave': 'Brave', 'chrome': 'Chrome', 'chromium': 'Chromium', 'edge':", "aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7, ) from .compat import compat_b64decode, compat_cookiejar_Cookie from .minicurses import MultilinePrinter,", "\"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend \"\"\" desktop_environment = _get_linux_desktop_environment(os.environ) logger.debug(f'detected desktop environment: {desktop_environment.name}') if desktop_environment", "encrypted_key.startswith(prefix): logger.error('invalid key') return None return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) def pbkdf2_sha1(password, salt, iterations, key_length):", "host_key = host_key.decode('utf-8') name = name.decode('utf-8') value = value.decode('utf-8') path = path.decode('utf-8') is_encrypted", "None result = ctypes.string_at(blob_out.pbData, blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData) return result def _config_home(): return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))", "tmpdir: cursor = None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.connection.text_factory = bytes column_names", "ChromeCookieDecryptor: \"\"\" Overview: Linux: - cookies are either v10 or v11 - v10:", "xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None) desktop_session = env.get('DESKTOP_SESSION', None) if xdg_current_desktop is not None:", "recently used one i, paths = 0, [] with _create_progress_bar(logger) as progress_bar: for", "logger) elif keyring == _LinuxKeyring.GNOMEKEYRING: return _get_gnome_keyring_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.BASICTEXT: #", "None: xdg_current_desktop = xdg_current_desktop.split(':')[0].strip() if xdg_current_desktop == 'Unity': if desktop_session is not None", "return jar class ParserError(Exception): pass class DataParser: def __init__(self, data, logger): self._data =", "return stdout except Exception as e: logger.warning(f'exception running kwallet-query: {error_to_str(e)}') return b'' def", "Please consult ' 'the kwallet-query man page for details') return b'' else: if", "all keys # and presumably searches for its key in the list. It", "dbus while opening the browser in KDE: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" keyring_name =", "_extract_safari_cookies(profile, logger) elif browser_name in CHROMIUM_BASED_BROWSERS: return _extract_chrome_cookies(browser_name, profile, keyring, logger) else: raise", "def _extract_safari_cookies(profile, logger): if profile is not None: logger.error('safari does not support profiles')", "from .compat import compat_b64decode, compat_cookiejar_Cookie from .minicurses import MultilinePrinter, QuietMultilinePrinter from .utils import", "elif sys.platform == 'win32': return WindowsChromeCookieDecryptor(browser_root, logger) else: raise NotImplementedError(f'Chrome cookie decryption is", "YoutubeDLCookieJar(cookie_file) if os.access(cookie_file, os.R_OK): jar.load(ignore_discard=True, ignore_expires=True) cookie_jars.append(jar) return _merge_cookie_jars(cookie_jars) def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(),", "not None: cookie_file = expand_path(cookie_file) jar = YoutubeDLCookieJar(cookie_file) if os.access(cookie_file, os.R_OK): jar.load(ignore_discard=True, ignore_expires=True)", "= os.path.expanduser('~/Library/Application Support') browser_dir = { 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(appdata, 'Google/Chrome'), 'chromium':", "= MultilinePrinter(file, preserve_output=False) printer.print = lambda message: printer.print_at_line(f'[Cookies] {message}', 0) return printer def", "of size {len(data)} has no cookies') return p.skip_to(record_offsets[0], 'unknown page header field') with", "int((datetime(2001, 1, 1, 0, 0, tzinfo=timezone.utc) + timedelta(seconds=timestamp)).timestamp()) def _parse_safari_cookies_header(data, logger): p =", "= proc.communicate_or_kill() if stdout[-1:] == b'\\n': stdout = stdout[:-1] return stdout except Exception", "'Chromium', 'edge': 'Microsoft Edge' if sys.platform == 'darwin' else 'Chromium', 'opera': 'Opera' if", "The name of the wallet used to store network passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet which", "class ChromeCookieDecryptor: \"\"\" Overview: Linux: - cookies are either v10 or v11 -", "obtain password from OSX keychain') try: proc = Popen( ['security', 'find-generic-password', '-w', #", "with open(path, encoding='utf8') as f: data = json.load(f) try: base64_key = data['os_crypt']['encrypted_key'] except", "return is_encrypted, compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), path=path, path_specified=bool(path),", "keyring=None): if browser_name == 'firefox': return _extract_firefox_cookies(profile, logger) elif browser_name == 'safari': return", "be installed to read from KWallet. kwallet-query should be' 'included in the kwallet", "name of the wallet used to store network passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet which does", "MacChromeCookieDecryptor(browser_keyring_name, logger) elif sys.platform == 'win32': return WindowsChromeCookieDecryptor(browser_root, logger) else: raise NotImplementedError(f'Chrome cookie", "DPAPI encrypted # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return _decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8') def _extract_safari_cookies(profile, logger): if profile is", "host, name, value, path, expiry, isSecure FROM moz_cookies') jar = YoutubeDLCookieJar() with _create_progress_bar(logger)", "because chrome does not check hasEntry and instead # just tries to read", "kwallet returns \"\") whereas kwallet-query # checks hasEntry. To verify this: # dbus-monitor", "in the same way as KWallet, # using `dbus-monitor` during startup, it can", "only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v11_key, self._logger) else: self._cookie_counts['other'] += 1 return None", "tmpdir): # cannot open sqlite databases if they are already in use (e.g.", "filename, logger): # if there are multiple browser profiles, take the most recently", "presumably searches for its key in the list. It appears that we must", "= logger.progress_bar() if printer: return printer printer = QuietMultilinePrinter() printer.print = lambda _:", "'account' '-s', f'{browser_keyring_name} Safe Storage'], # match 'service' stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr =", "are multiple browser profiles, take the most recently used one i, paths =", "read from keyring') return b'' def _get_linux_keyring_password(browser_keyring_name, keyring, logger): # note: chrome/chromium can", "0} @staticmethod def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1003,", "- KeyStorageLinux::CreateService \"\"\" def decrypt(self, encrypted_value): raise NotImplementedError('Must be implemented by sub classes')", "_creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa: F841 try: p.skip_to(domain_offset) domain = p.read_cstring() p.skip_to(name_offset) name", "# dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" # while starting chrome. # this may be a", "cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path),", "self._v11_key = None if password is None else self.derive_key(password) self._cookie_counts = {'v10': 0,", "_process_chrome_cookie(decryptor, *line) if not cookie: failed_cookies += 1 continue elif not is_encrypted: unencrypted_cookies", "= p.read_uint() is_secure = bool(flags & 0x0001) p.skip(4, 'unknown record field 2') domain_offset", "value, path, expiry, is_secure) in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') cookie =", "def __init__(self, browser_keyring_name, logger, *, keyring=None): self._logger = logger self._v10_key = self.derive_key(b'peanuts') password", "if item.get_label() == f'{browser_keyring_name} Safe Storage': return item.get_secret() else: logger.error('failed to read from", "num_bytes < 0: raise ParserError(f'invalid skip of {num_bytes} bytes') def skip_to(self, offset, description='unknown'):", "1 jar.set_cookie(cookie) if failed_cookies > 0: failed_message = f' ({failed_cookies} could not be", "= self.read_bytes(1) if c == b'\\x00': return b''.join(buffer).decode('utf-8') else: buffer.append(c) def skip(self, num_bytes,", "p.expect_bytes(b'cook', 'database signature') number_of_pages = p.read_uint(big_endian=True) page_sizes = [p.read_uint(big_endian=True) for _ in range(number_of_pages)]", "secure_column = 'is_secure' if 'is_secure' in column_names else 'secure' cursor.execute(f'SELECT host_key, name, value,", "= DataParser(data, logger) record_size = p.read_uint() p.skip(4, 'unknown record field 1') flags =", "os.path.join(appdata_local, R'Chromium\\User Data'), 'edge': os.path.join(appdata_local, R'Microsoft\\Edge\\User Data'), 'opera': os.path.join(appdata_roaming, R'Opera Software\\Opera Stable'), 'vivaldi':", "key') return None return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) def pbkdf2_sha1(password, salt, iterations, key_length): return pbkdf2_hmac('sha1',", "return data def expect_bytes(self, expected_value, message): value = self.read_bytes(len(expected_value)) if value != expected_value:", "# cannot open sqlite databases if they are already in use (e.g. by", "p.skip_to(path_offset) path = p.read_cstring() p.skip_to(value_offset) value = p.read_cstring() except UnicodeDecodeError: logger.warning('failed to parse", "OSX keychain') try: proc = Popen( ['security', 'find-generic-password', '-w', # write password to", "!= {expected_value} ({message})') def read_uint(self, big_endian=False): data_format = '>I' if big_endian else '<I'", "return _LinuxDesktopEnvironment.KDE elif xdg_current_desktop == 'Pantheon': return _LinuxDesktopEnvironment.PANTHEON elif xdg_current_desktop == 'XFCE': return", "parts of the database structure is the same - there are a few", "'<I' return struct.unpack(data_format, self.read_bytes(4))[0] def read_double(self, big_endian=False): data_format = '>d' if big_endian else", "if desktop_session in ('mate', 'gnome'): return _LinuxDesktopEnvironment.GNOME elif 'kde' in desktop_session: return _LinuxDesktopEnvironment.KDE", "iterations=1, key_length=16) @property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value): version = encrypted_value[:3]", "dbus call to the following function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet \"\"\" default_wallet = 'kdewallet' try:", "'win32': return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif sys.platform == 'darwin': return os.path.expanduser('~/Library/Application Support/Firefox') else: raise ValueError(f'unsupported", "to decrypt cookie (AES-CBC) because UTF-8 decoding failed. Possibly the key is wrong?',", "raise ParserError(f'unexpected value: {value} != {expected_value} ({message})') def read_uint(self, big_endian=False): data_format = '>I'", "cookie (AES-GCM) because UTF-8 decoding failed. Possibly the key is wrong?', only_once=True) return", "is not None: output_jar.filename = jar.filename return output_jar def _is_path(value): return os.path.sep in", "ctypes.wintypes import DWORD class DATA_BLOB(ctypes.Structure): _fields_ = [('cbData', DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))] buffer =", "_firefox_browser_dir(): if sys.platform in ('linux', 'linux2'): return os.path.expanduser('~/.mozilla/firefox') elif sys.platform == 'win32': return", "elif sys.platform == 'darwin': appdata = os.path.expanduser('~/Library/Application Support') browser_dir = { 'brave': os.path.join(appdata,", "- v11 keys can be stored in various places depending on the activate", "this platform: {sys.platform}') class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger, *, keyring=None): self._logger =", "of the record') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=domain, domain_specified=bool(domain),", "def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1003, key_length=16) @property", "key_storage_ # Chromium supports a flag: --password-store=<basic|gnome|kwallet> so the automatic detection # will", "_get_chromium_based_browser_settings(browser_name) if profile is None: search_root = config['browser_dir'] elif _is_path(profile): search_root = profile", "State', logger) if path is None: logger.error('could not find local state file') return", "https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\" from ctypes.wintypes import DWORD class DATA_BLOB(ctypes.Structure): _fields_ = [('cbData', DWORD), ('pbData',", "# any other prefix means the data is DPAPI encrypted # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return", "'old data' which were stored as plaintext # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return encrypted_value class WindowsChromeCookieDecryptor(ChromeCookieDecryptor):", "ctypes.byref(blob_out) # pDataOut ) if not ret: logger.warning('failed to decrypt with DPAPI', only_once=True)", "try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.connection.text_factory = bytes column_names = _get_column_names(cursor, 'cookies') secure_column", "= p.read_uint() name_offset = p.read_uint() path_offset = p.read_uint() value_offset = p.read_uint() p.skip(8, 'unknown", "not installed. ' 'Please install by running `python3 -m pip install secretstorage`.') except", "sys.platform in ('linux', 'linux2'): return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring) elif sys.platform == 'darwin': return", "not find {browser_name} cookies database in \"{search_root}\"') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') decryptor =", "self.read_bytes(len(expected_value)) if value != expected_value: raise ParserError(f'unexpected value: {value} != {expected_value} ({message})') def", "_get_mac_keyring_password(browser_keyring_name, logger) self._v10_key = None if password is None else self.derive_key(password) self._cookie_counts =", "return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) def _open_database_copy(database_path, tmpdir): # cannot open sqlite databases if they", "(Optional)\"\"\" # Do not print to files/pipes, loggers, or when --no-progress is used", "'other': 0} @property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value): version = encrypted_value[:3]", "= encrypted_value[:3] ciphertext = encrypted_value[3:] if version == b'v10': self._cookie_counts['v10'] += 1 return", "def _choose_linux_keyring(logger): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend \"\"\" desktop_environment = _get_linux_desktop_environment(os.environ) logger.debug(f'detected desktop environment: {desktop_environment.name}')", "encrypted_value): version = encrypted_value[:3] ciphertext = encrypted_value[3:] if version == b'v10': self._cookie_counts['v10'] +=", "matter here. return b'' else: logger.debug('password found') if stdout[-1:] == b'\\n': stdout =", "_get_linux_keyring_password(browser_keyring_name, keyring, logger) self._v11_key = None if password is None else self.derive_key(password) self._cookie_counts", "None) if xdg_current_desktop is not None: xdg_current_desktop = xdg_current_desktop.split(':')[0].strip() if xdg_current_desktop == 'Unity':", "b''.join(buffer).decode('utf-8') else: buffer.append(c) def skip(self, num_bytes, description='unknown'): if num_bytes > 0: self._logger.debug(f'skipping {num_bytes}", "None encrypted_key = compat_b64decode(base64_key) prefix = b'DPAPI' if not encrypted_key.startswith(prefix): logger.error('invalid key') return", "SECRETSTORAGE_UNAVAILABLE_REASON = f'as the `secretstorage` module could not be initialized. {_err}' CHROMIUM_BASED_BROWSERS =", "preserve_output=False) printer.print = lambda message: printer.print_at_line(f'[Cookies] {message}', 0) return printer def _create_progress_bar(logger): if", "= 'kdewallet' try: proc = Popen([ 'dbus-send', '--session', '--print-reply=literal', '--dest=org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet.networkWallet' ],", "does not seem to organise keys in the same way as KWallet, #", "local state file') return None logger.debug(f'Found local state file at \"{path}\"') with open(path,", "cookies from {browser_name}') if not SQLITE_AVAILABLE: logger.warning(f'Cannot extract cookies from {browser_name} without sqlite3", "_parse_browser_specification(browser_name, profile=None, keyring=None): if browser_name not in SUPPORTED_BROWSERS: raise ValueError(f'unsupported browser: \"{browser_name}\"') if", "sys.platform == 'win32': return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif sys.platform == 'darwin': return os.path.expanduser('~/Library/Application Support/Firefox') else:", "_process_chrome_cookie(decryptor, host_key, name, value, encrypted_value, path, expires_utc, is_secure): host_key = host_key.decode('utf-8') name =", "is None: self._logger.warning('cannot decrypt v10 cookies: no key found', only_once=True) return None #", "v11 cookies: no key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v11_key, self._logger) else:", "'XFCE': return _LinuxDesktopEnvironment.XFCE elif desktop_session is not None: if desktop_session in ('mate', 'gnome'):", "jar.set_cookie(cookie) if failed_cookies > 0: failed_message = f' ({failed_cookies} could not be decrypted)'", "plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-CBC) because UTF-8 decoding failed. Possibly", "big_endian=False): data_format = '>I' if big_endian else '<I' return struct.unpack(data_format, self.read_bytes(4))[0] def read_double(self,", "password from kwallet. Using empty string instead') # this sometimes occurs in KDE", "# dwFlags ctypes.byref(blob_out) # pDataOut ) if not ret: logger.warning('failed to decrypt with", "if profile is None: search_root = config['browser_dir'] elif _is_path(profile): search_root = profile config['browser_dir']", "None: cursor.connection.close() def _process_chrome_cookie(decryptor, host_key, name, value, encrypted_value, path, expires_utc, is_secure): host_key =", "Sources: - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc - KeyStorageLinux::CreateService \"\"\" def decrypt(self, encrypted_value):", "> 0: failed_message = f' ({failed_cookies} could not be decrypted)' else: failed_message =", "only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) else: self._cookie_counts['other'] += 1 # other", "self._ydl.report_warning(message, only_once) def error(self, message): if self._ydl: self._ydl.report_error(message) def progress_bar(self): \"\"\"Return a context", "'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(appdata, 'Google/Chrome'), 'chromium': os.path.join(appdata, 'Chromium'), 'edge': os.path.join(appdata, 'Microsoft Edge'), 'opera': os.path.join(appdata,", "cookies') jar = YoutubeDLCookieJar() failed_cookies = 0 unencrypted_cookies = 0 with _create_progress_bar(logger) as", "is wrong?', only_once=True) return None def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, logger): try: plaintext", "logger): p = DataParser(data, logger) record_size = p.read_uint() p.skip(4, 'unknown record field 1')", "tmpdir) cursor.connection.text_factory = bytes column_names = _get_column_names(cursor, 'cookies') secure_column = 'is_secure' if 'is_secure'", "buffer.append(c) def skip(self, num_bytes, description='unknown'): if num_bytes > 0: self._logger.debug(f'skipping {num_bytes} bytes ({description}):", "host_key, name, value, encrypted_value, path, expires_utc, is_secure): host_key = host_key.decode('utf-8') name = name.decode('utf-8')", "self._cookie_counts['v11'] += 1 if self._v11_key is None: self._logger.warning('cannot decrypt v11 cookies: no key", "None return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) else: self._cookie_counts['other'] += 1 # other prefixes are", "logger.warning(f'Cannot extract cookies from {browser_name} without sqlite3 support. ' 'Please use a python", "_ in range(number_of_cookies)] if number_of_cookies == 0: logger.debug(f'a cookies page of size {len(data)}", "is None: search_root = config['browser_dir'] elif _is_path(profile): search_root = profile config['browser_dir'] = os.path.dirname(profile)", "by snooping on dbus while opening the browser in KDE: # dbus-monitor \"interface='org.kde.KWallet'\"", "= lambda message: printer.print_at_line(f'[Cookies] {message}', 0) return printer def _create_progress_bar(logger): if hasattr(logger, 'progress_bar'):", "NULL None, # pPromptStruct: information about prompts to display 0, # dwFlags ctypes.byref(blob_out)", "class ParserError(Exception): pass class DataParser: def __init__(self, data, logger): self._data = data self.cursor", "return YoutubeDLCookieJar() config = _get_chromium_based_browser_settings(browser_name) if profile is None: search_root = config['browser_dir'] elif", "= True except ImportError: # although sqlite3 is part of the standard library,", "return _LinuxDesktopEnvironment.GNOME elif xdg_current_desktop == 'X-Cinnamon': return _LinuxDesktopEnvironment.CINNAMON elif xdg_current_desktop == 'KDE': return", "aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7, ) from .compat import compat_b64decode, compat_cookiejar_Cookie from .minicurses import MultilinePrinter, QuietMultilinePrinter", "here. return b'' else: logger.debug('password found') if stdout[-1:] == b'\\n': stdout = stdout[:-1]", "'Unity': if desktop_session is not None and 'gnome-fallback' in desktop_session: return _LinuxDesktopEnvironment.GNOME else:", "'cookies') secure_column = 'is_secure' if 'is_secure' in column_names else 'secure' cursor.execute(f'SELECT host_key, name,", "= stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet = \"{network_wallet}\"') return network_wallet except Exception as e: logger.warning(f'exception while", "prefix means the data is DPAPI encrypted # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return _decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8') def", "return _LinuxDesktopEnvironment.XFCE else: if 'GNOME_DESKTOP_SESSION_ID' in env: return _LinuxDesktopEnvironment.GNOME elif 'KDE_FULL_SESSION' in env:", "os.path.expanduser('~/.config')) def _open_database_copy(database_path, tmpdir): # cannot open sqlite databases if they are already", "'edge': os.path.join(appdata, 'Microsoft Edge'), 'opera': os.path.join(appdata, 'com.operasoftware.Opera'), 'vivaldi': os.path.join(appdata, 'Vivaldi'), }[browser_name] else: raise", "ctypes.create_string_buffer(ciphertext) blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer) blob_out = DATA_BLOB() ret = ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in), #", "= self.derive_key(b'peanuts') password = _get_linux_keyring_password(browser_keyring_name, keyring, logger) self._v11_key = None if password is", "[2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc - KeyStorageLinux::CreateService \"\"\" def decrypt(self, encrypted_value): raise NotImplementedError('Must be implemented by", "other prefixes are considered 'old data' which were stored as plaintext # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm", "is not None: cursor.connection.close() def _process_chrome_cookie(decryptor, host_key, name, value, encrypted_value, path, expires_utc, is_secure):", "ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag = raw_ciphertext[-authentication_tag_length:] return _decrypt_aes_gcm(ciphertext, self._v10_key, nonce, authentication_tag, self._logger) else:", "Local State') return None encrypted_key = compat_b64decode(base64_key) prefix = b'DPAPI' if not encrypted_key.startswith(prefix):", "# when basic text is chosen, all cookies are stored as v10 (so", "def decrypt(self, encrypted_value): raise NotImplementedError('Must be implemented by sub classes') @property def cookie_counts(self):", "is encrypted with DPAPI - not v10: encrypted with DPAPI Sources: - [1]", "return record_size def parse_safari_cookies(data, jar=None, logger=YDLLogger()): \"\"\" References: - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc - this data", "os.path.join(appdata_local, R'Google\\Chrome\\User Data'), 'chromium': os.path.join(appdata_local, R'Chromium\\User Data'), 'edge': os.path.join(appdata_local, R'Microsoft\\Edge\\User Data'), 'opera': os.path.join(appdata_roaming,", "enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') is_encrypted, cookie = _process_chrome_cookie(decryptor, *line) if not", "sys.platform == 'darwin' else 'Chromium', 'vivaldi': 'Vivaldi' if sys.platform == 'darwin' else 'Chrome',", "base64_key = data['os_crypt']['encrypted_key'] except KeyError: logger.error('no encrypted key in Local State') return None", "failed_message = f' ({failed_cookies} could not be decrypted)' else: failed_message = '' logger.info(f'Extracted", "# pOptionalEntropy: salt? None, # pvReserved: must be NULL None, # pPromptStruct: information", "None, # pvReserved: must be NULL None, # pPromptStruct: information about prompts to", "in KDE because chrome does not check hasEntry and instead # just tries", "key in Local State') return None encrypted_key = compat_b64decode(base64_key) prefix = b'DPAPI' if", "kwallet package for your distribution') return b'' network_wallet = _get_kwallet_network_wallet(logger) try: proc =", "firefox') if not SQLITE_AVAILABLE: logger.warning('Cannot extract cookies from firefox without sqlite3 support. '", "_is_path(profile): search_root = profile config['browser_dir'] = os.path.dirname(profile) if config['supports_profiles'] else profile else: if", "cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value): version = encrypted_value[:3] ciphertext = encrypted_value[3:] if", "Possibly the key is wrong?', only_once=True) return None def _decrypt_windows_dpapi(ciphertext, logger): \"\"\" References:", "LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger, *, keyring=None): self._logger = logger self._v10_key = self.derive_key(b'peanuts')", "\"\"\" The name of the wallet used to store network passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet", "progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False,", "keyring, logger) else: raise ValueError(f'unknown browser: {browser_name}') def _extract_firefox_cookies(profile, logger): logger.info('Extracting cookies from", "# https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return _decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8') def _extract_safari_cookies(profile, logger): if profile is not None:", "read of {num_bytes} bytes') end = self.cursor + num_bytes if end > len(self._data):", "opening the browser in KDE: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" keyring_name = { 'brave':", "\"{keyring}\"') if profile is not None and _is_path(profile): profile = os.path.expanduser(profile) return browser_name,", "page for details') return b'' else: if stdout.lower().startswith(b'failed to read'): logger.debug('failed to read", "if not ret: logger.warning('failed to decrypt with DPAPI', only_once=True) return None result =", "_parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring)) if cookie_file is not None: cookie_file = expand_path(cookie_file)", "read_double(self, big_endian=False): data_format = '>d' if big_endian else '<d' return struct.unpack(data_format, self.read_bytes(8))[0] def", "Chromium supports a flag: --password-store=<basic|gnome|kwallet> so the automatic detection # will not be", "stdout = stdout[:-1] return stdout except Exception as e: logger.warning(f'exception running kwallet-query: {error_to_str(e)}')", "= self._ydl._out_files['error'] try: if not file.isatty(): return except BaseException: return printer = MultilinePrinter(file,", "- self.cursor, description) def skip_to_end(self, description='unknown'): self.skip_to(len(self._data), description) def _mac_absolute_time_to_posix(timestamp): return int((datetime(2001, 1,", "important parts of the database structure is the same - there are a", "logger) def pbkdf2_sha1(password, salt, iterations, key_length): return pbkdf2_hmac('sha1', password, salt, iterations, key_length) def", "from {browser_name}{failed_message}') counts = decryptor.cookie_counts.copy() counts['unencrypted'] = unencrypted_cookies logger.debug(f'cookie version breakdown: {counts}') return", "1, 1, 0, 0, tzinfo=timezone.utc) + timedelta(seconds=timestamp)).timestamp()) def _parse_safari_cookies_header(data, logger): p = DataParser(data,", "error(self, message): if self._ydl: self._ydl.report_error(message) def progress_bar(self): \"\"\"Return a context manager with a", "def read_uint(self, big_endian=False): data_format = '>I' if big_endian else '<I' return struct.unpack(data_format, self.read_bytes(4))[0]", "{message}', 0) return printer def _create_progress_bar(logger): if hasattr(logger, 'progress_bar'): printer = logger.progress_bar() if", "def _create_progress_bar(logger): if hasattr(logger, 'progress_bar'): printer = logger.progress_bar() if printer: return printer printer", "Support/Firefox') else: raise ValueError(f'unsupported platform: {sys.platform}') def _get_chromium_based_browser_settings(browser_name): # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if sys.platform in", "_get_column_names(cursor, table_name): table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall() return [row[1].decode('utf-8') for row in table_info] def", "of {num_bytes} bytes') def skip_to(self, offset, description='unknown'): self.skip(offset - self.cursor, description) def skip_to_end(self,", "there are multiple browser profiles, take the most recently used one i, paths", "= p.read_cstring() p.skip_to(name_offset) name = p.read_cstring() p.skip_to(path_offset) path = p.read_cstring() p.skip_to(value_offset) value =", "\"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment \"\"\" xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None) desktop_session = env.get('DESKTOP_SESSION', None) if", "if big_endian else '<d' return struct.unpack(data_format, self.read_bytes(8))[0] def read_cstring(self): buffer = [] while", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment \"\"\" xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None) desktop_session = env.get('DESKTOP_SESSION', None) if xdg_current_desktop", "\"\"\" References: - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc - this data appears to be out of date", "pbkdf2_hmac from .aes import ( aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7, ) from .compat import compat_b64decode,", "os.path.sep in value def _parse_browser_specification(browser_name, profile=None, keyring=None): if browser_name not in SUPPORTED_BROWSERS: raise", "dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" # while starting chrome. # this may be a bug", "is None: raise FileNotFoundError(f'could not find {browser_name} cookies database in \"{search_root}\"') logger.debug(f'Extracting cookies", "= { 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(appdata, 'Google/Chrome'), 'chromium': os.path.join(appdata, 'Chromium'), 'edge': os.path.join(appdata,", "rest={}) jar.set_cookie(cookie) return record_size def parse_safari_cookies(data, jar=None, logger=YDLLogger()): \"\"\" References: - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc -", "== _LinuxDesktopEnvironment.KDE: linux_keyring = _LinuxKeyring.KWALLET elif desktop_environment == _LinuxDesktopEnvironment.OTHER: linux_keyring = _LinuxKeyring.BASICTEXT else:", "signature') number_of_cookies = p.read_uint() record_offsets = [p.read_uint() for _ in range(number_of_cookies)] if number_of_cookies", "path_specified=bool(path), secure=is_secure, expires=expiry, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) logger.info(f'Extracted {len(jar)} cookies from firefox')", "= {'v10': 0, 'other': 0} @property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value):", "encrypted with a fixed key - v11: AES-CBC encrypted with an OS protected", "Stable'), 'vivaldi': os.path.join(appdata_local, R'Vivaldi\\User Data'), }[browser_name] elif sys.platform == 'darwin': appdata = os.path.expanduser('~/Library/Application", "def load_cookies(cookie_file, browser_specification, ydl): cookie_jars = [] if browser_specification is not None: browser_name,", "search_root = config['browser_dir'] cookie_database_path = _find_most_recently_used_file(search_root, 'Cookies', logger) if cookie_database_path is None: raise", "'Please install by running `python3 -m pip install secretstorage`.') except Exception as _err:", "logger def read_bytes(self, num_bytes): if num_bytes < 0: raise ParserError(f'invalid read of {num_bytes}", "\"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment \"\"\" OTHER = auto() CINNAMON = auto() GNOME = auto()", "if jar is None: jar = YoutubeDLCookieJar() page_sizes, body_start = _parse_safari_cookies_header(data, logger) p", "_firefox_browser_dir() elif _is_path(profile): search_root = profile else: search_root = os.path.join(_firefox_browser_dir(), profile) cookie_database_path =", "None else self.derive_key(password) self._cookie_counts = {'v10': 0, 'other': 0} @staticmethod def derive_key(password): #", "from .minicurses import MultilinePrinter, QuietMultilinePrinter from .utils import Popen, YoutubeDLCookieJar, error_to_str, expand_path try:", "{message}') def warning(self, message, only_once=False): if self._ydl: self._ydl.report_warning(message, only_once) def error(self, message): if", "_fields_ = [('cbData', DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))] buffer = ctypes.create_string_buffer(ciphertext) blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer)", "os.path.join(appdata, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(appdata, 'Google/Chrome'), 'chromium': os.path.join(appdata, 'Chromium'), 'edge': os.path.join(appdata, 'Microsoft Edge'), 'opera':", "self._logger) else: self._cookie_counts['other'] += 1 # any other prefix means the data is", "env: return _LinuxDesktopEnvironment.KDE return _LinuxDesktopEnvironment.OTHER def _choose_linux_keyring(logger): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend \"\"\" desktop_environment =", "Popen([ 'kwallet-query', '--read-password', f'{browser_keyring_name} Safe Storage', '--folder', f'{browser_keyring_name} Keys', network_wallet ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)", "return output_jar def _is_path(value): return os.path.sep in value def _parse_browser_specification(browser_name, profile=None, keyring=None): if", "path_offset = p.read_uint() value_offset = p.read_uint() p.skip(8, 'unknown record field 3') expiration_date =", "== 0: logger.debug(f'a cookies page of size {len(data)} has no cookies') return p.skip_to(record_offsets[0],", "PANTHEON = auto() UNITY = auto() XFCE = auto() class _LinuxKeyring(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h", "salt, iterations, key_length): return pbkdf2_hmac('sha1', password, salt, iterations, key_length) def _decrypt_aes_cbc(ciphertext, key, logger,", "kwallet-query to obtain password from kwallet') if shutil.which('kwallet-query') is None: logger.error('kwallet-query command not", "to organise keys in the same way as KWallet, # using `dbus-monitor` during", "bytes here and there which are skipped during parsing \"\"\" if jar is", "_get_chromium_based_browser_settings(browser_name): # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if sys.platform in ('linux', 'linux2'): config = _config_home() browser_dir =", "available {SECRETSTORAGE_UNAVAILABLE_REASON}') return b'' # the Gnome keyring does not seem to organise", "timedelta, timezone from enum import Enum, auto from hashlib import pbkdf2_hmac from .aes", "Edge' if sys.platform == 'darwin' else 'Chromium', 'opera': 'Opera' if sys.platform == 'darwin'", "use (e.g. by the browser) database_copy_path = os.path.join(tmpdir, 'temporary.sqlite') shutil.copy(database_path, database_copy_path) conn =", "basic text is chosen, all cookies are stored as v10 (so no keyring", "R'Vivaldi\\User Data'), }[browser_name] elif sys.platform == 'darwin': appdata = os.path.expanduser('~/Library/Application Support') browser_dir =", "chrome. # this may be a bug as the intended behaviour is to", "is not None: if desktop_session in ('mate', 'gnome'): return _LinuxDesktopEnvironment.GNOME elif 'kde' in", "YoutubeDLCookieJar, error_to_str, expand_path try: import sqlite3 SQLITE_AVAILABLE = True except ImportError: # although", "{num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}') elif num_bytes < 0: raise ParserError(f'invalid skip of {num_bytes}", "output_jar def _is_path(value): return os.path.sep in value def _parse_browser_specification(browser_name, profile=None, keyring=None): if browser_name", "None def _get_windows_v10_key(browser_root, logger): path = _find_most_recently_used_file(browser_root, 'Local State', logger) if path is", "in Local State') return None encrypted_key = compat_b64decode(base64_key) prefix = b'DPAPI' if not", "logger, keyring=keyring) elif sys.platform == 'darwin': return MacChromeCookieDecryptor(browser_keyring_name, logger) elif sys.platform == 'win32':", "not None: browser_name, profile, keyring = _parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring)) if cookie_file", "# other prefixes are considered 'old data' which were stored as plaintext #", "xdg_current_desktop.split(':')[0].strip() if xdg_current_desktop == 'Unity': if desktop_session is not None and 'gnome-fallback' in", "num_bytes if end > len(self._data): raise ParserError('reached end of input') data = self._data[self.cursor:end]", "_LinuxKeyring.GNOMEKEYRING: return _get_gnome_keyring_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.BASICTEXT: # when basic text is", "find-generic-password: {error_to_str(e)}') return None def _get_windows_v10_key(browser_root, logger): path = _find_most_recently_used_file(browser_root, 'Local State', logger)", "open(path, encoding='utf8') as f: data = json.load(f) try: base64_key = data['os_crypt']['encrypted_key'] except KeyError:", "return [row[1].decode('utf-8') for row in table_info] def _find_most_recently_used_file(root, filename, logger): # if there", "compat_cookiejar_Cookie from .minicurses import MultilinePrinter, QuietMultilinePrinter from .utils import Popen, YoutubeDLCookieJar, error_to_str, expand_path", "2') domain_offset = p.read_uint() name_offset = p.read_uint() path_offset = p.read_uint() value_offset = p.read_uint()", "= len(table) for i, (host, name, value, path, expiry, is_secure) in enumerate(table): progress_bar.print(f'Loading", "= unencrypted_cookies logger.debug(f'cookie version breakdown: {counts}') return jar finally: if cursor is not", "0} @staticmethod def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1,", "{error_to_str(e)}') return None def _get_windows_v10_key(browser_root, logger): path = _find_most_recently_used_file(browser_root, 'Local State', logger) if", "= os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): raise FileNotFoundError('could not find safari cookies database') with", "printer: return printer printer = QuietMultilinePrinter() printer.print = lambda _: None return printer", "xdg_current_desktop == 'GNOME': return _LinuxDesktopEnvironment.GNOME elif xdg_current_desktop == 'X-Cinnamon': return _LinuxDesktopEnvironment.CINNAMON elif xdg_current_desktop", "_LinuxDesktopEnvironment.OTHER: linux_keyring = _LinuxKeyring.BASICTEXT else: linux_keyring = _LinuxKeyring.GNOMEKEYRING return linux_keyring def _get_kwallet_network_wallet(logger): \"\"\"", "searched') if file == filename: paths.append(os.path.join(curr_root, file)) return None if not paths else", "\"{filename}\": {i: 6d} files searched') if file == filename: paths.append(os.path.join(curr_root, file)) return None", "}[browser_name] browsers_without_profiles = {'opera'} return { 'browser_dir': browser_dir, 'keyring_name': keyring_name, 'supports_profiles': browser_name not", "key_length=16) @property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value): version = encrypted_value[:3] ciphertext", "from: \"{cookie_database_path}\"') decryptor = get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger, keyring=keyring) with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor", "DataParser(data, logger) p.expect_bytes(b'cook', 'database signature') number_of_pages = p.read_uint(big_endian=True) page_sizes = [p.read_uint(big_endian=True) for _", "logger self._v10_key = _get_windows_v10_key(browser_root, logger) self._cookie_counts = {'v10': 0, 'other': 0} @property def", "keyring=None): if browser_name not in SUPPORTED_BROWSERS: raise ValueError(f'unsupported browser: \"{browser_name}\"') if keyring not", "at the end of the record') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None,", "'safari': return _extract_safari_cookies(profile, logger) elif browser_name in CHROMIUM_BASED_BROWSERS: return _extract_chrome_cookies(browser_name, profile, keyring, logger)", "'chromium'), 'edge': os.path.join(config, 'microsoft-edge'), 'opera': os.path.join(config, 'opera'), 'vivaldi': os.path.join(config, 'vivaldi'), }[browser_name] elif sys.platform", "sys.platform == 'darwin': appdata = os.path.expanduser('~/Library/Application Support') browser_dir = { 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'),", "browser_name not in browsers_without_profiles } def _extract_chrome_cookies(browser_name, profile, keyring, logger): logger.info(f'Extracting cookies from", "(host, name, value, path, expiry, is_secure) in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}')", "1 continue elif not is_encrypted: unencrypted_cookies += 1 jar.set_cookie(cookie) if failed_cookies > 0:", "version breakdown: {counts}') return jar finally: if cursor is not None: cursor.connection.close() def", "'page signature') number_of_cookies = p.read_uint() record_offsets = [p.read_uint() for _ in range(number_of_cookies)] if", "# https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1003, key_length=16) @property def cookie_counts(self): return self._cookie_counts def", "in all cases. keyring = _LinuxKeyring[keyring] if keyring else _choose_linux_keyring(logger) logger.debug(f'Chosen keyring: {keyring.name}')", "salt? None, # pvReserved: must be NULL None, # pPromptStruct: information about prompts", "can be determined by snooping on dbus while opening the browser in KDE:", "profile, keyring, logger): logger.info(f'Extracting cookies from {browser_name}') if not SQLITE_AVAILABLE: logger.warning(f'Cannot extract cookies", "profile config['browser_dir'] = os.path.dirname(profile) if config['supports_profiles'] else profile else: if config['supports_profiles']: search_root =", "logger) p.skip_to_end('footer') return jar class _LinuxDesktopEnvironment(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment \"\"\" OTHER = auto()", "not check hasEntry and instead # just tries to read the value (which", "--v=1 2>&1 | grep key_storage_ # Chromium supports a flag: --password-store=<basic|gnome|kwallet> so the", "table_info] def _find_most_recently_used_file(root, filename, logger): # if there are multiple browser profiles, take", "'supports_profiles': browser_name not in browsers_without_profiles } def _extract_chrome_cookies(browser_name, profile, keyring, logger): logger.info(f'Extracting cookies", "same - there are a few bytes here and there which are skipped", "blob_out = DATA_BLOB() ret = ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in), # pDataIn None, # ppszDataDescr: human", "possible to compile python without # sqlite support. See: https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE = False", "not seem to organise keys in the same way as KWallet, # using", "_LinuxDesktopEnvironment.GNOME elif 'kde' in desktop_session: return _LinuxDesktopEnvironment.KDE elif 'xfce' in desktop_session: return _LinuxDesktopEnvironment.XFCE", "browser: {browser_name}') def _extract_firefox_cookies(profile, logger): logger.info('Extracting cookies from firefox') if not SQLITE_AVAILABLE: logger.warning('Cannot", "== 'Pantheon': return _LinuxDesktopEnvironment.PANTHEON elif xdg_current_desktop == 'XFCE': return _LinuxDesktopEnvironment.XFCE elif desktop_session is", "no keyring password is required) return None assert False, f'Unknown keyring {keyring}' def", "to stdout '-a', browser_keyring_name, # match 'account' '-s', f'{browser_keyring_name} Safe Storage'], # match", "_get_column_names(cursor, 'cookies') secure_column = 'is_secure' if 'is_secure' in column_names else 'secure' cursor.execute(f'SELECT host_key,", "failed. Possibly the key is wrong?', only_once=True) return None def _decrypt_windows_dpapi(ciphertext, logger): \"\"\"", "number_of_pages = p.read_uint(big_endian=True) page_sizes = [p.read_uint(big_endian=True) for _ in range(number_of_pages)] return page_sizes, p.cursor", "Mac: - cookies are either v10 or not v10 - v10: AES-CBC encrypted", "cookies: no key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) else: self._cookie_counts['other']", "a random password and store # it, but that doesn't matter here. return", "_config_home(): return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) def _open_database_copy(database_path, tmpdir): # cannot open sqlite databases if", "'unknown record field 2') domain_offset = p.read_uint() name_offset = p.read_uint() path_offset = p.read_uint()", "p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page signature') number_of_cookies = p.read_uint() record_offsets = [p.read_uint() for _ in range(number_of_cookies)]", "should be' 'included in the kwallet package for your distribution') return b'' network_wallet", "other prefix means the data is DPAPI encrypted # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return _decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8')", "_extract_safari_cookies(profile, logger): if profile is not None: logger.error('safari does not support profiles') if", "else: return _LinuxDesktopEnvironment.UNITY elif xdg_current_desktop == 'GNOME': return _LinuxDesktopEnvironment.GNOME elif xdg_current_desktop == 'X-Cinnamon':", "logger) p.read_bytes(record_length) p.skip_to_end('space in between pages') def _parse_safari_cookies_record(data, jar, logger): p = DataParser(data,", "'Chromium'), 'edge': os.path.join(appdata, 'Microsoft Edge'), 'opera': os.path.join(appdata, 'com.operasoftware.Opera'), 'vivaldi': os.path.join(appdata, 'Vivaldi'), }[browser_name] else:", "_get_gnome_keyring_password(browser_keyring_name, logger): if not SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage not available {SECRETSTORAGE_UNAVAILABLE_REASON}') return b'' # the", "1 return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) elif version == b'v11': self._cookie_counts['v11'] += 1 if", "try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-GCM) because UTF-8 decoding", "a key which is encrypted with DPAPI - not v10: encrypted with DPAPI", "file at \"{path}\"') with open(path, encoding='utf8') as f: data = json.load(f) try: base64_key", "chromium --enable-logging=stderr --v=1 2>&1 | grep key_storage_ # Chromium supports a flag: --password-store=<basic|gnome|kwallet>", "support') return YoutubeDLCookieJar() if profile is None: search_root = _firefox_browser_dir() elif _is_path(profile): search_root", "from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1003, key_length=16) @property def cookie_counts(self): return self._cookie_counts", "return printer = MultilinePrinter(file, preserve_output=False) printer.print = lambda message: printer.print_at_line(f'[Cookies] {message}', 0) return", "_LinuxDesktopEnvironment.GNOME elif xdg_current_desktop == 'X-Cinnamon': return _LinuxDesktopEnvironment.CINNAMON elif xdg_current_desktop == 'KDE': return _LinuxDesktopEnvironment.KDE", "field 1') flags = p.read_uint() is_secure = bool(flags & 0x0001) p.skip(4, 'unknown record", "'Microsoft Edge'), 'opera': os.path.join(appdata, 'com.operasoftware.Opera'), 'vivaldi': os.path.join(appdata, 'Vivaldi'), }[browser_name] else: raise ValueError(f'unsupported platform:", "sqlite3 support. ' 'Please use a python interpreter compiled with sqlite3 support') return", "= env.get('DESKTOP_SESSION', None) if xdg_current_desktop is not None: xdg_current_desktop = xdg_current_desktop.split(':')[0].strip() if xdg_current_desktop", "context manager with a print method. (Optional)\"\"\" # Do not print to files/pipes,", "# pvReserved: must be NULL None, # pPromptStruct: information about prompts to display", "'unknown record field 3') expiration_date = _mac_absolute_time_to_posix(p.read_double()) _creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa: F841", "_merge_cookie_jars(cookie_jars) def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *, keyring=None): if browser_name == 'firefox': return _extract_firefox_cookies(profile,", "database in \"{search_root}\"') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') decryptor = get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger, keyring=keyring)", "description) def _mac_absolute_time_to_posix(timestamp): return int((datetime(2001, 1, 1, 0, 0, tzinfo=timezone.utc) + timedelta(seconds=timestamp)).timestamp()) def", "may be a bug as the intended behaviour is to generate a random", "if not SQLITE_AVAILABLE: logger.warning(f'Cannot extract cookies from {browser_name} without sqlite3 support. ' 'Please", "browser_dir = { 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(config, 'google-chrome'), 'chromium': os.path.join(config, 'chromium'), 'edge':", "= logger self._v10_key = _get_windows_v10_key(browser_root, logger) self._cookie_counts = {'v10': 0, 'other': 0} @property", "data_format = '>I' if big_endian else '<I' return struct.unpack(data_format, self.read_bytes(4))[0] def read_double(self, big_endian=False):", "ValueError: logger.warning('failed to decrypt cookie (AES-GCM) because the MAC check failed. Possibly the", "is wrong?', only_once=True) return None try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt", "browser in KDE: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" keyring_name = { 'brave': 'Brave', 'chrome':", "column_names else 'secure' cursor.execute(f'SELECT host_key, name, value, encrypted_value, path, expires_utc, {secure_column} FROM cookies')", "expiry, isSecure FROM moz_cookies') jar = YoutubeDLCookieJar() with _create_progress_bar(logger) as progress_bar: table =", "= f.read() jar = parse_safari_cookies(cookies_data, logger=logger) logger.info(f'Extracted {len(jar)} cookies from safari') return jar", "salt=b'<PASSWORD>', iterations=1003, key_length=16) @property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value): version =", "is not installed. ' 'Please install by running `python3 -m pip install secretstorage`.')", "counts = decryptor.cookie_counts.copy() counts['unencrypted'] = unencrypted_cookies logger.debug(f'cookie version breakdown: {counts}') return jar finally:", "about prompts to display 0, # dwFlags ctypes.byref(blob_out) # pDataOut ) if not", "_LinuxDesktopEnvironment.OTHER def _choose_linux_keyring(logger): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend \"\"\" desktop_environment = _get_linux_desktop_environment(os.environ) logger.debug(f'detected desktop environment:", "elif desktop_session is not None: if desktop_session in ('mate', 'gnome'): return _LinuxDesktopEnvironment.GNOME elif", "self.cursor = end return data def expect_bytes(self, expected_value, message): value = self.read_bytes(len(expected_value)) if", "0, 'other': 0} @staticmethod def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return pbkdf2_sha1(password,", "None) desktop_session = env.get('DESKTOP_SESSION', None) if xdg_current_desktop is not None: xdg_current_desktop = xdg_current_desktop.split(':')[0].strip()", "not is_encrypted: unencrypted_cookies += 1 jar.set_cookie(cookie) if failed_cookies > 0: failed_message = f'", "keys # and presumably searches for its key in the list. It appears", "logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page signature') number_of_cookies = p.read_uint() record_offsets = [p.read_uint() for _ in", "name_offset = p.read_uint() path_offset = p.read_uint() value_offset = p.read_uint() p.skip(8, 'unknown record field", "number_of_cookies = p.read_uint() record_offsets = [p.read_uint() for _ in range(number_of_cookies)] if number_of_cookies ==", "output_jar = YoutubeDLCookieJar() for jar in jars: for cookie in jar: output_jar.set_cookie(cookie) if", "= os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): logger.debug('Trying secondary cookie location') cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if", "sys.platform in ('linux', 'linux2'): config = _config_home() browser_dir = { 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'),", "is DPAPI encrypted # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return _decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8') def _extract_safari_cookies(profile, logger): if profile", "= False try: import secretstorage SECRETSTORAGE_AVAILABLE = True except ImportError: SECRETSTORAGE_AVAILABLE = False", "error_to_str, expand_path try: import sqlite3 SQLITE_AVAILABLE = True except ImportError: # although sqlite3", "# noqa: F841 try: p.skip_to(domain_offset) domain = p.read_cstring() p.skip_to(name_offset) name = p.read_cstring() p.skip_to(path_offset)", "NetworkWallet: {e}') return default_wallet def _get_kwallet_password(browser_keyring_name, logger): logger.debug('using kwallet-query to obtain password from", "# https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if sys.platform in ('linux', 'linux2'): config = _config_home() browser_dir = {", "_LinuxDesktopEnvironment(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment \"\"\" OTHER = auto() CINNAMON = auto() GNOME =", "table = cursor.fetchall() total_cookie_count = len(table) for i, (host, name, value, path, expiry,", "return os.path.expanduser('~/.mozilla/firefox') elif sys.platform == 'win32': return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif sys.platform == 'darwin': return", "value.decode('utf-8') path = path.decode('utf-8') is_encrypted = not value and encrypted_value if is_encrypted: value", "which are skipped during parsing \"\"\" if jar is None: jar = YoutubeDLCookieJar()", "SelectedLinuxBackend \"\"\" KWALLET = auto() GNOMEKEYRING = auto() BASICTEXT = auto() SUPPORTED_KEYRINGS =", "default_wallet def _get_kwallet_password(browser_keyring_name, logger): logger.debug('using kwallet-query to obtain password from kwallet') if shutil.which('kwallet-query')", "if config['supports_profiles'] else profile else: if config['supports_profiles']: search_root = os.path.join(config['browser_dir'], profile) else: logger.error(f'{browser_name}", "_err: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = f'as the `secretstorage` module could not be", "State') return None encrypted_key = compat_b64decode(base64_key) prefix = b'DPAPI' if not encrypted_key.startswith(prefix): logger.error('invalid", "keyring == _LinuxKeyring.GNOMEKEYRING: return _get_gnome_keyring_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.BASICTEXT: # when basic", "stdout, stderr = proc.communicate_or_kill() if proc.returncode != 0: logger.warning('failed to read NetworkWallet') return", "to read the value (which kwallet returns \"\") whereas kwallet-query # checks hasEntry.", "return _LinuxDesktopEnvironment.OTHER def _choose_linux_keyring(logger): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend \"\"\" desktop_environment = _get_linux_desktop_environment(os.environ) logger.debug(f'detected desktop", "v11: AES-CBC encrypted with an OS protected key (keyring) - v11 keys can", "are stored as v10 (so no keyring password is required) return None assert", "total_cookie_count = len(table) for i, line in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}')", "'Vivaldi' if sys.platform == 'darwin' else 'Chrome', }[browser_name] browsers_without_profiles = {'opera'} return {", "logger.info(f'Extracted {len(jar)} cookies from safari') return jar class ParserError(Exception): pass class DataParser: def", "return _LinuxDesktopEnvironment.GNOME elif 'kde' in desktop_session: return _LinuxDesktopEnvironment.KDE elif 'xfce' in desktop_session: return", "SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = ( 'as the `secretstorage` module is not installed.", "item in col.get_all_items(): if item.get_label() == f'{browser_keyring_name} Safe Storage': return item.get_secret() else: logger.error('failed", "of input') data = self._data[self.cursor:end] self.cursor = end return data def expect_bytes(self, expected_value,", "is None: self._logger.warning('cannot decrypt v11 cookies: no key found', only_once=True) return None return", "as tmpdir: cursor = None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.connection.text_factory = bytes", "= bool(flags & 0x0001) p.skip(4, 'unknown record field 2') domain_offset = p.read_uint() name_offset", "ParserError(Exception): pass class DataParser: def __init__(self, data, logger): self._data = data self.cursor =", "None else self.derive_key(password) self._cookie_counts = {'v10': 0, 'v11': 0, 'other': 0} @staticmethod def", "port_specified=False, domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie)", "value_offset = p.read_uint() p.skip(8, 'unknown record field 3') expiration_date = _mac_absolute_time_to_posix(p.read_double()) _creation_date =", "KWalletDBus::NetworkWallet which does a dbus call to the following function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet \"\"\"", "return self._cookie_counts def decrypt(self, encrypted_value): version = encrypted_value[:3] ciphertext = encrypted_value[3:] if version", "auto() GNOMEKEYRING = auto() BASICTEXT = auto() SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys() def _get_linux_desktop_environment(env): \"\"\"", "self._data[self.cursor:end] self.cursor = end return data def expect_bytes(self, expected_value, message): value = self.read_bytes(len(expected_value))", "= _parse_safari_cookies_header(data, logger) p = DataParser(data[body_start:], logger) for page_size in page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size), jar,", "in CHROMIUM_BASED_BROWSERS: return _extract_chrome_cookies(browser_name, profile, keyring, logger) else: raise ValueError(f'unknown browser: {browser_name}') def", "sys.platform == 'darwin' else 'Chrome', }[browser_name] browsers_without_profiles = {'opera'} return { 'browser_dir': browser_dir,", "not None: cursor.connection.close() def _process_chrome_cookie(decryptor, host_key, name, value, encrypted_value, path, expires_utc, is_secure): host_key", "logger.error('invalid key') return None return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) def pbkdf2_sha1(password, salt, iterations, key_length): return", "offset, description='unknown'): self.skip(offset - self.cursor, description) def skip_to_end(self, description='unknown'): self.skip_to(len(self._data), description) def _mac_absolute_time_to_posix(timestamp):", "kwallet. Using empty string instead') # this sometimes occurs in KDE because chrome", "cursor.connection.close() def _firefox_browser_dir(): if sys.platform in ('linux', 'linux2'): return os.path.expanduser('~/.mozilla/firefox') elif sys.platform ==", "if password is None else self.derive_key(password) self._cookie_counts = {'v10': 0, 'v11': 0, 'other':", "desktop_environment == _LinuxDesktopEnvironment.OTHER: linux_keyring = _LinuxKeyring.BASICTEXT else: linux_keyring = _LinuxKeyring.GNOMEKEYRING return linux_keyring def", "None: cookie_file = expand_path(cookie_file) jar = YoutubeDLCookieJar(cookie_file) if os.access(cookie_file, os.R_OK): jar.load(ignore_discard=True, ignore_expires=True) cookie_jars.append(jar)", "keyring') return b'' def _get_linux_keyring_password(browser_keyring_name, keyring, logger): # note: chrome/chromium can be run", "{browser_name}') if not SQLITE_AVAILABLE: logger.warning(f'Cannot extract cookies from {browser_name} without sqlite3 support. '", "jar = YoutubeDLCookieJar(cookie_file) if os.access(cookie_file, os.R_OK): jar.load(ignore_discard=True, ignore_expires=True) cookie_jars.append(jar) return _merge_cookie_jars(cookie_jars) def extract_cookies_from_browser(browser_name,", "_create_progress_bar(logger) as progress_bar: for i, record_offset in enumerate(record_offsets): progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies: 6d}')", "in range(number_of_cookies)] if number_of_cookies == 0: logger.debug(f'a cookies page of size {len(data)} has", "following flags to determine which keyring backend # it has chosen to use", "if os.access(cookie_file, os.R_OK): jar.load(ignore_discard=True, ignore_expires=True) cookie_jars.append(jar) return _merge_cookie_jars(cookie_jars) def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *,", "key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) else: self._cookie_counts['other'] += 1", "network_wallet ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode != 0: logger.error(f'kwallet-query", "path, expires_utc, {secure_column} FROM cookies') jar = YoutubeDLCookieJar() failed_cookies = 0 unencrypted_cookies =", "# write password to stdout '-a', browser_keyring_name, # match 'account' '-s', f'{browser_keyring_name} Safe", "config['supports_profiles'] else profile else: if config['supports_profiles']: search_root = os.path.join(config['browser_dir'], profile) else: logger.error(f'{browser_name} does", "cookie_database_path = _find_most_recently_used_file(search_root, 'cookies.sqlite', logger) if cookie_database_path is None: raise FileNotFoundError(f'could not find", "printer def load_cookies(cookie_file, browser_specification, ydl): cookie_jars = [] if browser_specification is not None:", "return { 'browser_dir': browser_dir, 'keyring_name': keyring_name, 'supports_profiles': browser_name not in browsers_without_profiles } def", "_find_most_recently_used_file(root, filename, logger): # if there are multiple browser profiles, take the most", "with a fixed key - v11: AES-CBC encrypted with an OS protected key", "value: {value} != {expected_value} ({message})') def read_uint(self, big_endian=False): data_format = '>I' if big_endian", "be out of date but the important parts of the database structure is", "self._ydl.params.get('noprogress') or self._ydl.params.get('logger'): return file = self._ydl._out_files['error'] try: if not file.isatty(): return except", "+= 1 return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) elif version == b'v11': self._cookie_counts['v11'] += 1", "self._data = data self.cursor = 0 self._logger = logger def read_bytes(self, num_bytes): if", "encrypted # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return _decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8') def _extract_safari_cookies(profile, logger): if profile is not", "browser_specification is not None: browser_name, profile, keyring = _parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring))", "for its key in the list. It appears that we must do the", "contextlib.closing(secretstorage.dbus_init()) as con: col = secretstorage.get_default_collection(con) for item in col.get_all_items(): if item.get_label() ==", "_decrypt_aes_cbc(ciphertext, self._v11_key, self._logger) else: self._cookie_counts['other'] += 1 return None class MacChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self,", "conn = sqlite3.connect(database_copy_path) return conn.cursor() def _get_column_names(cursor, table_name): table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall() return", "- not v10: encrypted with DPAPI Sources: - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc", "logger.error('no encrypted key in Local State') return None encrypted_key = compat_b64decode(base64_key) prefix =", "'as the `secretstorage` module is not installed. ' 'Please install by running `python3", "value (which kwallet returns \"\") whereas kwallet-query # checks hasEntry. To verify this:", "= p.read_uint() p.skip(8, 'unknown record field 3') expiration_date = _mac_absolute_time_to_posix(p.read_double()) _creation_date = _mac_absolute_time_to_posix(p.read_double())", "`python3 -m pip install secretstorage`.') except Exception as _err: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON", "return page_sizes, p.cursor def _parse_safari_cookies_page(data, jar, logger): p = DataParser(data, logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page", "use # chromium --enable-logging=stderr --v=1 2>&1 | grep key_storage_ # Chromium supports a", "i, record_offset in enumerate(record_offsets): progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies: 6d}') p.skip_to(record_offset, 'space between records')", "not print to files/pipes, loggers, or when --no-progress is used if not self._ydl", "path is None: logger.error('could not find local state file') return None logger.debug(f'Found local", "all cookies are stored as v10 (so no keyring password is required) return", "profile) else: logger.error(f'{browser_name} does not support profiles') search_root = config['browser_dir'] cookie_database_path = _find_most_recently_used_file(search_root,", "= bytes column_names = _get_column_names(cursor, 'cookies') secure_column = 'is_secure' if 'is_secure' in column_names", "SECRETSTORAGE_AVAILABLE = True except ImportError: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = ( 'as the", "conn.cursor() def _get_column_names(cursor, table_name): table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall() return [row[1].decode('utf-8') for row in", "def _parse_safari_cookies_header(data, logger): p = DataParser(data, logger) p.expect_bytes(b'cook', 'database signature') number_of_pages = p.read_uint(big_endian=True)", "env.get('XDG_CURRENT_DESKTOP', None) desktop_session = env.get('DESKTOP_SESSION', None) if xdg_current_desktop is not None: xdg_current_desktop =", "be initialized. {_err}' CHROMIUM_BASED_BROWSERS = {'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi'} SUPPORTED_BROWSERS =", "' * 16): plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector)) try: return plaintext.decode('utf-8') except UnicodeDecodeError:", "# this sometimes occurs in KDE because chrome does not check hasEntry and", "read password from kwallet. Using empty string instead') # this sometimes occurs in", "self.derive_key(password) self._cookie_counts = {'v10': 0, 'v11': 0, 'other': 0} @staticmethod def derive_key(password): #", "v10: encrypted with DPAPI Sources: - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc - KeyStorageLinux::CreateService", "expires=expires_utc, discard=False, comment=None, comment_url=None, rest={}) class ChromeCookieDecryptor: \"\"\" Overview: Linux: - cookies are", "'opera': 'Opera' if sys.platform == 'darwin' else 'Chromium', 'vivaldi': 'Vivaldi' if sys.platform ==", "MAC check failed. Possibly the key is wrong?', only_once=True) return None try: return", "def _config_home(): return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) def _open_database_copy(database_path, tmpdir): # cannot open sqlite databases", "part of the standard library, it is possible to compile python without #", "_parse_safari_cookies_page(data, jar, logger): p = DataParser(data, logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page signature') number_of_cookies = p.read_uint()", "== b'\\x00': return b''.join(buffer).decode('utf-8') else: buffer.append(c) def skip(self, num_bytes, description='unknown'): if num_bytes >", "from {browser_name} without sqlite3 support. ' 'Please use a python interpreter compiled with", "stdout = stdout[:-1] return stdout except Exception as e: logger.warning(f'exception running find-generic-password: {error_to_str(e)}')", "determine which keyring backend # it has chosen to use # chromium --enable-logging=stderr", "plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-GCM) because UTF-8 decoding failed. Possibly", "= _LinuxKeyring.KWALLET elif desktop_environment == _LinuxDesktopEnvironment.OTHER: linux_keyring = _LinuxKeyring.BASICTEXT else: linux_keyring = _LinuxKeyring.GNOMEKEYRING", "default_wallet = 'kdewallet' try: proc = Popen([ 'dbus-send', '--session', '--print-reply=literal', '--dest=org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet.networkWallet'", "profile is not None: logger.error('safari does not support profiles') if sys.platform != 'darwin':", "'gnome-fallback' in desktop_session: return _LinuxDesktopEnvironment.GNOME else: return _LinuxDesktopEnvironment.UNITY elif xdg_current_desktop == 'GNOME': return", "= path.decode('utf-8') is_encrypted = not value and encrypted_value if is_encrypted: value = decryptor.decrypt(encrypted_value)", "To verify this: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" # while starting chrome. # this", "result def _config_home(): return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) def _open_database_copy(database_path, tmpdir): # cannot open sqlite", "cookie_database_path is None: raise FileNotFoundError(f'could not find firefox cookies database in {search_root}') logger.debug(f'Extracting", "for jar in jars: for cookie in jar: output_jar.set_cookie(cookie) if jar.filename is not", "= CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'} class YDLLogger: def __init__(self, ydl=None): self._ydl = ydl", "Exception as e: logger.warning(f'exception running find-generic-password: {error_to_str(e)}') return None def _get_windows_v10_key(browser_root, logger): path", "decrypt with DPAPI', only_once=True) return None result = ctypes.string_at(blob_out.pbData, blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData) return result", "network passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet which does a dbus call to the following function:", "logger) else: raise NotImplementedError(f'Chrome cookie decryption is not supported on this platform: {sys.platform}')", "def _parse_browser_specification(browser_name, profile=None, keyring=None): if browser_name not in SUPPORTED_BROWSERS: raise ValueError(f'unsupported browser: \"{browser_name}\"')", "cookie_database_path is None: raise FileNotFoundError(f'could not find {browser_name} cookies database in \"{search_root}\"') logger.debug(f'Extracting", "kwallet-query man page for details') return b'' else: if stdout.lower().startswith(b'failed to read'): logger.debug('failed", "return b'' def _get_gnome_keyring_password(browser_keyring_name, logger): if not SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage not available {SECRETSTORAGE_UNAVAILABLE_REASON}') return", "profile else: if config['supports_profiles']: search_root = os.path.join(config['browser_dir'], profile) else: logger.error(f'{browser_name} does not support", "@staticmethod def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1003, key_length=16)", "most recently used one i, paths = 0, [] with _create_progress_bar(logger) as progress_bar:", "False SECRETSTORAGE_UNAVAILABLE_REASON = ( 'as the `secretstorage` module is not installed. ' 'Please", "= _get_column_names(cursor, 'cookies') secure_column = 'is_secure' if 'is_secure' in column_names else 'secure' cursor.execute(f'SELECT", "def _get_windows_v10_key(browser_root, logger): path = _find_most_recently_used_file(browser_root, 'Local State', logger) if path is None:", "cookies: no key found', only_once=True) return None # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc # kNonceLength nonce_length =", "self._ydl.report_error(message) def progress_bar(self): \"\"\"Return a context manager with a print method. (Optional)\"\"\" #", "chromium lists all keys # and presumably searches for its key in the", "class _LinuxKeyring(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend \"\"\" KWALLET = auto() GNOMEKEYRING = auto() BASICTEXT", "def _extract_chrome_cookies(browser_name, profile, keyring, logger): logger.info(f'Extracting cookies from {browser_name}') if not SQLITE_AVAILABLE: logger.warning(f'Cannot", "= end return data def expect_bytes(self, expected_value, message): value = self.read_bytes(len(expected_value)) if value", "return jar finally: if cursor is not None: cursor.connection.close() def _firefox_browser_dir(): if sys.platform", "the list. It appears that we must do the same. # https://github.com/jaraco/keyring/issues/556 with", "pOptionalEntropy: salt? None, # pvReserved: must be NULL None, # pPromptStruct: information about", "!= 'darwin': raise ValueError(f'unsupported platform: {sys.platform}') cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): logger.debug('Trying", "appdata = os.path.expanduser('~/Library/Application Support') browser_dir = { 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(appdata, 'Google/Chrome'),", "return except BaseException: return printer = MultilinePrinter(file, preserve_output=False) printer.print = lambda message: printer.print_at_line(f'[Cookies]", "the browser in KDE: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" keyring_name = { 'brave': 'Brave',", "decrypt(self, encrypted_value): raise NotImplementedError('Must be implemented by sub classes') @property def cookie_counts(self): raise", "if big_endian else '<I' return struct.unpack(data_format, self.read_bytes(4))[0] def read_double(self, big_endian=False): data_format = '>d'", "0: self._logger.debug(f'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}') elif num_bytes < 0: raise ParserError(f'invalid skip", "@property def cookie_counts(self): raise NotImplementedError('Must be implemented by sub classes') def get_cookie_decryptor(browser_root, browser_keyring_name,", "return conn.cursor() def _get_column_names(cursor, table_name): table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall() return [row[1].decode('utf-8') for row", "else: self._cookie_counts['other'] += 1 # other prefixes are considered 'old data' which were", "'org.kde.KWallet.networkWallet' ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode != 0: logger.warning('failed", "return None if not paths else max(paths, key=lambda path: os.lstat(path).st_mtime) def _merge_cookie_jars(jars): output_jar", "except Exception as e: logger.warning(f'exception running kwallet-query: {error_to_str(e)}') return b'' def _get_gnome_keyring_password(browser_keyring_name, logger):", "= name.decode('utf-8') value = value.decode('utf-8') path = path.decode('utf-8') is_encrypted = not value and", "ParserError(f'invalid read of {num_bytes} bytes') end = self.cursor + num_bytes if end >", "read NetworkWallet') return default_wallet else: network_wallet = stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet = \"{network_wallet}\"') return network_wallet", "observed that chromium lists all keys # and presumably searches for its key", "support profiles') search_root = config['browser_dir'] cookie_database_path = _find_most_recently_used_file(search_root, 'Cookies', logger) if cookie_database_path is", "compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date,", "# just tries to read the value (which kwallet returns \"\") whereas kwallet-query", "the key is wrong?', only_once=True) return None try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed", "= len(table) for i, line in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') is_encrypted,", "= p.read_uint() path_offset = p.read_uint() value_offset = p.read_uint() p.skip(8, 'unknown record field 3')", "p.skip_to(domain_offset) domain = p.read_cstring() p.skip_to(name_offset) name = p.read_cstring() p.skip_to(path_offset) path = p.read_cstring() p.skip_to(value_offset)", "password to stdout '-a', browser_keyring_name, # match 'account' '-s', f'{browser_keyring_name} Safe Storage'], #", "= cursor.fetchall() total_cookie_count = len(table) for i, (host, name, value, path, expiry, is_secure)", "None def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, logger): try: plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag,", "= \"{network_wallet}\"') return network_wallet except Exception as e: logger.warning(f'exception while obtaining NetworkWallet: {e}')", "SUPPORTED_BROWSERS: raise ValueError(f'unsupported browser: \"{browser_name}\"') if keyring not in (None, *SUPPORTED_KEYRINGS): raise ValueError(f'unsupported", "'/modules/kwalletd5', 'org.kde.KWallet.networkWallet' ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode != 0:", "if path is None: logger.error('could not find local state file') return None logger.debug(f'Found", "database in {search_root}') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor =", "with contextlib.closing(secretstorage.dbus_init()) as con: col = secretstorage.get_default_collection(con) for item in col.get_all_items(): if item.get_label()", "stderr = proc.communicate_or_kill() if proc.returncode != 0: logger.error(f'kwallet-query failed with return code {proc.returncode}.", "'<d' return struct.unpack(data_format, self.read_bytes(8))[0] def read_cstring(self): buffer = [] while True: c =", "field') with _create_progress_bar(logger) as progress_bar: for i, record_offset in enumerate(record_offsets): progress_bar.print(f'Loading cookie {i:", "'is_secure' if 'is_secure' in column_names else 'secure' cursor.execute(f'SELECT host_key, name, value, encrypted_value, path,", "table_info({table_name})').fetchall() return [row[1].decode('utf-8') for row in table_info] def _find_most_recently_used_file(root, filename, logger): # if", "for curr_root, dirs, files in os.walk(root): for file in files: i += 1", "skipped during parsing \"\"\" if jar is None: jar = YoutubeDLCookieJar() page_sizes, body_start", "the kwallet package for your distribution') return b'' network_wallet = _get_kwallet_network_wallet(logger) try: proc", "is_encrypted, None return is_encrypted, compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'),", "self.derive_key(b'peanuts') password = _get_linux_keyring_password(browser_keyring_name, keyring, logger) self._v11_key = None if password is None", "not encrypted_key.startswith(prefix): logger.error('invalid key') return None return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) def pbkdf2_sha1(password, salt, iterations,", "if there are multiple browser profiles, take the most recently used one i,", "= value.decode('utf-8') path = path.decode('utf-8') is_encrypted = not value and encrypted_value if is_encrypted:", "or self._ydl.params.get('logger'): return file = self._ydl._out_files['error'] try: if not file.isatty(): return except BaseException:", "browsers_without_profiles = {'opera'} return { 'browser_dir': browser_dir, 'keyring_name': keyring_name, 'supports_profiles': browser_name not in", "else: if stdout.lower().startswith(b'failed to read'): logger.debug('failed to read password from kwallet. Using empty", "secretstorage.get_default_collection(con) for item in col.get_all_items(): if item.get_label() == f'{browser_keyring_name} Safe Storage': return item.get_secret()", "checks hasEntry. To verify this: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" # while starting chrome.", "database_copy_path) conn = sqlite3.connect(database_copy_path) return conn.cursor() def _get_column_names(cursor, table_name): table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall()", "xdg_current_desktop == 'XFCE': return _LinuxDesktopEnvironment.XFCE elif desktop_session is not None: if desktop_session in", "port=None, port_specified=False, domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False, comment=None, comment_url=None, rest={})", "secure=is_secure, expires=expiration_date, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) return record_size def parse_safari_cookies(data, jar=None, logger=YDLLogger()):", "SQLITE_AVAILABLE: logger.warning('Cannot extract cookies from firefox without sqlite3 support. ' 'Please use a", "def cookie_counts(self): raise NotImplementedError('Must be implemented by sub classes') def get_cookie_decryptor(browser_root, browser_keyring_name, logger,", "DataParser: def __init__(self, data, logger): self._data = data self.cursor = 0 self._logger =", "8 # boringssl # EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length = 16 raw_ciphertext = ciphertext nonce =", "data def expect_bytes(self, expected_value, message): value = self.read_bytes(len(expected_value)) if value != expected_value: raise", "logger.info(f'Extracting cookies from {browser_name}') if not SQLITE_AVAILABLE: logger.warning(f'Cannot extract cookies from {browser_name} without", "return is_encrypted, None return is_encrypted, compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host_key, domain_specified=bool(host_key),", "MacChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger): self._logger = logger password = _get_mac_keyring_password(browser_keyring_name, logger) self._v10_key", "cookie_jars.append(extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring)) if cookie_file is not None: cookie_file = expand_path(cookie_file) jar", "if sys.platform == 'darwin' else 'Chromium', 'opera': 'Opera' if sys.platform == 'darwin' else", "skip(self, num_bytes, description='unknown'): if num_bytes > 0: self._logger.debug(f'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}') elif", "version=0, name=name, value=value, port=None, port_specified=False, domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False,", "self._v10_key = self.derive_key(b'peanuts') password = _get_linux_keyring_password(browser_keyring_name, keyring, logger) self._v11_key = None if password", "because the MAC check failed. Possibly the key is wrong?', only_once=True) return None", "'vivaldi': os.path.join(appdata_local, R'Vivaldi\\User Data'), }[browser_name] elif sys.platform == 'darwin': appdata = os.path.expanduser('~/Library/Application Support')", "_decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) elif version == b'v11': self._cookie_counts['v11'] += 1 if self._v11_key is", "environment: {desktop_environment.name}') if desktop_environment == _LinuxDesktopEnvironment.KDE: linux_keyring = _LinuxKeyring.KWALLET elif desktop_environment == _LinuxDesktopEnvironment.OTHER:", "if config['supports_profiles']: search_root = os.path.join(config['browser_dir'], profile) else: logger.error(f'{browser_name} does not support profiles') search_root", "browser_name == 'safari': return _extract_safari_cookies(profile, logger) elif browser_name in CHROMIUM_BASED_BROWSERS: return _extract_chrome_cookies(browser_name, profile,", "desktop_environment == _LinuxDesktopEnvironment.KDE: linux_keyring = _LinuxKeyring.KWALLET elif desktop_environment == _LinuxDesktopEnvironment.OTHER: linux_keyring = _LinuxKeyring.BASICTEXT", "from .utils import Popen, YoutubeDLCookieJar, error_to_str, expand_path try: import sqlite3 SQLITE_AVAILABLE = True", "None: search_root = _firefox_browser_dir() elif _is_path(profile): search_root = profile else: search_root = os.path.join(_firefox_browser_dir(),", "with _create_progress_bar(logger) as progress_bar: for curr_root, dirs, files in os.walk(root): for file in", "return _decrypt_aes_cbc(ciphertext, self._v11_key, self._logger) else: self._cookie_counts['other'] += 1 return None class MacChromeCookieDecryptor(ChromeCookieDecryptor): def", "not in browsers_without_profiles } def _extract_chrome_cookies(browser_name, profile, keyring, logger): logger.info(f'Extracting cookies from {browser_name}')", "if version == b'v10': self._cookie_counts['v10'] += 1 if self._v10_key is None: self._logger.warning('cannot decrypt", "with open(cookies_path, 'rb') as f: cookies_data = f.read() jar = parse_safari_cookies(cookies_data, logger=logger) logger.info(f'Extracted", "search_root = _firefox_browser_dir() elif _is_path(profile): search_root = profile else: search_root = os.path.join(_firefox_browser_dir(), profile)", "logger) if cookie_database_path is None: raise FileNotFoundError(f'could not find firefox cookies database in", "6d}/{total_cookie_count: 6d}') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'),", "protected key (keyring) and more key derivation iterations than linux - not v10:", "v11 - v10: AES-CBC encrypted with a fixed key - v11: AES-CBC encrypted", "\"\"\" desktop_environment = _get_linux_desktop_environment(os.environ) logger.debug(f'detected desktop environment: {desktop_environment.name}') if desktop_environment == _LinuxDesktopEnvironment.KDE: linux_keyring", "with DPAPI', only_once=True) return None result = ctypes.string_at(blob_out.pbData, blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData) return result def", "return file = self._ydl._out_files['error'] try: if not file.isatty(): return except BaseException: return printer", "while obtaining NetworkWallet: {e}') return default_wallet def _get_kwallet_password(browser_keyring_name, logger): logger.debug('using kwallet-query to obtain", "logger.debug('Trying secondary cookie location') cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): raise FileNotFoundError('could not", "\"\"\" def decrypt(self, encrypted_value): raise NotImplementedError('Must be implemented by sub classes') @property def", "f'{browser_keyring_name} Safe Storage', '--folder', f'{browser_keyring_name} Keys', network_wallet ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr =", "output_jar.set_cookie(cookie) if jar.filename is not None: output_jar.filename = jar.filename return output_jar def _is_path(value):", "password = _get_mac_keyring_password(browser_keyring_name, logger) self._v10_key = None if password is None else self.derive_key(password)", "no cookies') return p.skip_to(record_offsets[0], 'unknown page header field') with _create_progress_bar(logger) as progress_bar: for", "appears to be out of date but the important parts of the database", "[p.read_uint(big_endian=True) for _ in range(number_of_pages)] return page_sizes, p.cursor def _parse_safari_cookies_page(data, jar, logger): p", "return stdout except Exception as e: logger.warning(f'exception running find-generic-password: {error_to_str(e)}') return None def", "return b'' def _get_linux_keyring_password(browser_keyring_name, keyring, logger): # note: chrome/chromium can be run with", "self._cookie_counts['v10'] += 1 if self._v10_key is None: self._logger.warning('cannot decrypt v10 cookies: no key", "it is possible to compile python without # sqlite support. See: https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE", "= os.path.expandvars('%LOCALAPPDATA%') appdata_roaming = os.path.expandvars('%APPDATA%') browser_dir = { 'brave': os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User Data'), 'chrome':", "without # sqlite support. See: https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE = False try: import secretstorage SECRETSTORAGE_AVAILABLE", "raise ParserError(f'invalid read of {num_bytes} bytes') end = self.cursor + num_bytes if end", "DPAPI Sources: - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc - KeyStorageLinux::CreateService \"\"\" def decrypt(self,", "`secretstorage` module could not be initialized. {_err}' CHROMIUM_BASED_BROWSERS = {'brave', 'chrome', 'chromium', 'edge',", "of the database structure is the same - there are a few bytes", "prefix = b'DPAPI' if not encrypted_key.startswith(prefix): logger.error('invalid key') return None return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger)", "_get_kwallet_network_wallet(logger): \"\"\" The name of the wallet used to store network passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc", "= Popen( ['security', 'find-generic-password', '-w', # write password to stdout '-a', browser_keyring_name, #", "compat_b64decode, compat_cookiejar_Cookie from .minicurses import MultilinePrinter, QuietMultilinePrinter from .utils import Popen, YoutubeDLCookieJar, error_to_str,", "else: raise ValueError(f'unsupported platform: {sys.platform}') def _get_chromium_based_browser_settings(browser_name): # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if sys.platform in ('linux',", "'Opera' if sys.platform == 'darwin' else 'Chromium', 'vivaldi': 'Vivaldi' if sys.platform == 'darwin'", "{ 'brave': 'Brave', 'chrome': 'Chrome', 'chromium': 'Chromium', 'edge': 'Microsoft Edge' if sys.platform ==", "return WindowsChromeCookieDecryptor(browser_root, logger) else: raise NotImplementedError(f'Chrome cookie decryption is not supported on this", "], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode != 0: logger.warning('failed to", "supports a flag: --password-store=<basic|gnome|kwallet> so the automatic detection # will not be sufficient", "self._cookie_counts = {'v10': 0, 'v11': 0, 'other': 0} @staticmethod def derive_key(password): # values", "max(paths, key=lambda path: os.lstat(path).st_mtime) def _merge_cookie_jars(jars): output_jar = YoutubeDLCookieJar() for jar in jars:", "jar = parse_safari_cookies(cookies_data, logger=logger) logger.info(f'Extracted {len(jar)} cookies from safari') return jar class ParserError(Exception):", "self._ydl or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'): return file = self._ydl._out_files['error'] try: if not file.isatty():", "import ( aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7, ) from .compat import compat_b64decode, compat_cookiejar_Cookie from .minicurses", "'chrome': os.path.join(appdata_local, R'Google\\Chrome\\User Data'), 'chromium': os.path.join(appdata_local, R'Chromium\\User Data'), 'edge': os.path.join(appdata_local, R'Microsoft\\Edge\\User Data'), 'opera':", "to decrypt with DPAPI', only_once=True) return None result = ctypes.string_at(blob_out.pbData, blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData) return", "record_size p.skip_to(record_size, 'space at the end of the record') cookie = compat_cookiejar_Cookie( version=0,", "elif _is_path(profile): search_root = profile config['browser_dir'] = os.path.dirname(profile) if config['supports_profiles'] else profile else:", "self._cookie_counts['other'] += 1 # other prefixes are considered 'old data' which were stored", "else 'Chromium', 'vivaldi': 'Vivaldi' if sys.platform == 'darwin' else 'Chrome', }[browser_name] browsers_without_profiles =", "failed_cookies > 0: failed_message = f' ({failed_cookies} could not be decrypted)' else: failed_message", "self._ydl._out_files['error'] try: if not file.isatty(): return except BaseException: return printer = MultilinePrinter(file, preserve_output=False)", "None: if desktop_session in ('mate', 'gnome'): return _LinuxDesktopEnvironment.GNOME elif 'kde' in desktop_session: return", "raise NotImplementedError('Must be implemented by sub classes') @property def cookie_counts(self): raise NotImplementedError('Must be", "0: failed_message = f' ({failed_cookies} could not be decrypted)' else: failed_message = ''", "{sys.platform}') def _get_chromium_based_browser_settings(browser_name): # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if sys.platform in ('linux', 'linux2'): config = _config_home()", "= _mac_absolute_time_to_posix(p.read_double()) # noqa: F841 try: p.skip_to(domain_offset) domain = p.read_cstring() p.skip_to(name_offset) name =", "'chromium': os.path.join(appdata, 'Chromium'), 'edge': os.path.join(appdata, 'Microsoft Edge'), 'opera': os.path.join(appdata, 'com.operasoftware.Opera'), 'vivaldi': os.path.join(appdata, 'Vivaldi'),", "# chromium --enable-logging=stderr --v=1 2>&1 | grep key_storage_ # Chromium supports a flag:", "# https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc # kNonceLength nonce_length = 96 // 8 # boringssl # EVP_AEAD_AES_GCM_TAG_LEN", "a dbus call to the following function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet \"\"\" default_wallet = 'kdewallet'", "the activate desktop environment [2] Mac: - cookies are either v10 or not", "p.read_uint() record_offsets = [p.read_uint() for _ in range(number_of_cookies)] if number_of_cookies == 0: logger.debug(f'a", "elif browser_name == 'safari': return _extract_safari_cookies(profile, logger) elif browser_name in CHROMIUM_BASED_BROWSERS: return _extract_chrome_cookies(browser_name,", "values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1003, key_length=16) @property def cookie_counts(self): return", "YoutubeDLCookieJar() failed_cookies = 0 unencrypted_cookies = 0 with _create_progress_bar(logger) as progress_bar: table =", "in desktop_session: return _LinuxDesktopEnvironment.GNOME else: return _LinuxDesktopEnvironment.UNITY elif xdg_current_desktop == 'GNOME': return _LinuxDesktopEnvironment.GNOME", "logger) elif sys.platform == 'win32': return WindowsChromeCookieDecryptor(browser_root, logger) else: raise NotImplementedError(f'Chrome cookie decryption", "by the browser) database_copy_path = os.path.join(tmpdir, 'temporary.sqlite') shutil.copy(database_path, database_copy_path) conn = sqlite3.connect(database_copy_path) return", "ciphertext nonce = raw_ciphertext[:nonce_length] ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag = raw_ciphertext[-authentication_tag_length:] return _decrypt_aes_gcm(ciphertext, self._v10_key,", "'linux2'): config = _config_home() browser_dir = { 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(config, 'google-chrome'),", "os.path.join(config['browser_dir'], profile) else: logger.error(f'{browser_name} does not support profiles') search_root = config['browser_dir'] cookie_database_path =", "from enum import Enum, auto from hashlib import pbkdf2_hmac from .aes import (", "p.skip_to(name_offset) name = p.read_cstring() p.skip_to(path_offset) path = p.read_cstring() p.skip_to(value_offset) value = p.read_cstring() except", "desktop_session: return _LinuxDesktopEnvironment.GNOME else: return _LinuxDesktopEnvironment.UNITY elif xdg_current_desktop == 'GNOME': return _LinuxDesktopEnvironment.GNOME elif", "printer.print_at_line(f'[Cookies] {message}', 0) return printer def _create_progress_bar(logger): if hasattr(logger, 'progress_bar'): printer = logger.progress_bar()", "{len(jar)} cookies from firefox') return jar finally: if cursor is not None: cursor.connection.close()", "Data'), 'edge': os.path.join(appdata_local, R'Microsoft\\Edge\\User Data'), 'opera': os.path.join(appdata_roaming, R'Opera Software\\Opera Stable'), 'vivaldi': os.path.join(appdata_local, R'Vivaldi\\User", "'brave': 'Brave', 'chrome': 'Chrome', 'chromium': 'Chromium', 'edge': 'Microsoft Edge' if sys.platform == 'darwin'", "kNonceLength nonce_length = 96 // 8 # boringssl # EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length = 16", "{num_bytes} bytes') end = self.cursor + num_bytes if end > len(self._data): raise ParserError('reached", "{len(data)} has no cookies') return p.skip_to(record_offsets[0], 'unknown page header field') with _create_progress_bar(logger) as", "not be sufficient in all cases. keyring = _LinuxKeyring[keyring] if keyring else _choose_linux_keyring(logger)", "logger, *, keyring=None): if sys.platform in ('linux', 'linux2'): return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring) elif", "'cookies.sqlite', logger) if cookie_database_path is None: raise FileNotFoundError(f'could not find firefox cookies database", "def read_cstring(self): buffer = [] while True: c = self.read_bytes(1) if c ==", "logger=YDLLogger()): \"\"\" References: - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc - this data appears to be out of", "None: self._logger.warning('cannot decrypt v10 cookies: no key found', only_once=True) return None # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc", "is not None: cursor.connection.close() def _firefox_browser_dir(): if sys.platform in ('linux', 'linux2'): return os.path.expanduser('~/.mozilla/firefox')", "def _get_gnome_keyring_password(browser_keyring_name, logger): if not SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage not available {SECRETSTORAGE_UNAVAILABLE_REASON}') return b'' #", "date but the important parts of the database structure is the same -", "p = DataParser(data[body_start:], logger) for page_size in page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger) p.skip_to_end('footer') return", "i += 1 progress_bar.print(f'Searching for \"{filename}\": {i: 6d} files searched') if file ==", "not None and 'gnome-fallback' in desktop_session: return _LinuxDesktopEnvironment.GNOME else: return _LinuxDesktopEnvironment.UNITY elif xdg_current_desktop", "key_length) def _decrypt_aes_cbc(ciphertext, key, logger, initialization_vector=b' ' * 16): plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key,", "generate a random password and store # it, but that doesn't matter here.", "elif keyring == _LinuxKeyring.BASICTEXT: # when basic text is chosen, all cookies are", "i, (host, name, value, path, expiry, is_secure) in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count:", "run with the following flags to determine which keyring backend # it has", "and 'gnome-fallback' in desktop_session: return _LinuxDesktopEnvironment.GNOME else: return _LinuxDesktopEnvironment.UNITY elif xdg_current_desktop == 'GNOME':", "as _err: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = f'as the `secretstorage` module could not", "+= 1 return None class MacChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger): self._logger = logger", "return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-GCM) because UTF-8 decoding failed.", "not value and encrypted_value if is_encrypted: value = decryptor.decrypt(encrypted_value) if value is None:", "self._v10_key, self._logger) elif version == b'v11': self._cookie_counts['v11'] += 1 if self._v11_key is None:", "import os import shutil import struct import subprocess import sys import tempfile from", "use a python interpreter compiled with sqlite3 support') return YoutubeDLCookieJar() config = _get_chromium_based_browser_settings(browser_name)", "be observed that chromium lists all keys # and presumably searches for its", "name=name, value=value, port=None, port_specified=False, domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiry, discard=False, comment=None,", "rest={}) class ChromeCookieDecryptor: \"\"\" Overview: Linux: - cookies are either v10 or v11", "printer = logger.progress_bar() if printer: return printer printer = QuietMultilinePrinter() printer.print = lambda", "'opera', 'vivaldi'} SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'} class YDLLogger: def __init__(self, ydl=None):", "= YoutubeDLCookieJar() failed_cookies = 0 unencrypted_cookies = 0 with _create_progress_bar(logger) as progress_bar: table", "KeyError: logger.error('no encrypted key in Local State') return None encrypted_key = compat_b64decode(base64_key) prefix", "no key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v11_key, self._logger) else: self._cookie_counts['other'] +=", "elif xdg_current_desktop == 'X-Cinnamon': return _LinuxDesktopEnvironment.CINNAMON elif xdg_current_desktop == 'KDE': return _LinuxDesktopEnvironment.KDE elif", "'win32': return WindowsChromeCookieDecryptor(browser_root, logger) else: raise NotImplementedError(f'Chrome cookie decryption is not supported on", "compat_b64decode(base64_key) prefix = b'DPAPI' if not encrypted_key.startswith(prefix): logger.error('invalid key') return None return _decrypt_windows_dpapi(encrypted_key[len(prefix):],", "{desktop_environment.name}') if desktop_environment == _LinuxDesktopEnvironment.KDE: linux_keyring = _LinuxKeyring.KWALLET elif desktop_environment == _LinuxDesktopEnvironment.OTHER: linux_keyring", "in SUPPORTED_BROWSERS: raise ValueError(f'unsupported browser: \"{browser_name}\"') if keyring not in (None, *SUPPORTED_KEYRINGS): raise", "decrypt v10 cookies: no key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger)", "organise keys in the same way as KWallet, # using `dbus-monitor` during startup,", "the intended behaviour is to generate a random password and store # it,", "key, nonce, authentication_tag, logger): try: plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce) except ValueError:", "(AES-GCM) because the MAC check failed. Possibly the key is wrong?', only_once=True) return", "0x0001) p.skip(4, 'unknown record field 2') domain_offset = p.read_uint() name_offset = p.read_uint() path_offset", "encrypted_value class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_root, logger): self._logger = logger self._v10_key = _get_windows_v10_key(browser_root,", "iterations, key_length): return pbkdf2_hmac('sha1', password, salt, iterations, key_length) def _decrypt_aes_cbc(ciphertext, key, logger, initialization_vector=b'", "activate desktop environment [2] Mac: - cookies are either v10 or not v10", "chrome/chromium can be run with the following flags to determine which keyring backend", "could not be decrypted)' else: failed_message = '' logger.info(f'Extracted {len(jar)} cookies from {browser_name}{failed_message}')", "secretstorage`.') except Exception as _err: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = f'as the `secretstorage`", "'Please use a python interpreter compiled with sqlite3 support') return YoutubeDLCookieJar() config =", "various places depending on the activate desktop environment [2] Mac: - cookies are", "structure is the same - there are a few bytes here and there", "def _find_most_recently_used_file(root, filename, logger): # if there are multiple browser profiles, take the", "return item.get_secret() else: logger.error('failed to read from keyring') return b'' def _get_linux_keyring_password(browser_keyring_name, keyring,", "= _find_most_recently_used_file(search_root, 'cookies.sqlite', logger) if cookie_database_path is None: raise FileNotFoundError(f'could not find firefox", "random password and store # it, but that doesn't matter here. return b''", "R'Google\\Chrome\\User Data'), 'chromium': os.path.join(appdata_local, R'Chromium\\User Data'), 'edge': os.path.join(appdata_local, R'Microsoft\\Edge\\User Data'), 'opera': os.path.join(appdata_roaming, R'Opera", "implemented by sub classes') def get_cookie_decryptor(browser_root, browser_keyring_name, logger, *, keyring=None): if sys.platform in", "' 'must be installed to read from KWallet. kwallet-query should be' 'included in", "= ctypes.create_string_buffer(ciphertext) blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer) blob_out = DATA_BLOB() ret = ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in),", "self._cookie_counts def decrypt(self, encrypted_value): version = encrypted_value[:3] ciphertext = encrypted_value[3:] if version ==", "is None: return is_encrypted, None return is_encrypted, compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False,", "'chromium': os.path.join(appdata_local, R'Chromium\\User Data'), 'edge': os.path.join(appdata_local, R'Microsoft\\Edge\\User Data'), 'opera': os.path.join(appdata_roaming, R'Opera Software\\Opera Stable'),", "except Exception as e: logger.warning(f'exception while obtaining NetworkWallet: {e}') return default_wallet def _get_kwallet_password(browser_keyring_name,", "logger, keyring=keyring) with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try: cursor = _open_database_copy(cookie_database_path,", "with DPAPI - not v10: encrypted with DPAPI Sources: - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ -", "*, keyring=None): if sys.platform in ('linux', 'linux2'): return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring) elif sys.platform", "expires=expiry, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) logger.info(f'Extracted {len(jar)} cookies from firefox') return jar", "is chosen, all cookies are stored as v10 (so no keyring password is", "appdata_local = os.path.expandvars('%LOCALAPPDATA%') appdata_roaming = os.path.expandvars('%APPDATA%') browser_dir = { 'brave': os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User Data'),", "def read_double(self, big_endian=False): data_format = '>d' if big_endian else '<d' return struct.unpack(data_format, self.read_bytes(8))[0]", "nonce_length = 96 // 8 # boringssl # EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length = 16 raw_ciphertext", "find local state file') return None logger.debug(f'Found local state file at \"{path}\"') with", "'Please use a python interpreter compiled with sqlite3 support') return YoutubeDLCookieJar() if profile", "= data self.cursor = 0 self._logger = logger def read_bytes(self, num_bytes): if num_bytes", "def _get_mac_keyring_password(browser_keyring_name, logger): logger.debug('using find-generic-password to obtain password from OSX keychain') try: proc", "KDE because chrome does not check hasEntry and instead # just tries to", "'chrome': 'Chrome', 'chromium': 'Chromium', 'edge': 'Microsoft Edge' if sys.platform == 'darwin' else 'Chromium',", "raise ValueError(f'unsupported browser: \"{browser_name}\"') if keyring not in (None, *SUPPORTED_KEYRINGS): raise ValueError(f'unsupported keyring:", "end > len(self._data): raise ParserError('reached end of input') data = self._data[self.cursor:end] self.cursor =", "return result def _config_home(): return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) def _open_database_copy(database_path, tmpdir): # cannot open", "the database structure is the same - there are a few bytes here", "name, value, encrypted_value, path, expires_utc, {secure_column} FROM cookies') jar = YoutubeDLCookieJar() failed_cookies =", "jar = YoutubeDLCookieJar() failed_cookies = 0 unencrypted_cookies = 0 with _create_progress_bar(logger) as progress_bar:", "cookies from safari') return jar class ParserError(Exception): pass class DataParser: def __init__(self, data,", "desktop environment [2] Mac: - cookies are either v10 or not v10 -", "auto() class _LinuxKeyring(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend \"\"\" KWALLET = auto() GNOMEKEYRING = auto()", "3') expiration_date = _mac_absolute_time_to_posix(p.read_double()) _creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa: F841 try: p.skip_to(domain_offset) domain", "parse_safari_cookies(cookies_data, logger=logger) logger.info(f'Extracted {len(jar)} cookies from safari') return jar class ParserError(Exception): pass class", "version == b'v10': self._cookie_counts['v10'] += 1 if self._v10_key is None: self._logger.warning('cannot decrypt v10", "function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet \"\"\" default_wallet = 'kdewallet' try: proc = Popen([ 'dbus-send', '--session',", "key found', only_once=True) return None # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc # kNonceLength nonce_length = 96 //", "for page_size in page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger) p.skip_to_end('footer') return jar class _LinuxDesktopEnvironment(Enum): \"\"\"", "== filename: paths.append(os.path.join(curr_root, file)) return None if not paths else max(paths, key=lambda path:", "def _parse_safari_cookies_record(data, jar, logger): p = DataParser(data, logger) record_size = p.read_uint() p.skip(4, 'unknown", "DWORD class DATA_BLOB(ctypes.Structure): _fields_ = [('cbData', DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))] buffer = ctypes.create_string_buffer(ciphertext) blob_in", "logger) for page_size in page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger) p.skip_to_end('footer') return jar class _LinuxDesktopEnvironment(Enum):", "be stored in various places depending on the activate desktop environment [2] Mac:", "between records') record_length = _parse_safari_cookies_record(data[record_offset:], jar, logger) p.read_bytes(record_length) p.skip_to_end('space in between pages') def", "# match 'account' '-s', f'{browser_keyring_name} Safe Storage'], # match 'service' stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout,", "read_uint(self, big_endian=False): data_format = '>I' if big_endian else '<I' return struct.unpack(data_format, self.read_bytes(4))[0] def", "logger.warning(f'exception running find-generic-password: {error_to_str(e)}') return None def _get_windows_v10_key(browser_root, logger): path = _find_most_recently_used_file(browser_root, 'Local", "0 self._logger = logger def read_bytes(self, num_bytes): if num_bytes < 0: raise ParserError(f'invalid", "NotImplementedError('Must be implemented by sub classes') @property def cookie_counts(self): raise NotImplementedError('Must be implemented", "encrypted_value if is_encrypted: value = decryptor.decrypt(encrypted_value) if value is None: return is_encrypted, None", "if cookie_database_path is None: raise FileNotFoundError(f'could not find {browser_name} cookies database in \"{search_root}\"')", "logger.debug(f'Chosen keyring: {keyring.name}') if keyring == _LinuxKeyring.KWALLET: return _get_kwallet_password(browser_keyring_name, logger) elif keyring ==", "Exception as _err: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = f'as the `secretstorage` module could", "{sys.platform}') cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): logger.debug('Trying secondary cookie location') cookies_path =", "'Chrome', 'chromium': 'Chromium', 'edge': 'Microsoft Edge' if sys.platform == 'darwin' else 'Chromium', 'opera':", "using `dbus-monitor` during startup, it can be observed that chromium lists all keys", "return os.path.expanduser('~/Library/Application Support/Firefox') else: raise ValueError(f'unsupported platform: {sys.platform}') def _get_chromium_based_browser_settings(browser_name): # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if", "are either v10 or v11 - v10: AES-CBC encrypted with a fixed key", "import DWORD class DATA_BLOB(ctypes.Structure): _fields_ = [('cbData', DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))] buffer = ctypes.create_string_buffer(ciphertext)", "_get_gnome_keyring_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.BASICTEXT: # when basic text is chosen, all", "to generate a random password and store # it, but that doesn't matter", "progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies: 6d}') p.skip_to(record_offset, 'space between records') record_length = _parse_safari_cookies_record(data[record_offset:], jar,", "None: raise FileNotFoundError(f'could not find {browser_name} cookies database in \"{search_root}\"') logger.debug(f'Extracting cookies from:", "sys.platform == 'darwin': return MacChromeCookieDecryptor(browser_keyring_name, logger) elif sys.platform == 'win32': return WindowsChromeCookieDecryptor(browser_root, logger)", "'dbus-send', '--session', '--print-reply=literal', '--dest=org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet.networkWallet' ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill()", "the MAC check failed. Possibly the key is wrong?', only_once=True) return None try:", "'-w', # write password to stdout '-a', browser_keyring_name, # match 'account' '-s', f'{browser_keyring_name}", "authentication_tag = raw_ciphertext[-authentication_tag_length:] return _decrypt_aes_gcm(ciphertext, self._v10_key, nonce, authentication_tag, self._logger) else: self._cookie_counts['other'] += 1", "# pDataIn None, # ppszDataDescr: human readable description of pDataIn None, # pOptionalEntropy:", "as progress_bar: for i, record_offset in enumerate(record_offsets): progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies: 6d}') p.skip_to(record_offset,", "key in the list. It appears that we must do the same. #", "and store # it, but that doesn't matter here. return b'' else: logger.debug('password", "auto() CINNAMON = auto() GNOME = auto() KDE = auto() PANTHEON = auto()", "KWallet and kwallet-query ' 'must be installed to read from KWallet. kwallet-query should", "elif xdg_current_desktop == 'GNOME': return _LinuxDesktopEnvironment.GNOME elif xdg_current_desktop == 'X-Cinnamon': return _LinuxDesktopEnvironment.CINNAMON elif", "It appears that we must do the same. # https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init()) as", "end return data def expect_bytes(self, expected_value, message): value = self.read_bytes(len(expected_value)) if value !=", "from firefox without sqlite3 support. ' 'Please use a python interpreter compiled with", "sys.platform in ('linux', 'linux2'): return os.path.expanduser('~/.mozilla/firefox') elif sys.platform == 'win32': return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif", "16): plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector)) try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to", "0: raise ParserError(f'invalid skip of {num_bytes} bytes') def skip_to(self, offset, description='unknown'): self.skip(offset -", "v10 cookies: no key found', only_once=True) return None # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc # kNonceLength nonce_length", "_get_kwallet_network_wallet(logger) try: proc = Popen([ 'kwallet-query', '--read-password', f'{browser_keyring_name} Safe Storage', '--folder', f'{browser_keyring_name} Keys',", "intended behaviour is to generate a random password and store # it, but", "_LinuxDesktopEnvironment.KDE elif 'xfce' in desktop_session: return _LinuxDesktopEnvironment.XFCE else: if 'GNOME_DESKTOP_SESSION_ID' in env: return", "_extract_firefox_cookies(profile, logger) elif browser_name == 'safari': return _extract_safari_cookies(profile, logger) elif browser_name in CHROMIUM_BASED_BROWSERS:", "only_once=True) return None # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc # kNonceLength nonce_length = 96 // 8 #", "running `python3 -m pip install secretstorage`.') except Exception as _err: SECRETSTORAGE_AVAILABLE = False", "= encrypted_value[3:] if version == b'v10': self._cookie_counts['v10'] += 1 if self._v10_key is None:", "= cursor.fetchall() total_cookie_count = len(table) for i, line in enumerate(table): progress_bar.print(f'Loading cookie {i:", "None: cursor.connection.close() def _firefox_browser_dir(): if sys.platform in ('linux', 'linux2'): return os.path.expanduser('~/.mozilla/firefox') elif sys.platform", "starting chrome. # this may be a bug as the intended behaviour is", "'secure' cursor.execute(f'SELECT host_key, name, value, encrypted_value, path, expires_utc, {secure_column} FROM cookies') jar =", "= 0 self._logger = logger def read_bytes(self, num_bytes): if num_bytes < 0: raise", "self._logger = logger password = _get_mac_keyring_password(browser_keyring_name, logger) self._v10_key = None if password is", "{error_to_str(e)}') return b'' def _get_gnome_keyring_password(browser_keyring_name, logger): if not SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage not available {SECRETSTORAGE_UNAVAILABLE_REASON}')", "sys import tempfile from datetime import datetime, timedelta, timezone from enum import Enum,", "= None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.execute('SELECT host, name, value, path, expiry,", "obtaining NetworkWallet: {e}') return default_wallet def _get_kwallet_password(browser_keyring_name, logger): logger.debug('using kwallet-query to obtain password", "if sys.platform in ('linux', 'linux2'): config = _config_home() browser_dir = { 'brave': os.path.join(config,", "'darwin' else 'Chromium', 'vivaldi': 'Vivaldi' if sys.platform == 'darwin' else 'Chrome', }[browser_name] browsers_without_profiles", "= not value and encrypted_value if is_encrypted: value = decryptor.decrypt(encrypted_value) if value is", "return None def _get_windows_v10_key(browser_root, logger): path = _find_most_recently_used_file(browser_root, 'Local State', logger) if path", "return b'' # the Gnome keyring does not seem to organise keys in", "buffer = ctypes.create_string_buffer(ciphertext) blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer) blob_out = DATA_BLOB() ret = ctypes.windll.crypt32.CryptUnprotectData(", "does not support profiles') if sys.platform != 'darwin': raise ValueError(f'unsupported platform: {sys.platform}') cookies_path", ") if not ret: logger.warning('failed to decrypt with DPAPI', only_once=True) return None result", "_LinuxKeyring.GNOMEKEYRING return linux_keyring def _get_kwallet_network_wallet(logger): \"\"\" The name of the wallet used to", "domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) return", "MultilinePrinter, QuietMultilinePrinter from .utils import Popen, YoutubeDLCookieJar, error_to_str, expand_path try: import sqlite3 SQLITE_AVAILABLE", "cookie in jar: output_jar.set_cookie(cookie) if jar.filename is not None: output_jar.filename = jar.filename return", "None: browser_name, profile, keyring = _parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring)) if cookie_file is", "else: search_root = os.path.join(_firefox_browser_dir(), profile) cookie_database_path = _find_most_recently_used_file(search_root, 'cookies.sqlite', logger) if cookie_database_path is", "= jar.filename return output_jar def _is_path(value): return os.path.sep in value def _parse_browser_specification(browser_name, profile=None,", "GNOME = auto() KDE = auto() PANTHEON = auto() UNITY = auto() XFCE", "{proc.returncode}. Please consult ' 'the kwallet-query man page for details') return b'' else:", "b'' network_wallet = _get_kwallet_network_wallet(logger) try: proc = Popen([ 'kwallet-query', '--read-password', f'{browser_keyring_name} Safe Storage',", "were stored as plaintext # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return encrypted_value class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_root,", "xdg_current_desktop == 'KDE': return _LinuxDesktopEnvironment.KDE elif xdg_current_desktop == 'Pantheon': return _LinuxDesktopEnvironment.PANTHEON elif xdg_current_desktop", "> len(self._data): raise ParserError('reached end of input') data = self._data[self.cursor:end] self.cursor = end", "cookies from: \"{cookie_database_path}\"') decryptor = get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger, keyring=keyring) with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir:", "page_size in page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger) p.skip_to_end('footer') return jar class _LinuxDesktopEnvironment(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h", "this may be a bug as the intended behaviour is to generate a", "b'v11': self._cookie_counts['v11'] += 1 if self._v11_key is None: self._logger.warning('cannot decrypt v11 cookies: no", "config['supports_profiles']: search_root = os.path.join(config['browser_dir'], profile) else: logger.error(f'{browser_name} does not support profiles') search_root =", "v10 (so no keyring password is required) return None assert False, f'Unknown keyring", "col = secretstorage.get_default_collection(con) for item in col.get_all_items(): if item.get_label() == f'{browser_keyring_name} Safe Storage':", "if browser_name not in SUPPORTED_BROWSERS: raise ValueError(f'unsupported browser: \"{browser_name}\"') if keyring not in", "_LinuxKeyring.__members__.keys() def _get_linux_desktop_environment(env): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment \"\"\" xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None) desktop_session =", "os.path.join(appdata_roaming, R'Opera Software\\Opera Stable'), 'vivaldi': os.path.join(appdata_local, R'Vivaldi\\User Data'), }[browser_name] elif sys.platform == 'darwin':", "return _LinuxDesktopEnvironment.UNITY elif xdg_current_desktop == 'GNOME': return _LinuxDesktopEnvironment.GNOME elif xdg_current_desktop == 'X-Cinnamon': return", "Windows: - cookies are either v10 or not v10 - v10: AES-GCM encrypted", "# https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return encrypted_value class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_root, logger): self._logger = logger", "record_size def parse_safari_cookies(data, jar=None, logger=YDLLogger()): \"\"\" References: - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc - this data appears", "p.read_cstring() except UnicodeDecodeError: logger.warning('failed to parse Safari cookie because UTF-8 decoding failed', only_once=True)", "from kwallet. Using empty string instead') # this sometimes occurs in KDE because", "cookies from {browser_name}{failed_message}') counts = decryptor.cookie_counts.copy() counts['unencrypted'] = unencrypted_cookies logger.debug(f'cookie version breakdown: {counts}')", "than linux - not v10: 'old data' stored as plaintext Windows: - cookies", "- [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc - KeyStorageLinux::CreateService \"\"\" def decrypt(self, encrypted_value): raise", "p.read_cstring() p.skip_to(name_offset) name = p.read_cstring() p.skip_to(path_offset) path = p.read_cstring() p.skip_to(value_offset) value = p.read_cstring()", "because UTF-8 decoding failed. Possibly the key is wrong?', only_once=True) return None def", "== _LinuxKeyring.KWALLET: return _get_kwallet_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.GNOMEKEYRING: return _get_gnome_keyring_password(browser_keyring_name, logger) elif", "def _merge_cookie_jars(jars): output_jar = YoutubeDLCookieJar() for jar in jars: for cookie in jar:", "= auto() GNOMEKEYRING = auto() BASICTEXT = auto() SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys() def _get_linux_desktop_environment(env):", "try: base64_key = data['os_crypt']['encrypted_key'] except KeyError: logger.error('no encrypted key in Local State') return", "determined by snooping on dbus while opening the browser in KDE: # dbus-monitor", "is None: logger.error('could not find local state file') return None logger.debug(f'Found local state", "else: linux_keyring = _LinuxKeyring.GNOMEKEYRING return linux_keyring def _get_kwallet_network_wallet(logger): \"\"\" The name of the", "'win32': appdata_local = os.path.expandvars('%LOCALAPPDATA%') appdata_roaming = os.path.expandvars('%APPDATA%') browser_dir = { 'brave': os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User", "`secretstorage` module is not installed. ' 'Please install by running `python3 -m pip", "= 0 with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count = len(table) for", ".aes import ( aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7, ) from .compat import compat_b64decode, compat_cookiejar_Cookie from", "encrypted_value[:3] ciphertext = encrypted_value[3:] if version == b'v10': self._cookie_counts['v10'] += 1 if self._v10_key", "( 'as the `secretstorage` module is not installed. ' 'Please install by running", "{num_bytes} bytes') def skip_to(self, offset, description='unknown'): self.skip(offset - self.cursor, description) def skip_to_end(self, description='unknown'):", "which keyring backend # it has chosen to use # chromium --enable-logging=stderr --v=1", "try: if not file.isatty(): return except BaseException: return printer = MultilinePrinter(file, preserve_output=False) printer.print", "json.load(f) try: base64_key = data['os_crypt']['encrypted_key'] except KeyError: logger.error('no encrypted key in Local State')", "for your distribution') return b'' network_wallet = _get_kwallet_network_wallet(logger) try: proc = Popen([ 'kwallet-query',", "(which kwallet returns \"\") whereas kwallet-query # checks hasEntry. To verify this: #", "_is_path(profile): search_root = profile else: search_root = os.path.join(_firefox_browser_dir(), profile) cookie_database_path = _find_most_recently_used_file(search_root, 'cookies.sqlite',", "= _mac_absolute_time_to_posix(p.read_double()) _creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa: F841 try: p.skip_to(domain_offset) domain = p.read_cstring()", "jar = YoutubeDLCookieJar() page_sizes, body_start = _parse_safari_cookies_header(data, logger) p = DataParser(data[body_start:], logger) for", "logger.debug(f'a cookies page of size {len(data)} has no cookies') return p.skip_to(record_offsets[0], 'unknown page", "0, tzinfo=timezone.utc) + timedelta(seconds=timestamp)).timestamp()) def _parse_safari_cookies_header(data, logger): p = DataParser(data, logger) p.expect_bytes(b'cook', 'database", "return None try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-GCM) because", "not in (None, *SUPPORTED_KEYRINGS): raise ValueError(f'unsupported keyring: \"{keyring}\"') if profile is not None", "'google-chrome'), 'chromium': os.path.join(config, 'chromium'), 'edge': os.path.join(config, 'microsoft-edge'), 'opera': os.path.join(config, 'opera'), 'vivaldi': os.path.join(config, 'vivaldi'),", "as e: logger.warning(f'exception while obtaining NetworkWallet: {e}') return default_wallet def _get_kwallet_password(browser_keyring_name, logger): logger.debug('using", "return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring) elif sys.platform == 'darwin': return MacChromeCookieDecryptor(browser_keyring_name, logger) elif sys.platform", "tempfile from datetime import datetime, timedelta, timezone from enum import Enum, auto from", "_LinuxKeyring(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend \"\"\" KWALLET = auto() GNOMEKEYRING = auto() BASICTEXT =", "message): value = self.read_bytes(len(expected_value)) if value != expected_value: raise ParserError(f'unexpected value: {value} !=", "else: logger.error('failed to read from keyring') return b'' def _get_linux_keyring_password(browser_keyring_name, keyring, logger): #", "not v10 - v10: AES-GCM encrypted with a key which is encrypted with", "}[browser_name] else: raise ValueError(f'unsupported platform: {sys.platform}') # Linux keyring names can be determined", "None # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc # kNonceLength nonce_length = 96 // 8 # boringssl #", "the same. # https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init()) as con: col = secretstorage.get_default_collection(con) for item", "its key in the list. It appears that we must do the same.", "return record_size p.skip_to(record_size, 'space at the end of the record') cookie = compat_cookiejar_Cookie(", "browser_keyring_name, logger, *, keyring=None): if sys.platform in ('linux', 'linux2'): return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring)", "expect_bytes(self, expected_value, message): value = self.read_bytes(len(expected_value)) if value != expected_value: raise ParserError(f'unexpected value:", "encrypted_key = compat_b64decode(base64_key) prefix = b'DPAPI' if not encrypted_key.startswith(prefix): logger.error('invalid key') return None", "os.walk(root): for file in files: i += 1 progress_bar.print(f'Searching for \"{filename}\": {i: 6d}", "value def _parse_browser_specification(browser_name, profile=None, keyring=None): if browser_name not in SUPPORTED_BROWSERS: raise ValueError(f'unsupported browser:", "or when --no-progress is used if not self._ydl or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'): return", "an OS protected key (keyring) and more key derivation iterations than linux -", "read'): logger.debug('failed to read password from kwallet. Using empty string instead') # this", "or v11 - v10: AES-CBC encrypted with a fixed key - v11: AES-CBC", "for file in files: i += 1 progress_bar.print(f'Searching for \"{filename}\": {i: 6d} files", "version=0, name=name, value=value, port=None, port_specified=False, domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiry, discard=False,", "return struct.unpack(data_format, self.read_bytes(8))[0] def read_cstring(self): buffer = [] while True: c = self.read_bytes(1)", "= DataParser(data[body_start:], logger) for page_size in page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger) p.skip_to_end('footer') return jar", "flag: --password-store=<basic|gnome|kwallet> so the automatic detection # will not be sufficient in all", "encrypted with an OS protected key (keyring) and more key derivation iterations than", "# pPromptStruct: information about prompts to display 0, # dwFlags ctypes.byref(blob_out) # pDataOut", "return code {proc.returncode}. Please consult ' 'the kwallet-query man page for details') return", "'X-Cinnamon': return _LinuxDesktopEnvironment.CINNAMON elif xdg_current_desktop == 'KDE': return _LinuxDesktopEnvironment.KDE elif xdg_current_desktop == 'Pantheon':", "c = self.read_bytes(1) if c == b'\\x00': return b''.join(buffer).decode('utf-8') else: buffer.append(c) def skip(self,", "config['keyring_name'], logger, keyring=keyring) with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try: cursor =", "self._cookie_counts = {'v10': 0, 'other': 0} @property def cookie_counts(self): return self._cookie_counts def decrypt(self,", "Wallet::NetworkWallet \"\"\" default_wallet = 'kdewallet' try: proc = Popen([ 'dbus-send', '--session', '--print-reply=literal', '--dest=org.kde.kwalletd5',", "*line) if not cookie: failed_cookies += 1 continue elif not is_encrypted: unencrypted_cookies +=", "b'' else: if stdout.lower().startswith(b'failed to read'): logger.debug('failed to read password from kwallet. Using", "cursor.connection.close() def _process_chrome_cookie(decryptor, host_key, name, value, encrypted_value, path, expires_utc, is_secure): host_key = host_key.decode('utf-8')", "{i: 6d} files searched') if file == filename: paths.append(os.path.join(curr_root, file)) return None if", "if cookie_database_path is None: raise FileNotFoundError(f'could not find firefox cookies database in {search_root}')", "isSecure FROM moz_cookies') jar = YoutubeDLCookieJar() with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall()", "return _LinuxDesktopEnvironment.GNOME else: return _LinuxDesktopEnvironment.UNITY elif xdg_current_desktop == 'GNOME': return _LinuxDesktopEnvironment.GNOME elif xdg_current_desktop", "not support profiles') if sys.platform != 'darwin': raise ValueError(f'unsupported platform: {sys.platform}') cookies_path =", "len(table) for i, (host, name, value, path, expiry, is_secure) in enumerate(table): progress_bar.print(f'Loading cookie", "= {'v10': 0, 'v11': 0, 'other': 0} @staticmethod def derive_key(password): # values from", "depending on the activate desktop environment [2] Mac: - cookies are either v10", "import struct import subprocess import sys import tempfile from datetime import datetime, timedelta,", "logger.info('Extracting cookies from firefox') if not SQLITE_AVAILABLE: logger.warning('Cannot extract cookies from firefox without", "plaintext Windows: - cookies are either v10 or not v10 - v10: AES-GCM", "Exception as e: logger.warning(f'exception running kwallet-query: {error_to_str(e)}') return b'' def _get_gnome_keyring_password(browser_keyring_name, logger): if", "elif xdg_current_desktop == 'Pantheon': return _LinuxDesktopEnvironment.PANTHEON elif xdg_current_desktop == 'XFCE': return _LinuxDesktopEnvironment.XFCE elif", "= self._data[self.cursor:end] self.cursor = end return data def expect_bytes(self, expected_value, message): value =", "= proc.communicate_or_kill() if proc.returncode != 0: logger.error(f'kwallet-query failed with return code {proc.returncode}. Please", "e: logger.warning(f'exception running kwallet-query: {error_to_str(e)}') return b'' def _get_gnome_keyring_password(browser_keyring_name, logger): if not SECRETSTORAGE_AVAILABLE:", "warning(self, message, only_once=False): if self._ydl: self._ydl.report_warning(message, only_once) def error(self, message): if self._ydl: self._ydl.report_error(message)", "jar finally: if cursor is not None: cursor.connection.close() def _process_chrome_cookie(decryptor, host_key, name, value,", "big_endian else '<I' return struct.unpack(data_format, self.read_bytes(4))[0] def read_double(self, big_endian=False): data_format = '>d' if", "= _open_database_copy(cookie_database_path, tmpdir) cursor.connection.text_factory = bytes column_names = _get_column_names(cursor, 'cookies') secure_column = 'is_secure'", "running kwallet-query: {error_to_str(e)}') return b'' def _get_gnome_keyring_password(browser_keyring_name, logger): if not SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage not", "raise ParserError('reached end of input') data = self._data[self.cursor:end] self.cursor = end return data", "is None: jar = YoutubeDLCookieJar() page_sizes, body_start = _parse_safari_cookies_header(data, logger) p = DataParser(data[body_start:],", "will not be sufficient in all cases. keyring = _LinuxKeyring[keyring] if keyring else", "{value} != {expected_value} ({message})') def read_uint(self, big_endian=False): data_format = '>I' if big_endian else", "is required) return None assert False, f'Unknown keyring {keyring}' def _get_mac_keyring_password(browser_keyring_name, logger): logger.debug('using", "import datetime, timedelta, timezone from enum import Enum, auto from hashlib import pbkdf2_hmac", "if 'is_secure' in column_names else 'secure' cursor.execute(f'SELECT host_key, name, value, encrypted_value, path, expires_utc,", "message: printer.print_at_line(f'[Cookies] {message}', 0) return printer def _create_progress_bar(logger): if hasattr(logger, 'progress_bar'): printer =", "sys.platform == 'win32': appdata_local = os.path.expandvars('%LOCALAPPDATA%') appdata_roaming = os.path.expandvars('%APPDATA%') browser_dir = { 'brave':", "out of date but the important parts of the database structure is the", "Data'), 'opera': os.path.join(appdata_roaming, R'Opera Software\\Opera Stable'), 'vivaldi': os.path.join(appdata_local, R'Vivaldi\\User Data'), }[browser_name] elif sys.platform", "{'firefox', 'safari'} class YDLLogger: def __init__(self, ydl=None): self._ydl = ydl def debug(self, message):", "\"\") whereas kwallet-query # checks hasEntry. To verify this: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\"", "self._logger.warning('cannot decrypt v10 cookies: no key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v10_key,", "domain = p.read_cstring() p.skip_to(name_offset) name = p.read_cstring() p.skip_to(path_offset) path = p.read_cstring() p.skip_to(value_offset) value", "Possibly the key is wrong?', only_once=True) return None def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag,", "( aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7, ) from .compat import compat_b64decode, compat_cookiejar_Cookie from .minicurses import", "finally: if cursor is not None: cursor.connection.close() def _process_chrome_cookie(decryptor, host_key, name, value, encrypted_value,", "= 16 raw_ciphertext = ciphertext nonce = raw_ciphertext[:nonce_length] ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag =", "be sufficient in all cases. keyring = _LinuxKeyring[keyring] if keyring else _choose_linux_keyring(logger) logger.debug(f'Chosen", "stdout[-1:] == b'\\n': stdout = stdout[:-1] return stdout except Exception as e: logger.warning(f'exception", "else self.derive_key(password) self._cookie_counts = {'v10': 0, 'v11': 0, 'other': 0} @staticmethod def derive_key(password):", "keyring=None): self._logger = logger self._v10_key = self.derive_key(b'peanuts') password = _get_linux_keyring_password(browser_keyring_name, keyring, logger) self._v11_key", "find {browser_name} cookies database in \"{search_root}\"') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') decryptor = get_cookie_decryptor(config['browser_dir'],", "if not paths else max(paths, key=lambda path: os.lstat(path).st_mtime) def _merge_cookie_jars(jars): output_jar = YoutubeDLCookieJar()", "only_once=True) return None def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, logger): try: plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext,", "browser_keyring_name, # match 'account' '-s', f'{browser_keyring_name} Safe Storage'], # match 'service' stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)", "multiple browser profiles, take the most recently used one i, paths = 0,", "are skipped during parsing \"\"\" if jar is None: jar = YoutubeDLCookieJar() page_sizes,", "the standard library, it is possible to compile python without # sqlite support.", "if xdg_current_desktop == 'Unity': if desktop_session is not None and 'gnome-fallback' in desktop_session:", "value is None: return is_encrypted, None return is_encrypted, compat_cookiejar_Cookie( version=0, name=name, value=value, port=None,", "required) return None assert False, f'Unknown keyring {keyring}' def _get_mac_keyring_password(browser_keyring_name, logger): logger.debug('using find-generic-password", "in ('linux', 'linux2'): return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring) elif sys.platform == 'darwin': return MacChromeCookieDecryptor(browser_keyring_name,", "class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_root, logger): self._logger = logger self._v10_key = _get_windows_v10_key(browser_root, logger)", "state file') return None logger.debug(f'Found local state file at \"{path}\"') with open(path, encoding='utf8')", "os.path.expanduser('~/.mozilla/firefox') elif sys.platform == 'win32': return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif sys.platform == 'darwin': return os.path.expanduser('~/Library/Application", "dirs, files in os.walk(root): for file in files: i += 1 progress_bar.print(f'Searching for", "References: - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc - this data appears to be out of date but", "appears that we must do the same. # https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init()) as con:", "either v10 or v11 - v10: AES-CBC encrypted with a fixed key -", "def _get_linux_keyring_password(browser_keyring_name, keyring, logger): # note: chrome/chromium can be run with the following", "logger.warning(f'exception while obtaining NetworkWallet: {e}') return default_wallet def _get_kwallet_password(browser_keyring_name, logger): logger.debug('using kwallet-query to", "return None return _decrypt_aes_cbc(ciphertext, self._v11_key, self._logger) else: self._cookie_counts['other'] += 1 return None class", "= ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in), # pDataIn None, # ppszDataDescr: human readable description of pDataIn", "AES-CBC encrypted with an OS protected key (keyring) and more key derivation iterations", "support profiles') if sys.platform != 'darwin': raise ValueError(f'unsupported platform: {sys.platform}') cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies')", "- cookies are either v10 or not v10 - v10: AES-GCM encrypted with", "'darwin' else 'Chromium', 'opera': 'Opera' if sys.platform == 'darwin' else 'Chromium', 'vivaldi': 'Vivaldi'", "name=name, value=value, port=None, port_specified=False, domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False, comment=None,", "'GNOME': return _LinuxDesktopEnvironment.GNOME elif xdg_current_desktop == 'X-Cinnamon': return _LinuxDesktopEnvironment.CINNAMON elif xdg_current_desktop == 'KDE':", "None: raise FileNotFoundError(f'could not find firefox cookies database in {search_root}') logger.debug(f'Extracting cookies from:", "network_wallet except Exception as e: logger.warning(f'exception while obtaining NetworkWallet: {e}') return default_wallet def", "when basic text is chosen, all cookies are stored as v10 (so no", "path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) return record_size def parse_safari_cookies(data, jar=None,", "end = self.cursor + num_bytes if end > len(self._data): raise ParserError('reached end of", "as f: data = json.load(f) try: base64_key = data['os_crypt']['encrypted_key'] except KeyError: logger.error('no encrypted", "ImportError: # although sqlite3 is part of the standard library, it is possible", "and kwallet-query ' 'must be installed to read from KWallet. kwallet-query should be'", "= auto() BASICTEXT = auto() SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys() def _get_linux_desktop_environment(env): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment", "version == b'v11': self._cookie_counts['v11'] += 1 if self._v11_key is None: self._logger.warning('cannot decrypt v11", "logger): logger.info(f'Extracting cookies from {browser_name}') if not SQLITE_AVAILABLE: logger.warning(f'Cannot extract cookies from {browser_name}", "- not v10: 'old data' stored as plaintext Windows: - cookies are either", "self.read_bytes(1) if c == b'\\x00': return b''.join(buffer).decode('utf-8') else: buffer.append(c) def skip(self, num_bytes, description='unknown'):", "and more key derivation iterations than linux - not v10: 'old data' stored", "check hasEntry and instead # just tries to read the value (which kwallet", "man page for details') return b'' else: if stdout.lower().startswith(b'failed to read'): logger.debug('failed to", "for _ in range(number_of_cookies)] if number_of_cookies == 0: logger.debug(f'a cookies page of size", "profile is None: search_root = _firefox_browser_dir() elif _is_path(profile): search_root = profile else: search_root", "in ('linux', 'linux2'): return os.path.expanduser('~/.mozilla/firefox') elif sys.platform == 'win32': return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif sys.platform", "'included in the kwallet package for your distribution') return b'' network_wallet = _get_kwallet_network_wallet(logger)", "can be stored in various places depending on the activate desktop environment [2]", "logger): \"\"\" References: - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\" from ctypes.wintypes import DWORD class DATA_BLOB(ctypes.Structure): _fields_", "for i, line in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') is_encrypted, cookie =", "raise NotImplementedError('Must be implemented by sub classes') def get_cookie_decryptor(browser_root, browser_keyring_name, logger, *, keyring=None):", "range(number_of_pages)] return page_sizes, p.cursor def _parse_safari_cookies_page(data, jar, logger): p = DataParser(data, logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00',", "if shutil.which('kwallet-query') is None: logger.error('kwallet-query command not found. KWallet and kwallet-query ' 'must", "in jars: for cookie in jar: output_jar.set_cookie(cookie) if jar.filename is not None: output_jar.filename", "DATA_BLOB(ctypes.sizeof(buffer), buffer) blob_out = DATA_BLOB() ret = ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in), # pDataIn None, #", "in desktop_session: return _LinuxDesktopEnvironment.KDE elif 'xfce' in desktop_session: return _LinuxDesktopEnvironment.XFCE else: if 'GNOME_DESKTOP_SESSION_ID'", "p.read_uint() p.skip(8, 'unknown record field 3') expiration_date = _mac_absolute_time_to_posix(p.read_double()) _creation_date = _mac_absolute_time_to_posix(p.read_double()) #", "UTF-8 decoding failed. Possibly the key is wrong?', only_once=True) return None def _decrypt_aes_gcm(ciphertext,", "cookies_data = f.read() jar = parse_safari_cookies(cookies_data, logger=logger) logger.info(f'Extracted {len(jar)} cookies from safari') return", "total_cookie_count = len(table) for i, (host, name, value, path, expiry, is_secure) in enumerate(table):", "# the Gnome keyring does not seem to organise keys in the same", "key, initialization_vector)) try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-CBC) because", "python interpreter compiled with sqlite3 support') return YoutubeDLCookieJar() if profile is None: search_root", "while starting chrome. # this may be a bug as the intended behaviour", "proc.returncode != 0: logger.warning('failed to read NetworkWallet') return default_wallet else: network_wallet = stdout.decode('utf-8').strip()", "_LinuxDesktopEnvironment.XFCE else: if 'GNOME_DESKTOP_SESSION_ID' in env: return _LinuxDesktopEnvironment.GNOME elif 'KDE_FULL_SESSION' in env: return", "return None def _decrypt_windows_dpapi(ciphertext, logger): \"\"\" References: - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\" from ctypes.wintypes import", "Possibly the key is wrong?', only_once=True) return None try: return plaintext.decode('utf-8') except UnicodeDecodeError:", "size {len(data)} has no cookies') return p.skip_to(record_offsets[0], 'unknown page header field') with _create_progress_bar(logger)", "elif xdg_current_desktop == 'KDE': return _LinuxDesktopEnvironment.KDE elif xdg_current_desktop == 'Pantheon': return _LinuxDesktopEnvironment.PANTHEON elif", "as progress_bar: table = cursor.fetchall() total_cookie_count = len(table) for i, line in enumerate(table):", "cursor.fetchall() total_cookie_count = len(table) for i, line in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count:", "ciphertext = encrypted_value[3:] if version == b'v10': self._cookie_counts['v10'] += 1 return _decrypt_aes_cbc(ciphertext, self._v10_key,", "found. KWallet and kwallet-query ' 'must be installed to read from KWallet. kwallet-query", "encrypted_value[3:] if version == b'v10': self._cookie_counts['v10'] += 1 return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) elif", "b'\\n': stdout = stdout[:-1] return stdout except Exception as e: logger.warning(f'exception running kwallet-query:", "6d}') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path,", "os.path.dirname(profile) if config['supports_profiles'] else profile else: if config['supports_profiles']: search_root = os.path.join(config['browser_dir'], profile) else:", "See: https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE = False try: import secretstorage SECRETSTORAGE_AVAILABLE = True except ImportError:", "read_cstring(self): buffer = [] while True: c = self.read_bytes(1) if c == b'\\x00':", "https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc - this data appears to be out of date but the important", "is_secure) in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') cookie = compat_cookiejar_Cookie( version=0, name=name,", "return _LinuxDesktopEnvironment.CINNAMON elif xdg_current_desktop == 'KDE': return _LinuxDesktopEnvironment.KDE elif xdg_current_desktop == 'Pantheon': return", "logger.debug(f'NetworkWallet = \"{network_wallet}\"') return network_wallet except Exception as e: logger.warning(f'exception while obtaining NetworkWallet:", "== 'KDE': return _LinuxDesktopEnvironment.KDE elif xdg_current_desktop == 'Pantheon': return _LinuxDesktopEnvironment.PANTHEON elif xdg_current_desktop ==", "interpreter compiled with sqlite3 support') return YoutubeDLCookieJar() config = _get_chromium_based_browser_settings(browser_name) if profile is", "import json import os import shutil import struct import subprocess import sys import", "[] with _create_progress_bar(logger) as progress_bar: for curr_root, dirs, files in os.walk(root): for file", "('linux', 'linux2'): return os.path.expanduser('~/.mozilla/firefox') elif sys.platform == 'win32': return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif sys.platform ==", "that chromium lists all keys # and presumably searches for its key in", "installed. ' 'Please install by running `python3 -m pip install secretstorage`.') except Exception", "'Chromium', 'vivaldi': 'Vivaldi' if sys.platform == 'darwin' else 'Chrome', }[browser_name] browsers_without_profiles = {'opera'}", "python interpreter compiled with sqlite3 support') return YoutubeDLCookieJar() config = _get_chromium_based_browser_settings(browser_name) if profile", "be a bug as the intended behaviour is to generate a random password", "# if there are multiple browser profiles, take the most recently used one", "key=lambda path: os.lstat(path).st_mtime) def _merge_cookie_jars(jars): output_jar = YoutubeDLCookieJar() for jar in jars: for", "browser_dir = { 'brave': os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User Data'), 'chrome': os.path.join(appdata_local, R'Google\\Chrome\\User Data'), 'chromium': os.path.join(appdata_local,", "if keyring == _LinuxKeyring.KWALLET: return _get_kwallet_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.GNOMEKEYRING: return _get_gnome_keyring_password(browser_keyring_name,", "logger.error(f'{browser_name} does not support profiles') search_root = config['browser_dir'] cookie_database_path = _find_most_recently_used_file(search_root, 'Cookies', logger)", "logger.warning('failed to decrypt cookie (AES-GCM) because UTF-8 decoding failed. Possibly the key is", "wrong?', only_once=True) return None def _decrypt_windows_dpapi(ciphertext, logger): \"\"\" References: - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\" from", "are either v10 or not v10 - v10: AES-GCM encrypted with a key", "and presumably searches for its key in the list. It appears that we", "{'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi'} SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'} class", "'space between records') record_length = _parse_safari_cookies_record(data[record_offset:], jar, logger) p.read_bytes(record_length) p.skip_to_end('space in between pages')", "' 'Please install by running `python3 -m pip install secretstorage`.') except Exception as", "interpreter compiled with sqlite3 support') return YoutubeDLCookieJar() if profile is None: search_root =", "'--print-reply=literal', '--dest=org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet.networkWallet' ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode", "def _open_database_copy(database_path, tmpdir): # cannot open sqlite databases if they are already in", "not SQLITE_AVAILABLE: logger.warning(f'Cannot extract cookies from {browser_name} without sqlite3 support. ' 'Please use", "'linux2'): return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring) elif sys.platform == 'darwin': return MacChromeCookieDecryptor(browser_keyring_name, logger) elif", "logger): logger.debug('using kwallet-query to obtain password from kwallet') if shutil.which('kwallet-query') is None: logger.error('kwallet-query", "'Microsoft Edge' if sys.platform == 'darwin' else 'Chromium', 'opera': 'Opera' if sys.platform ==", "_open_database_copy(cookie_database_path, tmpdir) cursor.connection.text_factory = bytes column_names = _get_column_names(cursor, 'cookies') secure_column = 'is_secure' if", "{expected_value} ({message})') def read_uint(self, big_endian=False): data_format = '>I' if big_endian else '<I' return", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment \"\"\" OTHER = auto() CINNAMON = auto() GNOME = auto() KDE", "datetime, timedelta, timezone from enum import Enum, auto from hashlib import pbkdf2_hmac from", "_create_progress_bar(logger): if hasattr(logger, 'progress_bar'): printer = logger.progress_bar() if printer: return printer printer =", "while opening the browser in KDE: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" keyring_name = {", "_LinuxDesktopEnvironment.GNOME elif 'KDE_FULL_SESSION' in env: return _LinuxDesktopEnvironment.KDE return _LinuxDesktopEnvironment.OTHER def _choose_linux_keyring(logger): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc", "bytes column_names = _get_column_names(cursor, 'cookies') secure_column = 'is_secure' if 'is_secure' in column_names else", "if browser_name == 'firefox': return _extract_firefox_cookies(profile, logger) elif browser_name == 'safari': return _extract_safari_cookies(profile,", "f'{browser_keyring_name} Safe Storage'], # match 'service' stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if", "'vivaldi'), }[browser_name] elif sys.platform == 'win32': appdata_local = os.path.expandvars('%LOCALAPPDATA%') appdata_roaming = os.path.expandvars('%APPDATA%') browser_dir", "'gnome'): return _LinuxDesktopEnvironment.GNOME elif 'kde' in desktop_session: return _LinuxDesktopEnvironment.KDE elif 'xfce' in desktop_session:", "auto() SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys() def _get_linux_desktop_environment(env): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment \"\"\" xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP',", "== 'darwin' else 'Chromium', 'opera': 'Opera' if sys.platform == 'darwin' else 'Chromium', 'vivaldi':", "jar class ParserError(Exception): pass class DataParser: def __init__(self, data, logger): self._data = data", "of date but the important parts of the database structure is the same", "num_bytes): if num_bytes < 0: raise ParserError(f'invalid read of {num_bytes} bytes') end =", "return printer printer = QuietMultilinePrinter() printer.print = lambda _: None return printer def", "{i: 6d}/{total_cookie_count: 6d}') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host, domain_specified=bool(host),", "def __init__(self, data, logger): self._data = data self.cursor = 0 self._logger = logger", "= os.path.dirname(profile) if config['supports_profiles'] else profile else: if config['supports_profiles']: search_root = os.path.join(config['browser_dir'], profile)", "1 return None class MacChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger): self._logger = logger password", "not cookie: failed_cookies += 1 continue elif not is_encrypted: unencrypted_cookies += 1 jar.set_cookie(cookie)", "bool(flags & 0x0001) p.skip(4, 'unknown record field 2') domain_offset = p.read_uint() name_offset =", "is wrong?', only_once=True) return None def _decrypt_windows_dpapi(ciphertext, logger): \"\"\" References: - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\"", "= _find_most_recently_used_file(search_root, 'Cookies', logger) if cookie_database_path is None: raise FileNotFoundError(f'could not find {browser_name}", "if profile is not None and _is_path(profile): profile = os.path.expanduser(profile) return browser_name, profile,", "}[browser_name] elif sys.platform == 'darwin': appdata = os.path.expanduser('~/Library/Application Support') browser_dir = { 'brave':", "table = cursor.fetchall() total_cookie_count = len(table) for i, line in enumerate(table): progress_bar.print(f'Loading cookie", "== 'win32': return WindowsChromeCookieDecryptor(browser_root, logger) else: raise NotImplementedError(f'Chrome cookie decryption is not supported", "jar: output_jar.set_cookie(cookie) if jar.filename is not None: output_jar.filename = jar.filename return output_jar def", "grep key_storage_ # Chromium supports a flag: --password-store=<basic|gnome|kwallet> so the automatic detection #", "used to store network passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet which does a dbus call to", "[] if browser_specification is not None: browser_name, profile, keyring = _parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name, profile,", "string instead') # this sometimes occurs in KDE because chrome does not check", "= _get_chromium_based_browser_settings(browser_name) if profile is None: search_root = config['browser_dir'] elif _is_path(profile): search_root =", "encrypted_value[:3] ciphertext = encrypted_value[3:] if version == b'v10': self._cookie_counts['v10'] += 1 return _decrypt_aes_cbc(ciphertext,", "= secretstorage.get_default_collection(con) for item in col.get_all_items(): if item.get_label() == f'{browser_keyring_name} Safe Storage': return", "sys.platform == 'darwin' else 'Chromium', 'opera': 'Opera' if sys.platform == 'darwin' else 'Chromium',", "= Popen([ 'kwallet-query', '--read-password', f'{browser_keyring_name} Safe Storage', '--folder', f'{browser_keyring_name} Keys', network_wallet ], stdout=subprocess.PIPE,", "'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(config, 'google-chrome'), 'chromium': os.path.join(config, 'chromium'), 'edge': os.path.join(config, 'microsoft-edge'), 'opera':", "b'' # the Gnome keyring does not seem to organise keys in the", "CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'} class YDLLogger: def __init__(self, ydl=None): self._ydl = ydl def", "not be decrypted)' else: failed_message = '' logger.info(f'Extracted {len(jar)} cookies from {browser_name}{failed_message}') counts", "occurs in KDE because chrome does not check hasEntry and instead # just", "ppszDataDescr: human readable description of pDataIn None, # pOptionalEntropy: salt? None, # pvReserved:", "is None: logger.error('kwallet-query command not found. KWallet and kwallet-query ' 'must be installed", "is_secure = bool(flags & 0x0001) p.skip(4, 'unknown record field 2') domain_offset = p.read_uint()", "'rb') as f: cookies_data = f.read() jar = parse_safari_cookies(cookies_data, logger=logger) logger.info(f'Extracted {len(jar)} cookies", "2>&1 | grep key_storage_ # Chromium supports a flag: --password-store=<basic|gnome|kwallet> so the automatic", "'Local State', logger) if path is None: logger.error('could not find local state file')", "buffer) blob_out = DATA_BLOB() ret = ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in), # pDataIn None, # ppszDataDescr:", "pDataIn None, # pOptionalEntropy: salt? None, # pvReserved: must be NULL None, #", "table_name): table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall() return [row[1].decode('utf-8') for row in table_info] def _find_most_recently_used_file(root,", "continue elif not is_encrypted: unencrypted_cookies += 1 jar.set_cookie(cookie) if failed_cookies > 0: failed_message", "authentication_tag, self._logger) else: self._cookie_counts['other'] += 1 # any other prefix means the data", "with sqlite3 support') return YoutubeDLCookieJar() config = _get_chromium_based_browser_settings(browser_name) if profile is None: search_root", "UTF-8 decoding failed. Possibly the key is wrong?', only_once=True) return None def _decrypt_windows_dpapi(ciphertext,", "pDataIn None, # ppszDataDescr: human readable description of pDataIn None, # pOptionalEntropy: salt?", "+= 1 continue elif not is_encrypted: unencrypted_cookies += 1 jar.set_cookie(cookie) if failed_cookies >", "if keyring else _choose_linux_keyring(logger) logger.debug(f'Chosen keyring: {keyring.name}') if keyring == _LinuxKeyring.KWALLET: return _get_kwallet_password(browser_keyring_name,", "os.path.join(appdata, 'Google/Chrome'), 'chromium': os.path.join(appdata, 'Chromium'), 'edge': os.path.join(appdata, 'Microsoft Edge'), 'opera': os.path.join(appdata, 'com.operasoftware.Opera'), 'vivaldi':", "or not v10 - v10: AES-CBC encrypted with an OS protected key (keyring)", "has no cookies') return p.skip_to(record_offsets[0], 'unknown page header field') with _create_progress_bar(logger) as progress_bar:", "(e.g. by the browser) database_copy_path = os.path.join(tmpdir, 'temporary.sqlite') shutil.copy(database_path, database_copy_path) conn = sqlite3.connect(database_copy_path)", "_extract_firefox_cookies(profile, logger): logger.info('Extracting cookies from firefox') if not SQLITE_AVAILABLE: logger.warning('Cannot extract cookies from", "= auto() XFCE = auto() class _LinuxKeyring(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend \"\"\" KWALLET =", "DPAPI - not v10: encrypted with DPAPI Sources: - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ - [2]", "def _mac_absolute_time_to_posix(timestamp): return int((datetime(2001, 1, 1, 0, 0, tzinfo=timezone.utc) + timedelta(seconds=timestamp)).timestamp()) def _parse_safari_cookies_header(data,", "logger) record_size = p.read_uint() p.skip(4, 'unknown record field 1') flags = p.read_uint() is_secure", "to decrypt cookie (AES-GCM) because the MAC check failed. Possibly the key is", "(AES-GCM) because UTF-8 decoding failed. Possibly the key is wrong?', only_once=True) return None", "'Chrome', }[browser_name] browsers_without_profiles = {'opera'} return { 'browser_dir': browser_dir, 'keyring_name': keyring_name, 'supports_profiles': browser_name", "= '>d' if big_endian else '<d' return struct.unpack(data_format, self.read_bytes(8))[0] def read_cstring(self): buffer =", "platform: {sys.platform}') cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): logger.debug('Trying secondary cookie location') cookies_path", "cookie_counts(self): raise NotImplementedError('Must be implemented by sub classes') def get_cookie_decryptor(browser_root, browser_keyring_name, logger, *,", "is_encrypted = not value and encrypted_value if is_encrypted: value = decryptor.decrypt(encrypted_value) if value", "more key derivation iterations than linux - not v10: 'old data' stored as", "'Vivaldi'), }[browser_name] else: raise ValueError(f'unsupported platform: {sys.platform}') # Linux keyring names can be", "[1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc - KeyStorageLinux::CreateService \"\"\" def decrypt(self, encrypted_value): raise NotImplementedError('Must", "domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiry, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) logger.info(f'Extracted", "return _decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8') def _extract_safari_cookies(profile, logger): if profile is not None: logger.error('safari does", "= p.read_uint() value_offset = p.read_uint() p.skip(8, 'unknown record field 3') expiration_date = _mac_absolute_time_to_posix(p.read_double())", "xdg_current_desktop = xdg_current_desktop.split(':')[0].strip() if xdg_current_desktop == 'Unity': if desktop_session is not None and", "elif xdg_current_desktop == 'XFCE': return _LinuxDesktopEnvironment.XFCE elif desktop_session is not None: if desktop_session", "with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.connection.text_factory", "env: return _LinuxDesktopEnvironment.GNOME elif 'KDE_FULL_SESSION' in env: return _LinuxDesktopEnvironment.KDE return _LinuxDesktopEnvironment.OTHER def _choose_linux_keyring(logger):", "has chosen to use # chromium --enable-logging=stderr --v=1 2>&1 | grep key_storage_ #", "auto() PANTHEON = auto() UNITY = auto() XFCE = auto() class _LinuxKeyring(Enum): \"\"\"", "except Exception as e: logger.warning(f'exception running find-generic-password: {error_to_str(e)}') return None def _get_windows_v10_key(browser_root, logger):", "None return is_encrypted, compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), path=path,", "return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-CBC) because UTF-8 decoding failed.", "return _get_kwallet_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.GNOMEKEYRING: return _get_gnome_keyring_password(browser_keyring_name, logger) elif keyring ==", "_get_mac_keyring_password(browser_keyring_name, logger): logger.debug('using find-generic-password to obtain password from OSX keychain') try: proc =", "None def _decrypt_windows_dpapi(ciphertext, logger): \"\"\" References: - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\" from ctypes.wintypes import DWORD", "DATA_BLOB(ctypes.Structure): _fields_ = [('cbData', DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))] buffer = ctypes.create_string_buffer(ciphertext) blob_in = DATA_BLOB(ctypes.sizeof(buffer),", "def info(self, message): if self._ydl: self._ydl.to_screen(f'[Cookies] {message}') def warning(self, message, only_once=False): if self._ydl:", "result = ctypes.string_at(blob_out.pbData, blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData) return result def _config_home(): return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) def", "column_names = _get_column_names(cursor, 'cookies') secure_column = 'is_secure' if 'is_secure' in column_names else 'secure'", "keys can be stored in various places depending on the activate desktop environment", "file.isatty(): return except BaseException: return printer = MultilinePrinter(file, preserve_output=False) printer.print = lambda message:", "a print method. (Optional)\"\"\" # Do not print to files/pipes, loggers, or when", "= auto() UNITY = auto() XFCE = auto() class _LinuxKeyring(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend", "os.path.join(appdata, 'Microsoft Edge'), 'opera': os.path.join(appdata, 'com.operasoftware.Opera'), 'vivaldi': os.path.join(appdata, 'Vivaldi'), }[browser_name] else: raise ValueError(f'unsupported", "import subprocess import sys import tempfile from datetime import datetime, timedelta, timezone from", "path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) return record_size def parse_safari_cookies(data,", "file)) return None if not paths else max(paths, key=lambda path: os.lstat(path).st_mtime) def _merge_cookie_jars(jars):", "= f'as the `secretstorage` module could not be initialized. {_err}' CHROMIUM_BASED_BROWSERS = {'brave',", "elif 'xfce' in desktop_session: return _LinuxDesktopEnvironment.XFCE else: if 'GNOME_DESKTOP_SESSION_ID' in env: return _LinuxDesktopEnvironment.GNOME", "desktop_session: return _LinuxDesktopEnvironment.XFCE else: if 'GNOME_DESKTOP_SESSION_ID' in env: return _LinuxDesktopEnvironment.GNOME elif 'KDE_FULL_SESSION' in", "not found. KWallet and kwallet-query ' 'must be installed to read from KWallet.", "return None assert False, f'Unknown keyring {keyring}' def _get_mac_keyring_password(browser_keyring_name, logger): logger.debug('using find-generic-password to", "None try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-GCM) because UTF-8", "proc = Popen([ 'dbus-send', '--session', '--print-reply=literal', '--dest=org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet.networkWallet' ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout,", "timedelta(seconds=timestamp)).timestamp()) def _parse_safari_cookies_header(data, logger): p = DataParser(data, logger) p.expect_bytes(b'cook', 'database signature') number_of_pages =", "raise NotImplementedError(f'Chrome cookie decryption is not supported on this platform: {sys.platform}') class LinuxChromeCookieDecryptor(ChromeCookieDecryptor):", "\"\"\" if jar is None: jar = YoutubeDLCookieJar() page_sizes, body_start = _parse_safari_cookies_header(data, logger)", "if sys.platform == 'darwin' else 'Chrome', }[browser_name] browsers_without_profiles = {'opera'} return { 'browser_dir':", "stored as v10 (so no keyring password is required) return None assert False,", "on dbus while opening the browser in KDE: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" keyring_name", "= 96 // 8 # boringssl # EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length = 16 raw_ciphertext =", "in table_info] def _find_most_recently_used_file(root, filename, logger): # if there are multiple browser profiles,", "p.skip_to_end('space in between pages') def _parse_safari_cookies_record(data, jar, logger): p = DataParser(data, logger) record_size", "tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.execute('SELECT host,", "code {proc.returncode}. Please consult ' 'the kwallet-query man page for details') return b''", "found') if stdout[-1:] == b'\\n': stdout = stdout[:-1] return stdout except Exception as", "AES-CBC encrypted with an OS protected key (keyring) - v11 keys can be", "else 'Chromium', 'opera': 'Opera' if sys.platform == 'darwin' else 'Chromium', 'vivaldi': 'Vivaldi' if", "True: c = self.read_bytes(1) if c == b'\\x00': return b''.join(buffer).decode('utf-8') else: buffer.append(c) def", "= YoutubeDLCookieJar() with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count = len(table) for", "from {browser_name}') if not SQLITE_AVAILABLE: logger.warning(f'Cannot extract cookies from {browser_name} without sqlite3 support.", "the wallet used to store network passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet which does a dbus", "- cookies are either v10 or v11 - v10: AES-CBC encrypted with a", "[2] Mac: - cookies are either v10 or not v10 - v10: AES-CBC", "def _is_path(value): return os.path.sep in value def _parse_browser_specification(browser_name, profile=None, keyring=None): if browser_name not", "platform: {sys.platform}') class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger, *, keyring=None): self._logger = logger", "# match 'service' stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if stdout[-1:] == b'\\n':", "'darwin': return os.path.expanduser('~/Library/Application Support/Firefox') else: raise ValueError(f'unsupported platform: {sys.platform}') def _get_chromium_based_browser_settings(browser_name): # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md", "jar = YoutubeDLCookieJar() with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count = len(table)", "logger.info(f'Extracted {len(jar)} cookies from {browser_name}{failed_message}') counts = decryptor.cookie_counts.copy() counts['unencrypted'] = unencrypted_cookies logger.debug(f'cookie version", "open(cookies_path, 'rb') as f: cookies_data = f.read() jar = parse_safari_cookies(cookies_data, logger=logger) logger.info(f'Extracted {len(jar)}", "browser: \"{browser_name}\"') if keyring not in (None, *SUPPORTED_KEYRINGS): raise ValueError(f'unsupported keyring: \"{keyring}\"') if", "# kNonceLength nonce_length = 96 // 8 # boringssl # EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length =", "page_sizes, body_start = _parse_safari_cookies_header(data, logger) p = DataParser(data[body_start:], logger) for page_size in page_sizes:", "debug(self, message): if self._ydl: self._ydl.write_debug(message) def info(self, message): if self._ydl: self._ydl.to_screen(f'[Cookies] {message}') def", "'other': 0} @staticmethod def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return pbkdf2_sha1(password, salt=b'<PASSWORD>',", "None, # pOptionalEntropy: salt? None, # pvReserved: must be NULL None, # pPromptStruct:", "except ImportError: # although sqlite3 is part of the standard library, it is", "derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1003, key_length=16) @property def", "encrypted with a key which is encrypted with DPAPI - not v10: encrypted", "{ 'brave': os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User Data'), 'chrome': os.path.join(appdata_local, R'Google\\Chrome\\User Data'), 'chromium': os.path.join(appdata_local, R'Chromium\\User Data'),", "the `secretstorage` module could not be initialized. {_err}' CHROMIUM_BASED_BROWSERS = {'brave', 'chrome', 'chromium',", "# boringssl # EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length = 16 raw_ciphertext = ciphertext nonce = raw_ciphertext[:nonce_length]", "_get_windows_v10_key(browser_root, logger): path = _find_most_recently_used_file(browser_root, 'Local State', logger) if path is None: logger.error('could", "not os.path.isfile(cookies_path): raise FileNotFoundError('could not find safari cookies database') with open(cookies_path, 'rb') as", "port_specified=False, domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiry, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie)", "self._logger.warning('cannot decrypt v10 cookies: no key found', only_once=True) return None # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc #", "else: raise ValueError(f'unknown browser: {browser_name}') def _extract_firefox_cookies(profile, logger): logger.info('Extracting cookies from firefox') if", "unencrypted_cookies = 0 with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count = len(table)", "auto() GNOME = auto() KDE = auto() PANTHEON = auto() UNITY = auto()", "def _extract_firefox_cookies(profile, logger): logger.info('Extracting cookies from firefox') if not SQLITE_AVAILABLE: logger.warning('Cannot extract cookies", "\"{browser_name}\"') if keyring not in (None, *SUPPORTED_KEYRINGS): raise ValueError(f'unsupported keyring: \"{keyring}\"') if profile", "ret = ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in), # pDataIn None, # ppszDataDescr: human readable description of", "'database signature') number_of_pages = p.read_uint(big_endian=True) page_sizes = [p.read_uint(big_endian=True) for _ in range(number_of_pages)] return", "although sqlite3 is part of the standard library, it is possible to compile", "logger) p.expect_bytes(b'cook', 'database signature') number_of_pages = p.read_uint(big_endian=True) page_sizes = [p.read_uint(big_endian=True) for _ in", "sys.platform == 'win32': return WindowsChromeCookieDecryptor(browser_root, logger) else: raise NotImplementedError(f'Chrome cookie decryption is not", "try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.execute('SELECT host, name, value, path, expiry, isSecure FROM", "there which are skipped during parsing \"\"\" if jar is None: jar =", "encrypted key in Local State') return None encrypted_key = compat_b64decode(base64_key) prefix = b'DPAPI'", "return printer def _create_progress_bar(logger): if hasattr(logger, 'progress_bar'): printer = logger.progress_bar() if printer: return", "_LinuxDesktopEnvironment.KDE: linux_keyring = _LinuxKeyring.KWALLET elif desktop_environment == _LinuxDesktopEnvironment.OTHER: linux_keyring = _LinuxKeyring.BASICTEXT else: linux_keyring", "NetworkWallet') return default_wallet else: network_wallet = stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet = \"{network_wallet}\"') return network_wallet except", "cookies are either v10 or v11 - v10: AES-CBC encrypted with a fixed", "logger.debug(f'detected desktop environment: {desktop_environment.name}') if desktop_environment == _LinuxDesktopEnvironment.KDE: linux_keyring = _LinuxKeyring.KWALLET elif desktop_environment", "must do the same. # https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init()) as con: col = secretstorage.get_default_collection(con)", "f' ({failed_cookies} could not be decrypted)' else: failed_message = '' logger.info(f'Extracted {len(jar)} cookies", "SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'} class YDLLogger: def __init__(self, ydl=None): self._ydl =", "shutil import struct import subprocess import sys import tempfile from datetime import datetime,", "elif num_bytes < 0: raise ParserError(f'invalid skip of {num_bytes} bytes') def skip_to(self, offset,", "cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.execute('SELECT host, name, value, path, expiry, isSecure FROM moz_cookies')", "decryption is not supported on this platform: {sys.platform}') class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name,", "return _LinuxDesktopEnvironment.XFCE elif desktop_session is not None: if desktop_session in ('mate', 'gnome'): return", "'chromium', 'edge', 'opera', 'vivaldi'} SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'} class YDLLogger: def", "1 # other prefixes are considered 'old data' which were stored as plaintext", "not be initialized. {_err}' CHROMIUM_BASED_BROWSERS = {'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi'} SUPPORTED_BROWSERS", "message, only_once=False): if self._ydl: self._ydl.report_warning(message, only_once) def error(self, message): if self._ydl: self._ydl.report_error(message) def", "SQLITE_AVAILABLE = False try: import secretstorage SECRETSTORAGE_AVAILABLE = True except ImportError: SECRETSTORAGE_AVAILABLE =", "if sys.platform == 'darwin' else 'Chromium', 'vivaldi': 'Vivaldi' if sys.platform == 'darwin' else", "password is None else self.derive_key(password) self._cookie_counts = {'v10': 0, 'v11': 0, 'other': 0}", "= os.path.join(tmpdir, 'temporary.sqlite') shutil.copy(database_path, database_copy_path) conn = sqlite3.connect(database_copy_path) return conn.cursor() def _get_column_names(cursor, table_name):", "contextlib import ctypes import json import os import shutil import struct import subprocess", "None: output_jar.filename = jar.filename return output_jar def _is_path(value): return os.path.sep in value def", "= _parse_safari_cookies_record(data[record_offset:], jar, logger) p.read_bytes(record_length) p.skip_to_end('space in between pages') def _parse_safari_cookies_record(data, jar, logger):", "!= expected_value: raise ParserError(f'unexpected value: {value} != {expected_value} ({message})') def read_uint(self, big_endian=False): data_format", "def decrypt(self, encrypted_value): version = encrypted_value[:3] ciphertext = encrypted_value[3:] if version == b'v10':", "browser_name == 'firefox': return _extract_firefox_cookies(profile, logger) elif browser_name == 'safari': return _extract_safari_cookies(profile, logger)", "skip_to(self, offset, description='unknown'): self.skip(offset - self.cursor, description) def skip_to_end(self, description='unknown'): self.skip_to(len(self._data), description) def", "desktop_session = env.get('DESKTOP_SESSION', None) if xdg_current_desktop is not None: xdg_current_desktop = xdg_current_desktop.split(':')[0].strip() if", "DataParser(data[body_start:], logger) for page_size in page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger) p.skip_to_end('footer') return jar class", "{browser_name} cookies database in \"{search_root}\"') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') decryptor = get_cookie_decryptor(config['browser_dir'], config['keyring_name'],", "encrypted with DPAPI - not v10: encrypted with DPAPI Sources: - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/", "= p.read_uint() p.skip(4, 'unknown record field 1') flags = p.read_uint() is_secure = bool(flags", "and there which are skipped during parsing \"\"\" if jar is None: jar", "searches for its key in the list. It appears that we must do", "they are already in use (e.g. by the browser) database_copy_path = os.path.join(tmpdir, 'temporary.sqlite')", "OTHER = auto() CINNAMON = auto() GNOME = auto() KDE = auto() PANTHEON", "in files: i += 1 progress_bar.print(f'Searching for \"{filename}\": {i: 6d} files searched') if", "logger) if cookie_database_path is None: raise FileNotFoundError(f'could not find {browser_name} cookies database in", "def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value): version = encrypted_value[:3] ciphertext = encrypted_value[3:]", "struct import subprocess import sys import tempfile from datetime import datetime, timedelta, timezone", "find firefox cookies database in {search_root}') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') with tempfile.TemporaryDirectory(prefix='yt_dlp') as", "'edge': os.path.join(appdata_local, R'Microsoft\\Edge\\User Data'), 'opera': os.path.join(appdata_roaming, R'Opera Software\\Opera Stable'), 'vivaldi': os.path.join(appdata_local, R'Vivaldi\\User Data'),", "proc = Popen([ 'kwallet-query', '--read-password', f'{browser_keyring_name} Safe Storage', '--folder', f'{browser_keyring_name} Keys', network_wallet ],", "page_sizes, p.cursor def _parse_safari_cookies_page(data, jar, logger): p = DataParser(data, logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page signature')", "value = decryptor.decrypt(encrypted_value) if value is None: return is_encrypted, None return is_encrypted, compat_cookiejar_Cookie(", "hasattr(logger, 'progress_bar'): printer = logger.progress_bar() if printer: return printer printer = QuietMultilinePrinter() printer.print", "'KDE_FULL_SESSION' in env: return _LinuxDesktopEnvironment.KDE return _LinuxDesktopEnvironment.OTHER def _choose_linux_keyring(logger): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend \"\"\"", "not supported on this platform: {sys.platform}') class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger, *,", "UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-GCM) because UTF-8 decoding failed. Possibly the key", "jars: for cookie in jar: output_jar.set_cookie(cookie) if jar.filename is not None: output_jar.filename =", "on this platform: {sys.platform}') class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger, *, keyring=None): self._logger", "os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif sys.platform == 'darwin': return os.path.expanduser('~/Library/Application Support/Firefox') else: raise ValueError(f'unsupported platform: {sys.platform}')", "- this data appears to be out of date but the important parts", "boringssl # EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length = 16 raw_ciphertext = ciphertext nonce = raw_ciphertext[:nonce_length] ciphertext", "1, 0, 0, tzinfo=timezone.utc) + timedelta(seconds=timestamp)).timestamp()) def _parse_safari_cookies_header(data, logger): p = DataParser(data, logger)", "implemented by sub classes') @property def cookie_counts(self): raise NotImplementedError('Must be implemented by sub", "_mac_absolute_time_to_posix(p.read_double()) # noqa: F841 try: p.skip_to(domain_offset) domain = p.read_cstring() p.skip_to(name_offset) name = p.read_cstring()", "does a dbus call to the following function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet \"\"\" default_wallet =", "progress_bar: table = cursor.fetchall() total_cookie_count = len(table) for i, line in enumerate(table): progress_bar.print(f'Loading", "_LinuxKeyring.KWALLET: return _get_kwallet_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.GNOMEKEYRING: return _get_gnome_keyring_password(browser_keyring_name, logger) elif keyring", "here and there which are skipped during parsing \"\"\" if jar is None:", "if num_bytes > 0: self._logger.debug(f'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}') elif num_bytes < 0:", "auto() BASICTEXT = auto() SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys() def _get_linux_desktop_environment(env): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment \"\"\"", "fixed key - v11: AES-CBC encrypted with an OS protected key (keyring) -", "sometimes occurs in KDE because chrome does not check hasEntry and instead #", "1 progress_bar.print(f'Searching for \"{filename}\": {i: 6d} files searched') if file == filename: paths.append(os.path.join(curr_root,", "= _config_home() browser_dir = { 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(config, 'google-chrome'), 'chromium': os.path.join(config,", "== f'{browser_keyring_name} Safe Storage': return item.get_secret() else: logger.error('failed to read from keyring') return", "None: jar = YoutubeDLCookieJar() page_sizes, body_start = _parse_safari_cookies_header(data, logger) p = DataParser(data[body_start:], logger)", "config['browser_dir'] = os.path.dirname(profile) if config['supports_profiles'] else profile else: if config['supports_profiles']: search_root = os.path.join(config['browser_dir'],", "os.path.join(appdata, 'com.operasoftware.Opera'), 'vivaldi': os.path.join(appdata, 'Vivaldi'), }[browser_name] else: raise ValueError(f'unsupported platform: {sys.platform}') # Linux", "_decrypt_aes_cbc(ciphertext, key, logger, initialization_vector=b' ' * 16): plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector)) try:", "self.cursor + num_bytes if end > len(self._data): raise ParserError('reached end of input') data", "decoding failed. Possibly the key is wrong?', only_once=True) return None def _decrypt_windows_dpapi(ciphertext, logger):", "None return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) def pbkdf2_sha1(password, salt, iterations, key_length): return pbkdf2_hmac('sha1', password, salt,", "= DataParser(data, logger) p.expect_bytes(b'cook', 'database signature') number_of_pages = p.read_uint(big_endian=True) page_sizes = [p.read_uint(big_endian=True) for", "def _process_chrome_cookie(decryptor, host_key, name, value, encrypted_value, path, expires_utc, is_secure): host_key = host_key.decode('utf-8') name", "hasEntry. To verify this: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" # while starting chrome. #", "of {num_bytes} bytes') end = self.cursor + num_bytes if end > len(self._data): raise", "_choose_linux_keyring(logger) logger.debug(f'Chosen keyring: {keyring.name}') if keyring == _LinuxKeyring.KWALLET: return _get_kwallet_password(browser_keyring_name, logger) elif keyring", "'unknown record field 1') flags = p.read_uint() is_secure = bool(flags & 0x0001) p.skip(4,", "be determined by snooping on dbus while opening the browser in KDE: #", "because UTF-8 decoding failed', only_once=True) return record_size p.skip_to(record_size, 'space at the end of", "plaintext # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return encrypted_value class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_root, logger): self._logger =", "progress_bar: for curr_root, dirs, files in os.walk(root): for file in files: i +=", "name, value, encrypted_value, path, expires_utc, is_secure): host_key = host_key.decode('utf-8') name = name.decode('utf-8') value", "`dbus-monitor` during startup, it can be observed that chromium lists all keys #", "return MacChromeCookieDecryptor(browser_keyring_name, logger) elif sys.platform == 'win32': return WindowsChromeCookieDecryptor(browser_root, logger) else: raise NotImplementedError(f'Chrome", "= '>I' if big_endian else '<I' return struct.unpack(data_format, self.read_bytes(4))[0] def read_double(self, big_endian=False): data_format", "{len(jar)} cookies from {browser_name}{failed_message}') counts = decryptor.cookie_counts.copy() counts['unencrypted'] = unencrypted_cookies logger.debug(f'cookie version breakdown:", "try: plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce) except ValueError: logger.warning('failed to decrypt cookie", "if proc.returncode != 0: logger.error(f'kwallet-query failed with return code {proc.returncode}. Please consult '", "for row in table_info] def _find_most_recently_used_file(root, filename, logger): # if there are multiple", "to compile python without # sqlite support. See: https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE = False try:", "search_root = config['browser_dir'] elif _is_path(profile): search_root = profile config['browser_dir'] = os.path.dirname(profile) if config['supports_profiles']", "load_cookies(cookie_file, browser_specification, ydl): cookie_jars = [] if browser_specification is not None: browser_name, profile,", "not None: xdg_current_desktop = xdg_current_desktop.split(':')[0].strip() if xdg_current_desktop == 'Unity': if desktop_session is not", "pip install secretstorage`.') except Exception as _err: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = f'as", "key (keyring) - v11 keys can be stored in various places depending on", "\"\"\" KWALLET = auto() GNOMEKEYRING = auto() BASICTEXT = auto() SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys()", "not available {SECRETSTORAGE_UNAVAILABLE_REASON}') return b'' # the Gnome keyring does not seem to", "comment=None, comment_url=None, rest={}) class ChromeCookieDecryptor: \"\"\" Overview: Linux: - cookies are either v10", "if xdg_current_desktop is not None: xdg_current_desktop = xdg_current_desktop.split(':')[0].strip() if xdg_current_desktop == 'Unity': if", "Enum, auto from hashlib import pbkdf2_hmac from .aes import ( aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7,", "return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1, key_length=16) @property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value):", "with DPAPI Sources: - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc - KeyStorageLinux::CreateService \"\"\" def", "b'\\n': stdout = stdout[:-1] return stdout except Exception as e: logger.warning(f'exception running find-generic-password:", "password from kwallet') if shutil.which('kwallet-query') is None: logger.error('kwallet-query command not found. KWallet and", "from firefox') if not SQLITE_AVAILABLE: logger.warning('Cannot extract cookies from firefox without sqlite3 support.", "import sys import tempfile from datetime import datetime, timedelta, timezone from enum import", "be decrypted)' else: failed_message = '' logger.info(f'Extracted {len(jar)} cookies from {browser_name}{failed_message}') counts =", "not None: output_jar.filename = jar.filename return output_jar def _is_path(value): return os.path.sep in value", "= _get_windows_v10_key(browser_root, logger) self._cookie_counts = {'v10': 0, 'other': 0} @property def cookie_counts(self): return", "ctypes import json import os import shutil import struct import subprocess import sys", "SQLITE_AVAILABLE = True except ImportError: # although sqlite3 is part of the standard", "value=value, port=None, port_specified=False, domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False, comment=None, comment_url=None,", "not v10 - v10: AES-CBC encrypted with an OS protected key (keyring) and", "CINNAMON = auto() GNOME = auto() KDE = auto() PANTHEON = auto() UNITY", "value=value, port=None, port_specified=False, domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiry, discard=False, comment=None, comment_url=None,", "is_encrypted, cookie = _process_chrome_cookie(decryptor, *line) if not cookie: failed_cookies += 1 continue elif", "in enumerate(record_offsets): progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies: 6d}') p.skip_to(record_offset, 'space between records') record_length =", "'com.operasoftware.Opera'), 'vivaldi': os.path.join(appdata, 'Vivaldi'), }[browser_name] else: raise ValueError(f'unsupported platform: {sys.platform}') # Linux keyring", "self.skip(offset - self.cursor, description) def skip_to_end(self, description='unknown'): self.skip_to(len(self._data), description) def _mac_absolute_time_to_posix(timestamp): return int((datetime(2001,", "path, expiry, isSecure FROM moz_cookies') jar = YoutubeDLCookieJar() with _create_progress_bar(logger) as progress_bar: table", "comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) logger.info(f'Extracted {len(jar)} cookies from firefox') return jar finally: if", "= [p.read_uint(big_endian=True) for _ in range(number_of_pages)] return page_sizes, p.cursor def _parse_safari_cookies_page(data, jar, logger):", "logger): path = _find_most_recently_used_file(browser_root, 'Local State', logger) if path is None: logger.error('could not", "decryptor.decrypt(encrypted_value) if value is None: return is_encrypted, None return is_encrypted, compat_cookiejar_Cookie( version=0, name=name,", "breakdown: {counts}') return jar finally: if cursor is not None: cursor.connection.close() def _process_chrome_cookie(decryptor,", "comment_url=None, rest={}) jar.set_cookie(cookie) logger.info(f'Extracted {len(jar)} cookies from firefox') return jar finally: if cursor", ".minicurses import MultilinePrinter, QuietMultilinePrinter from .utils import Popen, YoutubeDLCookieJar, error_to_str, expand_path try: import", "authentication_tag_length = 16 raw_ciphertext = ciphertext nonce = raw_ciphertext[:nonce_length] ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag", "= raw_ciphertext[-authentication_tag_length:] return _decrypt_aes_gcm(ciphertext, self._v10_key, nonce, authentication_tag, self._logger) else: self._cookie_counts['other'] += 1 #", "in ('linux', 'linux2'): config = _config_home() browser_dir = { 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'), 'chrome':", "'--session', '--print-reply=literal', '--dest=org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet.networkWallet' ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if", "logger.error(f'secretstorage not available {SECRETSTORAGE_UNAVAILABLE_REASON}') return b'' # the Gnome keyring does not seem", "on the activate desktop environment [2] Mac: - cookies are either v10 or", "to decrypt cookie (AES-GCM) because UTF-8 decoding failed. Possibly the key is wrong?',", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend \"\"\" KWALLET = auto() GNOMEKEYRING = auto() BASICTEXT = auto() SUPPORTED_KEYRINGS", "= {'v10': 0, 'other': 0} @staticmethod def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm", "stdout[:-1] return stdout except Exception as e: logger.warning(f'exception running kwallet-query: {error_to_str(e)}') return b''", "are a few bytes here and there which are skipped during parsing \"\"\"", "0, # dwFlags ctypes.byref(blob_out) # pDataOut ) if not ret: logger.warning('failed to decrypt", "'Pantheon': return _LinuxDesktopEnvironment.PANTHEON elif xdg_current_desktop == 'XFCE': return _LinuxDesktopEnvironment.XFCE elif desktop_session is not", "chosen, all cookies are stored as v10 (so no keyring password is required)", "if not encrypted_key.startswith(prefix): logger.error('invalid key') return None return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) def pbkdf2_sha1(password, salt,", "decrypted)' else: failed_message = '' logger.info(f'Extracted {len(jar)} cookies from {browser_name}{failed_message}') counts = decryptor.cookie_counts.copy()", "decrypt v10 cookies: no key found', only_once=True) return None # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc # kNonceLength", "a few bytes here and there which are skipped during parsing \"\"\" if", "self.cursor, description) def skip_to_end(self, description='unknown'): self.skip_to(len(self._data), description) def _mac_absolute_time_to_posix(timestamp): return int((datetime(2001, 1, 1,", "p.skip(8, 'unknown record field 3') expiration_date = _mac_absolute_time_to_posix(p.read_double()) _creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa:", "value = p.read_cstring() except UnicodeDecodeError: logger.warning('failed to parse Safari cookie because UTF-8 decoding", "from kwallet') if shutil.which('kwallet-query') is None: logger.error('kwallet-query command not found. KWallet and kwallet-query", "value = value.decode('utf-8') path = path.decode('utf-8') is_encrypted = not value and encrypted_value if", "elif sys.platform == 'darwin': return os.path.expanduser('~/Library/Application Support/Firefox') else: raise ValueError(f'unsupported platform: {sys.platform}') def", "None return _decrypt_aes_cbc(ciphertext, self._v11_key, self._logger) else: self._cookie_counts['other'] += 1 return None class MacChromeCookieDecryptor(ChromeCookieDecryptor):", "# this may be a bug as the intended behaviour is to generate", "'-s', f'{browser_keyring_name} Safe Storage'], # match 'service' stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill()", "display 0, # dwFlags ctypes.byref(blob_out) # pDataOut ) if not ret: logger.warning('failed to", "if not SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage not available {SECRETSTORAGE_UNAVAILABLE_REASON}') return b'' # the Gnome keyring", "return struct.unpack(data_format, self.read_bytes(4))[0] def read_double(self, big_endian=False): data_format = '>d' if big_endian else '<d'", "keyring: \"{keyring}\"') if profile is not None and _is_path(profile): profile = os.path.expanduser(profile) return", "in jar: output_jar.set_cookie(cookie) if jar.filename is not None: output_jar.filename = jar.filename return output_jar", "__init__(self, data, logger): self._data = data self.cursor = 0 self._logger = logger def", "= raw_ciphertext[:nonce_length] ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag = raw_ciphertext[-authentication_tag_length:] return _decrypt_aes_gcm(ciphertext, self._v10_key, nonce, authentication_tag,", "== b'v10': self._cookie_counts['v10'] += 1 if self._v10_key is None: self._logger.warning('cannot decrypt v10 cookies:", "for _ in range(number_of_pages)] return page_sizes, p.cursor def _parse_safari_cookies_page(data, jar, logger): p =", "= p.read_cstring() p.skip_to(path_offset) path = p.read_cstring() p.skip_to(value_offset) value = p.read_cstring() except UnicodeDecodeError: logger.warning('failed", "with a key which is encrypted with DPAPI - not v10: encrypted with", "decoding failed', only_once=True) return record_size p.skip_to(record_size, 'space at the end of the record')", "None: logger.error('safari does not support profiles') if sys.platform != 'darwin': raise ValueError(f'unsupported platform:", "cursor.connection.text_factory = bytes column_names = _get_column_names(cursor, 'cookies') secure_column = 'is_secure' if 'is_secure' in", "# EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length = 16 raw_ciphertext = ciphertext nonce = raw_ciphertext[:nonce_length] ciphertext =", "with sqlite3 support') return YoutubeDLCookieJar() if profile is None: search_root = _firefox_browser_dir() elif", "= '' logger.info(f'Extracted {len(jar)} cookies from {browser_name}{failed_message}') counts = decryptor.cookie_counts.copy() counts['unencrypted'] = unencrypted_cookies", "pbkdf2_sha1(password, salt, iterations, key_length): return pbkdf2_hmac('sha1', password, salt, iterations, key_length) def _decrypt_aes_cbc(ciphertext, key,", "kwallet') if shutil.which('kwallet-query') is None: logger.error('kwallet-query command not found. KWallet and kwallet-query '", "to read from KWallet. kwallet-query should be' 'included in the kwallet package for", "YoutubeDLCookieJar() for jar in jars: for cookie in jar: output_jar.set_cookie(cookie) if jar.filename is", "= { 'brave': 'Brave', 'chrome': 'Chrome', 'chromium': 'Chromium', 'edge': 'Microsoft Edge' if sys.platform", "find safari cookies database') with open(cookies_path, 'rb') as f: cookies_data = f.read() jar", "DataParser(data, logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page signature') number_of_cookies = p.read_uint() record_offsets = [p.read_uint() for _", "== 'darwin' else 'Chromium', 'vivaldi': 'Vivaldi' if sys.platform == 'darwin' else 'Chrome', }[browser_name]", "if is_encrypted: value = decryptor.decrypt(encrypted_value) if value is None: return is_encrypted, None return", "R'Microsoft\\Edge\\User Data'), 'opera': os.path.join(appdata_roaming, R'Opera Software\\Opera Stable'), 'vivaldi': os.path.join(appdata_local, R'Vivaldi\\User Data'), }[browser_name] elif", "we must do the same. # https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init()) as con: col =", "human readable description of pDataIn None, # pOptionalEntropy: salt? None, # pvReserved: must", "--no-progress is used if not self._ydl or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'): return file =", "progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') is_encrypted, cookie = _process_chrome_cookie(decryptor, *line) if not cookie:", "key derivation iterations than linux - not v10: 'old data' stored as plaintext", "+= 1 if self._v10_key is None: self._logger.warning('cannot decrypt v10 cookies: no key found',", "in page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger) p.skip_to_end('footer') return jar class _LinuxDesktopEnvironment(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment", "- cookies are either v10 or not v10 - v10: AES-CBC encrypted with", "os import shutil import struct import subprocess import sys import tempfile from datetime", "is None else self.derive_key(password) self._cookie_counts = {'v10': 0, 'other': 0} @staticmethod def derive_key(password):", "'KDE': return _LinuxDesktopEnvironment.KDE elif xdg_current_desktop == 'Pantheon': return _LinuxDesktopEnvironment.PANTHEON elif xdg_current_desktop == 'XFCE':", "_find_most_recently_used_file(browser_root, 'Local State', logger) if path is None: logger.error('could not find local state", "record_offset in enumerate(record_offsets): progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies: 6d}') p.skip_to(record_offset, 'space between records') record_length", "*, keyring=None): self._logger = logger self._v10_key = self.derive_key(b'peanuts') password = _get_linux_keyring_password(browser_keyring_name, keyring, logger)", "if cookie_file is not None: cookie_file = expand_path(cookie_file) jar = YoutubeDLCookieJar(cookie_file) if os.access(cookie_file,", "is used if not self._ydl or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'): return file = self._ydl._out_files['error']", "class _LinuxDesktopEnvironment(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment \"\"\" OTHER = auto() CINNAMON = auto() GNOME", "if stdout.lower().startswith(b'failed to read'): logger.debug('failed to read password from kwallet. Using empty string", "that doesn't matter here. return b'' else: logger.debug('password found') if stdout[-1:] == b'\\n':", "return _LinuxDesktopEnvironment.KDE elif 'xfce' in desktop_session: return _LinuxDesktopEnvironment.XFCE else: if 'GNOME_DESKTOP_SESSION_ID' in env:", "logger): logger.debug('using find-generic-password to obtain password from OSX keychain') try: proc = Popen(", "network_wallet = stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet = \"{network_wallet}\"') return network_wallet except Exception as e: logger.warning(f'exception", "logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') decryptor = get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger, keyring=keyring) with tempfile.TemporaryDirectory(prefix='yt_dlp') as", "sub classes') def get_cookie_decryptor(browser_root, browser_keyring_name, logger, *, keyring=None): if sys.platform in ('linux', 'linux2'):", "= decryptor.cookie_counts.copy() counts['unencrypted'] = unencrypted_cookies logger.debug(f'cookie version breakdown: {counts}') return jar finally: if", "from: \"{cookie_database_path}\"') with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try: cursor = _open_database_copy(cookie_database_path,", "name, value, path, expiry, is_secure) in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') cookie", "decrypt v11 cookies: no key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v11_key, self._logger)", "expected_value: raise ParserError(f'unexpected value: {value} != {expected_value} ({message})') def read_uint(self, big_endian=False): data_format =", "\"\"\" Overview: Linux: - cookies are either v10 or v11 - v10: AES-CBC", "so the automatic detection # will not be sufficient in all cases. keyring", "ydl=None): self._ydl = ydl def debug(self, message): if self._ydl: self._ydl.write_debug(message) def info(self, message):", "def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1, key_length=16) @property", ".compat import compat_b64decode, compat_cookiejar_Cookie from .minicurses import MultilinePrinter, QuietMultilinePrinter from .utils import Popen,", "name.decode('utf-8') value = value.decode('utf-8') path = path.decode('utf-8') is_encrypted = not value and encrypted_value", "def __init__(self, browser_keyring_name, logger): self._logger = logger password = _get_mac_keyring_password(browser_keyring_name, logger) self._v10_key =", "browser_specification, ydl): cookie_jars = [] if browser_specification is not None: browser_name, profile, keyring", "salt=b'<PASSWORD>', iterations=1, key_length=16) @property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value): version =", "desktop_session is not None and 'gnome-fallback' in desktop_session: return _LinuxDesktopEnvironment.GNOME else: return _LinuxDesktopEnvironment.UNITY", "logger): # if there are multiple browser profiles, take the most recently used", "Safe Storage'], # match 'service' stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if stdout[-1:]", "return _extract_chrome_cookies(browser_name, profile, keyring, logger) else: raise ValueError(f'unknown browser: {browser_name}') def _extract_firefox_cookies(profile, logger):", ".utils import Popen, YoutubeDLCookieJar, error_to_str, expand_path try: import sqlite3 SQLITE_AVAILABLE = True except", "R'Opera Software\\Opera Stable'), 'vivaldi': os.path.join(appdata_local, R'Vivaldi\\User Data'), }[browser_name] elif sys.platform == 'darwin': appdata", "= auto() KDE = auto() PANTHEON = auto() UNITY = auto() XFCE =", "ParserError(f'unexpected value: {value} != {expected_value} ({message})') def read_uint(self, big_endian=False): data_format = '>I' if", "if sys.platform in ('linux', 'linux2'): return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring) elif sys.platform == 'darwin':", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend \"\"\" desktop_environment = _get_linux_desktop_environment(os.environ) logger.debug(f'detected desktop environment: {desktop_environment.name}') if desktop_environment ==", "-m pip install secretstorage`.') except Exception as _err: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON =", "domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) return record_size", "record field 2') domain_offset = p.read_uint() name_offset = p.read_uint() path_offset = p.read_uint() value_offset", "jar.set_cookie(cookie) logger.info(f'Extracted {len(jar)} cookies from firefox') return jar finally: if cursor is not", "counts['unencrypted'] = unencrypted_cookies logger.debug(f'cookie version breakdown: {counts}') return jar finally: if cursor is", "config['browser_dir'] cookie_database_path = _find_most_recently_used_file(search_root, 'Cookies', logger) if cookie_database_path is None: raise FileNotFoundError(f'could not", "names can be determined by snooping on dbus while opening the browser in", "_LinuxDesktopEnvironment.KDE return _LinuxDesktopEnvironment.OTHER def _choose_linux_keyring(logger): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend \"\"\" desktop_environment = _get_linux_desktop_environment(os.environ) logger.debug(f'detected", "def _get_chromium_based_browser_settings(browser_name): # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if sys.platform in ('linux', 'linux2'): config = _config_home() browser_dir", "return default_wallet else: network_wallet = stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet = \"{network_wallet}\"') return network_wallet except Exception", "browser_name not in SUPPORTED_BROWSERS: raise ValueError(f'unsupported browser: \"{browser_name}\"') if keyring not in (None,", "_config_home() browser_dir = { 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(config, 'google-chrome'), 'chromium': os.path.join(config, 'chromium'),", "'Google/Chrome'), 'chromium': os.path.join(appdata, 'Chromium'), 'edge': os.path.join(appdata, 'Microsoft Edge'), 'opera': os.path.join(appdata, 'com.operasoftware.Opera'), 'vivaldi': os.path.join(appdata,", "decrypt cookie (AES-CBC) because UTF-8 decoding failed. Possibly the key is wrong?', only_once=True)", "if desktop_environment == _LinuxDesktopEnvironment.KDE: linux_keyring = _LinuxKeyring.KWALLET elif desktop_environment == _LinuxDesktopEnvironment.OTHER: linux_keyring =", "('linux', 'linux2'): config = _config_home() browser_dir = { 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(config,", "self._ydl.write_debug(message) def info(self, message): if self._ydl: self._ydl.to_screen(f'[Cookies] {message}') def warning(self, message, only_once=False): if", "v10: 'old data' stored as plaintext Windows: - cookies are either v10 or", "browser_name in CHROMIUM_BASED_BROWSERS: return _extract_chrome_cookies(browser_name, profile, keyring, logger) else: raise ValueError(f'unknown browser: {browser_name}')", "ValueError(f'unsupported platform: {sys.platform}') def _get_chromium_based_browser_settings(browser_name): # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if sys.platform in ('linux', 'linux2'): config", "ValueError(f'unknown browser: {browser_name}') def _extract_firefox_cookies(profile, logger): logger.info('Extracting cookies from firefox') if not SQLITE_AVAILABLE:", "import compat_b64decode, compat_cookiejar_Cookie from .minicurses import MultilinePrinter, QuietMultilinePrinter from .utils import Popen, YoutubeDLCookieJar,", "WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_root, logger): self._logger = logger self._v10_key = _get_windows_v10_key(browser_root, logger) self._cookie_counts", "logger.debug(f'Found local state file at \"{path}\"') with open(path, encoding='utf8') as f: data =", "\"type=method_return\" # while starting chrome. # this may be a bug as the", "install secretstorage`.') except Exception as _err: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = f'as the", "0 unencrypted_cookies = 0 with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count =", "else: self._cookie_counts['other'] += 1 # any other prefix means the data is DPAPI", "{sys.platform}') # Linux keyring names can be determined by snooping on dbus while", "LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring) elif sys.platform == 'darwin': return MacChromeCookieDecryptor(browser_keyring_name, logger) elif sys.platform ==", "None class MacChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger): self._logger = logger password = _get_mac_keyring_password(browser_keyring_name,", "read_bytes(self, num_bytes): if num_bytes < 0: raise ParserError(f'invalid read of {num_bytes} bytes') end", "def expect_bytes(self, expected_value, message): value = self.read_bytes(len(expected_value)) if value != expected_value: raise ParserError(f'unexpected", "# pDataOut ) if not ret: logger.warning('failed to decrypt with DPAPI', only_once=True) return", "instead # just tries to read the value (which kwallet returns \"\") whereas", "< 0: raise ParserError(f'invalid skip of {num_bytes} bytes') def skip_to(self, offset, description='unknown'): self.skip(offset", "in \"{search_root}\"') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') decryptor = get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger, keyring=keyring) with", "cookies database in \"{search_root}\"') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') decryptor = get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger,", "end of the record') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=domain,", "to be out of date but the important parts of the database structure", "F841 try: p.skip_to(domain_offset) domain = p.read_cstring() p.skip_to(name_offset) name = p.read_cstring() p.skip_to(path_offset) path =", "p = DataParser(data, logger) p.expect_bytes(b'cook', 'database signature') number_of_pages = p.read_uint(big_endian=True) page_sizes = [p.read_uint(big_endian=True)", "the important parts of the database structure is the same - there are", "'must be installed to read from KWallet. kwallet-query should be' 'included in the", "elif keyring == _LinuxKeyring.GNOMEKEYRING: return _get_gnome_keyring_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.BASICTEXT: # when", "= [p.read_uint() for _ in range(number_of_cookies)] if number_of_cookies == 0: logger.debug(f'a cookies page", "QuietMultilinePrinter from .utils import Popen, YoutubeDLCookieJar, error_to_str, expand_path try: import sqlite3 SQLITE_AVAILABLE =", "= os.path.join(config['browser_dir'], profile) else: logger.error(f'{browser_name} does not support profiles') search_root = config['browser_dir'] cookie_database_path", "self._cookie_counts['other'] += 1 return None class MacChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger): self._logger =", "= _LinuxKeyring[keyring] if keyring else _choose_linux_keyring(logger) logger.debug(f'Chosen keyring: {keyring.name}') if keyring == _LinuxKeyring.KWALLET:", "= auto() class _LinuxKeyring(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend \"\"\" KWALLET = auto() GNOMEKEYRING =", "else max(paths, key=lambda path: os.lstat(path).st_mtime) def _merge_cookie_jars(jars): output_jar = YoutubeDLCookieJar() for jar in", "v10: AES-CBC encrypted with a fixed key - v11: AES-CBC encrypted with an", "logger.warning(f'exception running kwallet-query: {error_to_str(e)}') return b'' def _get_gnome_keyring_password(browser_keyring_name, logger): if not SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage", "for item in col.get_all_items(): if item.get_label() == f'{browser_keyring_name} Safe Storage': return item.get_secret() else:", "shutil.which('kwallet-query') is None: logger.error('kwallet-query command not found. KWallet and kwallet-query ' 'must be", "key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v11_key, self._logger) else: self._cookie_counts['other'] += 1", "is_encrypted, compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), path=path, path_specified=bool(path), secure=is_secure,", "p.skip(4, 'unknown record field 2') domain_offset = p.read_uint() name_offset = p.read_uint() path_offset =", "version == b'v10': self._cookie_counts['v10'] += 1 return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) elif version ==", "logger.error('could not find local state file') return None logger.debug(f'Found local state file at", "UNITY = auto() XFCE = auto() class _LinuxKeyring(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend \"\"\" KWALLET", "try: import sqlite3 SQLITE_AVAILABLE = True except ImportError: # although sqlite3 is part", "a context manager with a print method. (Optional)\"\"\" # Do not print to", "sys.platform != 'darwin': raise ValueError(f'unsupported platform: {sys.platform}') cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path):", "os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User Data'), 'chrome': os.path.join(appdata_local, R'Google\\Chrome\\User Data'), 'chromium': os.path.join(appdata_local, R'Chromium\\User Data'), 'edge': os.path.join(appdata_local,", "logger): p = DataParser(data, logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page signature') number_of_cookies = p.read_uint() record_offsets =", "Popen( ['security', 'find-generic-password', '-w', # write password to stdout '-a', browser_keyring_name, # match", "\"\"\" from ctypes.wintypes import DWORD class DATA_BLOB(ctypes.Structure): _fields_ = [('cbData', DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))]", "that we must do the same. # https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init()) as con: col", "BASICTEXT = auto() SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys() def _get_linux_desktop_environment(env): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment \"\"\" xdg_current_desktop", "a bug as the intended behaviour is to generate a random password and", "cookie location') cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): raise FileNotFoundError('could not find safari", "SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = f'as the `secretstorage` module could not be initialized.", "return None class MacChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger): self._logger = logger password =", "_find_most_recently_used_file(search_root, 'cookies.sqlite', logger) if cookie_database_path is None: raise FileNotFoundError(f'could not find firefox cookies", "return b''.join(buffer).decode('utf-8') else: buffer.append(c) def skip(self, num_bytes, description='unknown'): if num_bytes > 0: self._logger.debug(f'skipping", "return p.skip_to(record_offsets[0], 'unknown page header field') with _create_progress_bar(logger) as progress_bar: for i, record_offset", "os.path.join(appdata, 'Vivaldi'), }[browser_name] else: raise ValueError(f'unsupported platform: {sys.platform}') # Linux keyring names can", "domain_initial_dot=domain.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) return record_size def", "jar.set_cookie(cookie) return record_size def parse_safari_cookies(data, jar=None, logger=YDLLogger()): \"\"\" References: - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc - this", "'vivaldi': 'Vivaldi' if sys.platform == 'darwin' else 'Chrome', }[browser_name] browsers_without_profiles = {'opera'} return", "with _create_progress_bar(logger) as progress_bar: for i, record_offset in enumerate(record_offsets): progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies:", "_LinuxDesktopEnvironment.GNOME else: return _LinuxDesktopEnvironment.UNITY elif xdg_current_desktop == 'GNOME': return _LinuxDesktopEnvironment.GNOME elif xdg_current_desktop ==", "list. It appears that we must do the same. # https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init())", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc - KeyStorageLinux::CreateService \"\"\" def decrypt(self, encrypted_value): raise NotImplementedError('Must be", "elif desktop_environment == _LinuxDesktopEnvironment.OTHER: linux_keyring = _LinuxKeyring.BASICTEXT else: linux_keyring = _LinuxKeyring.GNOMEKEYRING return linux_keyring", "password = _get_linux_keyring_password(browser_keyring_name, keyring, logger) self._v11_key = None if password is None else", "QuietMultilinePrinter() printer.print = lambda _: None return printer def load_cookies(cookie_file, browser_specification, ydl): cookie_jars", "= False SECRETSTORAGE_UNAVAILABLE_REASON = ( 'as the `secretstorage` module is not installed. '", "host_key, name, value, encrypted_value, path, expires_utc, {secure_column} FROM cookies') jar = YoutubeDLCookieJar() failed_cookies", "logger): self._data = data self.cursor = 0 self._logger = logger def read_bytes(self, num_bytes):", "= _get_kwallet_network_wallet(logger) try: proc = Popen([ 'kwallet-query', '--read-password', f'{browser_keyring_name} Safe Storage', '--folder', f'{browser_keyring_name}", "is not None and 'gnome-fallback' in desktop_session: return _LinuxDesktopEnvironment.GNOME else: return _LinuxDesktopEnvironment.UNITY elif", "else 'secure' cursor.execute(f'SELECT host_key, name, value, encrypted_value, path, expires_utc, {secure_column} FROM cookies') jar", "'kwallet-query', '--read-password', f'{browser_keyring_name} Safe Storage', '--folder', f'{browser_keyring_name} Keys', network_wallet ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout,", "import shutil import struct import subprocess import sys import tempfile from datetime import", "pass class DataParser: def __init__(self, data, logger): self._data = data self.cursor = 0", "def parse_safari_cookies(data, jar=None, logger=YDLLogger()): \"\"\" References: - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc - this data appears to", "= None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.connection.text_factory = bytes column_names = _get_column_names(cursor,", "platform: {sys.platform}') def _get_chromium_based_browser_settings(browser_name): # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if sys.platform in ('linux', 'linux2'): config =", "'kde' in desktop_session: return _LinuxDesktopEnvironment.KDE elif 'xfce' in desktop_session: return _LinuxDesktopEnvironment.XFCE else: if", "store # it, but that doesn't matter here. return b'' else: logger.debug('password found')", "to read NetworkWallet') return default_wallet else: network_wallet = stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet = \"{network_wallet}\"') return", "number_of_cookies == 0: logger.debug(f'a cookies page of size {len(data)} has no cookies') return", "16 raw_ciphertext = ciphertext nonce = raw_ciphertext[:nonce_length] ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag = raw_ciphertext[-authentication_tag_length:]", "files searched') if file == filename: paths.append(os.path.join(curr_root, file)) return None if not paths", "'darwin': raise ValueError(f'unsupported platform: {sys.platform}') cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): logger.debug('Trying secondary", "def get_cookie_decryptor(browser_root, browser_keyring_name, logger, *, keyring=None): if sys.platform in ('linux', 'linux2'): return LinuxChromeCookieDecryptor(browser_keyring_name,", "* 16): plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector)) try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed", "filename: paths.append(os.path.join(curr_root, file)) return None if not paths else max(paths, key=lambda path: os.lstat(path).st_mtime)", "if version == b'v10': self._cookie_counts['v10'] += 1 return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) elif version", "'other': 0} @staticmethod def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return pbkdf2_sha1(password, salt=b'<PASSWORD>',", "1 # any other prefix means the data is DPAPI encrypted # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc", "import secretstorage SECRETSTORAGE_AVAILABLE = True except ImportError: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = (", "def _get_kwallet_password(browser_keyring_name, logger): logger.debug('using kwallet-query to obtain password from kwallet') if shutil.which('kwallet-query') is", "can be run with the following flags to determine which keyring backend #", "paths = 0, [] with _create_progress_bar(logger) as progress_bar: for curr_root, dirs, files in", "+= 1 if self._v11_key is None: self._logger.warning('cannot decrypt v11 cookies: no key found',", "'opera': os.path.join(config, 'opera'), 'vivaldi': os.path.join(config, 'vivaldi'), }[browser_name] elif sys.platform == 'win32': appdata_local =", "startup, it can be observed that chromium lists all keys # and presumably", "it, but that doesn't matter here. return b'' else: logger.debug('password found') if stdout[-1:]", "path.decode('utf-8') is_encrypted = not value and encrypted_value if is_encrypted: value = decryptor.decrypt(encrypted_value) if", "AES-GCM encrypted with a key which is encrypted with DPAPI - not v10:", "library, it is possible to compile python without # sqlite support. See: https://github.com/yt-dlp/yt-dlp/issues/544", "logger): if profile is not None: logger.error('safari does not support profiles') if sys.platform", "'safari'} class YDLLogger: def __init__(self, ydl=None): self._ydl = ydl def debug(self, message): if", "'microsoft-edge'), 'opera': os.path.join(config, 'opera'), 'vivaldi': os.path.join(config, 'vivaldi'), }[browser_name] elif sys.platform == 'win32': appdata_local", "password from OSX keychain') try: proc = Popen( ['security', 'find-generic-password', '-w', # write", "self._logger = logger def read_bytes(self, num_bytes): if num_bytes < 0: raise ParserError(f'invalid read", "return None return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) def pbkdf2_sha1(password, salt, iterations, key_length): return pbkdf2_hmac('sha1', password,", "from firefox') return jar finally: if cursor is not None: cursor.connection.close() def _firefox_browser_dir():", "cursor = None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.execute('SELECT host, name, value, path,", "but the important parts of the database structure is the same - there", "database_copy_path = os.path.join(tmpdir, 'temporary.sqlite') shutil.copy(database_path, database_copy_path) conn = sqlite3.connect(database_copy_path) return conn.cursor() def _get_column_names(cursor,", "in {search_root}') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None", "cookies are either v10 or not v10 - v10: AES-CBC encrypted with an", "running find-generic-password: {error_to_str(e)}') return None def _get_windows_v10_key(browser_root, logger): path = _find_most_recently_used_file(browser_root, 'Local State',", "desktop environment: {desktop_environment.name}') if desktop_environment == _LinuxDesktopEnvironment.KDE: linux_keyring = _LinuxKeyring.KWALLET elif desktop_environment ==", "pDataOut ) if not ret: logger.warning('failed to decrypt with DPAPI', only_once=True) return None", "could not be initialized. {_err}' CHROMIUM_BASED_BROWSERS = {'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi'}", "elif browser_name in CHROMIUM_BASED_BROWSERS: return _extract_chrome_cookies(browser_name, profile, keyring, logger) else: raise ValueError(f'unknown browser:", "'find-generic-password', '-w', # write password to stdout '-a', browser_keyring_name, # match 'account' '-s',", "as tmpdir: cursor = None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.execute('SELECT host, name,", "linux_keyring = _LinuxKeyring.BASICTEXT else: linux_keyring = _LinuxKeyring.GNOMEKEYRING return linux_keyring def _get_kwallet_network_wallet(logger): \"\"\" The", "return _LinuxDesktopEnvironment.GNOME elif 'KDE_FULL_SESSION' in env: return _LinuxDesktopEnvironment.KDE return _LinuxDesktopEnvironment.OTHER def _choose_linux_keyring(logger): \"\"\"", "os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) def _open_database_copy(database_path, tmpdir): # cannot open sqlite databases if they are", "os.path.expandvars('%LOCALAPPDATA%') appdata_roaming = os.path.expandvars('%APPDATA%') browser_dir = { 'brave': os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User Data'), 'chrome': os.path.join(appdata_local,", "linux - not v10: 'old data' stored as plaintext Windows: - cookies are", "as plaintext Windows: - cookies are either v10 or not v10 - v10:", "for details') return b'' else: if stdout.lower().startswith(b'failed to read'): logger.debug('failed to read password", "elif sys.platform == 'win32': appdata_local = os.path.expandvars('%LOCALAPPDATA%') appdata_roaming = os.path.expandvars('%APPDATA%') browser_dir = {", "data self.cursor = 0 self._logger = logger def read_bytes(self, num_bytes): if num_bytes <", "bytes') def skip_to(self, offset, description='unknown'): self.skip(offset - self.cursor, description) def skip_to_end(self, description='unknown'): self.skip_to(len(self._data),", "for i, record_offset in enumerate(record_offsets): progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies: 6d}') p.skip_to(record_offset, 'space between", "keyring=keyring) with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try: cursor = _open_database_copy(cookie_database_path, tmpdir)", "loggers, or when --no-progress is used if not self._ydl or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'):", "return _merge_cookie_jars(cookie_jars) def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *, keyring=None): if browser_name == 'firefox': return", "v10 or not v10 - v10: AES-GCM encrypted with a key which is", "if password is None else self.derive_key(password) self._cookie_counts = {'v10': 0, 'other': 0} @staticmethod", "record_length = _parse_safari_cookies_record(data[record_offset:], jar, logger) p.read_bytes(record_length) p.skip_to_end('space in between pages') def _parse_safari_cookies_record(data, jar,", "and instead # just tries to read the value (which kwallet returns \"\")", "to obtain password from OSX keychain') try: proc = Popen( ['security', 'find-generic-password', '-w',", "the data is DPAPI encrypted # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return _decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8') def _extract_safari_cookies(profile, logger):", "if failed_cookies > 0: failed_message = f' ({failed_cookies} could not be decrypted)' else:", "{'v10': 0, 'v11': 0, 'other': 0} @staticmethod def derive_key(password): # values from #", "return None result = ctypes.string_at(blob_out.pbData, blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData) return result def _config_home(): return os.environ.get('XDG_CONFIG_HOME',", "# checks hasEntry. To verify this: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" # while starting", "import sqlite3 SQLITE_AVAILABLE = True except ImportError: # although sqlite3 is part of", "during parsing \"\"\" if jar is None: jar = YoutubeDLCookieJar() page_sizes, body_start =", "if not cookie: failed_cookies += 1 continue elif not is_encrypted: unencrypted_cookies += 1", "the key is wrong?', only_once=True) return None def _decrypt_windows_dpapi(ciphertext, logger): \"\"\" References: -", "= logger self._v10_key = self.derive_key(b'peanuts') password = _get_linux_keyring_password(browser_keyring_name, keyring, logger) self._v11_key = None", "it can be observed that chromium lists all keys # and presumably searches", "if not SQLITE_AVAILABLE: logger.warning('Cannot extract cookies from firefox without sqlite3 support. ' 'Please", "not support profiles') search_root = config['browser_dir'] cookie_database_path = _find_most_recently_used_file(search_root, 'Cookies', logger) if cookie_database_path", "only_once) def error(self, message): if self._ydl: self._ydl.report_error(message) def progress_bar(self): \"\"\"Return a context manager", "value = self.read_bytes(len(expected_value)) if value != expected_value: raise ParserError(f'unexpected value: {value} != {expected_value}", "stdout, stderr = proc.communicate_or_kill() if proc.returncode != 0: logger.error(f'kwallet-query failed with return code", "def _get_kwallet_network_wallet(logger): \"\"\" The name of the wallet used to store network passwords.", "_LinuxDesktopEnvironment.KDE elif xdg_current_desktop == 'Pantheon': return _LinuxDesktopEnvironment.PANTHEON elif xdg_current_desktop == 'XFCE': return _LinuxDesktopEnvironment.XFCE", "files/pipes, loggers, or when --no-progress is used if not self._ydl or self._ydl.params.get('noprogress') or", "print to files/pipes, loggers, or when --no-progress is used if not self._ydl or", "encrypted_value, path, expires_utc, {secure_column} FROM cookies') jar = YoutubeDLCookieJar() failed_cookies = 0 unencrypted_cookies", "return linux_keyring def _get_kwallet_network_wallet(logger): \"\"\" The name of the wallet used to store", "linux_keyring def _get_kwallet_network_wallet(logger): \"\"\" The name of the wallet used to store network", "p.read_uint(big_endian=True) page_sizes = [p.read_uint(big_endian=True) for _ in range(number_of_pages)] return page_sizes, p.cursor def _parse_safari_cookies_page(data,", "path=path, path_specified=bool(path), secure=is_secure, expires=expiry, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) logger.info(f'Extracted {len(jar)} cookies from", "KDE: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" keyring_name = { 'brave': 'Brave', 'chrome': 'Chrome', 'chromium':", "raise ValueError(f'unsupported platform: {sys.platform}') cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): logger.debug('Trying secondary cookie", "self._logger.warning('cannot decrypt v11 cookies: no key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v11_key,", "field 2') domain_offset = p.read_uint() name_offset = p.read_uint() path_offset = p.read_uint() value_offset =", "blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer) blob_out = DATA_BLOB() ret = ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in), # pDataIn", "== _LinuxKeyring.BASICTEXT: # when basic text is chosen, all cookies are stored as", "_extract_chrome_cookies(browser_name, profile, keyring, logger): logger.info(f'Extracting cookies from {browser_name}') if not SQLITE_AVAILABLE: logger.warning(f'Cannot extract", "paths else max(paths, key=lambda path: os.lstat(path).st_mtime) def _merge_cookie_jars(jars): output_jar = YoutubeDLCookieJar() for jar", "if value != expected_value: raise ParserError(f'unexpected value: {value} != {expected_value} ({message})') def read_uint(self,", "file in files: i += 1 progress_bar.print(f'Searching for \"{filename}\": {i: 6d} files searched')", "for i, (host, name, value, path, expiry, is_secure) in enumerate(table): progress_bar.print(f'Loading cookie {i:", "sqlite databases if they are already in use (e.g. by the browser) database_copy_path", "and encrypted_value if is_encrypted: value = decryptor.decrypt(encrypted_value) if value is None: return is_encrypted,", "cookie = _process_chrome_cookie(decryptor, *line) if not cookie: failed_cookies += 1 continue elif not", "= _get_linux_keyring_password(browser_keyring_name, keyring, logger) self._v11_key = None if password is None else self.derive_key(password)", "Safe Storage': return item.get_secret() else: logger.error('failed to read from keyring') return b'' def", "import Popen, YoutubeDLCookieJar, error_to_str, expand_path try: import sqlite3 SQLITE_AVAILABLE = True except ImportError:", "f'Unknown keyring {keyring}' def _get_mac_keyring_password(browser_keyring_name, logger): logger.debug('using find-generic-password to obtain password from OSX", "({message})') def read_uint(self, big_endian=False): data_format = '>I' if big_endian else '<I' return struct.unpack(data_format,", "detection # will not be sufficient in all cases. keyring = _LinuxKeyring[keyring] if", "profiles') if sys.platform != 'darwin': raise ValueError(f'unsupported platform: {sys.platform}') cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if", "jar finally: if cursor is not None: cursor.connection.close() def _firefox_browser_dir(): if sys.platform in", "pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1, key_length=16) @property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value): version", "is_encrypted: unencrypted_cookies += 1 jar.set_cookie(cookie) if failed_cookies > 0: failed_message = f' ({failed_cookies}", "return _extract_firefox_cookies(profile, logger) elif browser_name == 'safari': return _extract_safari_cookies(profile, logger) elif browser_name in", "a flag: --password-store=<basic|gnome|kwallet> so the automatic detection # will not be sufficient in", "cookies from firefox') return jar finally: if cursor is not None: cursor.connection.close() def", "subprocess import sys import tempfile from datetime import datetime, timedelta, timezone from enum", "data is DPAPI encrypted # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return _decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8') def _extract_safari_cookies(profile, logger): if", "DataParser(data, logger) record_size = p.read_uint() p.skip(4, 'unknown record field 1') flags = p.read_uint()", "stderr = proc.communicate_or_kill() if stdout[-1:] == b'\\n': stdout = stdout[:-1] return stdout except", "'browser_dir': browser_dir, 'keyring_name': keyring_name, 'supports_profiles': browser_name not in browsers_without_profiles } def _extract_chrome_cookies(browser_name, profile,", "except ImportError: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = ( 'as the `secretstorage` module is", "browsers_without_profiles } def _extract_chrome_cookies(browser_name, profile, keyring, logger): logger.info(f'Extracting cookies from {browser_name}') if not", "jar.filename is not None: output_jar.filename = jar.filename return output_jar def _is_path(value): return os.path.sep", "_find_most_recently_used_file(search_root, 'Cookies', logger) if cookie_database_path is None: raise FileNotFoundError(f'could not find {browser_name} cookies", "if number_of_cookies == 0: logger.debug(f'a cookies page of size {len(data)} has no cookies')", "p.read_bytes(record_length) p.skip_to_end('space in between pages') def _parse_safari_cookies_record(data, jar, logger): p = DataParser(data, logger)", "= encrypted_value[3:] if version == b'v10': self._cookie_counts['v10'] += 1 return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger)", "else _choose_linux_keyring(logger) logger.debug(f'Chosen keyring: {keyring.name}') if keyring == _LinuxKeyring.KWALLET: return _get_kwallet_password(browser_keyring_name, logger) elif", "info(self, message): if self._ydl: self._ydl.to_screen(f'[Cookies] {message}') def warning(self, message, only_once=False): if self._ydl: self._ydl.report_warning(message,", "cannot open sqlite databases if they are already in use (e.g. by the", "_merge_cookie_jars(jars): output_jar = YoutubeDLCookieJar() for jar in jars: for cookie in jar: output_jar.set_cookie(cookie)", "self.derive_key(password) self._cookie_counts = {'v10': 0, 'other': 0} @staticmethod def derive_key(password): # values from", "kwallet-query ' 'must be installed to read from KWallet. kwallet-query should be' 'included", "Gnome keyring does not seem to organise keys in the same way as", "big_endian else '<d' return struct.unpack(data_format, self.read_bytes(8))[0] def read_cstring(self): buffer = [] while True:", "match 'service' stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if stdout[-1:] == b'\\n': stdout", "if c == b'\\x00': return b''.join(buffer).decode('utf-8') else: buffer.append(c) def skip(self, num_bytes, description='unknown'): if", "cursor is not None: cursor.connection.close() def _process_chrome_cookie(decryptor, host_key, name, value, encrypted_value, path, expires_utc,", "ValueError(f'unsupported browser: \"{browser_name}\"') if keyring not in (None, *SUPPORTED_KEYRINGS): raise ValueError(f'unsupported keyring: \"{keyring}\"')", "plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector)) try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt", "found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) else: self._cookie_counts['other'] += 1 #", "raw_ciphertext[:nonce_length] ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag = raw_ciphertext[-authentication_tag_length:] return _decrypt_aes_gcm(ciphertext, self._v10_key, nonce, authentication_tag, self._logger)", "same. # https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init()) as con: col = secretstorage.get_default_collection(con) for item in", "__init__(self, browser_keyring_name, logger, *, keyring=None): self._logger = logger self._v10_key = self.derive_key(b'peanuts') password =", "raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag = raw_ciphertext[-authentication_tag_length:] return _decrypt_aes_gcm(ciphertext, self._v10_key, nonce, authentication_tag, self._logger) else: self._cookie_counts['other'] +=", "def __init__(self, browser_root, logger): self._logger = logger self._v10_key = _get_windows_v10_key(browser_root, logger) self._cookie_counts =", "secondary cookie location') cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): raise FileNotFoundError('could not find", "tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.connection.text_factory =", "from OSX keychain') try: proc = Popen( ['security', 'find-generic-password', '-w', # write password", "are already in use (e.g. by the browser) database_copy_path = os.path.join(tmpdir, 'temporary.sqlite') shutil.copy(database_path,", "6d} files searched') if file == filename: paths.append(os.path.join(curr_root, file)) return None if not", "environment [2] Mac: - cookies are either v10 or not v10 - v10:", "def _parse_safari_cookies_page(data, jar, logger): p = DataParser(data, logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page signature') number_of_cookies =", "- https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc - this data appears to be out of date but the", "not self._ydl or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'): return file = self._ydl._out_files['error'] try: if not", "= proc.communicate_or_kill() if proc.returncode != 0: logger.warning('failed to read NetworkWallet') return default_wallet else:", "_LinuxDesktopEnvironment.XFCE elif desktop_session is not None: if desktop_session in ('mate', 'gnome'): return _LinuxDesktopEnvironment.GNOME", "if file == filename: paths.append(os.path.join(curr_root, file)) return None if not paths else max(paths,", "return _decrypt_aes_gcm(ciphertext, self._v10_key, nonce, authentication_tag, self._logger) else: self._cookie_counts['other'] += 1 # any other", "the record') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'),", "empty string instead') # this sometimes occurs in KDE because chrome does not", "a python interpreter compiled with sqlite3 support') return YoutubeDLCookieJar() config = _get_chromium_based_browser_settings(browser_name) if", "with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count = len(table) for i, (host,", "compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc,", "= config['browser_dir'] elif _is_path(profile): search_root = profile config['browser_dir'] = os.path.dirname(profile) if config['supports_profiles'] else", "{ 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(config, 'google-chrome'), 'chromium': os.path.join(config, 'chromium'), 'edge': os.path.join(config, 'microsoft-edge'),", "version = encrypted_value[:3] ciphertext = encrypted_value[3:] if version == b'v10': self._cookie_counts['v10'] += 1", "big_endian=False): data_format = '>d' if big_endian else '<d' return struct.unpack(data_format, self.read_bytes(8))[0] def read_cstring(self):", "'old data' stored as plaintext Windows: - cookies are either v10 or not", "Storage': return item.get_secret() else: logger.error('failed to read from keyring') return b'' def _get_linux_keyring_password(browser_keyring_name,", "cookies database') with open(cookies_path, 'rb') as f: cookies_data = f.read() jar = parse_safari_cookies(cookies_data,", "port=None, port_specified=False, domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiry, discard=False, comment=None, comment_url=None, rest={})", "protected key (keyring) - v11 keys can be stored in various places depending", "YoutubeDLCookieJar() config = _get_chromium_based_browser_settings(browser_name) if profile is None: search_root = config['browser_dir'] elif _is_path(profile):", "KWallet, # using `dbus-monitor` during startup, it can be observed that chromium lists", "a fixed key - v11: AES-CBC encrypted with an OS protected key (keyring)", "standard library, it is possible to compile python without # sqlite support. See:", "'' logger.info(f'Extracted {len(jar)} cookies from {browser_name}{failed_message}') counts = decryptor.cookie_counts.copy() counts['unencrypted'] = unencrypted_cookies logger.debug(f'cookie", "xdg_current_desktop == 'Pantheon': return _LinuxDesktopEnvironment.PANTHEON elif xdg_current_desktop == 'XFCE': return _LinuxDesktopEnvironment.XFCE elif desktop_session", "p.skip_to(value_offset) value = p.read_cstring() except UnicodeDecodeError: logger.warning('failed to parse Safari cookie because UTF-8", "os.path.join(config, 'vivaldi'), }[browser_name] elif sys.platform == 'win32': appdata_local = os.path.expandvars('%LOCALAPPDATA%') appdata_roaming = os.path.expandvars('%APPDATA%')", "is None: self._logger.warning('cannot decrypt v10 cookies: no key found', only_once=True) return None return", "& 0x0001) p.skip(4, 'unknown record field 2') domain_offset = p.read_uint() name_offset = p.read_uint()", "col.get_all_items(): if item.get_label() == f'{browser_keyring_name} Safe Storage': return item.get_secret() else: logger.error('failed to read", "prompts to display 0, # dwFlags ctypes.byref(blob_out) # pDataOut ) if not ret:", "profile=None, logger=YDLLogger(), *, keyring=None): if browser_name == 'firefox': return _extract_firefox_cookies(profile, logger) elif browser_name", "= 'is_secure' if 'is_secure' in column_names else 'secure' cursor.execute(f'SELECT host_key, name, value, encrypted_value,", "self._logger = logger self._v10_key = _get_windows_v10_key(browser_root, logger) self._cookie_counts = {'v10': 0, 'other': 0}", "flags = p.read_uint() is_secure = bool(flags & 0x0001) p.skip(4, 'unknown record field 2')", "is not None: xdg_current_desktop = xdg_current_desktop.split(':')[0].strip() if xdg_current_desktop == 'Unity': if desktop_session is", "stdout except Exception as e: logger.warning(f'exception running find-generic-password: {error_to_str(e)}') return None def _get_windows_v10_key(browser_root,", "install by running `python3 -m pip install secretstorage`.') except Exception as _err: SECRETSTORAGE_AVAILABLE", "(keyring) and more key derivation iterations than linux - not v10: 'old data'", "if stdout[-1:] == b'\\n': stdout = stdout[:-1] return stdout except Exception as e:", "secure=is_secure, expires=expiry, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) logger.info(f'Extracted {len(jar)} cookies from firefox') return", "line in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') is_encrypted, cookie = _process_chrome_cookie(decryptor, *line)", "keyring password is required) return None assert False, f'Unknown keyring {keyring}' def _get_mac_keyring_password(browser_keyring_name,", "__init__(self, ydl=None): self._ydl = ydl def debug(self, message): if self._ydl: self._ydl.write_debug(message) def info(self,", "= get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger, keyring=keyring) with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try:", "'chromium': os.path.join(config, 'chromium'), 'edge': os.path.join(config, 'microsoft-edge'), 'opera': os.path.join(config, 'opera'), 'vivaldi': os.path.join(config, 'vivaldi'), }[browser_name]", "with an OS protected key (keyring) and more key derivation iterations than linux", "None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.connection.text_factory = bytes column_names = _get_column_names(cursor, 'cookies')", "cookie decryption is not supported on this platform: {sys.platform}') class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self,", "({description}): {self.read_bytes(num_bytes)!r}') elif num_bytes < 0: raise ParserError(f'invalid skip of {num_bytes} bytes') def", "= DATA_BLOB() ret = ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in), # pDataIn None, # ppszDataDescr: human readable", "# dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" keyring_name = { 'brave': 'Brave', 'chrome': 'Chrome', 'chromium': 'Chromium',", "'GNOME_DESKTOP_SESSION_ID' in env: return _LinuxDesktopEnvironment.GNOME elif 'KDE_FULL_SESSION' in env: return _LinuxDesktopEnvironment.KDE return _LinuxDesktopEnvironment.OTHER", "= {'opera'} return { 'browser_dir': browser_dir, 'keyring_name': keyring_name, 'supports_profiles': browser_name not in browsers_without_profiles", "def debug(self, message): if self._ydl: self._ydl.write_debug(message) def info(self, message): if self._ydl: self._ydl.to_screen(f'[Cookies] {message}')", "p.skip_to(record_size, 'space at the end of the record') cookie = compat_cookiejar_Cookie( version=0, name=name,", "doesn't matter here. return b'' else: logger.debug('password found') if stdout[-1:] == b'\\n': stdout", "value, path, expiry, isSecure FROM moz_cookies') jar = YoutubeDLCookieJar() with _create_progress_bar(logger) as progress_bar:", "key (keyring) and more key derivation iterations than linux - not v10: 'old", "} def _extract_chrome_cookies(browser_name, profile, keyring, logger): logger.info(f'Extracting cookies from {browser_name}') if not SQLITE_AVAILABLE:", "= stdout[:-1] return stdout except Exception as e: logger.warning(f'exception running kwallet-query: {error_to_str(e)}') return", "name = p.read_cstring() p.skip_to(path_offset) path = p.read_cstring() p.skip_to(value_offset) value = p.read_cstring() except UnicodeDecodeError:", "= DATA_BLOB(ctypes.sizeof(buffer), buffer) blob_out = DATA_BLOB() ret = ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in), # pDataIn None,", "Linux keyring names can be determined by snooping on dbus while opening the", "p.cursor def _parse_safari_cookies_page(data, jar, logger): p = DataParser(data, logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page signature') number_of_cookies", "cookie {i: 6d}/{total_cookie_count: 6d}') is_encrypted, cookie = _process_chrome_cookie(decryptor, *line) if not cookie: failed_cookies", "chosen to use # chromium --enable-logging=stderr --v=1 2>&1 | grep key_storage_ # Chromium", "not os.path.isfile(cookies_path): logger.debug('Trying secondary cookie location') cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): raise", "0: logger.warning('failed to read NetworkWallet') return default_wallet else: network_wallet = stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet =", "proc.communicate_or_kill() if proc.returncode != 0: logger.error(f'kwallet-query failed with return code {proc.returncode}. Please consult", "ValueError(f'unsupported keyring: \"{keyring}\"') if profile is not None and _is_path(profile): profile = os.path.expanduser(profile)", "ParserError('reached end of input') data = self._data[self.cursor:end] self.cursor = end return data def", "Safe Storage', '--folder', f'{browser_keyring_name} Keys', network_wallet ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill()", "KDE = auto() PANTHEON = auto() UNITY = auto() XFCE = auto() class", "cases. keyring = _LinuxKeyring[keyring] if keyring else _choose_linux_keyring(logger) logger.debug(f'Chosen keyring: {keyring.name}') if keyring", "_create_progress_bar(logger) as progress_bar: for curr_root, dirs, files in os.walk(root): for file in files:", "class YDLLogger: def __init__(self, ydl=None): self._ydl = ydl def debug(self, message): if self._ydl:", "files in os.walk(root): for file in files: i += 1 progress_bar.print(f'Searching for \"{filename}\":", "return printer def load_cookies(cookie_file, browser_specification, ydl): cookie_jars = [] if browser_specification is not", "= expand_path(cookie_file) jar = YoutubeDLCookieJar(cookie_file) if os.access(cookie_file, os.R_OK): jar.load(ignore_discard=True, ignore_expires=True) cookie_jars.append(jar) return _merge_cookie_jars(cookie_jars)", "if sys.platform in ('linux', 'linux2'): return os.path.expanduser('~/.mozilla/firefox') elif sys.platform == 'win32': return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles')", "num_bytes, description='unknown'): if num_bytes > 0: self._logger.debug(f'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}') elif num_bytes", "self._ydl: self._ydl.report_warning(message, only_once) def error(self, message): if self._ydl: self._ydl.report_error(message) def progress_bar(self): \"\"\"Return a", "output_jar.filename = jar.filename return output_jar def _is_path(value): return os.path.sep in value def _parse_browser_specification(browser_name,", "datetime import datetime, timedelta, timezone from enum import Enum, auto from hashlib import", "_decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, logger): try: plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce) except", "OS protected key (keyring) - v11 keys can be stored in various places", "None and 'gnome-fallback' in desktop_session: return _LinuxDesktopEnvironment.GNOME else: return _LinuxDesktopEnvironment.UNITY elif xdg_current_desktop ==", "'chrome': os.path.join(appdata, 'Google/Chrome'), 'chromium': os.path.join(appdata, 'Chromium'), 'edge': os.path.join(appdata, 'Microsoft Edge'), 'opera': os.path.join(appdata, 'com.operasoftware.Opera'),", "{search_root}') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try:", "decryptor = get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger, keyring=keyring) with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None", "path, expiry, is_secure) in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') cookie = compat_cookiejar_Cookie(", "return encrypted_value class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_root, logger): self._logger = logger self._v10_key =", "logger): p = DataParser(data, logger) p.expect_bytes(b'cook', 'database signature') number_of_pages = p.read_uint(big_endian=True) page_sizes =", "host_key.decode('utf-8') name = name.decode('utf-8') value = value.decode('utf-8') path = path.decode('utf-8') is_encrypted = not", "as plaintext # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return encrypted_value class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_root, logger): self._logger", "'the kwallet-query man page for details') return b'' else: if stdout.lower().startswith(b'failed to read'):", "{'v10': 0, 'other': 0} @staticmethod def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return", "profile is None: search_root = config['browser_dir'] elif _is_path(profile): search_root = profile config['browser_dir'] =", "no key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) else: self._cookie_counts['other'] +=", "without sqlite3 support. ' 'Please use a python interpreter compiled with sqlite3 support')", "with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count = len(table) for i, line", "logger.error('kwallet-query command not found. KWallet and kwallet-query ' 'must be installed to read", "browser profiles, take the most recently used one i, paths = 0, []", "logger.debug('using find-generic-password to obtain password from OSX keychain') try: proc = Popen( ['security',", "logger.debug('failed to read password from kwallet. Using empty string instead') # this sometimes", "jar in jars: for cookie in jar: output_jar.set_cookie(cookie) if jar.filename is not None:", "profile, keyring, logger) else: raise ValueError(f'unknown browser: {browser_name}') def _extract_firefox_cookies(profile, logger): logger.info('Extracting cookies", "= _LinuxKeyring.BASICTEXT else: linux_keyring = _LinuxKeyring.GNOMEKEYRING return linux_keyring def _get_kwallet_network_wallet(logger): \"\"\" The name", "tmpdir) cursor.execute('SELECT host, name, value, path, expiry, isSecure FROM moz_cookies') jar = YoutubeDLCookieJar()", "ciphertext = encrypted_value[3:] if version == b'v10': self._cookie_counts['v10'] += 1 if self._v10_key is", "logger.debug('using kwallet-query to obtain password from kwallet') if shutil.which('kwallet-query') is None: logger.error('kwallet-query command", "_get_linux_keyring_password(browser_keyring_name, keyring, logger): # note: chrome/chromium can be run with the following flags", "is None else self.derive_key(password) self._cookie_counts = {'v10': 0, 'v11': 0, 'other': 0} @staticmethod", "cursor = None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.connection.text_factory = bytes column_names =", "for cookie in jar: output_jar.set_cookie(cookie) if jar.filename is not None: output_jar.filename = jar.filename", "cookie_jars = [] if browser_specification is not None: browser_name, profile, keyring = _parse_browser_specification(*browser_specification)", "row in table_info] def _find_most_recently_used_file(root, filename, logger): # if there are multiple browser", "{browser_name}') def _extract_firefox_cookies(profile, logger): logger.info('Extracting cookies from firefox') if not SQLITE_AVAILABLE: logger.warning('Cannot extract", "'Chromium', 'opera': 'Opera' if sys.platform == 'darwin' else 'Chromium', 'vivaldi': 'Vivaldi' if sys.platform", "information about prompts to display 0, # dwFlags ctypes.byref(blob_out) # pDataOut ) if", "else: raise ValueError(f'unsupported platform: {sys.platform}') # Linux keyring names can be determined by", "(None, *SUPPORTED_KEYRINGS): raise ValueError(f'unsupported keyring: \"{keyring}\"') if profile is not None and _is_path(profile):", "cursor.execute('SELECT host, name, value, path, expiry, isSecure FROM moz_cookies') jar = YoutubeDLCookieJar() with", "profiles') search_root = config['browser_dir'] cookie_database_path = _find_most_recently_used_file(search_root, 'Cookies', logger) if cookie_database_path is None:", "either v10 or not v10 - v10: AES-CBC encrypted with an OS protected", "= auto() GNOME = auto() KDE = auto() PANTHEON = auto() UNITY =", "comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) return record_size def parse_safari_cookies(data, jar=None, logger=YDLLogger()): \"\"\" References: -", "v10 - v10: AES-GCM encrypted with a key which is encrypted with DPAPI", "stored as plaintext # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return encrypted_value class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_root, logger):", "logger.error('safari does not support profiles') if sys.platform != 'darwin': raise ValueError(f'unsupported platform: {sys.platform}')", "SECRETSTORAGE_UNAVAILABLE_REASON = ( 'as the `secretstorage` module is not installed. ' 'Please install", "'linux2'): return os.path.expanduser('~/.mozilla/firefox') elif sys.platform == 'win32': return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif sys.platform == 'darwin':", "_parse_safari_cookies_page(p.read_bytes(page_size), jar, logger) p.skip_to_end('footer') return jar class _LinuxDesktopEnvironment(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment \"\"\" OTHER", "= auto() CINNAMON = auto() GNOME = auto() KDE = auto() PANTHEON =", "page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger) p.skip_to_end('footer') return jar class _LinuxDesktopEnvironment(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment \"\"\"", "'progress_bar'): printer = logger.progress_bar() if printer: return printer printer = QuietMultilinePrinter() printer.print =", "' 'Please use a python interpreter compiled with sqlite3 support') return YoutubeDLCookieJar() config", "the `secretstorage` module is not installed. ' 'Please install by running `python3 -m", "Keys', network_wallet ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode != 0:", "extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *, keyring=None): if browser_name == 'firefox': return _extract_firefox_cookies(profile, logger) elif", "else profile else: if config['supports_profiles']: search_root = os.path.join(config['browser_dir'], profile) else: logger.error(f'{browser_name} does not", "expand_path(cookie_file) jar = YoutubeDLCookieJar(cookie_file) if os.access(cookie_file, os.R_OK): jar.load(ignore_discard=True, ignore_expires=True) cookie_jars.append(jar) return _merge_cookie_jars(cookie_jars) def", "e: logger.warning(f'exception running find-generic-password: {error_to_str(e)}') return None def _get_windows_v10_key(browser_root, logger): path = _find_most_recently_used_file(browser_root,", "name=name, value=value, port=None, port_specified=False, domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False, comment=None,", "class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger, *, keyring=None): self._logger = logger self._v10_key =", "one i, paths = 0, [] with _create_progress_bar(logger) as progress_bar: for curr_root, dirs,", "name, value, path, expiry, isSecure FROM moz_cookies') jar = YoutubeDLCookieJar() with _create_progress_bar(logger) as", "record field 1') flags = p.read_uint() is_secure = bool(flags & 0x0001) p.skip(4, 'unknown", "with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.execute('SELECT", "6d}') is_encrypted, cookie = _process_chrome_cookie(decryptor, *line) if not cookie: failed_cookies += 1 continue", "], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode != 0: logger.error(f'kwallet-query failed", "return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) else: self._cookie_counts['other'] += 1 # other prefixes are considered", "\"interface='org.kde.KWallet'\" \"type=method_return\" keyring_name = { 'brave': 'Brave', 'chrome': 'Chrome', 'chromium': 'Chromium', 'edge': 'Microsoft", "env.get('DESKTOP_SESSION', None) if xdg_current_desktop is not None: xdg_current_desktop = xdg_current_desktop.split(':')[0].strip() if xdg_current_desktop ==", "_LinuxDesktopEnvironment.CINNAMON elif xdg_current_desktop == 'KDE': return _LinuxDesktopEnvironment.KDE elif xdg_current_desktop == 'Pantheon': return _LinuxDesktopEnvironment.PANTHEON", "by running `python3 -m pip install secretstorage`.') except Exception as _err: SECRETSTORAGE_AVAILABLE =", "profile, YDLLogger(ydl), keyring=keyring)) if cookie_file is not None: cookie_file = expand_path(cookie_file) jar =", "= xdg_current_desktop.split(':')[0].strip() if xdg_current_desktop == 'Unity': if desktop_session is not None and 'gnome-fallback'", "'v11': 0, 'other': 0} @staticmethod def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return", "store network passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet which does a dbus call to the following", "def read_bytes(self, num_bytes): if num_bytes < 0: raise ParserError(f'invalid read of {num_bytes} bytes')", "buffer = [] while True: c = self.read_bytes(1) if c == b'\\x00': return", "None if password is None else self.derive_key(password) self._cookie_counts = {'v10': 0, 'v11': 0,", "96 // 8 # boringssl # EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length = 16 raw_ciphertext = ciphertext", "raise FileNotFoundError('could not find safari cookies database') with open(cookies_path, 'rb') as f: cookies_data", "bytes') end = self.cursor + num_bytes if end > len(self._data): raise ParserError('reached end", "Safari cookie because UTF-8 decoding failed', only_once=True) return record_size p.skip_to(record_size, 'space at the", "ctypes.string_at(blob_out.pbData, blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData) return result def _config_home(): return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) def _open_database_copy(database_path, tmpdir):", "def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *, keyring=None): if browser_name == 'firefox': return _extract_firefox_cookies(profile, logger)", "R'BraveSoftware\\Brave-Browser\\User Data'), 'chrome': os.path.join(appdata_local, R'Google\\Chrome\\User Data'), 'chromium': os.path.join(appdata_local, R'Chromium\\User Data'), 'edge': os.path.join(appdata_local, R'Microsoft\\Edge\\User", "== 'darwin': return MacChromeCookieDecryptor(browser_keyring_name, logger) elif sys.platform == 'win32': return WindowsChromeCookieDecryptor(browser_root, logger) else:", "there are a few bytes here and there which are skipped during parsing", "xdg_current_desktop is not None: xdg_current_desktop = xdg_current_desktop.split(':')[0].strip() if xdg_current_desktop == 'Unity': if desktop_session", "= DataParser(data, logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page signature') number_of_cookies = p.read_uint() record_offsets = [p.read_uint() for", "raise ValueError(f'unsupported keyring: \"{keyring}\"') if profile is not None and _is_path(profile): profile =", "logger=YDLLogger(), *, keyring=None): if browser_name == 'firefox': return _extract_firefox_cookies(profile, logger) elif browser_name ==", "sqlite3 support') return YoutubeDLCookieJar() config = _get_chromium_based_browser_settings(browser_name) if profile is None: search_root =", "{self.read_bytes(num_bytes)!r}') elif num_bytes < 0: raise ParserError(f'invalid skip of {num_bytes} bytes') def skip_to(self,", "YoutubeDLCookieJar() page_sizes, body_start = _parse_safari_cookies_header(data, logger) p = DataParser(data[body_start:], logger) for page_size in", "note: chrome/chromium can be run with the following flags to determine which keyring", "file == filename: paths.append(os.path.join(curr_root, file)) return None if not paths else max(paths, key=lambda", "FROM cookies') jar = YoutubeDLCookieJar() failed_cookies = 0 unencrypted_cookies = 0 with _create_progress_bar(logger)", "self._cookie_counts = {'v10': 0, 'other': 0} @staticmethod def derive_key(password): # values from #", "'space at the end of the record') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value,", "just tries to read the value (which kwallet returns \"\") whereas kwallet-query #", "timezone from enum import Enum, auto from hashlib import pbkdf2_hmac from .aes import", "logger.error('failed to read from keyring') return b'' def _get_linux_keyring_password(browser_keyring_name, keyring, logger): # note:", "local state file at \"{path}\"') with open(path, encoding='utf8') as f: data = json.load(f)", "b'' def _get_linux_keyring_password(browser_keyring_name, keyring, logger): # note: chrome/chromium can be run with the", "keyring does not seem to organise keys in the same way as KWallet,", "support. ' 'Please use a python interpreter compiled with sqlite3 support') return YoutubeDLCookieJar()", "os.path.expanduser('~/Library/Application Support') browser_dir = { 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(appdata, 'Google/Chrome'), 'chromium': os.path.join(appdata,", "encrypted with an OS protected key (keyring) - v11 keys can be stored", "the browser) database_copy_path = os.path.join(tmpdir, 'temporary.sqlite') shutil.copy(database_path, database_copy_path) conn = sqlite3.connect(database_copy_path) return conn.cursor()", "input') data = self._data[self.cursor:end] self.cursor = end return data def expect_bytes(self, expected_value, message):", "logger): # note: chrome/chromium can be run with the following flags to determine", "expand_path try: import sqlite3 SQLITE_AVAILABLE = True except ImportError: # although sqlite3 is", "sqlite3 support') return YoutubeDLCookieJar() if profile is None: search_root = _firefox_browser_dir() elif _is_path(profile):", "os.path.join(config, 'opera'), 'vivaldi': os.path.join(config, 'vivaldi'), }[browser_name] elif sys.platform == 'win32': appdata_local = os.path.expandvars('%LOCALAPPDATA%')", "profile, keyring = _parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring)) if cookie_file is not None:", "'opera': os.path.join(appdata_roaming, R'Opera Software\\Opera Stable'), 'vivaldi': os.path.join(appdata_local, R'Vivaldi\\User Data'), }[browser_name] elif sys.platform ==", "expires_utc, {secure_column} FROM cookies') jar = YoutubeDLCookieJar() failed_cookies = 0 unencrypted_cookies = 0", "\"\"\" xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None) desktop_session = env.get('DESKTOP_SESSION', None) if xdg_current_desktop is not", "{browser_name}{failed_message}') counts = decryptor.cookie_counts.copy() counts['unencrypted'] = unencrypted_cookies logger.debug(f'cookie version breakdown: {counts}') return jar", "page of size {len(data)} has no cookies') return p.skip_to(record_offsets[0], 'unknown page header field')", "sys.platform == 'darwin': return os.path.expanduser('~/Library/Application Support/Firefox') else: raise ValueError(f'unsupported platform: {sys.platform}') def _get_chromium_based_browser_settings(browser_name):", "= f' ({failed_cookies} could not be decrypted)' else: failed_message = '' logger.info(f'Extracted {len(jar)}", "assert False, f'Unknown keyring {keyring}' def _get_mac_keyring_password(browser_keyring_name, logger): logger.debug('using find-generic-password to obtain password", "package for your distribution') return b'' network_wallet = _get_kwallet_network_wallet(logger) try: proc = Popen([", "the following function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet \"\"\" default_wallet = 'kdewallet' try: proc = Popen([", "logger.debug(f'cookie version breakdown: {counts}') return jar finally: if cursor is not None: cursor.connection.close()", "printer.print = lambda message: printer.print_at_line(f'[Cookies] {message}', 0) return printer def _create_progress_bar(logger): if hasattr(logger,", "used one i, paths = 0, [] with _create_progress_bar(logger) as progress_bar: for curr_root,", "as v10 (so no keyring password is required) return None assert False, f'Unknown", "# Linux keyring names can be determined by snooping on dbus while opening", "f'as the `secretstorage` module could not be initialized. {_err}' CHROMIUM_BASED_BROWSERS = {'brave', 'chrome',", "jar=None, logger=YDLLogger()): \"\"\" References: - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc - this data appears to be out", "if self._ydl: self._ydl.write_debug(message) def info(self, message): if self._ydl: self._ydl.to_screen(f'[Cookies] {message}') def warning(self, message,", "from KWallet. kwallet-query should be' 'included in the kwallet package for your distribution')", "password is required) return None assert False, f'Unknown keyring {keyring}' def _get_mac_keyring_password(browser_keyring_name, logger):", "cookie: failed_cookies += 1 continue elif not is_encrypted: unencrypted_cookies += 1 jar.set_cookie(cookie) if" ]
[ "managers def _ensure_present(mgr): try: mgr.version() except Exception: pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd():", "managers.GitManager() _ensure_present(mgr) mgr._invoke('init') mgr._invoke('config', 'user.email', '<EMAIL>') mgr._invoke('config', 'user.name', 'HGTools') os.makedirs('bar') touch('bar/baz') mgr._invoke('add', '.')", "hgtools import managers def _ensure_present(mgr): try: mgr.version() except Exception: pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir):", "<reponame>jaraco/hgtools import os import pytest from hgtools import managers def _ensure_present(mgr): try: mgr.version()", "import os import pytest from hgtools import managers def _ensure_present(mgr): try: mgr.version() except", "return tmpdir_as_cwd @pytest.fixture def git_repo(tmpdir_as_cwd): mgr = managers.GitManager() _ensure_present(mgr) mgr._invoke('init') mgr._invoke('config', 'user.email', '<EMAIL>')", "mgr._invoke('addremove') mgr._invoke('ci', '-m', 'committed') with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('ci', '-m', 'added", "baz: baz.write('content') mgr._invoke('commit', '-am', 'added content') return tmpdir_as_cwd def touch(filename): with open(filename, 'a'):", "mgr = managers.GitManager() _ensure_present(mgr) mgr._invoke('init') mgr._invoke('config', 'user.email', '<EMAIL>') mgr._invoke('config', 'user.name', 'HGTools') os.makedirs('bar') touch('bar/baz')", "git_repo(tmpdir_as_cwd): mgr = managers.GitManager() _ensure_present(mgr) mgr._invoke('init') mgr._invoke('config', 'user.email', '<EMAIL>') mgr._invoke('config', 'user.name', 'HGTools') os.makedirs('bar')", "managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init', '.') os.makedirs('bar') touch('bar/baz') mgr._invoke('addremove') mgr._invoke('ci', '-m', 'committed') with open('bar/baz', 'w')", "def hg_repo(tmpdir_as_cwd): mgr = managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init', '.') os.makedirs('bar') touch('bar/baz') mgr._invoke('addremove') mgr._invoke('ci', '-m',", "pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd(): yield tmpdir @pytest.fixture def hg_repo(tmpdir_as_cwd): mgr =", "baz.write('content') mgr._invoke('ci', '-m', 'added content') return tmpdir_as_cwd @pytest.fixture def git_repo(tmpdir_as_cwd): mgr = managers.GitManager()", "mgr._invoke('config', 'user.email', '<EMAIL>') mgr._invoke('config', 'user.name', 'HGTools') os.makedirs('bar') touch('bar/baz') mgr._invoke('add', '.') mgr._invoke('commit', '-m', 'committed')", "_ensure_present(mgr): try: mgr.version() except Exception: pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd(): yield tmpdir", "hg_repo(tmpdir_as_cwd): mgr = managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init', '.') os.makedirs('bar') touch('bar/baz') mgr._invoke('addremove') mgr._invoke('ci', '-m', 'committed')", "'w') as baz: baz.write('content') mgr._invoke('ci', '-m', 'added content') return tmpdir_as_cwd @pytest.fixture def git_repo(tmpdir_as_cwd):", "mgr._invoke('ci', '-m', 'committed') with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('ci', '-m', 'added content')", "from hgtools import managers def _ensure_present(mgr): try: mgr.version() except Exception: pytest.skip() @pytest.fixture def", "= managers.GitManager() _ensure_present(mgr) mgr._invoke('init') mgr._invoke('config', 'user.email', '<EMAIL>') mgr._invoke('config', 'user.name', 'HGTools') os.makedirs('bar') touch('bar/baz') mgr._invoke('add',", "'committed') with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('commit', '-am', 'added content') return tmpdir_as_cwd", "def _ensure_present(mgr): try: mgr.version() except Exception: pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd(): yield", "'.') os.makedirs('bar') touch('bar/baz') mgr._invoke('addremove') mgr._invoke('ci', '-m', 'committed') with open('bar/baz', 'w') as baz: baz.write('content')", "tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd(): yield tmpdir @pytest.fixture def hg_repo(tmpdir_as_cwd): mgr = managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init',", "_ensure_present(mgr) mgr._invoke('init') mgr._invoke('config', 'user.email', '<EMAIL>') mgr._invoke('config', 'user.name', 'HGTools') os.makedirs('bar') touch('bar/baz') mgr._invoke('add', '.') mgr._invoke('commit',", "yield tmpdir @pytest.fixture def hg_repo(tmpdir_as_cwd): mgr = managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init', '.') os.makedirs('bar') touch('bar/baz')", "with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('ci', '-m', 'added content') return tmpdir_as_cwd @pytest.fixture", "'user.name', 'HGTools') os.makedirs('bar') touch('bar/baz') mgr._invoke('add', '.') mgr._invoke('commit', '-m', 'committed') with open('bar/baz', 'w') as", "mgr._invoke('init', '.') os.makedirs('bar') touch('bar/baz') mgr._invoke('addremove') mgr._invoke('ci', '-m', 'committed') with open('bar/baz', 'w') as baz:", "'w') as baz: baz.write('content') mgr._invoke('commit', '-am', 'added content') return tmpdir_as_cwd def touch(filename): with", "_ensure_present(mgr) mgr._invoke('init', '.') os.makedirs('bar') touch('bar/baz') mgr._invoke('addremove') mgr._invoke('ci', '-m', 'committed') with open('bar/baz', 'w') as", "baz: baz.write('content') mgr._invoke('ci', '-m', 'added content') return tmpdir_as_cwd @pytest.fixture def git_repo(tmpdir_as_cwd): mgr =", "'-m', 'committed') with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('commit', '-am', 'added content') return", "os.makedirs('bar') touch('bar/baz') mgr._invoke('addremove') mgr._invoke('ci', '-m', 'committed') with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('ci',", "try: mgr.version() except Exception: pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd(): yield tmpdir @pytest.fixture", "@pytest.fixture def hg_repo(tmpdir_as_cwd): mgr = managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init', '.') os.makedirs('bar') touch('bar/baz') mgr._invoke('addremove') mgr._invoke('ci',", "@pytest.fixture def tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd(): yield tmpdir @pytest.fixture def hg_repo(tmpdir_as_cwd): mgr = managers.MercurialManager()", "tmpdir.as_cwd(): yield tmpdir @pytest.fixture def hg_repo(tmpdir_as_cwd): mgr = managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init', '.') os.makedirs('bar')", "mgr._invoke('commit', '-m', 'committed') with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('commit', '-am', 'added content')", "'committed') with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('ci', '-m', 'added content') return tmpdir_as_cwd", "Exception: pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd(): yield tmpdir @pytest.fixture def hg_repo(tmpdir_as_cwd): mgr", "'user.email', '<EMAIL>') mgr._invoke('config', 'user.name', 'HGTools') os.makedirs('bar') touch('bar/baz') mgr._invoke('add', '.') mgr._invoke('commit', '-m', 'committed') with", "'.') mgr._invoke('commit', '-m', 'committed') with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('commit', '-am', 'added", "touch('bar/baz') mgr._invoke('addremove') mgr._invoke('ci', '-m', 'committed') with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('ci', '-m',", "os import pytest from hgtools import managers def _ensure_present(mgr): try: mgr.version() except Exception:", "os.makedirs('bar') touch('bar/baz') mgr._invoke('add', '.') mgr._invoke('commit', '-m', 'committed') with open('bar/baz', 'w') as baz: baz.write('content')", "= managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init', '.') os.makedirs('bar') touch('bar/baz') mgr._invoke('addremove') mgr._invoke('ci', '-m', 'committed') with open('bar/baz',", "'-m', 'added content') return tmpdir_as_cwd @pytest.fixture def git_repo(tmpdir_as_cwd): mgr = managers.GitManager() _ensure_present(mgr) mgr._invoke('init')", "pytest from hgtools import managers def _ensure_present(mgr): try: mgr.version() except Exception: pytest.skip() @pytest.fixture", "import managers def _ensure_present(mgr): try: mgr.version() except Exception: pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir): with", "touch('bar/baz') mgr._invoke('add', '.') mgr._invoke('commit', '-m', 'committed') with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('commit',", "mgr._invoke('add', '.') mgr._invoke('commit', '-m', 'committed') with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('commit', '-am',", "mgr._invoke('config', 'user.name', 'HGTools') os.makedirs('bar') touch('bar/baz') mgr._invoke('add', '.') mgr._invoke('commit', '-m', 'committed') with open('bar/baz', 'w')", "open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('ci', '-m', 'added content') return tmpdir_as_cwd @pytest.fixture def", "open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('commit', '-am', 'added content') return tmpdir_as_cwd def touch(filename):", "'added content') return tmpdir_as_cwd @pytest.fixture def git_repo(tmpdir_as_cwd): mgr = managers.GitManager() _ensure_present(mgr) mgr._invoke('init') mgr._invoke('config',", "'<EMAIL>') mgr._invoke('config', 'user.name', 'HGTools') os.makedirs('bar') touch('bar/baz') mgr._invoke('add', '.') mgr._invoke('commit', '-m', 'committed') with open('bar/baz',", "'-m', 'committed') with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('ci', '-m', 'added content') return", "def git_repo(tmpdir_as_cwd): mgr = managers.GitManager() _ensure_present(mgr) mgr._invoke('init') mgr._invoke('config', 'user.email', '<EMAIL>') mgr._invoke('config', 'user.name', 'HGTools')", "content') return tmpdir_as_cwd @pytest.fixture def git_repo(tmpdir_as_cwd): mgr = managers.GitManager() _ensure_present(mgr) mgr._invoke('init') mgr._invoke('config', 'user.email',", "mgr._invoke('init') mgr._invoke('config', 'user.email', '<EMAIL>') mgr._invoke('config', 'user.name', 'HGTools') os.makedirs('bar') touch('bar/baz') mgr._invoke('add', '.') mgr._invoke('commit', '-m',", "tmpdir @pytest.fixture def hg_repo(tmpdir_as_cwd): mgr = managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init', '.') os.makedirs('bar') touch('bar/baz') mgr._invoke('addremove')", "'HGTools') os.makedirs('bar') touch('bar/baz') mgr._invoke('add', '.') mgr._invoke('commit', '-m', 'committed') with open('bar/baz', 'w') as baz:", "@pytest.fixture def git_repo(tmpdir_as_cwd): mgr = managers.GitManager() _ensure_present(mgr) mgr._invoke('init') mgr._invoke('config', 'user.email', '<EMAIL>') mgr._invoke('config', 'user.name',", "as baz: baz.write('content') mgr._invoke('commit', '-am', 'added content') return tmpdir_as_cwd def touch(filename): with open(filename,", "baz.write('content') mgr._invoke('commit', '-am', 'added content') return tmpdir_as_cwd def touch(filename): with open(filename, 'a'): pass", "mgr = managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init', '.') os.makedirs('bar') touch('bar/baz') mgr._invoke('addremove') mgr._invoke('ci', '-m', 'committed') with", "import pytest from hgtools import managers def _ensure_present(mgr): try: mgr.version() except Exception: pytest.skip()", "mgr.version() except Exception: pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd(): yield tmpdir @pytest.fixture def", "with tmpdir.as_cwd(): yield tmpdir @pytest.fixture def hg_repo(tmpdir_as_cwd): mgr = managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init', '.')", "except Exception: pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd(): yield tmpdir @pytest.fixture def hg_repo(tmpdir_as_cwd):", "tmpdir_as_cwd @pytest.fixture def git_repo(tmpdir_as_cwd): mgr = managers.GitManager() _ensure_present(mgr) mgr._invoke('init') mgr._invoke('config', 'user.email', '<EMAIL>') mgr._invoke('config',", "def tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd(): yield tmpdir @pytest.fixture def hg_repo(tmpdir_as_cwd): mgr = managers.MercurialManager() _ensure_present(mgr)", "with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('commit', '-am', 'added content') return tmpdir_as_cwd def", "as baz: baz.write('content') mgr._invoke('ci', '-m', 'added content') return tmpdir_as_cwd @pytest.fixture def git_repo(tmpdir_as_cwd): mgr", "mgr._invoke('ci', '-m', 'added content') return tmpdir_as_cwd @pytest.fixture def git_repo(tmpdir_as_cwd): mgr = managers.GitManager() _ensure_present(mgr)" ]
[ "isinstance(other, SQLQuery): self.items.extend(other.items) else: return NotImplemented return self def __len__(self): return len(self.query()) def", "def query(self, paramstyle=None): \"\"\" Returns the query part of the sql query. >>>", "and `offset`. Uses vars to interpolate. Otherwise, each clause can be a SQLQuery.", "r\"\"\"Creates a new SQLQuery. >>> SQLQuery(\"x\") <sql: 'x'> >>> q = SQLQuery(['SELECT *", "match.regs[3] token = sformat[tstart:tend] if token[0] in \"([\": level = level + 1", "get concatenated to produce the actual query. \"\"\" __slots__ = [\"items\"] # tested", "chunks.append((1, sformat[dollar + 1:pos])) else: chunks.append((0, sformat[pos:dollar + 1])) pos = dollar +", "NOW() WHERE name = %s' >>> q.values() [2, 'bob', 'Joseph'] \"\"\" if svars", "any given object to utf-8 encoded string. >>> safestr('hello') 'hello' >>> safestr(u'\\u1234') '\\xe1\\x88\\xb4'", "pos + 1) elif sformat[pos] in \"([\": pos, level = pos + 1,", "'%s' raise UnknownParamstyle, paramstyle def sqlquery(self): return SQLQuery([self]) def __add__(self, other): return self.sqlquery()", "characters in the query # For backward compatability, ignore escaping when the query", "in keys], sep=\", \", target=sql_query, prefix=\"(\", suffix=\")\") if _test: return sql_query db_cursor =", ">>> sqlwhere({'cust_id': 2, 'order_id':3}) <sql: 'order_id = 3 AND cust_id = 2'> >>>", "len(sformat): chunks.append((0, sformat[pos:])) return chunks def sqlwhere(dictionary, grouping=' AND '): \"\"\" Converts a", "{} if not processed and not isinstance(sql_query, SQLQuery): sql_query = reparam(sql_query, svars) return", "sqlify(obj): \"\"\" converts `obj` to its proper SQL version >>> sqlify(None) 'NULL' >>>", "encoding='utf-8'): r\"\"\" Converts any given object to unicode string. >>> safeunicode('hello') u'hello' >>>", "not self.ctx.transactions: self.ctx.commit() return db_cursor.rowcount def delete(self, table, where, using=None, svars=None, _test=False): \"\"\"", "what), ('FROM', sqllist(tables)), ('WHERE', where), ('GROUP BY', group), ('ORDER BY', order), ('LIMIT', limit),", "if not self.ctx.transactions: self.ctx.commit() return out def update(self, tables, where, svars=None, _test=False, **values):", "(ValueError, TypeError): return self.query() def __str__(self): return safestr(self._str()) def __unicode__(self): return safeunicode(self._str()) def", "sql_query.append(\", \") SQLQuery.join([SQLParam(row[k]) for k in keys], sep=\", \", target=sql_query, prefix=\"(\", suffix=\")\") if", "items elif isinstance(items, SQLParam): self.items = [items] elif isinstance(items, SQLQuery): self.items = list(items.items)", "_sqllist(a) else: return sqlparam(a).sqlquery() def _interpolate(sformat): \"\"\" Takes a format string and returns", "\"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks = [] pos = 0 while 1: dollar = sformat.find(\"$\", pos)", "tablename, seqname=None, _test=False, **values): \"\"\" Inserts `values` into `tablename`. Returns current sequence ID.", "each row to be inserted, each with the same set of keys. Returns", "AND b = %s' \"\"\" return SQLQuery.join([k + ' = ' + sqlparam(v)", "where=\"foo.bar_id = bar.id\", limit=5, _test=True) <sql: 'SELECT * FROM foo, bar WHERE foo.bar_id", "[\"value\"] def __init__(self, value): self.value = value def get_marker(self, paramstyle='pyformat'): if paramstyle ==", ">>> db = DB(None, {}) >>> db.select('foo', _test=True) <sql: 'SELECT * FROM foo'>", "= val else: nout = reparam(val, svars) def xjoin(a, b): if a and", "+ sqlquote(val) else: nout = SQLQuery(val) elif isinstance(val, (list, tuple)) and len(val) ==", "safeunicode(2) u'2' >>> safeunicode('\\xe1\\x88\\xb4') u'\\u1234' \"\"\" t = type(obj) if t is unicode:", "hasattr(obj, 'next'): # iterator return itertools.imap(safestr, obj) else: return str(obj) def sqlify(obj): \"\"\"", "tuple([sqlify(x) for x in self.values()]) except (ValueError, TypeError): return self.query() def __str__(self): return", "def __radd__(self, other): return other + self.sqlquery() def __str__(self): return str(self.value) def __repr__(self):", "y = ' + sqlquote(3) <sql: \"WHERE x = 't' AND y =", "target_items.append(item) if suffix: target_items.append(suffix) return target join = staticmethod(join) def _str(self): try: return", "AND y = 3\"> >>> 'WHERE x = ' + sqlquote(True) + '", "USING ' + sqllist(using) if where: q += ' WHERE ' + where", "%s, name = %s, created = NOW() WHERE name = %s' >>> q.values()", "and b: return a + ' ' + b else: return a or", "'pyformat']: return '%s' raise UnknownParamstyle, paramstyle def sqlquery(self): return SQLQuery([self]) def __add__(self, other):", "= 'Joe'\"> \"\"\" if svars is None: svars = {} where = self._where(where,", "return repr(obj.isoformat()) else: if isinstance(obj, unicode): obj = obj.encode('utf8') return repr(obj) def sqllist(lst):", "__add__(self, other): return self.sqlquery() + other def __radd__(self, other): return other + self.sqlquery()", "age=2, created=SQLLiteral('NOW()'), _test=True) >>> q <sql: \"INSERT INTO foo (age, name, created) VALUES", "level: match, pos = matchorfail(sformat, pos) tstart, tend = match.regs[3] token = sformat[tstart:tend]", "basestring): return lst else: return ', '.join(lst) def _sqllist(values): \"\"\" >>> _sqllist([1, 2,", ">>> sqlwhere({'a': 'a', 'b': 'b'}).query() 'a = %s AND b = %s' \"\"\"", "basestring): items = [other] elif isinstance(other, SQLQuery): items = other.items else: return NotImplemented", "provided, the items are appended to target instead of creating a new SQLQuery.", "% ( repr(self.text), self.pos) class SQLParam(object): \"\"\" Parameter in SQLQuery. >>> q =", "You can pass this sort of thing as a clause in any db", "not False: sql_query = self._process_insert_query(sql_query, tablename, seqname) if isinstance(sql_query, tuple): # for some", "self.sqlquery() def __str__(self): return str(self.value) def __repr__(self): return '<param: %s>' % repr(self.value) sqlparam", "text self.pos = pos def __str__(self): return \"unfinished expression in %s at char", "`vars`) and setting `values`. >>> db = DB(None, {}) >>> name = 'Joseph'", "row to be inserted, each with the same set of keys. Returns the", "('WHERE', where), ('GROUP BY', group), ('ORDER BY', order), ('LIMIT', limit), ('OFFSET', offset)) def", "sql, val in sql_clauses if val is not None] qout = SQLQuery.join(clauses) if", "db.supports_multiple_insert = True >>> values = [{\"name\": \"foo\", \"email\": \"<EMAIL>\"}, {\"name\": \"bar\", \"email\":", "\"INSERT INTO %s DEFAULT VALUES\" % table def multiple_insert(self, tablename, values, seqname=None, _test=False):", "def __iadd__(self, other): if isinstance(other, (basestring, SQLParam)): self.items.append(other) elif isinstance(other, SQLQuery): self.items.extend(other.items) else:", "_test=False, **values): \"\"\" Update `tables` with clause `where` (interpolated using `vars`) and setting", "== \".\" and \\ pos + 1 < len(sformat) and sformat[pos + 1]", "('GROUP BY', group), ('ORDER BY', order), ('LIMIT', limit), ('OFFSET', offset)) def gen_clause(self, sql,", "db_cursor.rowcount def delete(self, table, where, using=None, svars=None, _test=False): \"\"\" Deletes from `table` with", "SQLQuery.join([SQLParam(row[k]) for k in keys], sep=\", \", target=sql_query, prefix=\"(\", suffix=\")\") if _test: return", "grouping=', ') <sql: 'order_id = 3, cust_id = 2'> >>> sqlwhere({'a': 'a', 'b':", "of dictioanries, one for each row to be inserted, each with the same", "name=\", SQLParam('joe')]) >>> q.values() ['joe'] \"\"\" return [i.value for i in self.items if", "def __str__(self): return safestr(self._str()) def __unicode__(self): return safeunicode(self._str()) def __repr__(self): return '<sql: %s>'", "whether string should be evaled or not. from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee)", "def __init__(self): \"\"\"Creates a database. \"\"\" pass def query(self, sql_query,processed=False, svars=None): \"\"\" Execute", "match, pos = matchorfail(sformat, pos + 1) elif sformat[pos] in \"([\": pos, level", "\"\"\" dictionary = dictionary.copy() # eval mucks with it result = [] for", "this sort of thing as a clause in any db function. Otherwise, you", "= {} where = self._where(where, svars) query = ( \"UPDATE \" + sqllist(tables)", "return query db_cursor = self._db_cursor() self._db_execute(db_cursor, query) if not self.ctx.transactions: self.ctx.commit() return db_cursor.rowcount", "sqlquote([2, 3]) <sql: \"WHERE x = 't' AND y IN (2, 3)\"> \"\"\"", "target_items.append(prefix) for i, item in enumerate(items): if i != 0: target_items.append(sep) if isinstance(item,", "{}) >>> name = 'Joe' >>> db.delete('foo', where='name = $name', vars=locals(), _test=True) <sql:", "True and hash(1) == hash(True)` # we have to do this the hard", "\"SELECT * FROM foo WHERE x = 'f'\"> >>> db.query(\"SELECT * FROM foo", "where, svars=None, _test=False, **values): \"\"\" Update `tables` with clause `where` (interpolated using `vars`)", "+ q(_keys) + ' VALUES ' + q(_values) else: sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) return", "value def get_marker(self, paramstyle='pyformat'): if paramstyle == 'qmark': return '?' elif paramstyle ==", "\"email\": \"<EMAIL>\"}, {\"name\": \"bar\", \"email\": \"<EMAIL>\"}] >>> db.multiple_insert('person', values=values, _test=True) <sql: \"INSERT INTO", "$name', name='bob', age=2, ... created=SQLLiteral('NOW()'), vars=locals(), _test=True) >>> q <sql: \"UPDATE foo SET", "return self.query() % tuple([sqlify(x) for x in self.values()]) except (ValueError, TypeError): return self.query()", "`group`, `limit`, and `offset`. Uses vars to interpolate. Otherwise, each clause can be", "`reparam`-style list to use instead of interpolating. >>> db = DB(None, {}) >>>", "If `processed=True`, `vars` is a `reparam`-style list to use instead of interpolating. >>>", "\"\"\" pass class _ItplError(ValueError): def __init__(self, text, pos): ValueError.__init__(self) self.text = text self.pos", "long)): if sql == 'WHERE': nout = 'id = ' + sqlquote(val) else:", "% (tablename, ', '.join(keys))) for i, row in enumerate(values): if i != 0:", "', '.join(lst) def _sqllist(values): \"\"\" >>> _sqllist([1, 2, 3]) <sql: '(1, 2, 3)'>", ">>> db.select('foo', _test=True) <sql: 'SELECT * FROM foo'> >>> db.select(['foo', 'bar'], where=\"foo.bar_id =", "nout = val else: nout = reparam(val, svars) def xjoin(a, b): if a", "_values = SQLQuery.join([sqlparam(v) for v in values.values()], ', ') sql_query = \"INSERT INTO", "items = other.items else: return NotImplemented return SQLQuery(self.items + items) def __radd__(self, other):", "SQLQuery.join(['a', 'b'], ', ', prefix='(', suffix=')') <sql: '(a, b)'> If target argument is", "q2) else: self._db_execute(db_cursor, sql_query) try: out = db_cursor.fetchone()[0] out = range(out-len(values)+1, out+1) except", "to be made to find # the id of the inserted row. q1,", "' ' + b else: return a or b return xjoin(sql, nout) def", "seqname is not False: sql_query = self._process_insert_query(sql_query, tablename, seqname) if isinstance(sql_query, tuple): #", "name=?' \"\"\" s = [] for x in self.items: if isinstance(x, SQLParam): x", "dict(s=True)) <sql: \"s = 't'\"> >>> reparam(\"s IN $s\", dict(s=[1, 2])) <sql: 's", "self.pos) class SQLParam(object): \"\"\" Parameter in SQLQuery. >>> q = SQLQuery([\"SELECT * FROM", "return \"INSERT INTO %s DEFAULT VALUES\" % table def multiple_insert(self, tablename, values, seqname=None,", "test WHERE name=?' \"\"\" s = [] for x in self.items: if isinstance(x,", "\"\"\" if svars is None: svars = {} where = self._where(where, svars) q", "+ sqlquote(True) + ' AND y = ' + sqlquote(3) <sql: \"WHERE x", "u'\\u1234' \"\"\" t = type(obj) if t is unicode: return obj elif t", "dollar = sformat.find(\"$\", pos) if dollar < 0: break nextchar = sformat[dollar +", "`sqlquote`. >>> sqlquote('NOW()') <sql: \"'NOW()'\"> >>> sqlquote(SQLLiteral('NOW()')) <sql: 'NOW()'> \"\"\" def __init__(self, v):", "`processed=True`, `vars` is a `reparam`-style list to use instead of interpolating. >>> db", "long)): where = \"id = \" + sqlparam(where) elif isinstance(where, (list, tuple)) and", "setting `values`. >>> db = DB(None, {}) >>> name = 'Joseph' >>> q", ">>> q.query() 'SELECT * FROM test WHERE name=%s' >>> q.query(paramstyle='qmark') 'SELECT * FROM", "will call reparam for you. Internally, consists of `items`, which is a list", "DEFAULT VALUES\" % table def multiple_insert(self, tablename, values, seqname=None, _test=False): \"\"\" Inserts multiple", "if _test: return qout return self.query(qout, processed=True) def insert(self, tablename, seqname=None, _test=False, **values):", "Deletes from `table` with clauses `where` and `using`. >>> db = DB(None, {})", "isinstance(other, (basestring, SQLParam)): self.items.append(other) elif isinstance(other, SQLQuery): self.items.extend(other.items) else: return NotImplemented return self", "age = %s, name = %s, created = NOW() WHERE name = %s'", "hash(1) == hash(True)` # we have to do this the hard way... if", "other): if isinstance(other, basestring): items = [other] elif isinstance(other, SQLQuery): items = other.items", "db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'), _test=True) >>> q <sql: \"INSERT INTO foo (age, name,", "sqlwhere({'a': 'a', 'b': 'b'}).query() 'a = %s AND b = %s' \"\"\" return", "b'> Optinally, prefix and suffix arguments can be provided. >>> SQLQuery.join(['a', 'b'], ',", "\"\"\" Protects a string from `sqlquote`. >>> sqlquote('NOW()') <sql: \"'NOW()'\"> >>> sqlquote(SQLLiteral('NOW()')) <sql:", "pos = matchorfail(sformat, pos) tstart, tend = match.regs[3] token = sformat[tstart:tend] if token", "\"(\" + x + \")\" if values: _keys = SQLQuery.join(values.keys(), ', ') _values", "paramstyle in ['format', 'pyformat']: if '%' in x and '%%' not in x:", "where = reparam(where, svars) return where def select(self, tables, svars=None, what='*', where=None, order=None,", "append(self, value): self.items.append(value) def __add__(self, other): if isinstance(other, basestring): items = [other] elif", "vars to interpolate. Otherwise, each clause can be a SQLQuery. >>> db =", "'order_id = 3 AND cust_id = 2'> >>> sqlwhere({'cust_id': 2, 'order_id':3}, grouping=', ')", "nout = SQLQuery(val) elif isinstance(val, (list, tuple)) and len(val) == 2: nout =", "class SQLLiteral: \"\"\" Protects a string from `sqlquote`. >>> sqlquote('NOW()') <sql: \"'NOW()'\"> >>>", "clause. >>> sqllist(['a', 'b']) 'a, b' >>> sqllist('a') 'a' >>> sqllist(u'abc') u'abc' \"\"\"", "i, item in enumerate(items): if i != 0: target_items.append(sep) if isinstance(item, SQLQuery): target_items.extend(item.items)", "self._db_cursor() self._db_execute(db_cursor, query) if not self.ctx.transactions: self.ctx.commit() return db_cursor.rowcount def delete(self, table, where,", "Selects `what` from `tables` with clauses `where`, `order`, `group`, `limit`, and `offset`. Uses", "target.items if prefix: target_items.append(prefix) for i, item in enumerate(items): if i != 0:", "= 'Joe' >>> db.delete('foo', where='name = $name', vars=locals(), _test=True) <sql: \"DELETE FROM foo", "for use in something like a WHERE clause. >>> sqllist(['a', 'b']) 'a, b'", "else: target_items.append(item) if suffix: target_items.append(suffix) return target join = staticmethod(join) def _str(self): try:", "IN $s\", dict(s=[1, 2])) <sql: 's IN (1, 2)'> \"\"\" dictionary = dictionary.copy()", "DB(None, {}) >>> name = 'Joseph' >>> q = db.update('foo', where='name = $name',", "dictionary. Returns an `SQLQuery` for the result. >>> reparam(\"s = $s\", dict(s=True)) <sql:", "= 2'> >>> sqlwhere({'cust_id': 2, 'order_id':3}, grouping=', ') <sql: 'order_id = 3, cust_id", "k in keys], sep=\", \", target=sql_query, prefix=\"(\", suffix=\")\") if _test: return sql_query db_cursor", "itertools import datetime def safeunicode(obj, encoding='utf-8'): r\"\"\" Converts any given object to unicode", "= range(out-len(values)+1, out+1) except Exception: out = None if not self.ctx.transactions: self.ctx.commit() return", "+ q(_values) else: sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query def _get_insert_default_values_query(self, table): return \"INSERT", "name='joe'\"> >>> q.query() 'SELECT * FROM test WHERE name=%s' >>> q.values() ['joe'] \"\"\"", "obj elif hasattr(obj, 'next'): # iterator return itertools.imap(safestr, obj) else: return str(obj) def", "' AND y IN ' + sqlquote([2, 3]) <sql: \"WHERE x = 't'", "self.items.extend(other.items) else: return NotImplemented return self def __len__(self): return len(self.query()) def query(self, paramstyle=None):", "the id of the inserted row. q1, q2 = sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor,", "id of the inserted row. q1, q2 = sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2)", "return '%s' raise UnknownParamstyle, paramstyle def sqlquery(self): return SQLQuery([self]) def __add__(self, other): return", "hasattr(obj, '__unicode__') or isinstance(obj, unicode): return unicode(obj) else: return str(obj).decode(encoding) def safestr(obj, encoding='utf-8'):", "paramstyle is None or paramstyle in ['format', 'pyformat']: return '%s' raise UnknownParamstyle, paramstyle", "and len(where) == 2: where = SQLQuery(where[0], where[1]) elif isinstance(where, SQLQuery): pass else:", "( repr(self.text), self.pos) class SQLParam(object): \"\"\" Parameter in SQLQuery. >>> q = SQLQuery([\"SELECT", "+ 1) elif sformat[pos] in \"([\": pos, level = pos + 1, 1", "= text self.pos = pos def __str__(self): return \"unfinished expression in %s at", "make sure all rows have same keys. for v in values: if v.keys()", "') <sql: 'order_id = 3, cust_id = 2'> >>> sqlwhere({'a': 'a', 'b': 'b'}).query()", "self._db_execute(db_cursor, sql_query) try: out = db_cursor.fetchone()[0] out = range(out-len(values)+1, out+1) except Exception: out", "for the result. >>> reparam(\"s = $s\", dict(s=True)) <sql: \"s = 't'\"> >>>", "sqlquote's docstring def __init__(self, items=None): r\"\"\"Creates a new SQLQuery. >>> SQLQuery(\"x\") <sql: 'x'>", "in enumerate(items): if i != 0: target_items.append(sep) if isinstance(item, SQLQuery): target_items.extend(item.items) else: target_items.append(item)", "'a, b' >>> sqllist('a') 'a' >>> sqllist(u'abc') u'abc' \"\"\" if isinstance(lst, basestring): return", "'<sql: %s>' % repr(str(self)) class SQLLiteral: \"\"\" Protects a string from `sqlquote`. >>>", "', ') _values = SQLQuery.join([sqlparam(v) for v in values.values()], ', ') sql_query =", "sqllist(tables) + \" SET \" + sqlwhere(values, ', ') + \" WHERE \"", "dictionary.items()], grouping) def reparam(string_, dictionary): \"\"\" Takes a string and a dictionary and", "or not. from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee) \"\"\" from tokenize import tokenprog", "where = SQLQuery(where[0], where[1]) elif isinstance(where, SQLQuery): pass else: where = reparam(where, svars)", "clauses `where` and `using`. >>> db = DB(None, {}) >>> name = 'Joe'", "clause `SQLQuery`. >>> sqlwhere({'cust_id': 2, 'order_id':3}) <sql: 'order_id = 3 AND cust_id =", "BY', group), ('ORDER BY', order), ('LIMIT', limit), ('OFFSET', offset)) def gen_clause(self, sql, val,", "if isinstance(obj, unicode): obj = obj.encode('utf8') return repr(obj) def sqllist(lst): \"\"\" Converts the", "`SQLQuery` for the result. >>> reparam(\"s = $s\", dict(s=True)) <sql: \"s = 't'\">", "in a SQL query. >>> 'WHERE x = ' + sqlquote(True) + '", "'s IN (1, 2)'> \"\"\" dictionary = dictionary.copy() # eval mucks with it", "return sql_query def _get_insert_default_values_query(self, table): return \"INSERT INTO %s DEFAULT VALUES\" % table", "', ') + \" WHERE \" + where) if _test: return query db_cursor", "seqname is False: return None else: return out keys = values[0].keys() #@@ make", "nout = reparam(val, svars) def xjoin(a, b): if a and b: return a", "is a list of strings and SQLParams, which get concatenated to produce the", "creating a new SQLQuery. \"\"\" if target is None: target = SQLQuery() target_items", "in \"([\": pos, level = pos + 1, 1 while level: match, pos", "( ('SELECT', what), ('FROM', sqllist(tables)), ('WHERE', where), ('GROUP BY', group), ('ORDER BY', order),", "token = sformat[tstart:tend] if token[0] in \"([\": level = level + 1 elif", "elif paramstyle is None or paramstyle in ['format', 'pyformat']: return '%s' raise UnknownParamstyle,", "= 2, name = 'bob', created = NOW() WHERE name = 'Joseph'\"> >>>", "1:pos])) else: chunks.append((0, sformat[pos:dollar + 1])) pos = dollar + 1 + (nextchar", "= {} where = self._where(where, svars) q = 'DELETE FROM ' + table", "if pos < len(sformat): chunks.append((0, sformat[pos:])) return chunks def sqlwhere(dictionary, grouping=' AND '):", "\"<EMAIL>\"}] >>> db.multiple_insert('person', values=values, _test=True) <sql: \"INSERT INTO person (name, email) VALUES ('foo',", "sep=' ', prefix=None, suffix=None, target=None): \"\"\" Joins multiple queries. >>> SQLQuery.join(['a', 'b'], ',", "and returns a list of 2-tuples of the form (boolean, string) where boolean", "this the hard way... if obj is None: return 'NULL' elif obj is", "def _interpolate(sformat): \"\"\" Takes a format string and returns a list of 2-tuples", "elif isinstance(items, list): self.items = items elif isinstance(items, SQLParam): self.items = [items] elif", "class SQLProducer: \"\"\"Database\"\"\" def __init__(self): \"\"\"Creates a database. \"\"\" pass def query(self, sql_query,processed=False,", "arguments for use in something like a WHERE clause. >>> sqllist(['a', 'b']) 'a,", "interpolate it. If `processed=True`, `vars` is a `reparam`-style list to use instead of", "a or b return xjoin(sql, nout) def _where(self, where, svars): if isinstance(where, (int,", "name, created) VALUES (%s, %s, NOW())' >>> q.values() [2, 'bob'] \"\"\" def q(x):", "+ sqlparam(v) for k, v in dictionary.items()], grouping) def reparam(string_, dictionary): \"\"\" Takes", ">>> safeunicode('\\xe1\\x88\\xb4') u'\\u1234' \"\"\" t = type(obj) if t is unicode: return obj", "string from `sqlquote`. >>> sqlquote('NOW()') <sql: \"'NOW()'\"> >>> sqlquote(SQLLiteral('NOW()')) <sql: 'NOW()'> \"\"\" def", "db.query(\"SELECT * FROM foo WHERE x = $x\", vars=dict(x='f'), _test=True) <sql: \"SELECT *", "xjoin(a, b): if a and b: return a + ' ' + b", "'numeric': return ':1' elif paramstyle is None or paramstyle in ['format', 'pyformat']: return", "if there isn't one. >>> db = DB(None, {}) >>> q = db.insert('foo',", "pass this sort of thing as a clause in any db function. Otherwise,", "[other] elif isinstance(other, SQLQuery): items = other.items else: return NotImplemented return SQLQuery(self.items +", "name = 'Joe'\"> \"\"\" if svars is None: svars = {} where =", "keys], sep=\", \", target=sql_query, prefix=\"(\", suffix=\")\") if _test: return sql_query db_cursor = self._db_cursor()", "isinstance(other, basestring): items = [other] elif isinstance(other, SQLQuery): items = other.items else: return", "or paramstyle in ['format', 'pyformat']: return '%s' raise UnknownParamstyle, paramstyle def sqlquery(self): return", "are appended to target instead of creating a new SQLQuery. \"\"\" if target", "if svars is None: svars = {} if not processed and not isinstance(sql_query,", "for some databases, a separate query has to be made to find #", "string should be evaled or not. from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee) \"\"\"", "created=SQLLiteral('NOW()'), vars=locals(), _test=True) >>> q <sql: \"UPDATE foo SET age = 2, name", "<sql: \"SELECT * FROM foo WHERE x = 'f'\"> \"\"\" if svars is", "1])) pos = dollar + 1 + (nextchar == \"$\") if pos <", "_ItplError(ValueError): def __init__(self, text, pos): ValueError.__init__(self) self.text = text self.pos = pos def", "$s\", dict(s=[1, 2])) <sql: 's IN (1, 2)'> \"\"\" dictionary = dictionary.copy() #", "and isinstance(obj, datetime.datetime): return repr(obj.isoformat()) else: if isinstance(obj, unicode): obj = obj.encode('utf8') return", "result.append(chunk) return SQLQuery.join(result, '') class UnknownParamstyle(Exception): \"\"\" raised for unsupported db paramstyles (currently", "string) where boolean says whether string should be evaled or not. from <http://lfw.org/python/Itpl.py>", "\"\"\" You can pass this sort of thing as a clause in any", "+= ' USING ' + sqllist(using) if where: q += ' WHERE '", "<sql: 'x'> >>> q = SQLQuery(['SELECT * FROM ', 'test', ' WHERE x=',", "can pass a dictionary to the keyword argument `vars` and the function will", "q1) self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor, sql_query) try: out = db_cursor.fetchone()[0] out = range(out-len(values)+1,", "SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query def _get_insert_default_values_query(self, table): return \"INSERT INTO %s DEFAULT VALUES\" %", "t is unicode: return obj elif t is str: return obj.decode(encoding) elif t", "FROM foo WHERE x = \" + sqlquote('f'), _test=True) <sql: \"SELECT * FROM", "If target argument is provided, the items are appended to target instead of", "name = 'bob', created = NOW() WHERE name = 'Joseph'\"> >>> q.query() 'UPDATE", "utf-8 encoded string. >>> safestr('hello') 'hello' >>> safestr(u'\\u1234') '\\xe1\\x88\\xb4' >>> safestr(2) '2' \"\"\"", "return ', '.join(lst) def _sqllist(values): \"\"\" >>> _sqllist([1, 2, 3]) <sql: '(1, 2,", "return _sqllist(a) else: return sqlparam(a).sqlquery() def _interpolate(sformat): \"\"\" Takes a format string and", "NotImplemented return SQLQuery(self.items + items) def __radd__(self, other): if isinstance(other, basestring): items =", "isinstance(x, SQLParam): x = x.get_marker(paramstyle) s.append(safestr(x)) else: x = safestr(x) # automatically escape", "b)'> If target argument is provided, the items are appended to target instead", "= dollar + 1 + (nextchar == \"$\") if pos < len(sformat): chunks.append((0,", "v in values.values()], ', ') sql_query = \"INSERT INTO %s \" % tablename", "= self._where(where, svars) query = ( \"UPDATE \" + sqllist(tables) + \" SET", "given object to utf-8 encoded string. >>> safestr('hello') 'hello' >>> safestr(u'\\u1234') '\\xe1\\x88\\xb4' >>>", "return safeunicode(self._str()) def __repr__(self): return '<sql: %s>' % repr(str(self)) class SQLLiteral: \"\"\" Protects", "has to be made to find # the id of the inserted row.", "= self._db_cursor() self._db_execute(db_cursor, query) if not self.ctx.transactions: self.ctx.commit() return db_cursor.rowcount def delete(self, table,", "self.items = list(items.items) else: self.items = [items] # Take care of SQLLiterals for", "multiple rows into `tablename`. The `values` must be a list of dictioanries, one", ">>> sqlify(None) 'NULL' >>> sqlify(True) \"'t'\" >>> sqlify(3) '3' \"\"\" # because `1", "'f'\"> \"\"\" if svars is None: svars = {} if not processed and", "isinstance(obj, datetime.datetime): return repr(obj.isoformat()) else: if isinstance(obj, unicode): obj = obj.encode('utf8') return repr(obj)", "pos + 1 < len(sformat) and sformat[pos + 1] in namechars: match, pos", "clause can be a SQLQuery. >>> db = DB(None, {}) >>> db.select('foo', _test=True)", "return self.query(qout, processed=True) def insert(self, tablename, seqname=None, _test=False, **values): \"\"\" Inserts `values` into", "t = type(obj) if t is unicode: return obj elif t is str:", "%s at char %d\" % ( repr(self.text), self.pos) class SQLParam(object): \"\"\" Parameter in", ">>> 'WHERE x = ' + sqlquote(True) + ' AND y = '", ">>> db.multiple_insert('person', values=values, _test=True) <sql: \"INSERT INTO person (name, email) VALUES ('foo', '<EMAIL>'),", "string and a dictionary and interpolates the string using values from the dictionary.", "of the inserted rows. Set `seqname` to the ID if it's not the", "isinstance(items, SQLQuery): self.items = list(items.items) else: self.items = [items] # Take care of", "== \"$\") if pos < len(sformat): chunks.append((0, sformat[pos:])) return chunks def sqlwhere(dictionary, grouping='", "* FROM test WHERE x=1'> >>> q.query(), q.values() ('SELECT * FROM test WHERE", "[1]) >>> SQLQuery(SQLParam(1)) <sql: '1'> \"\"\" if items is None: self.items = []", "tables, svars=None, what='*', where=None, order=None, group=None, limit=None, offset=None, _test=False): \"\"\" Selects `what` from", "'%%') s.append(x) return \"\".join(s) def values(self): \"\"\" Returns the values of the parameters", "self.text = text self.pos = pos def __str__(self): return \"unfinished expression in %s", ">>> SQLQuery.join(['a', 'b'], ', ') <sql: 'a, b'> Optinally, prefix and suffix arguments", "isinstance(val, (int, long)): if sql == 'WHERE': nout = 'id = ' +", "val is not None] qout = SQLQuery.join(clauses) if _test: return qout return self.query(qout,", "sql_query) try: out = db_cursor.fetchone()[0] out = range(out-len(values)+1, out+1) except Exception: out =", "sql_clauses(self, what, tables, where, group, order, limit, offset): return ( ('SELECT', what), ('FROM',", "sqlquote('NOW()') <sql: \"'NOW()'\"> >>> sqlquote(SQLLiteral('NOW()')) <sql: 'NOW()'> \"\"\" def __init__(self, v): self.v =", "used in the sql query. >>> q = SQLQuery([\"SELECT * FROM test WHERE", "(list, tuple)) and len(where) == 2: where = SQLQuery(where[0], where[1]) elif isinstance(where, SQLQuery):", "_interpolate(sformat): \"\"\" Takes a format string and returns a list of 2-tuples of", "SQLQuery. >>> q = SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam(\"joe\")]) >>> q", "inserted row. q1, q2 = sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor, sql_query)", "_test=True) >>> q <sql: \"INSERT INTO foo (age, name, created) VALUES (2, 'bob',", "= matchorfail(sformat, pos) tstart, tend = match.regs[3] token = sformat[tstart:tend] if token ==", "a WHERE clause. >>> sqllist(['a', 'b']) 'a, b' >>> sqllist('a') 'a' >>> sqllist(u'abc')", "FROM foo WHERE x = 'f'\"> \"\"\" if svars is None: svars =", "where, group, order, limit, offset): return ( ('SELECT', what), ('FROM', sqllist(tables)), ('WHERE', where),", "return NotImplemented return SQLQuery(self.items + items) def __radd__(self, other): if isinstance(other, basestring): items", "else: if isinstance(obj, unicode): obj = obj.encode('utf8') return repr(obj) def sqllist(lst): \"\"\" Converts", "if items is None: self.items = [] elif isinstance(items, list): self.items = items", "('bar', '<EMAIL>')\"> \"\"\" if not values: return [] if not self.supports_multiple_insert: out =", "sql_query db_cursor = self._db_cursor() if seqname is not False: sql_query = self._process_insert_query(sql_query, tablename,", "else: return str(obj).decode(encoding) def safestr(obj, encoding='utf-8'): r\"\"\" Converts any given object to utf-8", "svars is None: svars = {} sql_clauses = self.sql_clauses(what, tables, where, group, order,", "'b'], ', ', prefix='(', suffix=')') <sql: '(a, b)'> If target argument is provided,", "<sql: '(a, b)'> If target argument is provided, the items are appended to", "return sql_query db_cursor = self._db_cursor() if seqname is not False: sql_query = self._process_insert_query(sql_query,", "* FROM foo WHERE x = $x\", vars=dict(x='f'), _test=True) <sql: \"SELECT * FROM", "= SQLQuery.join([sqlparam(v) for v in values.values()], ', ') sql_query = \"INSERT INTO %s", "_test=True) <sql: \"SELECT * FROM foo WHERE x = 'f'\"> \"\"\" if svars", "where: q += ' WHERE ' + where return q sqlproducer = SQLProducer()", "s.append(x) return \"\".join(s) def values(self): \"\"\" Returns the values of the parameters used", "target instead of creating a new SQLQuery. \"\"\" if target is None: target", "target_items = target.items if prefix: target_items.append(prefix) for i, item in enumerate(items): if i", ">>> db = DB(None, {}) >>> name = 'Joe' >>> db.delete('foo', where='name =", "do this the hard way... if obj is None: return 'NULL' elif obj", "use in a SQL query. >>> 'WHERE x = ' + sqlquote(True) +", "sure all rows have same keys. for v in values: if v.keys() !=", "2, 3]) <sql: '(1, 2, 3)'> \"\"\" items = [] items.append('(') for i,", "\" + sqlparam(where) elif isinstance(where, (list, tuple)) and len(where) == 2: where =", "= 2'> >>> sqlwhere({'a': 'a', 'b': 'b'}).query() 'a = %s AND b =", "x + \")\" if values: _keys = SQLQuery.join(values.keys(), ', ') _values = SQLQuery.join([sqlparam(v)", ">>> safestr('hello') 'hello' >>> safestr(u'\\u1234') '\\xe1\\x88\\xb4' >>> safestr(2) '2' \"\"\" if isinstance(obj, unicode):", "is None: svars = {} where = self._where(where, svars) q = 'DELETE FROM", "'DELETE FROM ' + table if using: q += ' USING ' +", "the actual query. \"\"\" __slots__ = [\"items\"] # tested in sqlquote's docstring def", "db.query(\"SELECT * FROM foo WHERE x = \" + sqlquote('f'), _test=True) <sql: \"SELECT", "= SQLQuery(['SELECT * FROM ', 'test', ' WHERE x=', SQLParam(1)]) >>> q <sql:", "out = None if not self.ctx.transactions: self.ctx.commit() return out def update(self, tables, where,", "+ self.items) def __iadd__(self, other): if isinstance(other, (basestring, SQLParam)): self.items.append(other) elif isinstance(other, SQLQuery):", "[] items.append('(') for i, v in enumerate(values): if i != 0: items.append(', ')", "created=SQLLiteral('NOW()'), _test=True) >>> q <sql: \"INSERT INTO foo (age, name, created) VALUES (2,", "1 elif token == \"}\": level = level - 1 chunks.append((1, sformat[dollar +", "(int, long)): where = \"id = \" + sqlparam(where) elif isinstance(where, (list, tuple))", "'WHERE x = ' + sqlquote(True) + ' AND y IN ' +", "type(obj) if t is unicode: return obj elif t is str: return obj.decode(encoding)", "(currently supported: qmark, numeric, format, pyformat) \"\"\" pass class _ItplError(ValueError): def __init__(self, text,", "`a` is quoted properly for use in a SQL query. >>> 'WHERE x", "LIMIT 5'> \"\"\" if svars is None: svars = {} sql_clauses = self.sql_clauses(what,", "SQLProducer: \"\"\"Database\"\"\" def __init__(self): \"\"\"Creates a database. \"\"\" pass def query(self, sql_query,processed=False, svars=None):", "else: return out keys = values[0].keys() #@@ make sure all keys are valid", "return itertools.imap(safestr, obj) else: return str(obj) def sqlify(obj): \"\"\" converts `obj` to its", "repr(obj) def sqllist(lst): \"\"\" Converts the arguments for use in something like a", "FROM ', 'test', ' WHERE x=', SQLParam(1)]) >>> q <sql: 'SELECT * FROM", "form (boolean, string) where boolean says whether string should be evaled or not.", "\"$\") if pos < len(sformat): chunks.append((0, sformat[pos:])) return chunks def sqlwhere(dictionary, grouping=' AND", "@author: lan (www.9miao.com) ''' import itertools import datetime def safeunicode(obj, encoding='utf-8'): r\"\"\" Converts", "= x.get_marker(paramstyle) s.append(safestr(x)) else: x = safestr(x) # automatically escape % characters in", "in namechars: chunks.append((0, sformat[pos:dollar])) match, pos = matchorfail(sformat, dollar + 1) while pos", "foo (age, name, created) VALUES (%s, %s, NOW())' >>> q.values() [2, 'bob'] \"\"\"", "True >>> values = [{\"name\": \"foo\", \"email\": \"<EMAIL>\"}, {\"name\": \"bar\", \"email\": \"<EMAIL>\"}] >>>", "default, or to `False` if there isn't one. >>> db = DB(None, {})", "1 + (nextchar == \"$\") if pos < len(sformat): chunks.append((0, sformat[pos:])) return chunks", "= db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'), _test=True) >>> q <sql: \"INSERT INTO foo (age,", "db_cursor = self._db_cursor() if seqname is not False: sql_query = self._process_insert_query(sql_query, tablename, seqname)", "= %s, created = NOW() WHERE name = %s' >>> q.values() [2, 'bob',", "q = 'DELETE FROM ' + table if using: q += ' USING", "name=\", SQLParam('joe')]) >>> q.query() 'SELECT * FROM test WHERE name=%s' >>> q.query(paramstyle='qmark') 'SELECT", "self._where(where, svars) q = 'DELETE FROM ' + table if using: q +=", "match = tokenprog.match(text, pos) if match is None: raise _ItplError(text, pos) return match,", "other): return self.sqlquery() + other def __radd__(self, other): return other + self.sqlquery() def", "3 AND cust_id = 2'> >>> sqlwhere({'cust_id': 2, 'order_id':3}, grouping=', ') <sql: 'order_id", "# automatically escape % characters in the query # For backward compatability, ignore", "* FROM foo, bar WHERE foo.bar_id = bar.id LIMIT 5'> \"\"\" if svars", "a list of dictioanries, one for each row to be inserted, each with", "'pyformat']: if '%' in x and '%%' not in x: x = x.replace('%',", "= safestr(x) # automatically escape % characters in the query # For backward", "INTO %s DEFAULT VALUES\" % table def multiple_insert(self, tablename, values, seqname=None, _test=False): \"\"\"", "UnknownParamstyle, paramstyle def sqlquery(self): return SQLQuery([self]) def __add__(self, other): return self.sqlquery() + other", "queries. >>> SQLQuery.join(['a', 'b'], ', ') <sql: 'a, b'> Optinally, prefix and suffix", "keys: raise ValueError, 'Bad data' sql_query = SQLQuery('INSERT INTO %s (%s) VALUES '", ">>> name = 'Joseph' >>> q = db.update('foo', where='name = $name', name='bob', age=2,", "not self.supports_multiple_insert: out = [self.insert(tablename, seqname=seqname, _test=_test, **v) for v in values] if", "class UnknownParamstyle(Exception): \"\"\" raised for unsupported db paramstyles (currently supported: qmark, numeric, format,", "argument is provided, the items are appended to target instead of creating a", "Update `tables` with clause `where` (interpolated using `vars`) and setting `values`. >>> db", "not the default, or to `False` if there isn't one. >>> db =", "* FROM test WHERE name=?' \"\"\" s = [] for x in self.items:", "from `tables` with clauses `where`, `order`, `group`, `limit`, and `offset`. Uses vars to", "None if not self.ctx.transactions: self.ctx.commit() return out def update(self, tables, where, svars=None, _test=False,", "svars) def xjoin(a, b): if a and b: return a + ' '", "on 2013-8-21 @author: lan (www.9miao.com) ''' import itertools import datetime def safeunicode(obj, encoding='utf-8'):", "elif nextchar in namechars: chunks.append((0, sformat[pos:dollar])) match, pos = matchorfail(sformat, dollar + 1)", "and isinstance(item.value, SQLLiteral): self.items[i] = item.value.v def append(self, value): self.items.append(value) def __add__(self, other):", "NOW() WHERE name = 'Joseph'\"> >>> q.query() 'UPDATE foo SET age = %s,", "thing as a clause in any db function. Otherwise, you can pass a", "= level + 1 elif token[0] in \")]\": level = level - 1", "SQLQuery.join(result, '') class UnknownParamstyle(Exception): \"\"\" raised for unsupported db paramstyles (currently supported: qmark,", "token[0] in \")]\": level = level - 1 else: break chunks.append((1, sformat[dollar +", "sql_query def _get_insert_default_values_query(self, table): return \"INSERT INTO %s DEFAULT VALUES\" % table def", "+ 2:pos - 1])) elif nextchar in namechars: chunks.append((0, sformat[pos:dollar])) match, pos =", "x = x.replace('%', '%%') s.append(x) return \"\".join(s) def values(self): \"\"\" Returns the values", "+ 1:pos])) else: chunks.append((0, sformat[pos:dollar + 1])) pos = dollar + 1 +", "2013-8-21 @author: lan (www.9miao.com) ''' import itertools import datetime def safeunicode(obj, encoding='utf-8'): r\"\"\"", "function. Otherwise, you can pass a dictionary to the keyword argument `vars` and", "foo\", _test=True) <sql: 'SELECT * FROM foo'> >>> db.query(\"SELECT * FROM foo WHERE", "x = safestr(x) # automatically escape % characters in the query # For", "limit), ('OFFSET', offset)) def gen_clause(self, sql, val, svars): if isinstance(val, (int, long)): if", "token == \"}\": level = level - 1 chunks.append((1, sformat[dollar + 2:pos -", "SQLParam): x = x.get_marker(paramstyle) s.append(safestr(x)) else: x = safestr(x) # automatically escape %", "SQLQuery(where[0], where[1]) elif isinstance(where, SQLQuery): pass else: where = reparam(where, svars) return where", "INTO person (name, email) VALUES ('foo', '<EMAIL>'), ('bar', '<EMAIL>')\"> \"\"\" if not values:", ">>> q = SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam('joe')]) >>> q.values() ['joe']", "in namechars: match, pos = matchorfail(sformat, pos + 1) elif sformat[pos] in \"([\":", "return \"'t'\" elif obj is False: return \"'f'\" elif datetime and isinstance(obj, datetime.datetime):", "_test=False, **values): \"\"\" Inserts `values` into `tablename`. Returns current sequence ID. Set `seqname`", "__iadd__(self, other): if isinstance(other, (basestring, SQLParam)): self.items.append(other) elif isinstance(other, SQLQuery): self.items.extend(other.items) else: return", "pos) tstart, tend = match.regs[3] token = sformat[tstart:tend] if token[0] in \"([\": level", "= 0 while 1: dollar = sformat.find(\"$\", pos) if dollar < 0: break", "isinstance(val, (list, tuple)) and len(val) == 2: nout = SQLQuery(val[0], val[1]) # backwards-compatibility", "of ids of the inserted rows. Set `seqname` to the ID if it's", "isn't one. >>> db = DB(None, {}) >>> q = db.insert('foo', name='bob', age=2,", "\"\"\" def q(x): return \"(\" + x + \")\" if values: _keys =", "any db function. Otherwise, you can pass a dictionary to the keyword argument", "foo WHERE name = 'Joe'\"> \"\"\" if svars is None: svars = {}", "is unicode: return obj elif t is str: return obj.decode(encoding) elif t in", "xjoin(sql, nout) def _where(self, where, svars): if isinstance(where, (int, long)): where = \"id", "\" + where) if _test: return query db_cursor = self._db_cursor() self._db_execute(db_cursor, query) if", "!= 0: target_items.append(sep) if isinstance(item, SQLQuery): target_items.extend(item.items) else: target_items.append(item) if suffix: target_items.append(suffix) return", "self._db_execute(db_cursor, query) if not self.ctx.transactions: self.ctx.commit() return db_cursor.rowcount def delete(self, table, where, using=None,", "svars): if isinstance(where, (int, long)): where = \"id = \" + sqlparam(where) elif", "chunks def sqlwhere(dictionary, grouping=' AND '): \"\"\" Converts a `dictionary` to an SQL", "and '%%' not in x: x = x.replace('%', '%%') s.append(x) return \"\".join(s) def", "there isn't one. >>> db = DB(None, {}) >>> q = db.insert('foo', name='bob',", "isn't one. >>> db = DB(None, {}) >>> db.supports_multiple_insert = True >>> values", "range(out-len(values)+1, out+1) except Exception: out = None if not self.ctx.transactions: self.ctx.commit() return out", "'b']) 'a, b' >>> sqllist('a') 'a' >>> sqllist(u'abc') u'abc' \"\"\" if isinstance(lst, basestring):", "in dictionary.items()], grouping) def reparam(string_, dictionary): \"\"\" Takes a string and a dictionary", "__add__(self, other): if isinstance(other, basestring): items = [other] elif isinstance(other, SQLQuery): items =", "5'> \"\"\" if svars is None: svars = {} sql_clauses = self.sql_clauses(what, tables,", "= [items] elif isinstance(items, SQLQuery): self.items = list(items.items) else: self.items = [items] #", "a string from `sqlquote`. >>> sqlquote('NOW()') <sql: \"'NOW()'\"> >>> sqlquote(SQLLiteral('NOW()')) <sql: 'NOW()'> \"\"\"", "\", target=sql_query, prefix=\"(\", suffix=\")\") if _test: return sql_query db_cursor = self._db_cursor() if seqname", "level + 1 elif token[0] in \")]\": level = level - 1 else:", "\"\"\" __slots__ = [\"items\"] # tested in sqlquote's docstring def __init__(self, items=None): r\"\"\"Creates", "- 1])) elif nextchar in namechars: chunks.append((0, sformat[pos:dollar])) match, pos = matchorfail(sformat, dollar", "{}) >>> db.select('foo', _test=True) <sql: 'SELECT * FROM foo'> >>> db.select(['foo', 'bar'], where=\"foo.bar_id", "a clause in any db function. Otherwise, you can pass a dictionary to", "datetime.datetime): return repr(obj.isoformat()) else: if isinstance(obj, unicode): obj = obj.encode('utf8') return repr(obj) def", "AND y IN ' + sqlquote([2, 3]) <sql: \"WHERE x = 't' AND", "as a clause in any db function. Otherwise, you can pass a dictionary", "group, order, limit, offset) clauses = [self.gen_clause(sql, val, svars) for sql, val in", "def sqllist(lst): \"\"\" Converts the arguments for use in something like a WHERE", "clauses = [self.gen_clause(sql, val, svars) for sql, val in sql_clauses if val is", "def __init__(self, text, pos): ValueError.__init__(self) self.text = text self.pos = pos def __str__(self):", "target = SQLQuery() target_items = target.items if prefix: target_items.append(prefix) for i, item in", "isinstance(where, SQLQuery): pass else: where = reparam(where, svars) return where def select(self, tables,", "+ 1) while pos < len(sformat): if sformat[pos] == \".\" and \\ pos", "<sql: \"s = 't'\"> >>> reparam(\"s IN $s\", dict(s=[1, 2])) <sql: 's IN", "def sqlify(obj): \"\"\" converts `obj` to its proper SQL version >>> sqlify(None) 'NULL'", "pos < len(sformat): if sformat[pos] == \".\" and \\ pos + 1 <", "\\ pos + 1 < len(sformat) and sformat[pos + 1] in namechars: match,", "class _ItplError(ValueError): def __init__(self, text, pos): ValueError.__init__(self) self.text = text self.pos = pos", "safeunicode(self._str()) def __repr__(self): return '<sql: %s>' % repr(str(self)) class SQLLiteral: \"\"\" Protects a", "# For backward compatability, ignore escaping when the query looks already escaped if", "SQLLiteral: \"\"\" Protects a string from `sqlquote`. >>> sqlquote('NOW()') <sql: \"'NOW()'\"> >>> sqlquote(SQLLiteral('NOW()'))", "isinstance(other, SQLQuery): items = other.items else: return NotImplemented return SQLQuery(self.items + items) def", "group, order, limit, offset): return ( ('SELECT', what), ('FROM', sqllist(tables)), ('WHERE', where), ('GROUP", "`what` from `tables` with clauses `where`, `order`, `group`, `limit`, and `offset`. Uses vars", "return ( ('SELECT', what), ('FROM', sqllist(tables)), ('WHERE', where), ('GROUP BY', group), ('ORDER BY',", "multiple queries. >>> SQLQuery.join(['a', 'b'], ', ') <sql: 'a, b'> Optinally, prefix and", "('OFFSET', offset)) def gen_clause(self, sql, val, svars): if isinstance(val, (int, long)): if sql", "SQL version >>> sqlify(None) 'NULL' >>> sqlify(True) \"'t'\" >>> sqlify(3) '3' \"\"\" #", "keys = values[0].keys() #@@ make sure all keys are valid # make sure", "'INSERT INTO foo (age, name, created) VALUES (%s, %s, NOW())' >>> q.values() [2,", "isinstance(where, (int, long)): where = \"id = \" + sqlparam(where) elif isinstance(where, (list,", "you can pass a dictionary to the keyword argument `vars` and the function", "_test: return qout return self.query(qout, processed=True) def insert(self, tablename, seqname=None, _test=False, **values): \"\"\"", "DB(None, {}) >>> name = 'Joe' >>> db.delete('foo', where='name = $name', vars=locals(), _test=True)", "Parameter in SQLQuery. >>> q = SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam(\"joe\")])", "in ['format', 'pyformat']: if '%' in x and '%%' not in x: x", "self.v = v def __repr__(self): return self.v class SQLProducer: \"\"\"Database\"\"\" def __init__(self): \"\"\"Creates", "SQLParam): self.items = [items] elif isinstance(items, SQLQuery): self.items = list(items.items) else: self.items =", "s.append(safestr(x)) else: x = safestr(x) # automatically escape % characters in the query", "[] for x in self.items: if isinstance(x, SQLParam): x = x.get_marker(paramstyle) s.append(safestr(x)) else:", "obj is True: return \"'t'\" elif obj is False: return \"'f'\" elif datetime", "for i, item in enumerate(items): if i != 0: target_items.append(sep) if isinstance(item, SQLQuery):", "the result. >>> reparam(\"s = $s\", dict(s=True)) <sql: \"s = 't'\"> >>> reparam(\"s", "def gen_clause(self, sql, val, svars): if isinstance(val, (int, long)): if sql == 'WHERE':", "return xjoin(sql, nout) def _where(self, where, svars): if isinstance(where, (int, long)): where =", "FROM foo'> >>> db.select(['foo', 'bar'], where=\"foo.bar_id = bar.id\", limit=5, _test=True) <sql: 'SELECT *", "elif isinstance(items, SQLQuery): self.items = list(items.items) else: self.items = [items] # Take care", "_keys = SQLQuery.join(values.keys(), ', ') _values = SQLQuery.join([sqlparam(v) for v in values.values()], ',", "group=None, limit=None, offset=None, _test=False): \"\"\" Selects `what` from `tables` with clauses `where`, `order`,", "'WHERE': nout = 'id = ' + sqlquote(val) else: nout = SQLQuery(val) elif", "_sqllist([1, 2, 3]) <sql: '(1, 2, 3)'> \"\"\" items = [] items.append('(') for", "not isinstance(sql_query, SQLQuery): sql_query = reparam(sql_query, svars) return sql_query def sql_clauses(self, what, tables,", "\"\"\" return [i.value for i in self.items if isinstance(i, SQLParam)] def join(items, sep='", "and sformat[pos + 1] in namechars: match, pos = matchorfail(sformat, pos + 1)", "list of 2-tuples of the form (boolean, string) where boolean says whether string", "boolean says whether string should be evaled or not. from <http://lfw.org/python/Itpl.py> (public domain,", "+ 1] in namechars: match, pos = matchorfail(sformat, pos + 1) elif sformat[pos]", "DB(None, {}) >>> db.supports_multiple_insert = True >>> values = [{\"name\": \"foo\", \"email\": \"<EMAIL>\"},", "out = range(out-len(values)+1, out+1) except Exception: out = None if not self.ctx.transactions: self.ctx.commit()", "target=sql_query, prefix=\"(\", suffix=\")\") if _test: return sql_query db_cursor = self._db_cursor() if seqname is", "in values.values()], ', ') sql_query = \"INSERT INTO %s \" % tablename +", "pass a dictionary to the keyword argument `vars` and the function will call", "3\"> >>> 'WHERE x = ' + sqlquote(True) + ' AND y IN", "test WHERE name=\", SQLParam('joe')]) >>> q.query() 'SELECT * FROM test WHERE name=%s' >>>", "def sql_clauses(self, what, tables, where, group, order, limit, offset): return ( ('SELECT', what),", "table): return \"INSERT INTO %s DEFAULT VALUES\" % table def multiple_insert(self, tablename, values,", "foo SET age = %s, name = %s, created = NOW() WHERE name", "x: x = x.replace('%', '%%') s.append(x) return \"\".join(s) def values(self): \"\"\" Returns the", "for sql, val in sql_clauses if val is not None] qout = SQLQuery.join(clauses)", ">>> reparam(\"s IN $s\", dict(s=[1, 2])) <sql: 's IN (1, 2)'> \"\"\" dictionary", "__init__(self, items=None): r\"\"\"Creates a new SQLQuery. >>> SQLQuery(\"x\") <sql: 'x'> >>> q =", "elif sformat[pos] in \"([\": pos, level = pos + 1, 1 while level:", "\"([\": level = level + 1 elif token[0] in \")]\": level = level", "get_marker(self, paramstyle='pyformat'): if paramstyle == 'qmark': return '?' elif paramstyle == 'numeric': return", "'bar'], where=\"foo.bar_id = bar.id\", limit=5, _test=True) <sql: 'SELECT * FROM foo, bar WHERE", "SQLLiterals for i, item in enumerate(self.items): if isinstance(item, SQLParam) and isinstance(item.value, SQLLiteral): self.items[i]", "= v def __repr__(self): return self.v class SQLProducer: \"\"\"Database\"\"\" def __init__(self): \"\"\"Creates a", "one. >>> db = DB(None, {}) >>> db.supports_multiple_insert = True >>> values =", "a format string and returns a list of 2-tuples of the form (boolean,", "not. from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee) \"\"\" from tokenize import tokenprog tokenprog", "2, 3)'> \"\"\" items = [] items.append('(') for i, v in enumerate(values): if", "name=%s' >>> q.values() ['joe'] \"\"\" __slots__ = [\"value\"] def __init__(self, value): self.value =", "tokenprog tokenprog = tokenprog def matchorfail(text, pos): match = tokenprog.match(text, pos) if match", "% repr(str(self)) class SQLLiteral: \"\"\" Protects a string from `sqlquote`. >>> sqlquote('NOW()') <sql:", "\"UPDATE foo SET age = 2, name = 'bob', created = NOW() WHERE", "= %s AND b = %s' \"\"\" return SQLQuery.join([k + ' = '", "qout return self.query(qout, processed=True) def insert(self, tablename, seqname=None, _test=False, **values): \"\"\" Inserts `values`", "1 while level: match, pos = matchorfail(sformat, pos) tstart, tend = match.regs[3] token", "cust_id = 2'> >>> sqlwhere({'cust_id': 2, 'order_id':3}, grouping=', ') <sql: 'order_id = 3,", "items is None: self.items = [] elif isinstance(items, list): self.items = items elif", "must be a list of dictioanries, one for each row to be inserted,", "encoded string. >>> safestr('hello') 'hello' >>> safestr(u'\\u1234') '\\xe1\\x88\\xb4' >>> safestr(2) '2' \"\"\" if", "test WHERE name=\", SQLParam('joe')]) >>> q.values() ['joe'] \"\"\" return [i.value for i in", "') sql_query = \"INSERT INTO %s \" % tablename + q(_keys) + '", "isinstance(other, basestring): items = [other] else: return NotImplemented return SQLQuery(items + self.items) def", "') items.append(sqlparam(v)) items.append(')') return SQLQuery(items) def sqlquote(a): \"\"\" Ensures `a` is quoted properly", "__init__(self, text, pos): ValueError.__init__(self) self.text = text self.pos = pos def __str__(self): return", "else: where = reparam(where, svars) return where def select(self, tables, svars=None, what='*', where=None,", "sqllist(using) if where: q += ' WHERE ' + where return q sqlproducer", "value): self.items.append(value) def __add__(self, other): if isinstance(other, basestring): items = [other] elif isinstance(other,", "= matchorfail(sformat, pos) tstart, tend = match.regs[3] token = sformat[tstart:tend] if token[0] in", "live, chunk in _interpolate(string_): if live: v = eval(chunk, dictionary) result.append(sqlquote(v)) else: result.append(chunk)", "\"\"\"Creates a database. \"\"\" pass def query(self, sql_query,processed=False, svars=None): \"\"\" Execute SQL query", "= self.sql_clauses(what, tables, where, group, order, limit, offset) clauses = [self.gen_clause(sql, val, svars)", "argument `vars` and the function will call reparam for you. Internally, consists of", "foo WHERE x = 'f'\"> >>> db.query(\"SELECT * FROM foo WHERE x =", "the form (boolean, string) where boolean says whether string should be evaled or", "b): if a and b: return a + ' ' + b else:", "offset)) def gen_clause(self, sql, val, svars): if isinstance(val, (int, long)): if sql ==", "q(x): return \"(\" + x + \")\" if values: _keys = SQLQuery.join(values.keys(), ',", "values: if v.keys() != keys: raise ValueError, 'Bad data' sql_query = SQLQuery('INSERT INTO", "= %s' >>> q.values() [2, 'bob', 'Joseph'] \"\"\" if svars is None: svars", "level = level - 1 else: break chunks.append((1, sformat[dollar + 1:pos])) else: chunks.append((0,", "db_cursor = self._db_cursor() self._db_execute(db_cursor, query) if not self.ctx.transactions: self.ctx.commit() return db_cursor.rowcount def delete(self,", "tend = match.regs[3] token = sformat[tstart:tend] if token == \"{\": level = level", "out+1) except Exception: out = None if not self.ctx.transactions: self.ctx.commit() return out def", "return '<sql: %s>' % repr(str(self)) class SQLLiteral: \"\"\" Protects a string from `sqlquote`.", "nextchar in namechars: chunks.append((0, sformat[pos:dollar])) match, pos = matchorfail(sformat, dollar + 1) while", "tokenprog = tokenprog def matchorfail(text, pos): match = tokenprog.match(text, pos) if match is", "('SELECT * FROM test WHERE x=%s', [1]) >>> SQLQuery(SQLParam(1)) <sql: '1'> \"\"\" if", "b = %s' \"\"\" return SQLQuery.join([k + ' = ' + sqlparam(v) for", "('foo', '<EMAIL>'), ('bar', '<EMAIL>')\"> \"\"\" if not values: return [] if not self.supports_multiple_insert:", "the list of ids of the inserted rows. Set `seqname` to the ID", "self.items[i] = item.value.v def append(self, value): self.items.append(value) def __add__(self, other): if isinstance(other, basestring):", "where def select(self, tables, svars=None, what='*', where=None, order=None, group=None, limit=None, offset=None, _test=False): \"\"\"", "some databases, a separate query has to be made to find # the", "'a', 'b': 'b'}).query() 'a = %s AND b = %s' \"\"\" return SQLQuery.join([k", "enumerate(self.items): if isinstance(item, SQLParam) and isinstance(item.value, SQLLiteral): self.items[i] = item.value.v def append(self, value):", "age=2, ... created=SQLLiteral('NOW()'), vars=locals(), _test=True) >>> q <sql: \"UPDATE foo SET age =", "return safestr(self._str()) def __unicode__(self): return safeunicode(self._str()) def __repr__(self): return '<sql: %s>' % repr(str(self))", "of thing as a clause in any db function. Otherwise, you can pass", "one for each row to be inserted, each with the same set of", "v = eval(chunk, dictionary) result.append(sqlquote(v)) else: result.append(chunk) return SQLQuery.join(result, '') class UnknownParamstyle(Exception): \"\"\"", "elif isinstance(val, SQLQuery): nout = val else: nout = reparam(val, svars) def xjoin(a,", "set of keys. Returns the list of ids of the inserted rows. Set", "q = SQLQuery(['SELECT * FROM ', 'test', ' WHERE x=', SQLParam(1)]) >>> q", "{} where = self._where(where, svars) query = ( \"UPDATE \" + sqllist(tables) +", "None or paramstyle in ['format', 'pyformat']: return '%s' raise UnknownParamstyle, paramstyle def sqlquery(self):", "return qout return self.query(qout, processed=True) def insert(self, tablename, seqname=None, _test=False, **values): \"\"\" Inserts", "= [items] # Take care of SQLLiterals for i, item in enumerate(self.items): if", "return self.query() def __str__(self): return safestr(self._str()) def __unicode__(self): return safeunicode(self._str()) def __repr__(self): return", "len(val) == 2: nout = SQLQuery(val[0], val[1]) # backwards-compatibility elif isinstance(val, SQLQuery): nout", "= SQLQuery(val[0], val[1]) # backwards-compatibility elif isinstance(val, SQLQuery): nout = val else: nout", "is None: return 'NULL' elif obj is True: return \"'t'\" elif obj is", "* FROM test WHERE name=%s' >>> q.query(paramstyle='qmark') 'SELECT * FROM test WHERE name=?'", "name=\", SQLParam(\"joe\")]) >>> q <sql: \"SELECT * FROM test WHERE name='joe'\"> >>> q.query()", "['format', 'pyformat']: return '%s' raise UnknownParamstyle, paramstyle def sqlquery(self): return SQLQuery([self]) def __add__(self,", "def query(self, sql_query,processed=False, svars=None): \"\"\" Execute SQL query `sql_query` using dictionary `vars` to", "+ sqlquote([2, 3]) <sql: \"WHERE x = 't' AND y IN (2, 3)\">", "return a or b return xjoin(sql, nout) def _where(self, where, svars): if isinstance(where,", "sqlwhere(values, ', ') + \" WHERE \" + where) if _test: return query", "v in dictionary.items()], grouping) def reparam(string_, dictionary): \"\"\" Takes a string and a", "nout = 'id = ' + sqlquote(val) else: nout = SQLQuery(val) elif isinstance(val,", "\"\"\" if svars is None: svars = {} where = self._where(where, svars) query", "'a = %s AND b = %s' \"\"\" return SQLQuery.join([k + ' =", "of interpolating. >>> db = DB(None, {}) >>> db.query(\"SELECT * FROM foo\", _test=True)", "= bar.id LIMIT 5'> \"\"\" if svars is None: svars = {} sql_clauses", "Set `seqname` to the ID if it's not the default, or to `False`", "self.items: if isinstance(x, SQLParam): x = x.get_marker(paramstyle) s.append(safestr(x)) else: x = safestr(x) #", "be made to find # the id of the inserted row. q1, q2", "%s, created = NOW() WHERE name = %s' >>> q.values() [2, 'bob', 'Joseph']", "\"'f'\" elif datetime and isinstance(obj, datetime.datetime): return repr(obj.isoformat()) else: if isinstance(obj, unicode): obj", "else: return NotImplemented return self def __len__(self): return len(self.query()) def query(self, paramstyle=None): \"\"\"", "and suffix arguments can be provided. >>> SQLQuery.join(['a', 'b'], ', ', prefix='(', suffix=')')", "'Joseph'\"> >>> q.query() 'UPDATE foo SET age = %s, name = %s, created", "# tested in sqlquote's docstring def __init__(self, items=None): r\"\"\"Creates a new SQLQuery. >>>", "level = level - 1 chunks.append((1, sformat[dollar + 2:pos - 1])) elif nextchar", "if where: q += ' WHERE ' + where return q sqlproducer =", ">>> SQLQuery(SQLParam(1)) <sql: '1'> \"\"\" if items is None: self.items = [] elif", "= 'bob', created = NOW() WHERE name = 'Joseph'\"> >>> q.query() 'UPDATE foo", "values, seqname=None, _test=False): \"\"\" Inserts multiple rows into `tablename`. The `values` must be", "pos = matchorfail(sformat, pos) tstart, tend = match.regs[3] token = sformat[tstart:tend] if token[0]", "sqllist(tables)), ('WHERE', where), ('GROUP BY', group), ('ORDER BY', order), ('LIMIT', limit), ('OFFSET', offset))", "None: self.items = [] elif isinstance(items, list): self.items = items elif isinstance(items, SQLParam):", "in self.items if isinstance(i, SQLParam)] def join(items, sep=' ', prefix=None, suffix=None, target=None): \"\"\"", "= [self.gen_clause(sql, val, svars) for sql, val in sql_clauses if val is not", ">>> sqlquote(SQLLiteral('NOW()')) <sql: 'NOW()'> \"\"\" def __init__(self, v): self.v = v def __repr__(self):", "new SQLQuery. \"\"\" if target is None: target = SQLQuery() target_items = target.items", "and interpolates the string using values from the dictionary. Returns an `SQLQuery` for", "\"\"\" if svars is None: svars = {} if not processed and not", "\"\"\" Takes a string and a dictionary and interpolates the string using values", "+ ' AND y IN ' + sqlquote([2, 3]) <sql: \"WHERE x =", "sformat[pos] == \".\" and \\ pos + 1 < len(sformat) and sformat[pos +", "Joins multiple queries. >>> SQLQuery.join(['a', 'b'], ', ') <sql: 'a, b'> Optinally, prefix", ">>> q.query(), q.values() ('SELECT * FROM test WHERE x=%s', [1]) >>> SQLQuery(SQLParam(1)) <sql:", "vars=locals(), _test=True) >>> q <sql: \"UPDATE foo SET age = 2, name =", "def __add__(self, other): return self.sqlquery() + other def __radd__(self, other): return other +", "chunks.append((0, sformat[pos:dollar])) pos, level = dollar + 2, 1 while level: match, pos", "(age, name, created) VALUES (2, 'bob', NOW())\"> >>> q.query() 'INSERT INTO foo (age,", "(name, email) VALUES ('foo', '<EMAIL>'), ('bar', '<EMAIL>')\"> \"\"\" if not values: return []", "\"INSERT INTO %s \" % tablename + q(_keys) + ' VALUES ' +", "iterator return itertools.imap(safestr, obj) else: return str(obj) def sqlify(obj): \"\"\" converts `obj` to", "isinstance(i, SQLParam)] def join(items, sep=' ', prefix=None, suffix=None, target=None): \"\"\" Joins multiple queries.", "= bar.id\", limit=5, _test=True) <sql: 'SELECT * FROM foo, bar WHERE foo.bar_id =", "dictionary and interpolates the string using values from the dictionary. Returns an `SQLQuery`", "= 'id = ' + sqlquote(val) else: nout = SQLQuery(val) elif isinstance(val, (list,", "[] for live, chunk in _interpolate(string_): if live: v = eval(chunk, dictionary) result.append(sqlquote(v))", "', 'test', ' WHERE x=', SQLParam(1)]) >>> q <sql: 'SELECT * FROM test", "elif paramstyle == 'numeric': return ':1' elif paramstyle is None or paramstyle in", "return self.sqlquery() + other def __radd__(self, other): return other + self.sqlquery() def __str__(self):", "svars=None): \"\"\" Execute SQL query `sql_query` using dictionary `vars` to interpolate it. If", "in \"([\": level = level + 1 elif token[0] in \")]\": level =", "def update(self, tables, where, svars=None, _test=False, **values): \"\"\" Update `tables` with clause `where`", "= ( \"UPDATE \" + sqllist(tables) + \" SET \" + sqlwhere(values, ',", "SQLQuery([self]) def __add__(self, other): return self.sqlquery() + other def __radd__(self, other): return other", "to `False` if there isn't one. >>> db = DB(None, {}) >>> q", "item in enumerate(self.items): if isinstance(item, SQLParam) and isinstance(item.value, SQLLiteral): self.items[i] = item.value.v def", "sql_query = self._process_insert_query(sql_query, tablename, seqname) if isinstance(sql_query, tuple): # for some databases, a", "\"\"\" from tokenize import tokenprog tokenprog = tokenprog def matchorfail(text, pos): match =", "__str__(self): return \"unfinished expression in %s at char %d\" % ( repr(self.text), self.pos)", "i != 0: items.append(', ') items.append(sqlparam(v)) items.append(')') return SQLQuery(items) def sqlquote(a): \"\"\" Ensures", "return self.v class SQLProducer: \"\"\"Database\"\"\" def __init__(self): \"\"\"Creates a database. \"\"\" pass def", "= \"abcdefghijklmnopqrstuvwxyz\" \\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks = [] pos = 0 while 1: dollar", "reparam(where, svars) return where def select(self, tables, svars=None, what='*', where=None, order=None, group=None, limit=None,", ">>> sqllist(u'abc') u'abc' \"\"\" if isinstance(lst, basestring): return lst else: return ', '.join(lst)", "SQLQuery(['SELECT * FROM ', 'test', ' WHERE x=', SQLParam(1)]) >>> q <sql: 'SELECT", "else: x = safestr(x) # automatically escape % characters in the query #", "(www.9miao.com) ''' import itertools import datetime def safeunicode(obj, encoding='utf-8'): r\"\"\" Converts any given", "seqname=seqname, _test=_test, **v) for v in values] if seqname is False: return None", "return str(obj) def sqlify(obj): \"\"\" converts `obj` to its proper SQL version >>>", "Take care of SQLLiterals for i, item in enumerate(self.items): if isinstance(item, SQLParam) and", "class SQLParam(object): \"\"\" Parameter in SQLQuery. >>> q = SQLQuery([\"SELECT * FROM test", "3, cust_id = 2'> >>> sqlwhere({'a': 'a', 'b': 'b'}).query() 'a = %s AND", "_where(self, where, svars): if isinstance(where, (int, long)): where = \"id = \" +", "+ ' AND y = ' + sqlquote(3) <sql: \"WHERE x = 't'", "2: nout = SQLQuery(val[0], val[1]) # backwards-compatibility elif isinstance(val, SQLQuery): nout = val", "'test', ' WHERE x=', SQLParam(1)]) >>> q <sql: 'SELECT * FROM test WHERE", "items = [other] elif isinstance(other, SQLQuery): items = other.items else: return NotImplemented return", "the items are appended to target instead of creating a new SQLQuery. \"\"\"", "'3' \"\"\" # because `1 == True and hash(1) == hash(True)` # we", "repr(self.text), self.pos) class SQLParam(object): \"\"\" Parameter in SQLQuery. >>> q = SQLQuery([\"SELECT *", "= values[0].keys() #@@ make sure all keys are valid # make sure all", "v in values] if seqname is False: return None else: return out keys", "if i != 0: target_items.append(sep) if isinstance(item, SQLQuery): target_items.extend(item.items) else: target_items.append(item) if suffix:", "in enumerate(values): if i != 0: sql_query.append(\", \") SQLQuery.join([SQLParam(row[k]) for k in keys],", "elif isinstance(other, SQLQuery): self.items.extend(other.items) else: return NotImplemented return self def __len__(self): return len(self.query())", "`seqname` to the ID if it's not the default, or to `False` if", "values] if seqname is False: return None else: return out keys = values[0].keys()", "`order`, `group`, `limit`, and `offset`. Uses vars to interpolate. Otherwise, each clause can", "if svars is None: svars = {} where = self._where(where, svars) query =", "evaled or not. from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee) \"\"\" from tokenize import", "\"}\": level = level - 1 chunks.append((1, sformat[dollar + 2:pos - 1])) elif", "level = pos + 1, 1 while level: match, pos = matchorfail(sformat, pos)", "Converts any given object to unicode string. >>> safeunicode('hello') u'hello' >>> safeunicode(2) u'2'", "= SQLQuery(val) elif isinstance(val, (list, tuple)) and len(val) == 2: nout = SQLQuery(val[0],", "tablename + q(_keys) + ' VALUES ' + q(_values) else: sql_query = SQLQuery(self._get_insert_default_values_query(tablename))", "if isinstance(where, (int, long)): where = \"id = \" + sqlparam(where) elif isinstance(where,", "__radd__(self, other): if isinstance(other, basestring): items = [other] else: return NotImplemented return SQLQuery(items", "if sql == 'WHERE': nout = 'id = ' + sqlquote(val) else: nout", "of the parameters used in the sql query. >>> q = SQLQuery([\"SELECT *", "VALUES ' + q(_values) else: sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query def _get_insert_default_values_query(self, table):", "'Joe'\"> \"\"\" if svars is None: svars = {} where = self._where(where, svars)", "\" + sqllist(tables) + \" SET \" + sqlwhere(values, ', ') + \"", "= 'Joseph' >>> q = db.update('foo', where='name = $name', name='bob', age=2, ... created=SQLLiteral('NOW()'),", "y IN (2, 3)\"> \"\"\" if isinstance(a, list): return _sqllist(a) else: return sqlparam(a).sqlquery()", "%s AND b = %s' \"\"\" return SQLQuery.join([k + ' = ' +", "SQLParam('joe')]) >>> q.values() ['joe'] \"\"\" return [i.value for i in self.items if isinstance(i,", "' VALUES ' + q(_values) else: sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query def _get_insert_default_values_query(self,", "val else: nout = reparam(val, svars) def xjoin(a, b): if a and b:", "result.append(sqlquote(v)) else: result.append(chunk) return SQLQuery.join(result, '') class UnknownParamstyle(Exception): \"\"\" raised for unsupported db", "' + sqlquote(3) <sql: \"WHERE x = 't' AND y = 3\"> >>>", "def multiple_insert(self, tablename, values, seqname=None, _test=False): \"\"\" Inserts multiple rows into `tablename`. The", "pos) if dollar < 0: break nextchar = sformat[dollar + 1] if nextchar", "('SELECT', what), ('FROM', sqllist(tables)), ('WHERE', where), ('GROUP BY', group), ('ORDER BY', order), ('LIMIT',", "val, svars) for sql, val in sql_clauses if val is not None] qout", "2: where = SQLQuery(where[0], where[1]) elif isinstance(where, SQLQuery): pass else: where = reparam(where,", "pass else: where = reparam(where, svars) return where def select(self, tables, svars=None, what='*',", "+ 2, 1 while level: match, pos = matchorfail(sformat, pos) tstart, tend =", "' + q(_values) else: sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query def _get_insert_default_values_query(self, table): return", "if prefix: target_items.append(prefix) for i, item in enumerate(items): if i != 0: target_items.append(sep)", "def __str__(self): return \"unfinished expression in %s at char %d\" % ( repr(self.text),", "Returns the values of the parameters used in the sql query. >>> q", "offset=None, _test=False): \"\"\" Selects `what` from `tables` with clauses `where`, `order`, `group`, `limit`,", "\"\"\" Inserts `values` into `tablename`. Returns current sequence ID. Set `seqname` to the", "order), ('LIMIT', limit), ('OFFSET', offset)) def gen_clause(self, sql, val, svars): if isinstance(val, (int,", "db.multiple_insert('person', values=values, _test=True) <sql: \"INSERT INTO person (name, email) VALUES ('foo', '<EMAIL>'), ('bar',", "level = dollar + 2, 1 while level: match, pos = matchorfail(sformat, pos)", "SQLParam class SQLQuery(object): \"\"\" You can pass this sort of thing as a", "[self.gen_clause(sql, val, svars) for sql, val in sql_clauses if val is not None]", ">>> reparam(\"s = $s\", dict(s=True)) <sql: \"s = 't'\"> >>> reparam(\"s IN $s\",", "self.items) def __iadd__(self, other): if isinstance(other, (basestring, SQLParam)): self.items.append(other) elif isinstance(other, SQLQuery): self.items.extend(other.items)", "what, tables, where, group, order, limit, offset): return ( ('SELECT', what), ('FROM', sqllist(tables)),", "valid # make sure all rows have same keys. for v in values:", "\"\"\" Converts the arguments for use in something like a WHERE clause. >>>", "limit=None, offset=None, _test=False): \"\"\" Selects `what` from `tables` with clauses `where`, `order`, `group`,", "is not None] qout = SQLQuery.join(clauses) if _test: return qout return self.query(qout, processed=True)", "elif obj is True: return \"'t'\" elif obj is False: return \"'f'\" elif", "token == \"{\": level = level + 1 elif token == \"}\": level", "val in sql_clauses if val is not None] qout = SQLQuery.join(clauses) if _test:", "= value def get_marker(self, paramstyle='pyformat'): if paramstyle == 'qmark': return '?' elif paramstyle", "chunks.append((0, sformat[pos:dollar])) match, pos = matchorfail(sformat, dollar + 1) while pos < len(sformat):", "* FROM test WHERE name=\", SQLParam('joe')]) >>> q.query() 'SELECT * FROM test WHERE", "AND '): \"\"\" Converts a `dictionary` to an SQL WHERE clause `SQLQuery`. >>>", "tokenprog.match(text, pos) if match is None: raise _ItplError(text, pos) return match, match.end() namechars", "Internally, consists of `items`, which is a list of strings and SQLParams, which", "or isinstance(obj, unicode): return unicode(obj) else: return str(obj).decode(encoding) def safestr(obj, encoding='utf-8'): r\"\"\" Converts", "sql_query = reparam(sql_query, svars) return sql_query def sql_clauses(self, what, tables, where, group, order,", "self.ctx.transactions: self.ctx.commit() return db_cursor.rowcount def delete(self, table, where, using=None, svars=None, _test=False): \"\"\" Deletes", "1) while pos < len(sformat): if sformat[pos] == \".\" and \\ pos +", "def insert(self, tablename, seqname=None, _test=False, **values): \"\"\" Inserts `values` into `tablename`. Returns current", "' + sqllist(using) if where: q += ' WHERE ' + where return", "limit=5, _test=True) <sql: 'SELECT * FROM foo, bar WHERE foo.bar_id = bar.id LIMIT", "keyword argument `vars` and the function will call reparam for you. Internally, consists", "tested in sqlquote's docstring def __init__(self, items=None): r\"\"\"Creates a new SQLQuery. >>> SQLQuery(\"x\")", "and hash(1) == hash(True)` # we have to do this the hard way...", "query = ( \"UPDATE \" + sqllist(tables) + \" SET \" + sqlwhere(values,", "!= 0: items.append(', ') items.append(sqlparam(v)) items.append(')') return SQLQuery(items) def sqlquote(a): \"\"\" Ensures `a`", "each with the same set of keys. Returns the list of ids of", "== hash(True)` # we have to do this the hard way... if obj", "* FROM test WHERE name=\", SQLParam(\"joe\")]) >>> q <sql: \"SELECT * FROM test", "len(sformat): if sformat[pos] == \".\" and \\ pos + 1 < len(sformat) and", "if seqname is not False: sql_query = self._process_insert_query(sql_query, tablename, seqname) if isinstance(sql_query, tuple):", "= ' + sqlquote(3) <sql: \"WHERE x = 't' AND y = 3\">", "else: chunks.append((0, sformat[pos:dollar + 1])) pos = dollar + 1 + (nextchar ==", "SQLParams, which get concatenated to produce the actual query. \"\"\" __slots__ = [\"items\"]", "is str: return obj.decode(encoding) elif t in [int, float, bool]: return unicode(obj) elif", "from tokenize import tokenprog tokenprog = tokenprog def matchorfail(text, pos): match = tokenprog.match(text,", "SQLQuery.join([sqlparam(v) for v in values.values()], ', ') sql_query = \"INSERT INTO %s \"", "dict(s=[1, 2])) <sql: 's IN (1, 2)'> \"\"\" dictionary = dictionary.copy() # eval", "\"bar\", \"email\": \"<EMAIL>\"}] >>> db.multiple_insert('person', values=values, _test=True) <sql: \"INSERT INTO person (name, email)", "unicode): return unicode(obj) else: return str(obj).decode(encoding) def safestr(obj, encoding='utf-8'): r\"\"\" Converts any given", "'b': 'b'}).query() 'a = %s AND b = %s' \"\"\" return SQLQuery.join([k +", "dollar + 1 + (nextchar == \"$\") if pos < len(sformat): chunks.append((0, sformat[pos:]))", "the query part of the sql query. >>> q = SQLQuery([\"SELECT * FROM", "= DB(None, {}) >>> db.select('foo', _test=True) <sql: 'SELECT * FROM foo'> >>> db.select(['foo',", "created = NOW() WHERE name = 'Joseph'\"> >>> q.query() 'UPDATE foo SET age", "\"WHERE x = 't' AND y IN (2, 3)\"> \"\"\" if isinstance(a, list):", "= [other] elif isinstance(other, SQLQuery): items = other.items else: return NotImplemented return SQLQuery(self.items", "3]) <sql: \"WHERE x = 't' AND y IN (2, 3)\"> \"\"\" if", "elif datetime and isinstance(obj, datetime.datetime): return repr(obj.isoformat()) else: if isinstance(obj, unicode): obj =", "\"unfinished expression in %s at char %d\" % ( repr(self.text), self.pos) class SQLParam(object):", "', ') <sql: 'a, b'> Optinally, prefix and suffix arguments can be provided.", "= True >>> values = [{\"name\": \"foo\", \"email\": \"<EMAIL>\"}, {\"name\": \"bar\", \"email\": \"<EMAIL>\"}]", "level - 1 else: break chunks.append((1, sformat[dollar + 1:pos])) else: chunks.append((0, sformat[pos:dollar +", "+ sqlparam(where) elif isinstance(where, (list, tuple)) and len(where) == 2: where = SQLQuery(where[0],", "'__unicode__') or isinstance(obj, unicode): return unicode(obj) else: return str(obj).decode(encoding) def safestr(obj, encoding='utf-8'): r\"\"\"", "in x and '%%' not in x: x = x.replace('%', '%%') s.append(x) return", "where='name = $name', name='bob', age=2, ... created=SQLLiteral('NOW()'), vars=locals(), _test=True) >>> q <sql: \"UPDATE", "def __init__(self, items=None): r\"\"\"Creates a new SQLQuery. >>> SQLQuery(\"x\") <sql: 'x'> >>> q", "FROM foo WHERE x = $x\", vars=dict(x='f'), _test=True) <sql: \"SELECT * FROM foo", "(list, tuple)) and len(val) == 2: nout = SQLQuery(val[0], val[1]) # backwards-compatibility elif", "q <sql: \"SELECT * FROM test WHERE name='joe'\"> >>> q.query() 'SELECT * FROM", "u'abc' \"\"\" if isinstance(lst, basestring): return lst else: return ', '.join(lst) def _sqllist(values):", "SQLQuery(val[0], val[1]) # backwards-compatibility elif isinstance(val, SQLQuery): nout = val else: nout =", "safestr(x) # automatically escape % characters in the query # For backward compatability,", "return obj.encode(encoding) elif isinstance(obj, str): return obj elif hasattr(obj, 'next'): # iterator return", "sqlquote(True) + ' AND y = ' + sqlquote(3) <sql: \"WHERE x =", "repr(str(self)) class SQLLiteral: \"\"\" Protects a string from `sqlquote`. >>> sqlquote('NOW()') <sql: \"'NOW()'\">", "i != 0: sql_query.append(\", \") SQLQuery.join([SQLParam(row[k]) for k in keys], sep=\", \", target=sql_query,", "NotImplemented return SQLQuery(items + self.items) def __iadd__(self, other): if isinstance(other, (basestring, SQLParam)): self.items.append(other)", "str): return obj elif hasattr(obj, 'next'): # iterator return itertools.imap(safestr, obj) else: return", "each clause can be a SQLQuery. >>> db = DB(None, {}) >>> db.select('foo',", "sequence ID. Set `seqname` to the ID if it's not the default, or", "\"\"\" Parameter in SQLQuery. >>> q = SQLQuery([\"SELECT * FROM test WHERE name=\",", "# because `1 == True and hash(1) == hash(True)` # we have to", "of `items`, which is a list of strings and SQLParams, which get concatenated", ">>> sqllist(['a', 'b']) 'a, b' >>> sqllist('a') 'a' >>> sqllist(u'abc') u'abc' \"\"\" if", "\"\"\" if isinstance(obj, unicode): return obj.encode(encoding) elif isinstance(obj, str): return obj elif hasattr(obj,", "+ b else: return a or b return xjoin(sql, nout) def _where(self, where,", "arguments can be provided. >>> SQLQuery.join(['a', 'b'], ', ', prefix='(', suffix=')') <sql: '(a,", "prefix=None, suffix=None, target=None): \"\"\" Joins multiple queries. >>> SQLQuery.join(['a', 'b'], ', ') <sql:", "= 'f'\"> \"\"\" if svars is None: svars = {} if not processed", "\"SELECT * FROM foo WHERE x = 'f'\"> \"\"\" if svars is None:", "sep=\", \", target=sql_query, prefix=\"(\", suffix=\")\") if _test: return sql_query db_cursor = self._db_cursor() if", "+ items) def __radd__(self, other): if isinstance(other, basestring): items = [other] else: return", "foo WHERE x = \" + sqlquote('f'), _test=True) <sql: \"SELECT * FROM foo", "x.get_marker(paramstyle) s.append(safestr(x)) else: x = safestr(x) # automatically escape % characters in the", "def xjoin(a, b): if a and b: return a + ' ' +", "2-tuples of the form (boolean, string) where boolean says whether string should be", "\"\"\" Inserts multiple rows into `tablename`. The `values` must be a list of", "UnknownParamstyle(Exception): \"\"\" raised for unsupported db paramstyles (currently supported: qmark, numeric, format, pyformat)", "', ') sql_query = \"INSERT INTO %s \" % tablename + q(_keys) +", "_interpolate(string_): if live: v = eval(chunk, dictionary) result.append(sqlquote(v)) else: result.append(chunk) return SQLQuery.join(result, '')", "val, svars): if isinstance(val, (int, long)): if sql == 'WHERE': nout = 'id", "+ 1 + (nextchar == \"$\") if pos < len(sformat): chunks.append((0, sformat[pos:])) return", "seqname) if isinstance(sql_query, tuple): # for some databases, a separate query has to", "target_items.append(suffix) return target join = staticmethod(join) def _str(self): try: return self.query() % tuple([sqlify(x)", "self.value = value def get_marker(self, paramstyle='pyformat'): if paramstyle == 'qmark': return '?' elif", "unicode string. >>> safeunicode('hello') u'hello' >>> safeunicode(2) u'2' >>> safeunicode('\\xe1\\x88\\xb4') u'\\u1234' \"\"\" t", "paramstyle in ['format', 'pyformat']: return '%s' raise UnknownParamstyle, paramstyle def sqlquery(self): return SQLQuery([self])", "age = 2, name = 'bob', created = NOW() WHERE name = 'Joseph'\">", "sql_query = SQLQuery('INSERT INTO %s (%s) VALUES ' % (tablename, ', '.join(keys))) for", "in %s at char %d\" % ( repr(self.text), self.pos) class SQLParam(object): \"\"\" Parameter", "<sql: \"INSERT INTO person (name, email) VALUES ('foo', '<EMAIL>'), ('bar', '<EMAIL>')\"> \"\"\" if", "using=None, svars=None, _test=False): \"\"\" Deletes from `table` with clauses `where` and `using`. >>>", "SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam(\"joe\")]) >>> q <sql: \"SELECT * FROM", ">>> q = db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'), _test=True) >>> q <sql: \"INSERT INTO", ">>> q = SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam('joe')]) >>> q.query() 'SELECT", "what='*', where=None, order=None, group=None, limit=None, offset=None, _test=False): \"\"\" Selects `what` from `tables` with", "+ \" WHERE \" + where) if _test: return query db_cursor = self._db_cursor()", "part of the sql query. >>> q = SQLQuery([\"SELECT * FROM test WHERE", "'order_id':3}) <sql: 'order_id = 3 AND cust_id = 2'> >>> sqlwhere({'cust_id': 2, 'order_id':3},", "of creating a new SQLQuery. \"\"\" if target is None: target = SQLQuery()", "if _test: return query db_cursor = self._db_cursor() self._db_execute(db_cursor, query) if not self.ctx.transactions: self.ctx.commit()", "') <sql: 'a, b'> Optinally, prefix and suffix arguments can be provided. >>>", "query. \"\"\" __slots__ = [\"items\"] # tested in sqlquote's docstring def __init__(self, items=None):", "\"\"\" if not values: return [] if not self.supports_multiple_insert: out = [self.insert(tablename, seqname=seqname,", "\"WHERE x = 't' AND y = 3\"> >>> 'WHERE x = '", "table if using: q += ' USING ' + sqllist(using) if where: q", "1 else: break chunks.append((1, sformat[dollar + 1:pos])) else: chunks.append((0, sformat[pos:dollar + 1])) pos", "SQLQuery.join(clauses) if _test: return qout return self.query(qout, processed=True) def insert(self, tablename, seqname=None, _test=False,", "<sql: \"'NOW()'\"> >>> sqlquote(SQLLiteral('NOW()')) <sql: 'NOW()'> \"\"\" def __init__(self, v): self.v = v", "self.values()]) except (ValueError, TypeError): return self.query() def __str__(self): return safestr(self._str()) def __unicode__(self): return", "q1, q2 = sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor, sql_query) try: out", "the inserted row. q1, q2 = sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor,", "and len(val) == 2: nout = SQLQuery(val[0], val[1]) # backwards-compatibility elif isinstance(val, SQLQuery):", "= SQLQuery.join(clauses) if _test: return qout return self.query(qout, processed=True) def insert(self, tablename, seqname=None,", "1) elif sformat[pos] in \"([\": pos, level = pos + 1, 1 while", "pos, level = pos + 1, 1 while level: match, pos = matchorfail(sformat,", "to produce the actual query. \"\"\" __slots__ = [\"items\"] # tested in sqlquote's", "_test=False): \"\"\" Selects `what` from `tables` with clauses `where`, `order`, `group`, `limit`, and", "SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam('joe')]) >>> q.values() ['joe'] \"\"\" return [i.value", "if not processed and not isinstance(sql_query, SQLQuery): sql_query = reparam(sql_query, svars) return sql_query", "svars=None, _test=False, **values): \"\"\" Update `tables` with clause `where` (interpolated using `vars`) and", "\" + sqlwhere(values, ', ') + \" WHERE \" + where) if _test:", "elif isinstance(other, SQLQuery): items = other.items else: return NotImplemented return SQLQuery(self.items + items)", "db.delete('foo', where='name = $name', vars=locals(), _test=True) <sql: \"DELETE FROM foo WHERE name =", "else: sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query def _get_insert_default_values_query(self, table): return \"INSERT INTO %s", "db = DB(None, {}) >>> db.supports_multiple_insert = True >>> values = [{\"name\": \"foo\",", "INTO foo (age, name, created) VALUES (2, 'bob', NOW())\"> >>> q.query() 'INSERT INTO", "have to do this the hard way... if obj is None: return 'NULL'", "automatically escape % characters in the query # For backward compatability, ignore escaping", "+ 1])) pos = dollar + 1 + (nextchar == \"$\") if pos", "'bob', NOW())\"> >>> q.query() 'INSERT INTO foo (age, name, created) VALUES (%s, %s,", "AND y IN (2, 3)\"> \"\"\" if isinstance(a, list): return _sqllist(a) else: return", "char %d\" % ( repr(self.text), self.pos) class SQLParam(object): \"\"\" Parameter in SQLQuery. >>>", "(interpolated using `vars`) and setting `values`. >>> db = DB(None, {}) >>> name", "x=', SQLParam(1)]) >>> q <sql: 'SELECT * FROM test WHERE x=1'> >>> q.query(),", "sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query def _get_insert_default_values_query(self, table): return \"INSERT INTO %s DEFAULT", "= db_cursor.fetchone()[0] out = range(out-len(values)+1, out+1) except Exception: out = None if not", "elif token == \"}\": level = level - 1 chunks.append((1, sformat[dollar + 2:pos", "encoding='utf-8'): r\"\"\" Converts any given object to utf-8 encoded string. >>> safestr('hello') 'hello'", "which is a list of strings and SQLParams, which get concatenated to produce", "pos) tstart, tend = match.regs[3] token = sformat[tstart:tend] if token == \"{\": level", "offset) clauses = [self.gen_clause(sql, val, svars) for sql, val in sql_clauses if val", "while level: match, pos = matchorfail(sformat, pos) tstart, tend = match.regs[3] token =", "self.items if isinstance(i, SQLParam)] def join(items, sep=' ', prefix=None, suffix=None, target=None): \"\"\" Joins", "query. >>> q = SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam('joe')]) >>> q.values()", "to interpolate. Otherwise, each clause can be a SQLQuery. >>> db = DB(None,", "def _get_insert_default_values_query(self, table): return \"INSERT INTO %s DEFAULT VALUES\" % table def multiple_insert(self,", "\"foo\", \"email\": \"<EMAIL>\"}, {\"name\": \"bar\", \"email\": \"<EMAIL>\"}] >>> db.multiple_insert('person', values=values, _test=True) <sql: \"INSERT", "'NULL' elif obj is True: return \"'t'\" elif obj is False: return \"'f'\"", "''' Created on 2013-8-21 @author: lan (www.9miao.com) ''' import itertools import datetime def", "it result = [] for live, chunk in _interpolate(string_): if live: v =", "interpolate. Otherwise, each clause can be a SQLQuery. >>> db = DB(None, {})", "SQLParam)] def join(items, sep=' ', prefix=None, suffix=None, target=None): \"\"\" Joins multiple queries. >>>", "'t'\"> >>> reparam(\"s IN $s\", dict(s=[1, 2])) <sql: 's IN (1, 2)'> \"\"\"", "(%s) VALUES ' % (tablename, ', '.join(keys))) for i, row in enumerate(values): if", "{}) >>> name = 'Joseph' >>> q = db.update('foo', where='name = $name', name='bob',", "self.items = [] elif isinstance(items, list): self.items = items elif isinstance(items, SQLParam): self.items", "**v) for v in values] if seqname is False: return None else: return", "', '.join(keys))) for i, row in enumerate(values): if i != 0: sql_query.append(\", \")", "matchorfail(text, pos): match = tokenprog.match(text, pos) if match is None: raise _ItplError(text, pos)", "(2, 3)\"> \"\"\" if isinstance(a, list): return _sqllist(a) else: return sqlparam(a).sqlquery() def _interpolate(sformat):", "< len(sformat) and sformat[pos + 1] in namechars: match, pos = matchorfail(sformat, pos", "return str(self.value) def __repr__(self): return '<param: %s>' % repr(self.value) sqlparam = SQLParam class", "db_cursor.fetchone()[0] out = range(out-len(values)+1, out+1) except Exception: out = None if not self.ctx.transactions:", "unicode: return obj elif t is str: return obj.decode(encoding) elif t in [int,", "_test=False): \"\"\" Inserts multiple rows into `tablename`. The `values` must be a list", "Takes a format string and returns a list of 2-tuples of the form", "sql_query = \"INSERT INTO %s \" % tablename + q(_keys) + ' VALUES", "if obj is None: return 'NULL' elif obj is True: return \"'t'\" elif", ">>> q.values() ['joe'] \"\"\" __slots__ = [\"value\"] def __init__(self, value): self.value = value", "= obj.encode('utf8') return repr(obj) def sqllist(lst): \"\"\" Converts the arguments for use in", "'t' AND y = 3\"> >>> 'WHERE x = ' + sqlquote(True) +", "tables, where, group, order, limit, offset): return ( ('SELECT', what), ('FROM', sqllist(tables)), ('WHERE',", "lan (www.9miao.com) ''' import itertools import datetime def safeunicode(obj, encoding='utf-8'): r\"\"\" Converts any", "def get_marker(self, paramstyle='pyformat'): if paramstyle == 'qmark': return '?' elif paramstyle == 'numeric':", "values.values()], ', ') sql_query = \"INSERT INTO %s \" % tablename + q(_keys)", "SQLQuery): self.items = list(items.items) else: self.items = [items] # Take care of SQLLiterals", "to `False` if there isn't one. >>> db = DB(None, {}) >>> db.supports_multiple_insert", "\"email\": \"<EMAIL>\"}] >>> db.multiple_insert('person', values=values, _test=True) <sql: \"INSERT INTO person (name, email) VALUES", "is True: return \"'t'\" elif obj is False: return \"'f'\" elif datetime and", "_test=True) <sql: 'SELECT * FROM foo'> >>> db.select(['foo', 'bar'], where=\"foo.bar_id = bar.id\", limit=5,", "dictionary = dictionary.copy() # eval mucks with it result = [] for live,", "= [] for x in self.items: if isinstance(x, SQLParam): x = x.get_marker(paramstyle) s.append(safestr(x))", "`where` and `using`. >>> db = DB(None, {}) >>> name = 'Joe' >>>", "{}) >>> db.supports_multiple_insert = True >>> values = [{\"name\": \"foo\", \"email\": \"<EMAIL>\"}, {\"name\":", "0: sql_query.append(\", \") SQLQuery.join([SQLParam(row[k]) for k in keys], sep=\", \", target=sql_query, prefix=\"(\", suffix=\")\")", "lst else: return ', '.join(lst) def _sqllist(values): \"\"\" >>> _sqllist([1, 2, 3]) <sql:", "= %s, name = %s, created = NOW() WHERE name = %s' >>>", "'\\xe1\\x88\\xb4' >>> safestr(2) '2' \"\"\" if isinstance(obj, unicode): return obj.encode(encoding) elif isinstance(obj, str):", "elif isinstance(where, (list, tuple)) and len(where) == 2: where = SQLQuery(where[0], where[1]) elif", "to target instead of creating a new SQLQuery. \"\"\" if target is None:", "Converts the arguments for use in something like a WHERE clause. >>> sqllist(['a',", "backward compatability, ignore escaping when the query looks already escaped if paramstyle in", "= tokenprog.match(text, pos) if match is None: raise _ItplError(text, pos) return match, match.end()", "def safeunicode(obj, encoding='utf-8'): r\"\"\" Converts any given object to unicode string. >>> safeunicode('hello')", "[2, 'bob', 'Joseph'] \"\"\" if svars is None: svars = {} where =", "\"'t'\" >>> sqlify(3) '3' \"\"\" # because `1 == True and hash(1) ==", ">>> db.query(\"SELECT * FROM foo WHERE x = $x\", vars=dict(x='f'), _test=True) <sql: \"SELECT", "NOW())' >>> q.values() [2, 'bob'] \"\"\" def q(x): return \"(\" + x +", "< 0: break nextchar = sformat[dollar + 1] if nextchar == \"{\": chunks.append((0,", "+ sqlquote('f'), _test=True) <sql: \"SELECT * FROM foo WHERE x = 'f'\"> \"\"\"", "query part of the sql query. >>> q = SQLQuery([\"SELECT * FROM test", "dollar + 1) while pos < len(sformat): if sformat[pos] == \".\" and \\", "[other] else: return NotImplemented return SQLQuery(items + self.items) def __iadd__(self, other): if isinstance(other,", ">>> q.query() 'SELECT * FROM test WHERE name=%s' >>> q.values() ['joe'] \"\"\" __slots__", "be a list of dictioanries, one for each row to be inserted, each", ">>> q <sql: \"SELECT * FROM test WHERE name='joe'\"> >>> q.query() 'SELECT *", "suffix: target_items.append(suffix) return target join = staticmethod(join) def _str(self): try: return self.query() %", "keys are valid # make sure all rows have same keys. for v", "def __str__(self): return str(self.value) def __repr__(self): return '<param: %s>' % repr(self.value) sqlparam =", "suffix=\")\") if _test: return sql_query db_cursor = self._db_cursor() if seqname is not False:", "2'> >>> sqlwhere({'a': 'a', 'b': 'b'}).query() 'a = %s AND b = %s'", "elif hasattr(obj, '__unicode__') or isinstance(obj, unicode): return unicode(obj) else: return str(obj).decode(encoding) def safestr(obj,", "x = ' + sqlquote(True) + ' AND y = ' + sqlquote(3)", ">>> db.query(\"SELECT * FROM foo\", _test=True) <sql: 'SELECT * FROM foo'> >>> db.query(\"SELECT", "isinstance(obj, unicode): obj = obj.encode('utf8') return repr(obj) def sqllist(lst): \"\"\" Converts the arguments", "q.values() [2, 'bob', 'Joseph'] \"\"\" if svars is None: svars = {} where", "= $x\", vars=dict(x='f'), _test=True) <sql: \"SELECT * FROM foo WHERE x = 'f'\">", "`False` if there isn't one. >>> db = DB(None, {}) >>> db.supports_multiple_insert =", "q.query() 'SELECT * FROM test WHERE name=%s' >>> q.values() ['joe'] \"\"\" __slots__ =", ">>> db.supports_multiple_insert = True >>> values = [{\"name\": \"foo\", \"email\": \"<EMAIL>\"}, {\"name\": \"bar\",", "if dollar < 0: break nextchar = sformat[dollar + 1] if nextchar ==", "chunks = [] pos = 0 while 1: dollar = sformat.find(\"$\", pos) if", "the query # For backward compatability, ignore escaping when the query looks already", "* FROM test WHERE x=%s', [1]) >>> SQLQuery(SQLParam(1)) <sql: '1'> \"\"\" if items", "of the inserted row. q1, q2 = sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2) else:", "return [i.value for i in self.items if isinstance(i, SQLParam)] def join(items, sep=' ',", "dollar + 2, 1 while level: match, pos = matchorfail(sformat, pos) tstart, tend", "INTO foo (age, name, created) VALUES (%s, %s, NOW())' >>> q.values() [2, 'bob']", "name = 'Joseph' >>> q = db.update('foo', where='name = $name', name='bob', age=2, ...", "_str(self): try: return self.query() % tuple([sqlify(x) for x in self.values()]) except (ValueError, TypeError):", "' AND y = ' + sqlquote(3) <sql: \"WHERE x = 't' AND", "pos < len(sformat): chunks.append((0, sformat[pos:])) return chunks def sqlwhere(dictionary, grouping=' AND '): \"\"\"", "to its proper SQL version >>> sqlify(None) 'NULL' >>> sqlify(True) \"'t'\" >>> sqlify(3)", "not None] qout = SQLQuery.join(clauses) if _test: return qout return self.query(qout, processed=True) def", "svars is None: svars = {} where = self._where(where, svars) query = (", "if sformat[pos] == \".\" and \\ pos + 1 < len(sformat) and sformat[pos", "%s' >>> q.values() [2, 'bob', 'Joseph'] \"\"\" if svars is None: svars =", ">>> q.query() 'UPDATE foo SET age = %s, name = %s, created =", "sformat[pos + 1] in namechars: match, pos = matchorfail(sformat, pos + 1) elif", "target is None: target = SQLQuery() target_items = target.items if prefix: target_items.append(prefix) for", "2, name = 'bob', created = NOW() WHERE name = 'Joseph'\"> >>> q.query()", ">>> q <sql: \"UPDATE foo SET age = 2, name = 'bob', created", "if it's not the default, or to `False` if there isn't one. >>>", "str(obj) def sqlify(obj): \"\"\" converts `obj` to its proper SQL version >>> sqlify(None)", "q.values() ['joe'] \"\"\" return [i.value for i in self.items if isinstance(i, SQLParam)] def", "# make sure all rows have same keys. for v in values: if", "db paramstyles (currently supported: qmark, numeric, format, pyformat) \"\"\" pass class _ItplError(ValueError): def", "v def __repr__(self): return self.v class SQLProducer: \"\"\"Database\"\"\" def __init__(self): \"\"\"Creates a database.", "_test=True) <sql: 'SELECT * FROM foo, bar WHERE foo.bar_id = bar.id LIMIT 5'>", "paramstyle == 'numeric': return ':1' elif paramstyle is None or paramstyle in ['format',", "rows. Set `seqname` to the ID if it's not the default, or to", "+ ' VALUES ' + q(_values) else: sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query def", "\"'t'\" elif obj is False: return \"'f'\" elif datetime and isinstance(obj, datetime.datetime): return", "Execute SQL query `sql_query` using dictionary `vars` to interpolate it. If `processed=True`, `vars`", "[self.insert(tablename, seqname=seqname, _test=_test, **v) for v in values] if seqname is False: return", ">>> q <sql: 'SELECT * FROM test WHERE x=1'> >>> q.query(), q.values() ('SELECT", "name = %s' >>> q.values() [2, 'bob', 'Joseph'] \"\"\" if svars is None:", "table, where, using=None, svars=None, _test=False): \"\"\" Deletes from `table` with clauses `where` and", "\")]\": level = level - 1 else: break chunks.append((1, sformat[dollar + 1:pos])) else:", "__repr__(self): return self.v class SQLProducer: \"\"\"Database\"\"\" def __init__(self): \"\"\"Creates a database. \"\"\" pass", "q.values() [2, 'bob'] \"\"\" def q(x): return \"(\" + x + \")\" if", "values of the parameters used in the sql query. >>> q = SQLQuery([\"SELECT", "len(sformat) and sformat[pos + 1] in namechars: match, pos = matchorfail(sformat, pos +", "\"\"\" Converts a `dictionary` to an SQL WHERE clause `SQLQuery`. >>> sqlwhere({'cust_id': 2,", "sqlquote(3) <sql: \"WHERE x = 't' AND y = 3\"> >>> 'WHERE x", "self.ctx.transactions: self.ctx.commit() return out def update(self, tables, where, svars=None, _test=False, **values): \"\"\" Update", "if isinstance(item, SQLQuery): target_items.extend(item.items) else: target_items.append(item) if suffix: target_items.append(suffix) return target join =", "return db_cursor.rowcount def delete(self, table, where, using=None, svars=None, _test=False): \"\"\" Deletes from `table`", "+ ' = ' + sqlparam(v) for k, v in dictionary.items()], grouping) def", "WHERE name = 'Joseph'\"> >>> q.query() 'UPDATE foo SET age = %s, name", "svars) query = ( \"UPDATE \" + sqllist(tables) + \" SET \" +", "DB(None, {}) >>> db.query(\"SELECT * FROM foo\", _test=True) <sql: 'SELECT * FROM foo'>", ">>> values = [{\"name\": \"foo\", \"email\": \"<EMAIL>\"}, {\"name\": \"bar\", \"email\": \"<EMAIL>\"}] >>> db.multiple_insert('person',", "where=None, order=None, group=None, limit=None, offset=None, _test=False): \"\"\" Selects `what` from `tables` with clauses", "sql query. >>> q = SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam('joe')]) >>>", "`tables` with clause `where` (interpolated using `vars`) and setting `values`. >>> db =", "== 'WHERE': nout = 'id = ' + sqlquote(val) else: nout = SQLQuery(val)", "else: return NotImplemented return SQLQuery(items + self.items) def __iadd__(self, other): if isinstance(other, (basestring,", "limit, offset): return ( ('SELECT', what), ('FROM', sqllist(tables)), ('WHERE', where), ('GROUP BY', group),", "q.values() ('SELECT * FROM test WHERE x=%s', [1]) >>> SQLQuery(SQLParam(1)) <sql: '1'> \"\"\"", "# backwards-compatibility elif isinstance(val, SQLQuery): nout = val else: nout = reparam(val, svars)", "q(_values) else: sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query def _get_insert_default_values_query(self, table): return \"INSERT INTO", "db = DB(None, {}) >>> db.select('foo', _test=True) <sql: 'SELECT * FROM foo'> >>>", "created) VALUES (%s, %s, NOW())' >>> q.values() [2, 'bob'] \"\"\" def q(x): return", "' WHERE x=', SQLParam(1)]) >>> q <sql: 'SELECT * FROM test WHERE x=1'>", "return '<param: %s>' % repr(self.value) sqlparam = SQLParam class SQLQuery(object): \"\"\" You can", "try: return self.query() % tuple([sqlify(x) for x in self.values()]) except (ValueError, TypeError): return", "'UPDATE foo SET age = %s, name = %s, created = NOW() WHERE", "i != 0: target_items.append(sep) if isinstance(item, SQLQuery): target_items.extend(item.items) else: target_items.append(item) if suffix: target_items.append(suffix)", "str(obj).decode(encoding) def safestr(obj, encoding='utf-8'): r\"\"\" Converts any given object to utf-8 encoded string.", "sqlwhere(dictionary, grouping=' AND '): \"\"\" Converts a `dictionary` to an SQL WHERE clause", "chunk in _interpolate(string_): if live: v = eval(chunk, dictionary) result.append(sqlquote(v)) else: result.append(chunk) return", "str(self.value) def __repr__(self): return '<param: %s>' % repr(self.value) sqlparam = SQLParam class SQLQuery(object):", "if isinstance(other, (basestring, SQLParam)): self.items.append(other) elif isinstance(other, SQLQuery): self.items.extend(other.items) else: return NotImplemented return", "\"INSERT INTO foo (age, name, created) VALUES (2, 'bob', NOW())\"> >>> q.query() 'INSERT", "reparam(val, svars) def xjoin(a, b): if a and b: return a + '", "match.end() namechars = \"abcdefghijklmnopqrstuvwxyz\" \\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks = [] pos = 0 while", "WHERE x = 'f'\"> \"\"\" if svars is None: svars = {} if", "self.query(qout, processed=True) def insert(self, tablename, seqname=None, _test=False, **values): \"\"\" Inserts `values` into `tablename`.", "def __radd__(self, other): if isinstance(other, basestring): items = [other] else: return NotImplemented return", "order=None, group=None, limit=None, offset=None, _test=False): \"\"\" Selects `what` from `tables` with clauses `where`,", "else: return sqlparam(a).sqlquery() def _interpolate(sformat): \"\"\" Takes a format string and returns a", "domain, Ka-Ping Yee) \"\"\" from tokenize import tokenprog tokenprog = tokenprog def matchorfail(text,", "return \"'f'\" elif datetime and isinstance(obj, datetime.datetime): return repr(obj.isoformat()) else: if isinstance(obj, unicode):", "2)'> \"\"\" dictionary = dictionary.copy() # eval mucks with it result = []", "= SQLParam class SQLQuery(object): \"\"\" You can pass this sort of thing as", "None: svars = {} if not processed and not isinstance(sql_query, SQLQuery): sql_query =", "is None: svars = {} where = self._where(where, svars) query = ( \"UPDATE", "for live, chunk in _interpolate(string_): if live: v = eval(chunk, dictionary) result.append(sqlquote(v)) else:", "'f'\"> >>> db.query(\"SELECT * FROM foo WHERE x = \" + sqlquote('f'), _test=True)", "', prefix=None, suffix=None, target=None): \"\"\" Joins multiple queries. >>> SQLQuery.join(['a', 'b'], ', ')", "== 2: nout = SQLQuery(val[0], val[1]) # backwards-compatibility elif isinstance(val, SQLQuery): nout =", "(age, name, created) VALUES (%s, %s, NOW())' >>> q.values() [2, 'bob'] \"\"\" def", "from `sqlquote`. >>> sqlquote('NOW()') <sql: \"'NOW()'\"> >>> sqlquote(SQLLiteral('NOW()')) <sql: 'NOW()'> \"\"\" def __init__(self,", "namechars = \"abcdefghijklmnopqrstuvwxyz\" \\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks = [] pos = 0 while 1:", "else: return NotImplemented return SQLQuery(self.items + items) def __radd__(self, other): if isinstance(other, basestring):", "namechars: match, pos = matchorfail(sformat, pos + 1) elif sformat[pos] in \"([\": pos,", "for i, row in enumerate(values): if i != 0: sql_query.append(\", \") SQLQuery.join([SQLParam(row[k]) for", "= [] for live, chunk in _interpolate(string_): if live: v = eval(chunk, dictionary)", "i in self.items if isinstance(i, SQLParam)] def join(items, sep=' ', prefix=None, suffix=None, target=None):", "interpolates the string using values from the dictionary. Returns an `SQLQuery` for the", "\"INSERT INTO person (name, email) VALUES ('foo', '<EMAIL>'), ('bar', '<EMAIL>')\"> \"\"\" if not", ">>> name = 'Joe' >>> db.delete('foo', where='name = $name', vars=locals(), _test=True) <sql: \"DELETE", "SQLQuery.join([k + ' = ' + sqlparam(v) for k, v in dictionary.items()], grouping)", "def _sqllist(values): \"\"\" >>> _sqllist([1, 2, 3]) <sql: '(1, 2, 3)'> \"\"\" items", "except (ValueError, TypeError): return self.query() def __str__(self): return safestr(self._str()) def __unicode__(self): return safeunicode(self._str())", ">>> SQLQuery.join(['a', 'b'], ', ', prefix='(', suffix=')') <sql: '(a, b)'> If target argument", "x = 'f'\"> \"\"\" if svars is None: svars = {} if not", "return match, match.end() namechars = \"abcdefghijklmnopqrstuvwxyz\" \\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks = [] pos =", "`values` must be a list of dictioanries, one for each row to be", "self.ctx.commit() return db_cursor.rowcount def delete(self, table, where, using=None, svars=None, _test=False): \"\"\" Deletes from", "= %s' \"\"\" return SQLQuery.join([k + ' = ' + sqlparam(v) for k,", "{\"name\": \"bar\", \"email\": \"<EMAIL>\"}] >>> db.multiple_insert('person', values=values, _test=True) <sql: \"INSERT INTO person (name,", "3)'> \"\"\" items = [] items.append('(') for i, v in enumerate(values): if i", "= [self.insert(tablename, seqname=seqname, _test=_test, **v) for v in values] if seqname is False:", "elif token[0] in \")]\": level = level - 1 else: break chunks.append((1, sformat[dollar", "return lst else: return ', '.join(lst) def _sqllist(values): \"\"\" >>> _sqllist([1, 2, 3])", "= tokenprog def matchorfail(text, pos): match = tokenprog.match(text, pos) if match is None:", "to the keyword argument `vars` and the function will call reparam for you.", "\"\"\" Joins multiple queries. >>> SQLQuery.join(['a', 'b'], ', ') <sql: 'a, b'> Optinally,", "to use instead of interpolating. >>> db = DB(None, {}) >>> db.query(\"SELECT *", "\"{\": level = level + 1 elif token == \"}\": level = level", "join(items, sep=' ', prefix=None, suffix=None, target=None): \"\"\" Joins multiple queries. >>> SQLQuery.join(['a', 'b'],", "using values from the dictionary. Returns an `SQLQuery` for the result. >>> reparam(\"s", "qout = SQLQuery.join(clauses) if _test: return qout return self.query(qout, processed=True) def insert(self, tablename,", "= item.value.v def append(self, value): self.items.append(value) def __add__(self, other): if isinstance(other, basestring): items", "elif t in [int, float, bool]: return unicode(obj) elif hasattr(obj, '__unicode__') or isinstance(obj,", "items.append(')') return SQLQuery(items) def sqlquote(a): \"\"\" Ensures `a` is quoted properly for use", "version >>> sqlify(None) 'NULL' >>> sqlify(True) \"'t'\" >>> sqlify(3) '3' \"\"\" # because", "target join = staticmethod(join) def _str(self): try: return self.query() % tuple([sqlify(x) for x", "return str(obj).decode(encoding) def safestr(obj, encoding='utf-8'): r\"\"\" Converts any given object to utf-8 encoded", "multiple_insert(self, tablename, values, seqname=None, _test=False): \"\"\" Inserts multiple rows into `tablename`. The `values`", "def q(x): return \"(\" + x + \")\" if values: _keys = SQLQuery.join(values.keys(),", "FROM test WHERE x=1'> >>> q.query(), q.values() ('SELECT * FROM test WHERE x=%s',", "rows have same keys. for v in values: if v.keys() != keys: raise", "(nextchar == \"$\") if pos < len(sformat): chunks.append((0, sformat[pos:])) return chunks def sqlwhere(dictionary,", "separate query has to be made to find # the id of the", "bar.id LIMIT 5'> \"\"\" if svars is None: svars = {} sql_clauses =", "`obj` to its proper SQL version >>> sqlify(None) 'NULL' >>> sqlify(True) \"'t'\" >>>", "obj.encode(encoding) elif isinstance(obj, str): return obj elif hasattr(obj, 'next'): # iterator return itertools.imap(safestr,", "# Take care of SQLLiterals for i, item in enumerate(self.items): if isinstance(item, SQLParam)", "+ sqllist(tables) + \" SET \" + sqlwhere(values, ', ') + \" WHERE", ">>> _sqllist([1, 2, 3]) <sql: '(1, 2, 3)'> \"\"\" items = [] items.append('(')", "returns a list of 2-tuples of the form (boolean, string) where boolean says", "order, limit, offset): return ( ('SELECT', what), ('FROM', sqllist(tables)), ('WHERE', where), ('GROUP BY',", "tstart, tend = match.regs[3] token = sformat[tstart:tend] if token[0] in \"([\": level =", "to be inserted, each with the same set of keys. Returns the list", "x = 't' AND y IN (2, 3)\"> \"\"\" if isinstance(a, list): return", "name = %s, created = NOW() WHERE name = %s' >>> q.values() [2,", "Yee) \"\"\" from tokenize import tokenprog tokenprog = tokenprog def matchorfail(text, pos): match", "while 1: dollar = sformat.find(\"$\", pos) if dollar < 0: break nextchar =", "match, match.end() namechars = \"abcdefghijklmnopqrstuvwxyz\" \\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks = [] pos = 0", "(1, 2)'> \"\"\" dictionary = dictionary.copy() # eval mucks with it result =", "u'hello' >>> safeunicode(2) u'2' >>> safeunicode('\\xe1\\x88\\xb4') u'\\u1234' \"\"\" t = type(obj) if t", "reparam for you. Internally, consists of `items`, which is a list of strings", "into `tablename`. The `values` must be a list of dictioanries, one for each", "_test=True) <sql: 'SELECT * FROM foo'> >>> db.query(\"SELECT * FROM foo WHERE x", "'Bad data' sql_query = SQLQuery('INSERT INTO %s (%s) VALUES ' % (tablename, ',", "# we have to do this the hard way... if obj is None:", "in sqlquote's docstring def __init__(self, items=None): r\"\"\"Creates a new SQLQuery. >>> SQLQuery(\"x\") <sql:", "items = [other] else: return NotImplemented return SQLQuery(items + self.items) def __iadd__(self, other):", "a `dictionary` to an SQL WHERE clause `SQLQuery`. >>> sqlwhere({'cust_id': 2, 'order_id':3}) <sql:", "< len(sformat): if sformat[pos] == \".\" and \\ pos + 1 < len(sformat)", "== 'numeric': return ':1' elif paramstyle is None or paramstyle in ['format', 'pyformat']:", "to an SQL WHERE clause `SQLQuery`. >>> sqlwhere({'cust_id': 2, 'order_id':3}) <sql: 'order_id =", "list): self.items = items elif isinstance(items, SQLParam): self.items = [items] elif isinstance(items, SQLQuery):", "0 while 1: dollar = sformat.find(\"$\", pos) if dollar < 0: break nextchar", "', prefix='(', suffix=')') <sql: '(a, b)'> If target argument is provided, the items", "if isinstance(a, list): return _sqllist(a) else: return sqlparam(a).sqlquery() def _interpolate(sformat): \"\"\" Takes a", "pos): ValueError.__init__(self) self.text = text self.pos = pos def __str__(self): return \"unfinished expression", "other): return other + self.sqlquery() def __str__(self): return str(self.value) def __repr__(self): return '<param:", "items) def __radd__(self, other): if isinstance(other, basestring): items = [other] else: return NotImplemented", "WHERE name = %s' >>> q.values() [2, 'bob', 'Joseph'] \"\"\" if svars is", "should be evaled or not. from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee) \"\"\" from", "\"abcdefghijklmnopqrstuvwxyz\" \\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks = [] pos = 0 while 1: dollar =", "clause `where` (interpolated using `vars`) and setting `values`. >>> db = DB(None, {})", "== \"}\": level = level - 1 chunks.append((1, sformat[dollar + 2:pos - 1]))", "an `SQLQuery` for the result. >>> reparam(\"s = $s\", dict(s=True)) <sql: \"s =", "foo SET age = 2, name = 'bob', created = NOW() WHERE name", "= $s\", dict(s=True)) <sql: \"s = 't'\"> >>> reparam(\"s IN $s\", dict(s=[1, 2]))", "* FROM test WHERE name='joe'\"> >>> q.query() 'SELECT * FROM test WHERE name=%s'", "something like a WHERE clause. >>> sqllist(['a', 'b']) 'a, b' >>> sqllist('a') 'a'", "+ 1 elif token[0] in \")]\": level = level - 1 else: break", "+ 1 < len(sformat) and sformat[pos + 1] in namechars: match, pos =", "itertools.imap(safestr, obj) else: return str(obj) def sqlify(obj): \"\"\" converts `obj` to its proper", "return \"\".join(s) def values(self): \"\"\" Returns the values of the parameters used in", "can be a SQLQuery. >>> db = DB(None, {}) >>> db.select('foo', _test=True) <sql:", "b: return a + ' ' + b else: return a or b", "level - 1 chunks.append((1, sformat[dollar + 2:pos - 1])) elif nextchar in namechars:", "with it result = [] for live, chunk in _interpolate(string_): if live: v", "ValueError, 'Bad data' sql_query = SQLQuery('INSERT INTO %s (%s) VALUES ' % (tablename,", "all rows have same keys. for v in values: if v.keys() != keys:", "isinstance(obj, str): return obj elif hasattr(obj, 'next'): # iterator return itertools.imap(safestr, obj) else:", "unicode): obj = obj.encode('utf8') return repr(obj) def sqllist(lst): \"\"\" Converts the arguments for", "looks already escaped if paramstyle in ['format', 'pyformat']: if '%' in x and", "IN (2, 3)\"> \"\"\" if isinstance(a, list): return _sqllist(a) else: return sqlparam(a).sqlquery() def", "pos) return match, match.end() namechars = \"abcdefghijklmnopqrstuvwxyz\" \\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks = [] pos", "for x in self.values()]) except (ValueError, TypeError): return self.query() def __str__(self): return safestr(self._str())", "current sequence ID. Set `seqname` to the ID if it's not the default,", "WHERE name=?' \"\"\" s = [] for x in self.items: if isinstance(x, SQLParam):", "self.query() def __str__(self): return safestr(self._str()) def __unicode__(self): return safeunicode(self._str()) def __repr__(self): return '<sql:", "pass class _ItplError(ValueError): def __init__(self, text, pos): ValueError.__init__(self) self.text = text self.pos =", "= 'f'\"> >>> db.query(\"SELECT * FROM foo WHERE x = \" + sqlquote('f'),", "FROM test WHERE name=%s' >>> q.values() ['joe'] \"\"\" __slots__ = [\"value\"] def __init__(self,", "+ other def __radd__(self, other): return other + self.sqlquery() def __str__(self): return str(self.value)", "'qmark': return '?' elif paramstyle == 'numeric': return ':1' elif paramstyle is None", "an SQL WHERE clause `SQLQuery`. >>> sqlwhere({'cust_id': 2, 'order_id':3}) <sql: 'order_id = 3", "return self def __len__(self): return len(self.query()) def query(self, paramstyle=None): \"\"\" Returns the query", "obj = obj.encode('utf8') return repr(obj) def sqllist(lst): \"\"\" Converts the arguments for use", "in self.values()]) except (ValueError, TypeError): return self.query() def __str__(self): return safestr(self._str()) def __unicode__(self):", "db.select(['foo', 'bar'], where=\"foo.bar_id = bar.id\", limit=5, _test=True) <sql: 'SELECT * FROM foo, bar", "None: svars = {} where = self._where(where, svars) q = 'DELETE FROM '", "_test=_test, **v) for v in values] if seqname is False: return None else:", "else: self.items = [items] # Take care of SQLLiterals for i, item in", "sformat[pos] in \"([\": pos, level = pos + 1, 1 while level: match,", "the hard way... if obj is None: return 'NULL' elif obj is True:", "inserted, each with the same set of keys. Returns the list of ids", "\"{\": chunks.append((0, sformat[pos:dollar])) pos, level = dollar + 2, 1 while level: match,", "['format', 'pyformat']: if '%' in x and '%%' not in x: x =", "safeunicode(obj, encoding='utf-8'): r\"\"\" Converts any given object to unicode string. >>> safeunicode('hello') u'hello'", "= None if not self.ctx.transactions: self.ctx.commit() return out def update(self, tables, where, svars=None,", "name='bob', age=2, created=SQLLiteral('NOW()'), _test=True) >>> q <sql: \"INSERT INTO foo (age, name, created)", "= [] pos = 0 while 1: dollar = sformat.find(\"$\", pos) if dollar", "= ' + sqlquote(val) else: nout = SQLQuery(val) elif isinstance(val, (list, tuple)) and", "svars = {} where = self._where(where, svars) q = 'DELETE FROM ' +", "_test=True) <sql: \"DELETE FROM foo WHERE name = 'Joe'\"> \"\"\" if svars is", "bool]: return unicode(obj) elif hasattr(obj, '__unicode__') or isinstance(obj, unicode): return unicode(obj) else: return", "sformat.find(\"$\", pos) if dollar < 0: break nextchar = sformat[dollar + 1] if", "[int, float, bool]: return unicode(obj) elif hasattr(obj, '__unicode__') or isinstance(obj, unicode): return unicode(obj)", "q += ' USING ' + sqllist(using) if where: q += ' WHERE", "self.sqlquery() + other def __radd__(self, other): return other + self.sqlquery() def __str__(self): return", "q.query(), q.values() ('SELECT * FROM test WHERE x=%s', [1]) >>> SQLQuery(SQLParam(1)) <sql: '1'>", "SET age = 2, name = 'bob', created = NOW() WHERE name =", "'a' >>> sqllist(u'abc') u'abc' \"\"\" if isinstance(lst, basestring): return lst else: return ',", "SQL query `sql_query` using dictionary `vars` to interpolate it. If `processed=True`, `vars` is", "%s \" % tablename + q(_keys) + ' VALUES ' + q(_values) else:", "function will call reparam for you. Internally, consists of `items`, which is a", "or b return xjoin(sql, nout) def _where(self, where, svars): if isinstance(where, (int, long)):", "def safestr(obj, encoding='utf-8'): r\"\"\" Converts any given object to utf-8 encoded string. >>>", "q <sql: 'SELECT * FROM test WHERE x=1'> >>> q.query(), q.values() ('SELECT *", "the string using values from the dictionary. Returns an `SQLQuery` for the result.", "'.join(lst) def _sqllist(values): \"\"\" >>> _sqllist([1, 2, 3]) <sql: '(1, 2, 3)'> \"\"\"", "chunks.append((1, sformat[dollar + 2:pos - 1])) elif nextchar in namechars: chunks.append((0, sformat[pos:dollar])) match,", "None: return 'NULL' elif obj is True: return \"'t'\" elif obj is False:", "\"\"\" if isinstance(lst, basestring): return lst else: return ', '.join(lst) def _sqllist(values): \"\"\"", "in the sql query. >>> q = SQLQuery([\"SELECT * FROM test WHERE name=\",", "given object to unicode string. >>> safeunicode('hello') u'hello' >>> safeunicode(2) u'2' >>> safeunicode('\\xe1\\x88\\xb4')", "in ['format', 'pyformat']: return '%s' raise UnknownParamstyle, paramstyle def sqlquery(self): return SQLQuery([self]) def", "target_items.extend(item.items) else: target_items.append(item) if suffix: target_items.append(suffix) return target join = staticmethod(join) def _str(self):", "`tablename`. The `values` must be a list of dictioanries, one for each row", "svars) q = 'DELETE FROM ' + table if using: q += '", "FROM test WHERE name=\", SQLParam('joe')]) >>> q.query() 'SELECT * FROM test WHERE name=%s'", "= DB(None, {}) >>> name = 'Joe' >>> db.delete('foo', where='name = $name', vars=locals(),", "= SQLQuery('INSERT INTO %s (%s) VALUES ' % (tablename, ', '.join(keys))) for i,", "<http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee) \"\"\" from tokenize import tokenprog tokenprog = tokenprog", "= 3 AND cust_id = 2'> >>> sqlwhere({'cust_id': 2, 'order_id':3}, grouping=', ') <sql:", "'SELECT * FROM test WHERE name=?' \"\"\" s = [] for x in", "Returns the query part of the sql query. >>> q = SQLQuery([\"SELECT *", "1 elif token[0] in \")]\": level = level - 1 else: break chunks.append((1,", "db = DB(None, {}) >>> db.query(\"SELECT * FROM foo\", _test=True) <sql: 'SELECT *", "(int, long)): if sql == 'WHERE': nout = 'id = ' + sqlquote(val)", "SQLQuery(items) def sqlquote(a): \"\"\" Ensures `a` is quoted properly for use in a", "i, item in enumerate(self.items): if isinstance(item, SQLParam) and isinstance(item.value, SQLLiteral): self.items[i] = item.value.v", "return \"unfinished expression in %s at char %d\" % ( repr(self.text), self.pos) class", "and `using`. >>> db = DB(None, {}) >>> name = 'Joe' >>> db.delete('foo',", "v in values: if v.keys() != keys: raise ValueError, 'Bad data' sql_query =", "if isinstance(item, SQLParam) and isinstance(item.value, SQLLiteral): self.items[i] = item.value.v def append(self, value): self.items.append(value)", "if not values: return [] if not self.supports_multiple_insert: out = [self.insert(tablename, seqname=seqname, _test=_test,", "in enumerate(values): if i != 0: items.append(', ') items.append(sqlparam(v)) items.append(')') return SQLQuery(items) def", "pos def __str__(self): return \"unfinished expression in %s at char %d\" % (", "= \" + sqlquote('f'), _test=True) <sql: \"SELECT * FROM foo WHERE x =", "3)\"> \"\"\" if isinstance(a, list): return _sqllist(a) else: return sqlparam(a).sqlquery() def _interpolate(sformat): \"\"\"", "limit, offset) clauses = [self.gen_clause(sql, val, svars) for sql, val in sql_clauses if", "return obj elif hasattr(obj, 'next'): # iterator return itertools.imap(safestr, obj) else: return str(obj)", "at char %d\" % ( repr(self.text), self.pos) class SQLParam(object): \"\"\" Parameter in SQLQuery.", "':1' elif paramstyle is None or paramstyle in ['format', 'pyformat']: return '%s' raise", "if isinstance(obj, unicode): return obj.encode(encoding) elif isinstance(obj, str): return obj elif hasattr(obj, 'next'):", "from the dictionary. Returns an `SQLQuery` for the result. >>> reparam(\"s = $s\",", "SQLQuery(val) elif isinstance(val, (list, tuple)) and len(val) == 2: nout = SQLQuery(val[0], val[1])", "bar WHERE foo.bar_id = bar.id LIMIT 5'> \"\"\" if svars is None: svars", "in the query # For backward compatability, ignore escaping when the query looks", "+ x + \")\" if values: _keys = SQLQuery.join(values.keys(), ', ') _values =", "= dictionary.copy() # eval mucks with it result = [] for live, chunk", "numeric, format, pyformat) \"\"\" pass class _ItplError(ValueError): def __init__(self, text, pos): ValueError.__init__(self) self.text", "= dollar + 2, 1 while level: match, pos = matchorfail(sformat, pos) tstart,", "paramstyle def sqlquery(self): return SQLQuery([self]) def __add__(self, other): return self.sqlquery() + other def", "obj elif t is str: return obj.decode(encoding) elif t in [int, float, bool]:", "= [\"value\"] def __init__(self, value): self.value = value def get_marker(self, paramstyle='pyformat'): if paramstyle", "+ self.sqlquery() def __str__(self): return str(self.value) def __repr__(self): return '<param: %s>' % repr(self.value)", "foo, bar WHERE foo.bar_id = bar.id LIMIT 5'> \"\"\" if svars is None:", "= sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor, sql_query) try: out = db_cursor.fetchone()[0]", "_test=False): \"\"\" Deletes from `table` with clauses `where` and `using`. >>> db =", "% characters in the query # For backward compatability, ignore escaping when the", "pos = dollar + 1 + (nextchar == \"$\") if pos < len(sformat):", "ValueError.__init__(self) self.text = text self.pos = pos def __str__(self): return \"unfinished expression in", "TypeError): return self.query() def __str__(self): return safestr(self._str()) def __unicode__(self): return safeunicode(self._str()) def __repr__(self):", "sqlquote(val) else: nout = SQLQuery(val) elif isinstance(val, (list, tuple)) and len(val) == 2:", "{}) >>> q = db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'), _test=True) >>> q <sql: \"INSERT", "test WHERE x=1'> >>> q.query(), q.values() ('SELECT * FROM test WHERE x=%s', [1])", "Returns current sequence ID. Set `seqname` to the ID if it's not the", "= SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam(\"joe\")]) >>> q <sql: \"SELECT *", "safestr(obj, encoding='utf-8'): r\"\"\" Converts any given object to utf-8 encoded string. >>> safestr('hello')", "list to use instead of interpolating. >>> db = DB(None, {}) >>> db.query(\"SELECT", "be evaled or not. from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee) \"\"\" from tokenize", "is not False: sql_query = self._process_insert_query(sql_query, tablename, seqname) if isinstance(sql_query, tuple): # for", "\") SQLQuery.join([SQLParam(row[k]) for k in keys], sep=\", \", target=sql_query, prefix=\"(\", suffix=\")\") if _test:", "def join(items, sep=' ', prefix=None, suffix=None, target=None): \"\"\" Joins multiple queries. >>> SQLQuery.join(['a',", "WHERE x = \" + sqlquote('f'), _test=True) <sql: \"SELECT * FROM foo WHERE", "return SQLQuery(items) def sqlquote(a): \"\"\" Ensures `a` is quoted properly for use in", "and a dictionary and interpolates the string using values from the dictionary. Returns", "sql == 'WHERE': nout = 'id = ' + sqlquote(val) else: nout =", "isinstance(sql_query, SQLQuery): sql_query = reparam(sql_query, svars) return sql_query def sql_clauses(self, what, tables, where,", "\"\"\" __slots__ = [\"value\"] def __init__(self, value): self.value = value def get_marker(self, paramstyle='pyformat'):", "\"\"\" Execute SQL query `sql_query` using dictionary `vars` to interpolate it. If `processed=True`,", "isinstance(obj, unicode): return obj.encode(encoding) elif isinstance(obj, str): return obj elif hasattr(obj, 'next'): #", "where boolean says whether string should be evaled or not. from <http://lfw.org/python/Itpl.py> (public", "db function. Otherwise, you can pass a dictionary to the keyword argument `vars`", "return sql_query def sql_clauses(self, what, tables, where, group, order, limit, offset): return (", "unsupported db paramstyles (currently supported: qmark, numeric, format, pyformat) \"\"\" pass class _ItplError(ValueError):", "+ 1, 1 while level: match, pos = matchorfail(sformat, pos) tstart, tend =", "sqlquery(self): return SQLQuery([self]) def __add__(self, other): return self.sqlquery() + other def __radd__(self, other):", "= ' + sqlquote(True) + ' AND y IN ' + sqlquote([2, 3])", "for i in self.items if isinstance(i, SQLParam)] def join(items, sep=' ', prefix=None, suffix=None,", "for k, v in dictionary.items()], grouping) def reparam(string_, dictionary): \"\"\" Takes a string", "not values: return [] if not self.supports_multiple_insert: out = [self.insert(tablename, seqname=seqname, _test=_test, **v)", "\"\"\" s = [] for x in self.items: if isinstance(x, SQLParam): x =", "if there isn't one. >>> db = DB(None, {}) >>> db.supports_multiple_insert = True", "other.items else: return NotImplemented return SQLQuery(self.items + items) def __radd__(self, other): if isinstance(other,", "'.join(keys))) for i, row in enumerate(values): if i != 0: sql_query.append(\", \") SQLQuery.join([SQLParam(row[k])", "\")\" if values: _keys = SQLQuery.join(values.keys(), ', ') _values = SQLQuery.join([sqlparam(v) for v", "docstring def __init__(self, items=None): r\"\"\"Creates a new SQLQuery. >>> SQLQuery(\"x\") <sql: 'x'> >>>", "WHERE name=\", SQLParam('joe')]) >>> q.query() 'SELECT * FROM test WHERE name=%s' >>> q.query(paramstyle='qmark')", "= matchorfail(sformat, pos + 1) elif sformat[pos] in \"([\": pos, level = pos", "way... if obj is None: return 'NULL' elif obj is True: return \"'t'\"", "`vars` and the function will call reparam for you. Internally, consists of `items`,", "raise _ItplError(text, pos) return match, match.end() namechars = \"abcdefghijklmnopqrstuvwxyz\" \\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks =", "produce the actual query. \"\"\" __slots__ = [\"items\"] # tested in sqlquote's docstring", "else: return str(obj) def sqlify(obj): \"\"\" converts `obj` to its proper SQL version", "a separate query has to be made to find # the id of", "grouping) def reparam(string_, dictionary): \"\"\" Takes a string and a dictionary and interpolates", "call reparam for you. Internally, consists of `items`, which is a list of", "vars=locals(), _test=True) <sql: \"DELETE FROM foo WHERE name = 'Joe'\"> \"\"\" if svars", ">>> db = DB(None, {}) >>> name = 'Joseph' >>> q = db.update('foo',", "'t' AND y IN (2, 3)\"> \"\"\" if isinstance(a, list): return _sqllist(a) else:", "and the function will call reparam for you. Internally, consists of `items`, which", "if token[0] in \"([\": level = level + 1 elif token[0] in \")]\":", "ID if it's not the default, or to `False` if there isn't one.", "tablename, values, seqname=None, _test=False): \"\"\" Inserts multiple rows into `tablename`. The `values` must", "sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor, sql_query) try: out = db_cursor.fetchone()[0] out", "= ' + sqlparam(v) for k, v in dictionary.items()], grouping) def reparam(string_, dictionary):", "the query looks already escaped if paramstyle in ['format', 'pyformat']: if '%' in", "svars = {} sql_clauses = self.sql_clauses(what, tables, where, group, order, limit, offset) clauses", "return out def update(self, tables, where, svars=None, _test=False, **values): \"\"\" Update `tables` with", "tokenize import tokenprog tokenprog = tokenprog def matchorfail(text, pos): match = tokenprog.match(text, pos)", "SQLLiteral): self.items[i] = item.value.v def append(self, value): self.items.append(value) def __add__(self, other): if isinstance(other,", "return SQLQuery.join(result, '') class UnknownParamstyle(Exception): \"\"\" raised for unsupported db paramstyles (currently supported:", "paramstyle=None): \"\"\" Returns the query part of the sql query. >>> q =", "== 2: where = SQLQuery(where[0], where[1]) elif isinstance(where, SQLQuery): pass else: where =", "item.value.v def append(self, value): self.items.append(value) def __add__(self, other): if isinstance(other, basestring): items =", "SQLParam(object): \"\"\" Parameter in SQLQuery. >>> q = SQLQuery([\"SELECT * FROM test WHERE", "isinstance(lst, basestring): return lst else: return ', '.join(lst) def _sqllist(values): \"\"\" >>> _sqllist([1,", "when the query looks already escaped if paramstyle in ['format', 'pyformat']: if '%'", "# the id of the inserted row. q1, q2 = sql_query self._db_execute(db_cursor, q1)", "FROM test WHERE name=\", SQLParam(\"joe\")]) >>> q <sql: \"SELECT * FROM test WHERE", "'a, b'> Optinally, prefix and suffix arguments can be provided. >>> SQLQuery.join(['a', 'b'],", "class SQLQuery(object): \"\"\" You can pass this sort of thing as a clause", "* FROM ', 'test', ' WHERE x=', SQLParam(1)]) >>> q <sql: 'SELECT *", "x = ' + sqlquote(True) + ' AND y IN ' + sqlquote([2,", "match, pos = matchorfail(sformat, pos) tstart, tend = match.regs[3] token = sformat[tstart:tend] if", "(tablename, ', '.join(keys))) for i, row in enumerate(values): if i != 0: sql_query.append(\",", "else: break chunks.append((1, sformat[dollar + 1:pos])) else: chunks.append((0, sformat[pos:dollar + 1])) pos =", "return obj elif t is str: return obj.decode(encoding) elif t in [int, float,", "paramstyle == 'qmark': return '?' elif paramstyle == 'numeric': return ':1' elif paramstyle", "% table def multiple_insert(self, tablename, values, seqname=None, _test=False): \"\"\" Inserts multiple rows into", "vars=dict(x='f'), _test=True) <sql: \"SELECT * FROM foo WHERE x = 'f'\"> >>> db.query(\"SELECT", "<sql: \"DELETE FROM foo WHERE name = 'Joe'\"> \"\"\" if svars is None:", "quoted properly for use in a SQL query. >>> 'WHERE x = '", "= reparam(where, svars) return where def select(self, tables, svars=None, what='*', where=None, order=None, group=None,", "SET \" + sqlwhere(values, ', ') + \" WHERE \" + where) if", "in any db function. Otherwise, you can pass a dictionary to the keyword", "'Joseph' >>> q = db.update('foo', where='name = $name', name='bob', age=2, ... created=SQLLiteral('NOW()'), vars=locals(),", "b' >>> sqllist('a') 'a' >>> sqllist(u'abc') u'abc' \"\"\" if isinstance(lst, basestring): return lst", "are valid # make sure all rows have same keys. for v in", "q(_keys) + ' VALUES ' + q(_values) else: sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query", "is None: target = SQLQuery() target_items = target.items if prefix: target_items.append(prefix) for i,", "foo WHERE x = $x\", vars=dict(x='f'), _test=True) <sql: \"SELECT * FROM foo WHERE", "where, svars): if isinstance(where, (int, long)): where = \"id = \" + sqlparam(where)", "safeunicode('hello') u'hello' >>> safeunicode(2) u'2' >>> safeunicode('\\xe1\\x88\\xb4') u'\\u1234' \"\"\" t = type(obj) if", "if a and b: return a + ' ' + b else: return", "sformat[pos:])) return chunks def sqlwhere(dictionary, grouping=' AND '): \"\"\" Converts a `dictionary` to", "unicode(obj) else: return str(obj).decode(encoding) def safestr(obj, encoding='utf-8'): r\"\"\" Converts any given object to", "already escaped if paramstyle in ['format', 'pyformat']: if '%' in x and '%%'", "if isinstance(i, SQLParam)] def join(items, sep=' ', prefix=None, suffix=None, target=None): \"\"\" Joins multiple", "2, 'order_id':3}) <sql: 'order_id = 3 AND cust_id = 2'> >>> sqlwhere({'cust_id': 2,", "using dictionary `vars` to interpolate it. If `processed=True`, `vars` is a `reparam`-style list", "object to unicode string. >>> safeunicode('hello') u'hello' >>> safeunicode(2) u'2' >>> safeunicode('\\xe1\\x88\\xb4') u'\\u1234'", "use instead of interpolating. >>> db = DB(None, {}) >>> db.query(\"SELECT * FROM", "= SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam('joe')]) >>> q.query() 'SELECT * FROM", "None else: return out keys = values[0].keys() #@@ make sure all keys are", "eval(chunk, dictionary) result.append(sqlquote(v)) else: result.append(chunk) return SQLQuery.join(result, '') class UnknownParamstyle(Exception): \"\"\" raised for", "appended to target instead of creating a new SQLQuery. \"\"\" if target is", "is None: svars = {} sql_clauses = self.sql_clauses(what, tables, where, group, order, limit,", ">>> sqlwhere({'cust_id': 2, 'order_id':3}, grouping=', ') <sql: 'order_id = 3, cust_id = 2'>", "for unsupported db paramstyles (currently supported: qmark, numeric, format, pyformat) \"\"\" pass class", "__init__(self, v): self.v = v def __repr__(self): return self.v class SQLProducer: \"\"\"Database\"\"\" def", "paramstyle='pyformat'): if paramstyle == 'qmark': return '?' elif paramstyle == 'numeric': return ':1'", "if svars is None: svars = {} where = self._where(where, svars) q =", "%s>' % repr(str(self)) class SQLLiteral: \"\"\" Protects a string from `sqlquote`. >>> sqlquote('NOW()')", "_test: return sql_query db_cursor = self._db_cursor() if seqname is not False: sql_query =", "% repr(self.value) sqlparam = SQLParam class SQLQuery(object): \"\"\" You can pass this sort", "IN ' + sqlquote([2, 3]) <sql: \"WHERE x = 't' AND y IN", "sort of thing as a clause in any db function. Otherwise, you can", "new SQLQuery. >>> SQLQuery(\"x\") <sql: 'x'> >>> q = SQLQuery(['SELECT * FROM ',", "= {} if not processed and not isinstance(sql_query, SQLQuery): sql_query = reparam(sql_query, svars)", "q <sql: \"UPDATE foo SET age = 2, name = 'bob', created =", "unicode(obj) elif hasattr(obj, '__unicode__') or isinstance(obj, unicode): return unicode(obj) else: return str(obj).decode(encoding) def", "self def __len__(self): return len(self.query()) def query(self, paramstyle=None): \"\"\" Returns the query part", "says whether string should be evaled or not. from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping", ">>> sqllist('a') 'a' >>> sqllist(u'abc') u'abc' \"\"\" if isinstance(lst, basestring): return lst else:", "2, 'order_id':3}, grouping=', ') <sql: 'order_id = 3, cust_id = 2'> >>> sqlwhere({'a':", "def values(self): \"\"\" Returns the values of the parameters used in the sql", "a + ' ' + b else: return a or b return xjoin(sql,", "where = self._where(where, svars) q = 'DELETE FROM ' + table if using:", "\"\"\" pass def query(self, sql_query,processed=False, svars=None): \"\"\" Execute SQL query `sql_query` using dictionary", "WHERE x = 'f'\"> >>> db.query(\"SELECT * FROM foo WHERE x = \"", "break nextchar = sformat[dollar + 1] if nextchar == \"{\": chunks.append((0, sformat[pos:dollar])) pos,", "in SQLQuery. >>> q = SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam(\"joe\")]) >>>", "is provided, the items are appended to target instead of creating a new", "and setting `values`. >>> db = DB(None, {}) >>> name = 'Joseph' >>>", "0: items.append(', ') items.append(sqlparam(v)) items.append(')') return SQLQuery(items) def sqlquote(a): \"\"\" Ensures `a` is", "2:pos - 1])) elif nextchar in namechars: chunks.append((0, sformat[pos:dollar])) match, pos = matchorfail(sformat,", "with clauses `where`, `order`, `group`, `limit`, and `offset`. Uses vars to interpolate. Otherwise,", "list of dictioanries, one for each row to be inserted, each with the", "pos = 0 while 1: dollar = sformat.find(\"$\", pos) if dollar < 0:", "= 3\"> >>> 'WHERE x = ' + sqlquote(True) + ' AND y", "% tuple([sqlify(x) for x in self.values()]) except (ValueError, TypeError): return self.query() def __str__(self):", "False: sql_query = self._process_insert_query(sql_query, tablename, seqname) if isinstance(sql_query, tuple): # for some databases,", "== True and hash(1) == hash(True)` # we have to do this the", "isinstance(sql_query, tuple): # for some databases, a separate query has to be made", "def _where(self, where, svars): if isinstance(where, (int, long)): where = \"id = \"", "db = DB(None, {}) >>> q = db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'), _test=True) >>>", "svars is None: svars = {} if not processed and not isinstance(sql_query, SQLQuery):", ">>> db.delete('foo', where='name = $name', vars=locals(), _test=True) <sql: \"DELETE FROM foo WHERE name", "Created on 2013-8-21 @author: lan (www.9miao.com) ''' import itertools import datetime def safeunicode(obj,", "safestr(u'\\u1234') '\\xe1\\x88\\xb4' >>> safestr(2) '2' \"\"\" if isinstance(obj, unicode): return obj.encode(encoding) elif isinstance(obj,", "return repr(obj) def sqllist(lst): \"\"\" Converts the arguments for use in something like", "object to utf-8 encoded string. >>> safestr('hello') 'hello' >>> safestr(u'\\u1234') '\\xe1\\x88\\xb4' >>> safestr(2)", "sure all keys are valid # make sure all rows have same keys.", "not self.ctx.transactions: self.ctx.commit() return out def update(self, tables, where, svars=None, _test=False, **values): \"\"\"", "== 'qmark': return '?' elif paramstyle == 'numeric': return ':1' elif paramstyle is", "__str__(self): return str(self.value) def __repr__(self): return '<param: %s>' % repr(self.value) sqlparam = SQLParam", "\"\"\" Ensures `a` is quoted properly for use in a SQL query. >>>", "= \"id = \" + sqlparam(where) elif isinstance(where, (list, tuple)) and len(where) ==", "\"([\": pos, level = pos + 1, 1 while level: match, pos =", "q = SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam(\"joe\")]) >>> q <sql: \"SELECT", "the keyword argument `vars` and the function will call reparam for you. Internally,", "_get_insert_default_values_query(self, table): return \"INSERT INTO %s DEFAULT VALUES\" % table def multiple_insert(self, tablename,", "* FROM foo WHERE x = 'f'\"> \"\"\" if svars is None: svars", "other + self.sqlquery() def __str__(self): return str(self.value) def __repr__(self): return '<param: %s>' %", "\"id = \" + sqlparam(where) elif isinstance(where, (list, tuple)) and len(where) == 2:", "which get concatenated to produce the actual query. \"\"\" __slots__ = [\"items\"] #", "Otherwise, each clause can be a SQLQuery. >>> db = DB(None, {}) >>>", "qmark, numeric, format, pyformat) \"\"\" pass class _ItplError(ValueError): def __init__(self, text, pos): ValueError.__init__(self)", "db = DB(None, {}) >>> name = 'Joe' >>> db.delete('foo', where='name = $name',", "query(self, paramstyle=None): \"\"\" Returns the query part of the sql query. >>> q", "= NOW() WHERE name = %s' >>> q.values() [2, 'bob', 'Joseph'] \"\"\" if", "SQLParam(\"joe\")]) >>> q <sql: \"SELECT * FROM test WHERE name='joe'\"> >>> q.query() 'SELECT", "2'> >>> sqlwhere({'cust_id': 2, 'order_id':3}, grouping=', ') <sql: 'order_id = 3, cust_id =", "in x: x = x.replace('%', '%%') s.append(x) return \"\".join(s) def values(self): \"\"\" Returns", "while pos < len(sformat): if sformat[pos] == \".\" and \\ pos + 1", "not in x: x = x.replace('%', '%%') s.append(x) return \"\".join(s) def values(self): \"\"\"", "prefix: target_items.append(prefix) for i, item in enumerate(items): if i != 0: target_items.append(sep) if", "FROM test WHERE name=%s' >>> q.query(paramstyle='qmark') 'SELECT * FROM test WHERE name=?' \"\"\"", "y IN ' + sqlquote([2, 3]) <sql: \"WHERE x = 't' AND y", "svars) for sql, val in sql_clauses if val is not None] qout =", "properly for use in a SQL query. >>> 'WHERE x = ' +", "foo WHERE x = 'f'\"> \"\"\" if svars is None: svars = {}", "<reponame>handsome3163/H2Dgame-Firefly<gh_stars>100-1000 #coding:utf8 ''' Created on 2013-8-21 @author: lan (www.9miao.com) ''' import itertools import", "True: return \"'t'\" elif obj is False: return \"'f'\" elif datetime and isinstance(obj,", "safestr(self._str()) def __unicode__(self): return safeunicode(self._str()) def __repr__(self): return '<sql: %s>' % repr(str(self)) class", "`offset`. Uses vars to interpolate. Otherwise, each clause can be a SQLQuery. >>>", "pos + 1, 1 while level: match, pos = matchorfail(sformat, pos) tstart, tend", "'order_id':3}, grouping=', ') <sql: 'order_id = 3, cust_id = 2'> >>> sqlwhere({'a': 'a',", "ID. Set `seqname` to the ID if it's not the default, or to", "obj.decode(encoding) elif t in [int, float, bool]: return unicode(obj) elif hasattr(obj, '__unicode__') or", "matchorfail(sformat, pos + 1) elif sformat[pos] in \"([\": pos, level = pos +", "values(self): \"\"\" Returns the values of the parameters used in the sql query.", "def delete(self, table, where, using=None, svars=None, _test=False): \"\"\" Deletes from `table` with clauses", "into `tablename`. Returns current sequence ID. Set `seqname` to the ID if it's", "v): self.v = v def __repr__(self): return self.v class SQLProducer: \"\"\"Database\"\"\" def __init__(self):", "= type(obj) if t is unicode: return obj elif t is str: return", "level = level + 1 elif token == \"}\": level = level -", "return unicode(obj) else: return str(obj).decode(encoding) def safestr(obj, encoding='utf-8'): r\"\"\" Converts any given object", "<sql: 'order_id = 3 AND cust_id = 2'> >>> sqlwhere({'cust_id': 2, 'order_id':3}, grouping=',", "v in enumerate(values): if i != 0: items.append(', ') items.append(sqlparam(v)) items.append(')') return SQLQuery(items)", "'') class UnknownParamstyle(Exception): \"\"\" raised for unsupported db paramstyles (currently supported: qmark, numeric,", "`False` if there isn't one. >>> db = DB(None, {}) >>> q =", "WHERE x=1'> >>> q.query(), q.values() ('SELECT * FROM test WHERE x=%s', [1]) >>>", "\"\"\"Database\"\"\" def __init__(self): \"\"\"Creates a database. \"\"\" pass def query(self, sql_query,processed=False, svars=None): \"\"\"", "offset): return ( ('SELECT', what), ('FROM', sqllist(tables)), ('WHERE', where), ('GROUP BY', group), ('ORDER", "['joe'] \"\"\" __slots__ = [\"value\"] def __init__(self, value): self.value = value def get_marker(self,", "paramstyles (currently supported: qmark, numeric, format, pyformat) \"\"\" pass class _ItplError(ValueError): def __init__(self,", "other): if isinstance(other, basestring): items = [other] else: return NotImplemented return SQLQuery(items +", "we have to do this the hard way... if obj is None: return", "'(1, 2, 3)'> \"\"\" items = [] items.append('(') for i, v in enumerate(values):", "SQLQuery): sql_query = reparam(sql_query, svars) return sql_query def sql_clauses(self, what, tables, where, group,", "%s (%s) VALUES ' % (tablename, ', '.join(keys))) for i, row in enumerate(values):", "using: q += ' USING ' + sqllist(using) if where: q += '", "SQLParam)): self.items.append(other) elif isinstance(other, SQLQuery): self.items.extend(other.items) else: return NotImplemented return self def __len__(self):", "if match is None: raise _ItplError(text, pos) return match, match.end() namechars = \"abcdefghijklmnopqrstuvwxyz\"", "database. \"\"\" pass def query(self, sql_query,processed=False, svars=None): \"\"\" Execute SQL query `sql_query` using", "%s' \"\"\" return SQLQuery.join([k + ' = ' + sqlparam(v) for k, v", "= 'DELETE FROM ' + table if using: q += ' USING '", "FROM test WHERE name=?' \"\"\" s = [] for x in self.items: if", "enumerate(values): if i != 0: items.append(', ') items.append(sqlparam(v)) items.append(')') return SQLQuery(items) def sqlquote(a):", "') _values = SQLQuery.join([sqlparam(v) for v in values.values()], ', ') sql_query = \"INSERT", "DB(None, {}) >>> q = db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'), _test=True) >>> q <sql:", "len(self.query()) def query(self, paramstyle=None): \"\"\" Returns the query part of the sql query.", "tables, where, group, order, limit, offset) clauses = [self.gen_clause(sql, val, svars) for sql,", "if i != 0: sql_query.append(\", \") SQLQuery.join([SQLParam(row[k]) for k in keys], sep=\", \",", "`sql_query` using dictionary `vars` to interpolate it. If `processed=True`, `vars` is a `reparam`-style", "= ' + sqlquote(True) + ' AND y = ' + sqlquote(3) <sql:", "NotImplemented return self def __len__(self): return len(self.query()) def query(self, paramstyle=None): \"\"\" Returns the", "table def multiple_insert(self, tablename, values, seqname=None, _test=False): \"\"\" Inserts multiple rows into `tablename`.", "def sqlquery(self): return SQLQuery([self]) def __add__(self, other): return self.sqlquery() + other def __radd__(self,", "if isinstance(x, SQLParam): x = x.get_marker(paramstyle) s.append(safestr(x)) else: x = safestr(x) # automatically", "staticmethod(join) def _str(self): try: return self.query() % tuple([sqlify(x) for x in self.values()]) except", "be provided. >>> SQLQuery.join(['a', 'b'], ', ', prefix='(', suffix=')') <sql: '(a, b)'> If", "if val is not None] qout = SQLQuery.join(clauses) if _test: return qout return", "'x'> >>> q = SQLQuery(['SELECT * FROM ', 'test', ' WHERE x=', SQLParam(1)])", "enumerate(values): if i != 0: sql_query.append(\", \") SQLQuery.join([SQLParam(row[k]) for k in keys], sep=\",", "= DB(None, {}) >>> db.supports_multiple_insert = True >>> values = [{\"name\": \"foo\", \"email\":", "WHERE name=\", SQLParam('joe')]) >>> q.values() ['joe'] \"\"\" return [i.value for i in self.items", "FROM test WHERE name=\", SQLParam('joe')]) >>> q.values() ['joe'] \"\"\" return [i.value for i", "elif isinstance(items, SQLParam): self.items = [items] elif isinstance(items, SQLQuery): self.items = list(items.items) else:", ">>> q.values() ['joe'] \"\"\" return [i.value for i in self.items if isinstance(i, SQLParam)]", "#@@ make sure all keys are valid # make sure all rows have", "'id = ' + sqlquote(val) else: nout = SQLQuery(val) elif isinstance(val, (list, tuple))", ">>> sqlify(True) \"'t'\" >>> sqlify(3) '3' \"\"\" # because `1 == True and", "pos): match = tokenprog.match(text, pos) if match is None: raise _ItplError(text, pos) return", "k, v in dictionary.items()], grouping) def reparam(string_, dictionary): \"\"\" Takes a string and", "FROM ' + table if using: q += ' USING ' + sqllist(using)", "'Joe' >>> db.delete('foo', where='name = $name', vars=locals(), _test=True) <sql: \"DELETE FROM foo WHERE", "items = [] items.append('(') for i, v in enumerate(values): if i != 0:", "query. >>> 'WHERE x = ' + sqlquote(True) + ' AND y =", "items.append(', ') items.append(sqlparam(v)) items.append(')') return SQLQuery(items) def sqlquote(a): \"\"\" Ensures `a` is quoted", "string using values from the dictionary. Returns an `SQLQuery` for the result. >>>", "rows into `tablename`. The `values` must be a list of dictioanries, one for", ">>> safestr(2) '2' \"\"\" if isinstance(obj, unicode): return obj.encode(encoding) elif isinstance(obj, str): return", "self._db_cursor() if seqname is not False: sql_query = self._process_insert_query(sql_query, tablename, seqname) if isinstance(sql_query,", "ignore escaping when the query looks already escaped if paramstyle in ['format', 'pyformat']:", "matchorfail(sformat, dollar + 1) while pos < len(sformat): if sformat[pos] == \".\" and", "= pos def __str__(self): return \"unfinished expression in %s at char %d\" %", "SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam('joe')]) >>> q.query() 'SELECT * FROM test", ">>> safestr(u'\\u1234') '\\xe1\\x88\\xb4' >>> safestr(2) '2' \"\"\" if isinstance(obj, unicode): return obj.encode(encoding) elif", "using `vars`) and setting `values`. >>> db = DB(None, {}) >>> name =", "delete(self, table, where, using=None, svars=None, _test=False): \"\"\" Deletes from `table` with clauses `where`", "sqllist('a') 'a' >>> sqllist(u'abc') u'abc' \"\"\" if isinstance(lst, basestring): return lst else: return", "for each row to be inserted, each with the same set of keys.", "<sql: \"WHERE x = 't' AND y IN (2, 3)\"> \"\"\" if isinstance(a,", "one. >>> db = DB(None, {}) >>> q = db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'),", "sformat[pos:dollar])) match, pos = matchorfail(sformat, dollar + 1) while pos < len(sformat): if", "and \\ pos + 1 < len(sformat) and sformat[pos + 1] in namechars:", "+ 1] if nextchar == \"{\": chunks.append((0, sformat[pos:dollar])) pos, level = dollar +", "foo (age, name, created) VALUES (2, 'bob', NOW())\"> >>> q.query() 'INSERT INTO foo", "dictionary.copy() # eval mucks with it result = [] for live, chunk in", ">>> db = DB(None, {}) >>> q = db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'), _test=True)", "_test: return query db_cursor = self._db_cursor() self._db_execute(db_cursor, query) if not self.ctx.transactions: self.ctx.commit() return", "row in enumerate(values): if i != 0: sql_query.append(\", \") SQLQuery.join([SQLParam(row[k]) for k in", "nextchar == \"{\": chunks.append((0, sformat[pos:dollar])) pos, level = dollar + 2, 1 while", "to interpolate it. If `processed=True`, `vars` is a `reparam`-style list to use instead", "def __unicode__(self): return safeunicode(self._str()) def __repr__(self): return '<sql: %s>' % repr(str(self)) class SQLLiteral:", "query) if not self.ctx.transactions: self.ctx.commit() return db_cursor.rowcount def delete(self, table, where, using=None, svars=None,", "basestring): items = [other] else: return NotImplemented return SQLQuery(items + self.items) def __iadd__(self,", "'NOW()'> \"\"\" def __init__(self, v): self.v = v def __repr__(self): return self.v class", "= match.regs[3] token = sformat[tstart:tend] if token[0] in \"([\": level = level +", "<sql: 'NOW()'> \"\"\" def __init__(self, v): self.v = v def __repr__(self): return self.v", "' + sqlquote(True) + ' AND y IN ' + sqlquote([2, 3]) <sql:", "sql_clauses = self.sql_clauses(what, tables, where, group, order, limit, offset) clauses = [self.gen_clause(sql, val,", "SQLParam) and isinstance(item.value, SQLLiteral): self.items[i] = item.value.v def append(self, value): self.items.append(value) def __add__(self,", "datetime and isinstance(obj, datetime.datetime): return repr(obj.isoformat()) else: if isinstance(obj, unicode): obj = obj.encode('utf8')", "return a + ' ' + b else: return a or b return", "for k in keys], sep=\", \", target=sql_query, prefix=\"(\", suffix=\")\") if _test: return sql_query", "a database. \"\"\" pass def query(self, sql_query,processed=False, svars=None): \"\"\" Execute SQL query `sql_query`", "('ORDER BY', order), ('LIMIT', limit), ('OFFSET', offset)) def gen_clause(self, sql, val, svars): if", "obj.encode('utf8') return repr(obj) def sqllist(lst): \"\"\" Converts the arguments for use in something", "sqlparam(a).sqlquery() def _interpolate(sformat): \"\"\" Takes a format string and returns a list of", "dictionary): \"\"\" Takes a string and a dictionary and interpolates the string using", "= level - 1 chunks.append((1, sformat[dollar + 2:pos - 1])) elif nextchar in", "value): self.value = value def get_marker(self, paramstyle='pyformat'): if paramstyle == 'qmark': return '?'", "' + sqlquote(val) else: nout = SQLQuery(val) elif isinstance(val, (list, tuple)) and len(val)", "__unicode__(self): return safeunicode(self._str()) def __repr__(self): return '<sql: %s>' % repr(str(self)) class SQLLiteral: \"\"\"", "a `reparam`-style list to use instead of interpolating. >>> db = DB(None, {})", "i, row in enumerate(values): if i != 0: sql_query.append(\", \") SQLQuery.join([SQLParam(row[k]) for k", "expression in %s at char %d\" % ( repr(self.text), self.pos) class SQLParam(object): \"\"\"", "try: out = db_cursor.fetchone()[0] out = range(out-len(values)+1, out+1) except Exception: out = None", "matchorfail(sformat, pos) tstart, tend = match.regs[3] token = sformat[tstart:tend] if token[0] in \"([\":", "= SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam('joe')]) >>> q.values() ['joe'] \"\"\" return", "repr(self.value) sqlparam = SQLParam class SQLQuery(object): \"\"\" You can pass this sort of", "1 < len(sformat) and sformat[pos + 1] in namechars: match, pos = matchorfail(sformat,", "is quoted properly for use in a SQL query. >>> 'WHERE x =", "nextchar = sformat[dollar + 1] if nextchar == \"{\": chunks.append((0, sformat[pos:dollar])) pos, level", "'SELECT * FROM foo, bar WHERE foo.bar_id = bar.id LIMIT 5'> \"\"\" if", "all keys are valid # make sure all rows have same keys. for", "= other.items else: return NotImplemented return SQLQuery(self.items + items) def __radd__(self, other): if", "insert(self, tablename, seqname=None, _test=False, **values): \"\"\" Inserts `values` into `tablename`. Returns current sequence", "svars): if isinstance(val, (int, long)): if sql == 'WHERE': nout = 'id =", "items are appended to target instead of creating a new SQLQuery. \"\"\" if", "__repr__(self): return '<sql: %s>' % repr(str(self)) class SQLLiteral: \"\"\" Protects a string from", "FROM foo WHERE name = 'Joe'\"> \"\"\" if svars is None: svars =", "test WHERE x=%s', [1]) >>> SQLQuery(SQLParam(1)) <sql: '1'> \"\"\" if items is None:", "'(a, b)'> If target argument is provided, the items are appended to target", "= \" + sqlparam(where) elif isinstance(where, (list, tuple)) and len(where) == 2: where", "be a SQLQuery. >>> db = DB(None, {}) >>> db.select('foo', _test=True) <sql: 'SELECT", "matchorfail(sformat, pos) tstart, tend = match.regs[3] token = sformat[tstart:tend] if token == \"{\":", "0: target_items.append(sep) if isinstance(item, SQLQuery): target_items.extend(item.items) else: target_items.append(item) if suffix: target_items.append(suffix) return target", "__radd__(self, other): return other + self.sqlquery() def __str__(self): return str(self.value) def __repr__(self): return", "update(self, tables, where, svars=None, _test=False, **values): \"\"\" Update `tables` with clause `where` (interpolated", "name = 'Joseph'\"> >>> q.query() 'UPDATE foo SET age = %s, name =", "import datetime def safeunicode(obj, encoding='utf-8'): r\"\"\" Converts any given object to unicode string.", "clause in any db function. Otherwise, you can pass a dictionary to the", "'bob'] \"\"\" def q(x): return \"(\" + x + \")\" if values: _keys", "def __init__(self, value): self.value = value def get_marker(self, paramstyle='pyformat'): if paramstyle == 'qmark':", "nout = SQLQuery(val[0], val[1]) # backwards-compatibility elif isinstance(val, SQLQuery): nout = val else:", "Exception: out = None if not self.ctx.transactions: self.ctx.commit() return out def update(self, tables,", "where='name = $name', vars=locals(), _test=True) <sql: \"DELETE FROM foo WHERE name = 'Joe'\">", "$name', vars=locals(), _test=True) <sql: \"DELETE FROM foo WHERE name = 'Joe'\"> \"\"\" if", "SQLParam('joe')]) >>> q.query() 'SELECT * FROM test WHERE name=%s' >>> q.query(paramstyle='qmark') 'SELECT *", "isinstance(items, list): self.items = items elif isinstance(items, SQLParam): self.items = [items] elif isinstance(items,", "in \")]\": level = level - 1 else: break chunks.append((1, sformat[dollar + 1:pos]))", "join = staticmethod(join) def _str(self): try: return self.query() % tuple([sqlify(x) for x in", "= list(items.items) else: self.items = [items] # Take care of SQLLiterals for i,", "WHERE name=\", SQLParam(\"joe\")]) >>> q <sql: \"SELECT * FROM test WHERE name='joe'\"> >>>", "raise UnknownParamstyle, paramstyle def sqlquery(self): return SQLQuery([self]) def __add__(self, other): return self.sqlquery() +", "can be provided. >>> SQLQuery.join(['a', 'b'], ', ', prefix='(', suffix=')') <sql: '(a, b)'>", "\" WHERE \" + where) if _test: return query db_cursor = self._db_cursor() self._db_execute(db_cursor,", "= 3, cust_id = 2'> >>> sqlwhere({'a': 'a', 'b': 'b'}).query() 'a = %s", "DB(None, {}) >>> db.select('foo', _test=True) <sql: 'SELECT * FROM foo'> >>> db.select(['foo', 'bar'],", "or to `False` if there isn't one. >>> db = DB(None, {}) >>>", "Inserts multiple rows into `tablename`. The `values` must be a list of dictioanries,", "a list of strings and SQLParams, which get concatenated to produce the actual", "= DB(None, {}) >>> db.query(\"SELECT * FROM foo\", _test=True) <sql: 'SELECT * FROM", "for v in values] if seqname is False: return None else: return out", "self.query() % tuple([sqlify(x) for x in self.values()]) except (ValueError, TypeError): return self.query() def", "INTO %s (%s) VALUES ' % (tablename, ', '.join(keys))) for i, row in", "else: nout = SQLQuery(val) elif isinstance(val, (list, tuple)) and len(val) == 2: nout", "1, 1 while level: match, pos = matchorfail(sformat, pos) tstart, tend = match.regs[3]", "isinstance(item, SQLQuery): target_items.extend(item.items) else: target_items.append(item) if suffix: target_items.append(suffix) return target join = staticmethod(join)", "test WHERE name=%s' >>> q.query(paramstyle='qmark') 'SELECT * FROM test WHERE name=?' \"\"\" s", "q = db.update('foo', where='name = $name', name='bob', age=2, ... created=SQLLiteral('NOW()'), vars=locals(), _test=True) >>>", "return 'NULL' elif obj is True: return \"'t'\" elif obj is False: return", "`vars` to interpolate it. If `processed=True`, `vars` is a `reparam`-style list to use", "Converts any given object to utf-8 encoded string. >>> safestr('hello') 'hello' >>> safestr(u'\\u1234')", "elif obj is False: return \"'f'\" elif datetime and isinstance(obj, datetime.datetime): return repr(obj.isoformat())", "return SQLQuery(items + self.items) def __iadd__(self, other): if isinstance(other, (basestring, SQLParam)): self.items.append(other) elif", "match.regs[3] token = sformat[tstart:tend] if token == \"{\": level = level + 1", "datetime def safeunicode(obj, encoding='utf-8'): r\"\"\" Converts any given object to unicode string. >>>", "= 't'\"> >>> reparam(\"s IN $s\", dict(s=[1, 2])) <sql: 's IN (1, 2)'>", "x = 't' AND y = 3\"> >>> 'WHERE x = ' +", "sformat[dollar + 1] if nextchar == \"{\": chunks.append((0, sformat[pos:dollar])) pos, level = dollar", "token[0] in \"([\": level = level + 1 elif token[0] in \")]\": level", "VALUES (%s, %s, NOW())' >>> q.values() [2, 'bob'] \"\"\" def q(x): return \"(\"", "_test=True) >>> q <sql: \"UPDATE foo SET age = 2, name = 'bob',", "= 'Joseph'\"> >>> q.query() 'UPDATE foo SET age = %s, name = %s,", "r\"\"\" Converts any given object to utf-8 encoded string. >>> safestr('hello') 'hello' >>>", "1])) elif nextchar in namechars: chunks.append((0, sformat[pos:dollar])) match, pos = matchorfail(sformat, dollar +", "reparam(sql_query, svars) return sql_query def sql_clauses(self, what, tables, where, group, order, limit, offset):", "'hello' >>> safestr(u'\\u1234') '\\xe1\\x88\\xb4' >>> safestr(2) '2' \"\"\" if isinstance(obj, unicode): return obj.encode(encoding)", "<sql: 'SELECT * FROM test WHERE x=1'> >>> q.query(), q.values() ('SELECT * FROM", "[i.value for i in self.items if isinstance(i, SQLParam)] def join(items, sep=' ', prefix=None,", "def __len__(self): return len(self.query()) def query(self, paramstyle=None): \"\"\" Returns the query part of", "sql, val, svars): if isinstance(val, (int, long)): if sql == 'WHERE': nout =", "select(self, tables, svars=None, what='*', where=None, order=None, group=None, limit=None, offset=None, _test=False): \"\"\" Selects `what`", "any given object to unicode string. >>> safeunicode('hello') u'hello' >>> safeunicode(2) u'2' >>>", "\"s = 't'\"> >>> reparam(\"s IN $s\", dict(s=[1, 2])) <sql: 's IN (1,", "obj is None: return 'NULL' elif obj is True: return \"'t'\" elif obj", "if t is unicode: return obj elif t is str: return obj.decode(encoding) elif", "s = [] for x in self.items: if isinstance(x, SQLParam): x = x.get_marker(paramstyle)", "format, pyformat) \"\"\" pass class _ItplError(ValueError): def __init__(self, text, pos): ValueError.__init__(self) self.text =", ">>> q <sql: \"INSERT INTO foo (age, name, created) VALUES (2, 'bob', NOW())\">", "(%s, %s, NOW())' >>> q.values() [2, 'bob'] \"\"\" def q(x): return \"(\" +", "sqlify(None) 'NULL' >>> sqlify(True) \"'t'\" >>> sqlify(3) '3' \"\"\" # because `1 ==", "if token == \"{\": level = level + 1 elif token == \"}\":", "it. If `processed=True`, `vars` is a `reparam`-style list to use instead of interpolating.", "SQLQuery): target_items.extend(item.items) else: target_items.append(item) if suffix: target_items.append(suffix) return target join = staticmethod(join) def", "dollar < 0: break nextchar = sformat[dollar + 1] if nextchar == \"{\":", "\"\"\" Returns the query part of the sql query. >>> q = SQLQuery([\"SELECT", "<sql: \"UPDATE foo SET age = 2, name = 'bob', created = NOW()", "is None: raise _ItplError(text, pos) return match, match.end() namechars = \"abcdefghijklmnopqrstuvwxyz\" \\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\";", ">>> db.select(['foo', 'bar'], where=\"foo.bar_id = bar.id\", limit=5, _test=True) <sql: 'SELECT * FROM foo,", "instead of creating a new SQLQuery. \"\"\" if target is None: target =", "for i, item in enumerate(self.items): if isinstance(item, SQLParam) and isinstance(item.value, SQLLiteral): self.items[i] =", "\"\"\" Takes a format string and returns a list of 2-tuples of the", "3]) <sql: '(1, 2, 3)'> \"\"\" items = [] items.append('(') for i, v", "items.append('(') for i, v in enumerate(values): if i != 0: items.append(', ') items.append(sqlparam(v))", "list of strings and SQLParams, which get concatenated to produce the actual query.", ">>> SQLQuery(\"x\") <sql: 'x'> >>> q = SQLQuery(['SELECT * FROM ', 'test', '", "['joe'] \"\"\" return [i.value for i in self.items if isinstance(i, SQLParam)] def join(items,", "def __add__(self, other): if isinstance(other, basestring): items = [other] elif isinstance(other, SQLQuery): items", "instead of interpolating. >>> db = DB(None, {}) >>> db.query(\"SELECT * FROM foo\",", "the same set of keys. Returns the list of ids of the inserted", "`items`, which is a list of strings and SQLParams, which get concatenated to", "[items] # Take care of SQLLiterals for i, item in enumerate(self.items): if isinstance(item,", "\" SET \" + sqlwhere(values, ', ') + \" WHERE \" + where)", "SQLQuery): items = other.items else: return NotImplemented return SQLQuery(self.items + items) def __radd__(self,", "hard way... if obj is None: return 'NULL' elif obj is True: return", "self.items.append(value) def __add__(self, other): if isinstance(other, basestring): items = [other] elif isinstance(other, SQLQuery):", "= NOW() WHERE name = 'Joseph'\"> >>> q.query() 'UPDATE foo SET age =", "Optinally, prefix and suffix arguments can be provided. >>> SQLQuery.join(['a', 'b'], ', ',", "IN (1, 2)'> \"\"\" dictionary = dictionary.copy() # eval mucks with it result", "'Joseph'] \"\"\" if svars is None: svars = {} where = self._where(where, svars)", "'NULL' >>> sqlify(True) \"'t'\" >>> sqlify(3) '3' \"\"\" # because `1 == True", "dictionary to the keyword argument `vars` and the function will call reparam for", ">>> 'WHERE x = ' + sqlquote(True) + ' AND y IN '", "' + sqlquote([2, 3]) <sql: \"WHERE x = 't' AND y IN (2,", "SQLQuery(SQLParam(1)) <sql: '1'> \"\"\" if items is None: self.items = [] elif isinstance(items,", "FROM test WHERE x=%s', [1]) >>> SQLQuery(SQLParam(1)) <sql: '1'> \"\"\" if items is", "'%' in x and '%%' not in x: x = x.replace('%', '%%') s.append(x)", "for x in self.items: if isinstance(x, SQLParam): x = x.get_marker(paramstyle) s.append(safestr(x)) else: x", "match, pos = matchorfail(sformat, dollar + 1) while pos < len(sformat): if sformat[pos]", "if i != 0: items.append(', ') items.append(sqlparam(v)) items.append(')') return SQLQuery(items) def sqlquote(a): \"\"\"", "u'2' >>> safeunicode('\\xe1\\x88\\xb4') u'\\u1234' \"\"\" t = type(obj) if t is unicode: return", "{} sql_clauses = self.sql_clauses(what, tables, where, group, order, limit, offset) clauses = [self.gen_clause(sql,", "find # the id of the inserted row. q1, q2 = sql_query self._db_execute(db_cursor,", "cust_id = 2'> >>> sqlwhere({'a': 'a', 'b': 'b'}).query() 'a = %s AND b", "* FROM test WHERE name=%s' >>> q.values() ['joe'] \"\"\" __slots__ = [\"value\"] def", "row. q1, q2 = sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor, sql_query) try:", "sformat[pos:dollar + 1])) pos = dollar + 1 + (nextchar == \"$\") if", "keys. for v in values: if v.keys() != keys: raise ValueError, 'Bad data'", "you. Internally, consists of `items`, which is a list of strings and SQLParams,", "of the form (boolean, string) where boolean says whether string should be evaled", "strings and SQLParams, which get concatenated to produce the actual query. \"\"\" __slots__", "`limit`, and `offset`. Uses vars to interpolate. Otherwise, each clause can be a", "FROM foo\", _test=True) <sql: 'SELECT * FROM foo'> >>> db.query(\"SELECT * FROM foo", "r\"\"\" Converts any given object to unicode string. >>> safeunicode('hello') u'hello' >>> safeunicode(2)", "return obj.decode(encoding) elif t in [int, float, bool]: return unicode(obj) elif hasattr(obj, '__unicode__')", "Returns an `SQLQuery` for the result. >>> reparam(\"s = $s\", dict(s=True)) <sql: \"s", "tokenprog def matchorfail(text, pos): match = tokenprog.match(text, pos) if match is None: raise", "x in self.items: if isinstance(x, SQLParam): x = x.get_marker(paramstyle) s.append(safestr(x)) else: x =", "of keys. Returns the list of ids of the inserted rows. Set `seqname`", "sqlparam = SQLParam class SQLQuery(object): \"\"\" You can pass this sort of thing", "care of SQLLiterals for i, item in enumerate(self.items): if isinstance(item, SQLParam) and isinstance(item.value,", "float, bool]: return unicode(obj) elif hasattr(obj, '__unicode__') or isinstance(obj, unicode): return unicode(obj) else:", "<sql: \"WHERE x = 't' AND y = 3\"> >>> 'WHERE x =", "elif isinstance(obj, str): return obj elif hasattr(obj, 'next'): # iterator return itertools.imap(safestr, obj)", "len(where) == 2: where = SQLQuery(where[0], where[1]) elif isinstance(where, SQLQuery): pass else: where", "= SQLQuery.join(values.keys(), ', ') _values = SQLQuery.join([sqlparam(v) for v in values.values()], ', ')", "pos = matchorfail(sformat, dollar + 1) while pos < len(sformat): if sformat[pos] ==", "is False: return None else: return out keys = values[0].keys() #@@ make sure", "$s\", dict(s=True)) <sql: \"s = 't'\"> >>> reparam(\"s IN $s\", dict(s=[1, 2])) <sql:", "name=%s' >>> q.query(paramstyle='qmark') 'SELECT * FROM test WHERE name=?' \"\"\" s = []", "sqlquote('f'), _test=True) <sql: \"SELECT * FROM foo WHERE x = 'f'\"> \"\"\" if", "sqlparam(where) elif isinstance(where, (list, tuple)) and len(where) == 2: where = SQLQuery(where[0], where[1])", "'next'): # iterator return itertools.imap(safestr, obj) else: return str(obj) def sqlify(obj): \"\"\" converts", "backwards-compatibility elif isinstance(val, SQLQuery): nout = val else: nout = reparam(val, svars) def", "return unicode(obj) elif hasattr(obj, '__unicode__') or isinstance(obj, unicode): return unicode(obj) else: return str(obj).decode(encoding)", "'1'> \"\"\" if items is None: self.items = [] elif isinstance(items, list): self.items", "query `sql_query` using dictionary `vars` to interpolate it. If `processed=True`, `vars` is a", "self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor, sql_query) try: out = db_cursor.fetchone()[0] out =", "* FROM foo'> >>> db.select(['foo', 'bar'], where=\"foo.bar_id = bar.id\", limit=5, _test=True) <sql: 'SELECT", "from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee) \"\"\" from tokenize import tokenprog tokenprog =", "= staticmethod(join) def _str(self): try: return self.query() % tuple([sqlify(x) for x in self.values()])", "not processed and not isinstance(sql_query, SQLQuery): sql_query = reparam(sql_query, svars) return sql_query def", "name='bob', age=2, ... created=SQLLiteral('NOW()'), vars=locals(), _test=True) >>> q <sql: \"UPDATE foo SET age", "use in something like a WHERE clause. >>> sqllist(['a', 'b']) 'a, b' >>>", "return None else: return out keys = values[0].keys() #@@ make sure all keys", "= level - 1 else: break chunks.append((1, sformat[dollar + 1:pos])) else: chunks.append((0, sformat[pos:dollar", "'?' elif paramstyle == 'numeric': return ':1' elif paramstyle is None or paramstyle", "WHERE name = 'Joe'\"> \"\"\" if svars is None: svars = {} where", "target argument is provided, the items are appended to target instead of creating", "for v in values: if v.keys() != keys: raise ValueError, 'Bad data' sql_query", "FROM foo WHERE x = 'f'\"> >>> db.query(\"SELECT * FROM foo WHERE x", "def reparam(string_, dictionary): \"\"\" Takes a string and a dictionary and interpolates the", "tuple): # for some databases, a separate query has to be made to", "where, using=None, svars=None, _test=False): \"\"\" Deletes from `table` with clauses `where` and `using`.", "SQLQuery.join(['a', 'b'], ', ') <sql: 'a, b'> Optinally, prefix and suffix arguments can", "\"\"\" Update `tables` with clause `where` (interpolated using `vars`) and setting `values`. >>>", "the values of the parameters used in the sql query. >>> q =", "'<EMAIL>')\"> \"\"\" if not values: return [] if not self.supports_multiple_insert: out = [self.insert(tablename,", "person (name, email) VALUES ('foo', '<EMAIL>'), ('bar', '<EMAIL>')\"> \"\"\" if not values: return", "result = [] for live, chunk in _interpolate(string_): if live: v = eval(chunk,", "pos = matchorfail(sformat, pos + 1) elif sformat[pos] in \"([\": pos, level =", "WHERE name='joe'\"> >>> q.query() 'SELECT * FROM test WHERE name=%s' >>> q.values() ['joe']", "- 1 else: break chunks.append((1, sformat[dollar + 1:pos])) else: chunks.append((0, sformat[pos:dollar + 1]))", "'2' \"\"\" if isinstance(obj, unicode): return obj.encode(encoding) elif isinstance(obj, str): return obj elif", "values[0].keys() #@@ make sure all keys are valid # make sure all rows", "= reparam(val, svars) def xjoin(a, b): if a and b: return a +", "def append(self, value): self.items.append(value) def __add__(self, other): if isinstance(other, basestring): items = [other]", "if isinstance(other, basestring): items = [other] elif isinstance(other, SQLQuery): items = other.items else:", "{} where = self._where(where, svars) q = 'DELETE FROM ' + table if", "<sql: \"INSERT INTO foo (age, name, created) VALUES (2, 'bob', NOW())\"> >>> q.query()", "return '?' elif paramstyle == 'numeric': return ':1' elif paramstyle is None or", "SQLQuery): pass else: where = reparam(where, svars) return where def select(self, tables, svars=None,", ">>> db = DB(None, {}) >>> db.supports_multiple_insert = True >>> values = [{\"name\":", "of SQLLiterals for i, item in enumerate(self.items): if isinstance(item, SQLParam) and isinstance(item.value, SQLLiteral):", "concatenated to produce the actual query. \"\"\" __slots__ = [\"items\"] # tested in", "') + \" WHERE \" + where) if _test: return query db_cursor =", "(public domain, Ka-Ping Yee) \"\"\" from tokenize import tokenprog tokenprog = tokenprog def", "`values` into `tablename`. Returns current sequence ID. Set `seqname` to the ID if", "__len__(self): return len(self.query()) def query(self, paramstyle=None): \"\"\" Returns the query part of the", "suffix=')') <sql: '(a, b)'> If target argument is provided, the items are appended", "\"\"\" raised for unsupported db paramstyles (currently supported: qmark, numeric, format, pyformat) \"\"\"", "svars = {} where = self._where(where, svars) query = ( \"UPDATE \" +", "+ \" SET \" + sqlwhere(values, ', ') + \" WHERE \" +", "= [\"items\"] # tested in sqlquote's docstring def __init__(self, items=None): r\"\"\"Creates a new", "target_items.append(sep) if isinstance(item, SQLQuery): target_items.extend(item.items) else: target_items.append(item) if suffix: target_items.append(suffix) return target join", "= [] items.append('(') for i, v in enumerate(values): if i != 0: items.append(',", "q <sql: \"INSERT INTO foo (age, name, created) VALUES (2, 'bob', NOW())\"> >>>", "and not isinstance(sql_query, SQLQuery): sql_query = reparam(sql_query, svars) return sql_query def sql_clauses(self, what,", "`tables` with clauses `where`, `order`, `group`, `limit`, and `offset`. Uses vars to interpolate.", "self.items = [items] # Take care of SQLLiterals for i, item in enumerate(self.items):", "and SQLParams, which get concatenated to produce the actual query. \"\"\" __slots__ =", "tuple)) and len(val) == 2: nout = SQLQuery(val[0], val[1]) # backwards-compatibility elif isinstance(val,", "[items] elif isinstance(items, SQLQuery): self.items = list(items.items) else: self.items = [items] # Take", "if v.keys() != keys: raise ValueError, 'Bad data' sql_query = SQLQuery('INSERT INTO %s", "pyformat) \"\"\" pass class _ItplError(ValueError): def __init__(self, text, pos): ValueError.__init__(self) self.text = text", "\" + sqlquote('f'), _test=True) <sql: \"SELECT * FROM foo WHERE x = 'f'\">", "< len(sformat): chunks.append((0, sformat[pos:])) return chunks def sqlwhere(dictionary, grouping=' AND '): \"\"\" Converts", "'SELECT * FROM test WHERE name=%s' >>> q.query(paramstyle='qmark') 'SELECT * FROM test WHERE", "obj is False: return \"'f'\" elif datetime and isinstance(obj, datetime.datetime): return repr(obj.isoformat()) else:", "in values] if seqname is False: return None else: return out keys =", "isinstance(a, list): return _sqllist(a) else: return sqlparam(a).sqlquery() def _interpolate(sformat): \"\"\" Takes a format", "' + sqlquote(True) + ' AND y = ' + sqlquote(3) <sql: \"WHERE", "1] in namechars: match, pos = matchorfail(sformat, pos + 1) elif sformat[pos] in", "\"UPDATE \" + sqllist(tables) + \" SET \" + sqlwhere(values, ', ') +", "'bob', 'Joseph'] \"\"\" if svars is None: svars = {} where = self._where(where,", "live: v = eval(chunk, dictionary) result.append(sqlquote(v)) else: result.append(chunk) return SQLQuery.join(result, '') class UnknownParamstyle(Exception):", "sqlquote(True) + ' AND y IN ' + sqlquote([2, 3]) <sql: \"WHERE x", "query. >>> q = SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam('joe')]) >>> q.query()", "with clauses `where` and `using`. >>> db = DB(None, {}) >>> name =", "if isinstance(lst, basestring): return lst else: return ', '.join(lst) def _sqllist(values): \"\"\" >>>", "False: return None else: return out keys = values[0].keys() #@@ make sure all", "<sql: 'SELECT * FROM foo'> >>> db.query(\"SELECT * FROM foo WHERE x =", ">>> q.query() 'INSERT INTO foo (age, name, created) VALUES (%s, %s, NOW())' >>>", "self.items = items elif isinstance(items, SQLParam): self.items = [items] elif isinstance(items, SQLQuery): self.items", "(boolean, string) where boolean says whether string should be evaled or not. from", "with the same set of keys. Returns the list of ids of the", ">>> sqlify(3) '3' \"\"\" # because `1 == True and hash(1) == hash(True)`", "sformat[pos:dollar])) pos, level = dollar + 2, 1 while level: match, pos =", "reparam(string_, dictionary): \"\"\" Takes a string and a dictionary and interpolates the string", "`values`. >>> db = DB(None, {}) >>> name = 'Joseph' >>> q =", "name = 'Joe' >>> db.delete('foo', where='name = $name', vars=locals(), _test=True) <sql: \"DELETE FROM", "_ItplError(text, pos) return match, match.end() namechars = \"abcdefghijklmnopqrstuvwxyz\" \\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks = []", "= $name', name='bob', age=2, ... created=SQLLiteral('NOW()'), vars=locals(), _test=True) >>> q <sql: \"UPDATE foo", "<sql: '1'> \"\"\" if items is None: self.items = [] elif isinstance(items, list):", "the sql query. >>> q = SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam('joe')])", "db.query(\"SELECT * FROM foo\", _test=True) <sql: 'SELECT * FROM foo'> >>> db.query(\"SELECT *", "y = 3\"> >>> 'WHERE x = ' + sqlquote(True) + ' AND", "1: dollar = sformat.find(\"$\", pos) if dollar < 0: break nextchar = sformat[dollar", "<sql: 's IN (1, 2)'> \"\"\" dictionary = dictionary.copy() # eval mucks with", ">>> q = db.update('foo', where='name = $name', name='bob', age=2, ... created=SQLLiteral('NOW()'), vars=locals(), _test=True)", "- 1 chunks.append((1, sformat[dollar + 2:pos - 1])) elif nextchar in namechars: chunks.append((0,", "in _interpolate(string_): if live: v = eval(chunk, dictionary) result.append(sqlquote(v)) else: result.append(chunk) return SQLQuery.join(result,", "t is str: return obj.decode(encoding) elif t in [int, float, bool]: return unicode(obj)", "sformat[tstart:tend] if token == \"{\": level = level + 1 elif token ==", "to unicode string. >>> safeunicode('hello') u'hello' >>> safeunicode(2) u'2' >>> safeunicode('\\xe1\\x88\\xb4') u'\\u1234' \"\"\"", "tuple)) and len(where) == 2: where = SQLQuery(where[0], where[1]) elif isinstance(where, SQLQuery): pass", "'SELECT * FROM foo'> >>> db.select(['foo', 'bar'], where=\"foo.bar_id = bar.id\", limit=5, _test=True) <sql:", "hash(True)` # we have to do this the hard way... if obj is", "namechars: chunks.append((0, sformat[pos:dollar])) match, pos = matchorfail(sformat, dollar + 1) while pos <", "FROM foo, bar WHERE foo.bar_id = bar.id LIMIT 5'> \"\"\" if svars is", "isinstance(val, SQLQuery): nout = val else: nout = reparam(val, svars) def xjoin(a, b):", "supported: qmark, numeric, format, pyformat) \"\"\" pass class _ItplError(ValueError): def __init__(self, text, pos):", "if target is None: target = SQLQuery() target_items = target.items if prefix: target_items.append(prefix)", "query has to be made to find # the id of the inserted", "other): if isinstance(other, (basestring, SQLParam)): self.items.append(other) elif isinstance(other, SQLQuery): self.items.extend(other.items) else: return NotImplemented", "to utf-8 encoded string. >>> safestr('hello') 'hello' >>> safestr(u'\\u1234') '\\xe1\\x88\\xb4' >>> safestr(2) '2'", "a string and a dictionary and interpolates the string using values from the", "foo'> >>> db.query(\"SELECT * FROM foo WHERE x = $x\", vars=dict(x='f'), _test=True) <sql:", "NOW())\"> >>> q.query() 'INSERT INTO foo (age, name, created) VALUES (%s, %s, NOW())'", "isinstance(where, (list, tuple)) and len(where) == 2: where = SQLQuery(where[0], where[1]) elif isinstance(where,", "dictionary) result.append(sqlquote(v)) else: result.append(chunk) return SQLQuery.join(result, '') class UnknownParamstyle(Exception): \"\"\" raised for unsupported", "query(self, sql_query,processed=False, svars=None): \"\"\" Execute SQL query `sql_query` using dictionary `vars` to interpolate", "result. >>> reparam(\"s = $s\", dict(s=True)) <sql: \"s = 't'\"> >>> reparam(\"s IN", "' % (tablename, ', '.join(keys))) for i, row in enumerate(values): if i !=", "sqlify(3) '3' \"\"\" # because `1 == True and hash(1) == hash(True)` #", "import itertools import datetime def safeunicode(obj, encoding='utf-8'): r\"\"\" Converts any given object to", "if svars is None: svars = {} sql_clauses = self.sql_clauses(what, tables, where, group,", "unicode): return obj.encode(encoding) elif isinstance(obj, str): return obj elif hasattr(obj, 'next'): # iterator", "db.select('foo', _test=True) <sql: 'SELECT * FROM foo'> >>> db.select(['foo', 'bar'], where=\"foo.bar_id = bar.id\",", "+ ' ' + b else: return a or b return xjoin(sql, nout)", "\".\" and \\ pos + 1 < len(sformat) and sformat[pos + 1] in", "x=1'> >>> q.query(), q.values() ('SELECT * FROM test WHERE x=%s', [1]) >>> SQLQuery(SQLParam(1))", "'SELECT * FROM test WHERE name=%s' >>> q.values() ['joe'] \"\"\" __slots__ = [\"value\"]", "svars = {} if not processed and not isinstance(sql_query, SQLQuery): sql_query = reparam(sql_query,", "SET age = %s, name = %s, created = NOW() WHERE name =", "SQLQuery(self.items + items) def __radd__(self, other): if isinstance(other, basestring): items = [other] else:", "of 2-tuples of the form (boolean, string) where boolean says whether string should", "{}) >>> db.query(\"SELECT * FROM foo\", _test=True) <sql: 'SELECT * FROM foo'> >>>", "= 't' AND y = 3\"> >>> 'WHERE x = ' + sqlquote(True)", "db = DB(None, {}) >>> name = 'Joseph' >>> q = db.update('foo', where='name", "sqlquote(a): \"\"\" Ensures `a` is quoted properly for use in a SQL query.", "= [] elif isinstance(items, list): self.items = items elif isinstance(items, SQLParam): self.items =", "b else: return a or b return xjoin(sql, nout) def _where(self, where, svars):", "q.query() 'INSERT INTO foo (age, name, created) VALUES (%s, %s, NOW())' >>> q.values()", "+ sqlquote(True) + ' AND y IN ' + sqlquote([2, 3]) <sql: \"WHERE", "* FROM foo WHERE x = 'f'\"> >>> db.query(\"SELECT * FROM foo WHERE", "break chunks.append((1, sformat[dollar + 1:pos])) else: chunks.append((0, sformat[pos:dollar + 1])) pos = dollar", "[\"items\"] # tested in sqlquote's docstring def __init__(self, items=None): r\"\"\"Creates a new SQLQuery.", "= items elif isinstance(items, SQLParam): self.items = [items] elif isinstance(items, SQLQuery): self.items =", "_sqllist(values): \"\"\" >>> _sqllist([1, 2, 3]) <sql: '(1, 2, 3)'> \"\"\" items =", "+ table if using: q += ' USING ' + sqllist(using) if where:", "suffix arguments can be provided. >>> SQLQuery.join(['a', 'b'], ', ', prefix='(', suffix=')') <sql:", "else: return ', '.join(lst) def _sqllist(values): \"\"\" >>> _sqllist([1, 2, 3]) <sql: '(1,", "' + table if using: q += ' USING ' + sqllist(using) if", "q.query() 'UPDATE foo SET age = %s, name = %s, created = NOW()", "\"\"\" return SQLQuery.join([k + ' = ' + sqlparam(v) for k, v in", ">>> db = DB(None, {}) >>> db.query(\"SELECT * FROM foo\", _test=True) <sql: 'SELECT", "FROM foo'> >>> db.query(\"SELECT * FROM foo WHERE x = $x\", vars=dict(x='f'), _test=True)", "group), ('ORDER BY', order), ('LIMIT', limit), ('OFFSET', offset)) def gen_clause(self, sql, val, svars):", "if isinstance(val, (int, long)): if sql == 'WHERE': nout = 'id = '", "return chunks def sqlwhere(dictionary, grouping=' AND '): \"\"\" Converts a `dictionary` to an", "v.keys() != keys: raise ValueError, 'Bad data' sql_query = SQLQuery('INSERT INTO %s (%s)", "'%%' not in x: x = x.replace('%', '%%') s.append(x) return \"\".join(s) def values(self):", "+ where) if _test: return query db_cursor = self._db_cursor() self._db_execute(db_cursor, query) if not", "% tablename + q(_keys) + ' VALUES ' + q(_values) else: sql_query =", "return NotImplemented return SQLQuery(items + self.items) def __iadd__(self, other): if isinstance(other, (basestring, SQLParam)):", "return other + self.sqlquery() def __str__(self): return str(self.value) def __repr__(self): return '<param: %s>'", "%s>' % repr(self.value) sqlparam = SQLParam class SQLQuery(object): \"\"\" You can pass this", "obj) else: return str(obj) def sqlify(obj): \"\"\" converts `obj` to its proper SQL", "== \"{\": level = level + 1 elif token == \"}\": level =", "== \"{\": chunks.append((0, sformat[pos:dollar])) pos, level = dollar + 2, 1 while level:", "item in enumerate(items): if i != 0: target_items.append(sep) if isinstance(item, SQLQuery): target_items.extend(item.items) else:", ">>> db.query(\"SELECT * FROM foo WHERE x = \" + sqlquote('f'), _test=True) <sql:", "SQLParam(1)]) >>> q <sql: 'SELECT * FROM test WHERE x=1'> >>> q.query(), q.values()", "2])) <sql: 's IN (1, 2)'> \"\"\" dictionary = dictionary.copy() # eval mucks", "self.items.append(other) elif isinstance(other, SQLQuery): self.items.extend(other.items) else: return NotImplemented return self def __len__(self): return", "values from the dictionary. Returns an `SQLQuery` for the result. >>> reparam(\"s =", "else: nout = reparam(val, svars) def xjoin(a, b): if a and b: return", "str: return obj.decode(encoding) elif t in [int, float, bool]: return unicode(obj) elif hasattr(obj,", "`using`. >>> db = DB(None, {}) >>> name = 'Joe' >>> db.delete('foo', where='name", "[] pos = 0 while 1: dollar = sformat.find(\"$\", pos) if dollar <", "sformat[tstart:tend] if token[0] in \"([\": level = level + 1 elif token[0] in", "sqlify(True) \"'t'\" >>> sqlify(3) '3' \"\"\" # because `1 == True and hash(1)", "WHERE clause `SQLQuery`. >>> sqlwhere({'cust_id': 2, 'order_id':3}) <sql: 'order_id = 3 AND cust_id", "= sformat.find(\"$\", pos) if dollar < 0: break nextchar = sformat[dollar + 1]", "where = \"id = \" + sqlparam(where) elif isinstance(where, (list, tuple)) and len(where)", "return [] if not self.supports_multiple_insert: out = [self.insert(tablename, seqname=seqname, _test=_test, **v) for v", "= 't' AND y IN (2, 3)\"> \"\"\" if isinstance(a, list): return _sqllist(a)", "VALUES ' % (tablename, ', '.join(keys))) for i, row in enumerate(values): if i", "AND y = ' + sqlquote(3) <sql: \"WHERE x = 't' AND y", "import tokenprog tokenprog = tokenprog def matchorfail(text, pos): match = tokenprog.match(text, pos) if", "Otherwise, you can pass a dictionary to the keyword argument `vars` and the", "escaped if paramstyle in ['format', 'pyformat']: if '%' in x and '%%' not", "= db.update('foo', where='name = $name', name='bob', age=2, ... created=SQLLiteral('NOW()'), vars=locals(), _test=True) >>> q", "+ 1 elif token == \"}\": level = level - 1 chunks.append((1, sformat[dollar", "\"\"\" >>> _sqllist([1, 2, 3]) <sql: '(1, 2, 3)'> \"\"\" items = []", "because `1 == True and hash(1) == hash(True)` # we have to do", "repr(obj.isoformat()) else: if isinstance(obj, unicode): obj = obj.encode('utf8') return repr(obj) def sqllist(lst): \"\"\"", "nout) def _where(self, where, svars): if isinstance(where, (int, long)): where = \"id =", "+ (nextchar == \"$\") if pos < len(sformat): chunks.append((0, sformat[pos:])) return chunks def", "= self._where(where, svars) q = 'DELETE FROM ' + table if using: q", "q.query(paramstyle='qmark') 'SELECT * FROM test WHERE name=?' \"\"\" s = [] for x", "SQLQuery): nout = val else: nout = reparam(val, svars) def xjoin(a, b): if", "the inserted rows. Set `seqname` to the ID if it's not the default,", "`1 == True and hash(1) == hash(True)` # we have to do this", "q.values() ['joe'] \"\"\" __slots__ = [\"value\"] def __init__(self, value): self.value = value def", "actual query. \"\"\" __slots__ = [\"items\"] # tested in sqlquote's docstring def __init__(self,", "gen_clause(self, sql, val, svars): if isinstance(val, (int, long)): if sql == 'WHERE': nout", "sformat[dollar + 1:pos])) else: chunks.append((0, sformat[pos:dollar + 1])) pos = dollar + 1", "#coding:utf8 ''' Created on 2013-8-21 @author: lan (www.9miao.com) ''' import itertools import datetime", "test WHERE name=\", SQLParam(\"joe\")]) >>> q <sql: \"SELECT * FROM test WHERE name='joe'\">", "tables, where, svars=None, _test=False, **values): \"\"\" Update `tables` with clause `where` (interpolated using", "VALUES (2, 'bob', NOW())\"> >>> q.query() 'INSERT INTO foo (age, name, created) VALUES", "query # For backward compatability, ignore escaping when the query looks already escaped", "return SQLQuery.join([k + ' = ' + sqlparam(v) for k, v in dictionary.items()],", "if isinstance(sql_query, tuple): # for some databases, a separate query has to be", "`where` (interpolated using `vars`) and setting `values`. >>> db = DB(None, {}) >>>", "'bob', created = NOW() WHERE name = 'Joseph'\"> >>> q.query() 'UPDATE foo SET", "2, 1 while level: match, pos = matchorfail(sformat, pos) tstart, tend = match.regs[3]", "= SQLQuery(where[0], where[1]) elif isinstance(where, SQLQuery): pass else: where = reparam(where, svars) return", "it's not the default, or to `False` if there isn't one. >>> db", "test WHERE name=%s' >>> q.values() ['joe'] \"\"\" __slots__ = [\"value\"] def __init__(self, value):", "if _test: return sql_query db_cursor = self._db_cursor() if seqname is not False: sql_query", "keys. Returns the list of ids of the inserted rows. Set `seqname` to", "[2, 'bob'] \"\"\" def q(x): return \"(\" + x + \")\" if values:", "isinstance(items, SQLParam): self.items = [items] elif isinstance(items, SQLQuery): self.items = list(items.items) else: self.items", ">>> q = SQLQuery(['SELECT * FROM ', 'test', ' WHERE x=', SQLParam(1)]) >>>", "SQLQuery(\"x\") <sql: 'x'> >>> q = SQLQuery(['SELECT * FROM ', 'test', ' WHERE", "b return xjoin(sql, nout) def _where(self, where, svars): if isinstance(where, (int, long)): where", "\"\"\" converts `obj` to its proper SQL version >>> sqlify(None) 'NULL' >>> sqlify(True)", "`where`, `order`, `group`, `limit`, and `offset`. Uses vars to interpolate. Otherwise, each clause", "of strings and SQLParams, which get concatenated to produce the actual query. \"\"\"", "pos) if match is None: raise _ItplError(text, pos) return match, match.end() namechars =", "elif isinstance(where, SQLQuery): pass else: where = reparam(where, svars) return where def select(self,", "\"\"\" t = type(obj) if t is unicode: return obj elif t is", "q = SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam('joe')]) >>> q.values() ['joe'] \"\"\"", "* FROM foo\", _test=True) <sql: 'SELECT * FROM foo'> >>> db.query(\"SELECT * FROM", "string. >>> safestr('hello') 'hello' >>> safestr(u'\\u1234') '\\xe1\\x88\\xb4' >>> safestr(2) '2' \"\"\" if isinstance(obj,", "+ sqlwhere(values, ', ') + \" WHERE \" + where) if _test: return", "SQLQuery(object): \"\"\" You can pass this sort of thing as a clause in", "clauses `where`, `order`, `group`, `limit`, and `offset`. Uses vars to interpolate. Otherwise, each", "name, created) VALUES (2, 'bob', NOW())\"> >>> q.query() 'INSERT INTO foo (age, name,", "Ka-Ping Yee) \"\"\" from tokenize import tokenprog tokenprog = tokenprog def matchorfail(text, pos):", "for use in a SQL query. >>> 'WHERE x = ' + sqlquote(True)", "__slots__ = [\"items\"] # tested in sqlquote's docstring def __init__(self, items=None): r\"\"\"Creates a", "<sql: 'SELECT * FROM foo, bar WHERE foo.bar_id = bar.id LIMIT 5'> \"\"\"", "' = ' + sqlparam(v) for k, v in dictionary.items()], grouping) def reparam(string_,", "+ sqlquote(3) <sql: \"WHERE x = 't' AND y = 3\"> >>> 'WHERE", "self.supports_multiple_insert: out = [self.insert(tablename, seqname=seqname, _test=_test, **v) for v in values] if seqname", "= DB(None, {}) >>> name = 'Joseph' >>> q = db.update('foo', where='name =", "val[1]) # backwards-compatibility elif isinstance(val, SQLQuery): nout = val else: nout = reparam(val,", "__str__(self): return safestr(self._str()) def __unicode__(self): return safeunicode(self._str()) def __repr__(self): return '<sql: %s>' %", "seqname=None, _test=False, **values): \"\"\" Inserts `values` into `tablename`. Returns current sequence ID. Set", ">>> sqlquote('NOW()') <sql: \"'NOW()'\"> >>> sqlquote(SQLLiteral('NOW()')) <sql: 'NOW()'> \"\"\" def __init__(self, v): self.v", "make sure all keys are valid # make sure all rows have same", "db.update('foo', where='name = $name', name='bob', age=2, ... created=SQLLiteral('NOW()'), vars=locals(), _test=True) >>> q <sql:", "= match.regs[3] token = sformat[tstart:tend] if token == \"{\": level = level +", "# for some databases, a separate query has to be made to find", "self.ctx.commit() return out def update(self, tables, where, svars=None, _test=False, **values): \"\"\" Update `tables`", "SQLQuery() target_items = target.items if prefix: target_items.append(prefix) for i, item in enumerate(items): if", "to the ID if it's not the default, or to `False` if there", "chunks.append((0, sformat[pos:dollar + 1])) pos = dollar + 1 + (nextchar == \"$\")", "SQL WHERE clause `SQLQuery`. >>> sqlwhere({'cust_id': 2, 'order_id':3}) <sql: 'order_id = 3 AND", "same keys. for v in values: if v.keys() != keys: raise ValueError, 'Bad", "for v in values.values()], ', ') sql_query = \"INSERT INTO %s \" %", "level = level + 1 elif token[0] in \")]\": level = level -", "grouping=' AND '): \"\"\" Converts a `dictionary` to an SQL WHERE clause `SQLQuery`.", "consists of `items`, which is a list of strings and SQLParams, which get", "if '%' in x and '%%' not in x: x = x.replace('%', '%%')", "values: _keys = SQLQuery.join(values.keys(), ', ') _values = SQLQuery.join([sqlparam(v) for v in values.values()],", "reparam(\"s IN $s\", dict(s=[1, 2])) <sql: 's IN (1, 2)'> \"\"\" dictionary =", "values = [{\"name\": \"foo\", \"email\": \"<EMAIL>\"}, {\"name\": \"bar\", \"email\": \"<EMAIL>\"}] >>> db.multiple_insert('person', values=values,", "def __repr__(self): return '<sql: %s>' % repr(str(self)) class SQLLiteral: \"\"\" Protects a string", "' + sqlparam(v) for k, v in dictionary.items()], grouping) def reparam(string_, dictionary): \"\"\"", "def __repr__(self): return '<param: %s>' % repr(self.value) sqlparam = SQLParam class SQLQuery(object): \"\"\"", "elif t is str: return obj.decode(encoding) elif t in [int, float, bool]: return", "\"\"\" if isinstance(a, list): return _sqllist(a) else: return sqlparam(a).sqlquery() def _interpolate(sformat): \"\"\" Takes", "x = 'f'\"> >>> db.query(\"SELECT * FROM foo WHERE x = \" +", "AND cust_id = 2'> >>> sqlwhere({'cust_id': 2, 'order_id':3}, grouping=', ') <sql: 'order_id =", "else: self._db_execute(db_cursor, sql_query) try: out = db_cursor.fetchone()[0] out = range(out-len(values)+1, out+1) except Exception:", "= [other] else: return NotImplemented return SQLQuery(items + self.items) def __iadd__(self, other): if", "of the sql query. >>> q = SQLQuery([\"SELECT * FROM test WHERE name=\",", "Uses vars to interpolate. Otherwise, each clause can be a SQLQuery. >>> db", "\"DELETE FROM foo WHERE name = 'Joe'\"> \"\"\" if svars is None: svars", "like a WHERE clause. >>> sqllist(['a', 'b']) 'a, b' >>> sqllist('a') 'a' >>>", "FROM test WHERE name='joe'\"> >>> q.query() 'SELECT * FROM test WHERE name=%s' >>>", "in self.items: if isinstance(x, SQLParam): x = x.get_marker(paramstyle) s.append(safestr(x)) else: x = safestr(x)", "enumerate(items): if i != 0: target_items.append(sep) if isinstance(item, SQLQuery): target_items.extend(item.items) else: target_items.append(item) if", "for i, v in enumerate(values): if i != 0: items.append(', ') items.append(sqlparam(v)) items.append(')')", "raised for unsupported db paramstyles (currently supported: qmark, numeric, format, pyformat) \"\"\" pass", "isinstance(item.value, SQLLiteral): self.items[i] = item.value.v def append(self, value): self.items.append(value) def __add__(self, other): if", "a new SQLQuery. >>> SQLQuery(\"x\") <sql: 'x'> >>> q = SQLQuery(['SELECT * FROM", "else: result.append(chunk) return SQLQuery.join(result, '') class UnknownParamstyle(Exception): \"\"\" raised for unsupported db paramstyles", "\"\"\" Selects `what` from `tables` with clauses `where`, `order`, `group`, `limit`, and `offset`.", "inserted rows. Set `seqname` to the ID if it's not the default, or", "return out keys = values[0].keys() #@@ make sure all keys are valid #", "provided. >>> SQLQuery.join(['a', 'b'], ', ', prefix='(', suffix=')') <sql: '(a, b)'> If target", "list of ids of the inserted rows. Set `seqname` to the ID if", "with clause `where` (interpolated using `vars`) and setting `values`. >>> db = DB(None,", "svars=None, _test=False): \"\"\" Deletes from `table` with clauses `where` and `using`. >>> db", "values=values, _test=True) <sql: \"INSERT INTO person (name, email) VALUES ('foo', '<EMAIL>'), ('bar', '<EMAIL>')\">", "pass def query(self, sql_query,processed=False, svars=None): \"\"\" Execute SQL query `sql_query` using dictionary `vars`", "is None: self.items = [] elif isinstance(items, list): self.items = items elif isinstance(items,", "WHERE x=', SQLParam(1)]) >>> q <sql: 'SELECT * FROM test WHERE x=1'> >>>", "SQL query. >>> 'WHERE x = ' + sqlquote(True) + ' AND y", "text, pos): ValueError.__init__(self) self.text = text self.pos = pos def __str__(self): return \"unfinished", "where[1]) elif isinstance(where, SQLQuery): pass else: where = reparam(where, svars) return where def", "INTO %s \" % tablename + q(_keys) + ' VALUES ' + q(_values)", "= target.items if prefix: target_items.append(prefix) for i, item in enumerate(items): if i !=", "return ':1' elif paramstyle is None or paramstyle in ['format', 'pyformat']: return '%s'", "= $name', vars=locals(), _test=True) <sql: \"DELETE FROM foo WHERE name = 'Joe'\"> \"\"\"", "' + b else: return a or b return xjoin(sql, nout) def _where(self,", "to do this the hard way... if obj is None: return 'NULL' elif", "databases, a separate query has to be made to find # the id", "= x.replace('%', '%%') s.append(x) return \"\".join(s) def values(self): \"\"\" Returns the values of", "= self._process_insert_query(sql_query, tablename, seqname) if isinstance(sql_query, tuple): # for some databases, a separate", "`table` with clauses `where` and `using`. >>> db = DB(None, {}) >>> name", "= sformat[tstart:tend] if token == \"{\": level = level + 1 elif token", "= {} sql_clauses = self.sql_clauses(what, tables, where, group, order, limit, offset) clauses =", "self._where(where, svars) query = ( \"UPDATE \" + sqllist(tables) + \" SET \"", "Returns the list of ids of the inserted rows. Set `seqname` to the", "list(items.items) else: self.items = [items] # Take care of SQLLiterals for i, item", "\"\"\" if items is None: self.items = [] elif isinstance(items, list): self.items =", "\"\"\" if svars is None: svars = {} sql_clauses = self.sql_clauses(what, tables, where,", "self.v class SQLProducer: \"\"\"Database\"\"\" def __init__(self): \"\"\"Creates a database. \"\"\" pass def query(self,", "string and returns a list of 2-tuples of the form (boolean, string) where", "if paramstyle in ['format', 'pyformat']: if '%' in x and '%%' not in", "elif hasattr(obj, 'next'): # iterator return itertools.imap(safestr, obj) else: return str(obj) def sqlify(obj):", "= level + 1 elif token == \"}\": level = level - 1", "'<param: %s>' % repr(self.value) sqlparam = SQLParam class SQLQuery(object): \"\"\" You can pass", "x.replace('%', '%%') s.append(x) return \"\".join(s) def values(self): \"\"\" Returns the values of the", "\"\"\" items = [] items.append('(') for i, v in enumerate(values): if i !=", "the arguments for use in something like a WHERE clause. >>> sqllist(['a', 'b'])", "email) VALUES ('foo', '<EMAIL>'), ('bar', '<EMAIL>')\"> \"\"\" if not values: return [] if", "def matchorfail(text, pos): match = tokenprog.match(text, pos) if match is None: raise _ItplError(text,", "if not self.supports_multiple_insert: out = [self.insert(tablename, seqname=seqname, _test=_test, **v) for v in values]", "return sqlparam(a).sqlquery() def _interpolate(sformat): \"\"\" Takes a format string and returns a list", "data' sql_query = SQLQuery('INSERT INTO %s (%s) VALUES ' % (tablename, ', '.join(keys)))", "foo.bar_id = bar.id LIMIT 5'> \"\"\" if svars is None: svars = {}", "The `values` must be a list of dictioanries, one for each row to", "Protects a string from `sqlquote`. >>> sqlquote('NOW()') <sql: \"'NOW()'\"> >>> sqlquote(SQLLiteral('NOW()')) <sql: 'NOW()'>", "'SELECT * FROM foo'> >>> db.query(\"SELECT * FROM foo WHERE x = $x\",", "\"\"\" Deletes from `table` with clauses `where` and `using`. >>> db = DB(None,", "in enumerate(self.items): if isinstance(item, SQLParam) and isinstance(item.value, SQLLiteral): self.items[i] = item.value.v def append(self,", "+ \")\" if values: _keys = SQLQuery.join(values.keys(), ', ') _values = SQLQuery.join([sqlparam(v) for", "format string and returns a list of 2-tuples of the form (boolean, string)", "_test=True) <sql: \"SELECT * FROM foo WHERE x = 'f'\"> >>> db.query(\"SELECT *", "query db_cursor = self._db_cursor() self._db_execute(db_cursor, query) if not self.ctx.transactions: self.ctx.commit() return db_cursor.rowcount def", "WHERE x=%s', [1]) >>> SQLQuery(SQLParam(1)) <sql: '1'> \"\"\" if items is None: self.items", "VALUES\" % table def multiple_insert(self, tablename, values, seqname=None, _test=False): \"\"\" Inserts multiple rows", "for you. Internally, consists of `items`, which is a list of strings and", "a list of 2-tuples of the form (boolean, string) where boolean says whether", "'b'}).query() 'a = %s AND b = %s' \"\"\" return SQLQuery.join([k + '", "can pass this sort of thing as a clause in any db function.", "a new SQLQuery. \"\"\" if target is None: target = SQLQuery() target_items =", "* FROM test WHERE name=\", SQLParam('joe')]) >>> q.values() ['joe'] \"\"\" return [i.value for", "# iterator return itertools.imap(safestr, obj) else: return str(obj) def sqlify(obj): \"\"\" converts `obj`", "WHERE name=%s' >>> q.query(paramstyle='qmark') 'SELECT * FROM test WHERE name=?' \"\"\" s =", "values: return [] if not self.supports_multiple_insert: out = [self.insert(tablename, seqname=seqname, _test=_test, **v) for", "return target join = staticmethod(join) def _str(self): try: return self.query() % tuple([sqlify(x) for", "raise ValueError, 'Bad data' sql_query = SQLQuery('INSERT INTO %s (%s) VALUES ' %", "Inserts `values` into `tablename`. Returns current sequence ID. Set `seqname` to the ID", "x = \" + sqlquote('f'), _test=True) <sql: \"SELECT * FROM foo WHERE x", "chunks.append((0, sformat[pos:])) return chunks def sqlwhere(dictionary, grouping=' AND '): \"\"\" Converts a `dictionary`", "else: return a or b return xjoin(sql, nout) def _where(self, where, svars): if", "safestr(2) '2' \"\"\" if isinstance(obj, unicode): return obj.encode(encoding) elif isinstance(obj, str): return obj", "q = SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam('joe')]) >>> q.query() 'SELECT *", "processed and not isinstance(sql_query, SQLQuery): sql_query = reparam(sql_query, svars) return sql_query def sql_clauses(self,", "1] if nextchar == \"{\": chunks.append((0, sformat[pos:dollar])) pos, level = dollar + 2,", "__init__(self): \"\"\"Creates a database. \"\"\" pass def query(self, sql_query,processed=False, svars=None): \"\"\" Execute SQL", "from `table` with clauses `where` and `using`. >>> db = DB(None, {}) >>>", "if values: _keys = SQLQuery.join(values.keys(), ', ') _values = SQLQuery.join([sqlparam(v) for v in", "parameters used in the sql query. >>> q = SQLQuery([\"SELECT * FROM test", "q.query() 'SELECT * FROM test WHERE name=%s' >>> q.query(paramstyle='qmark') 'SELECT * FROM test", "self.sql_clauses(what, tables, where, group, order, limit, offset) clauses = [self.gen_clause(sql, val, svars) for", "Ensures `a` is quoted properly for use in a SQL query. >>> 'WHERE", "( \"UPDATE \" + sqllist(tables) + \" SET \" + sqlwhere(values, ', ')", "<sql: 'order_id = 3, cust_id = 2'> >>> sqlwhere({'a': 'a', 'b': 'b'}).query() 'a", "= sformat[tstart:tend] if token[0] in \"([\": level = level + 1 elif token[0]", "__init__(self, value): self.value = value def get_marker(self, paramstyle='pyformat'): if paramstyle == 'qmark': return", "if nextchar == \"{\": chunks.append((0, sformat[pos:dollar])) pos, level = dollar + 2, 1", "prefix='(', suffix=')') <sql: '(a, b)'> If target argument is provided, the items are", "processed=True) def insert(self, tablename, seqname=None, _test=False, **values): \"\"\" Inserts `values` into `tablename`. Returns", "WHERE name=%s' >>> q.values() ['joe'] \"\"\" __slots__ = [\"value\"] def __init__(self, value): self.value", "[{\"name\": \"foo\", \"email\": \"<EMAIL>\"}, {\"name\": \"bar\", \"email\": \"<EMAIL>\"}] >>> db.multiple_insert('person', values=values, _test=True) <sql:", "sql_clauses if val is not None] qout = SQLQuery.join(clauses) if _test: return qout", "' USING ' + sqllist(using) if where: q += ' WHERE ' +", "created) VALUES (2, 'bob', NOW())\"> >>> q.query() 'INSERT INTO foo (age, name, created)", "foo'> >>> db.select(['foo', 'bar'], where=\"foo.bar_id = bar.id\", limit=5, _test=True) <sql: 'SELECT * FROM", "to find # the id of the inserted row. q1, q2 = sql_query", "!= 0: sql_query.append(\", \") SQLQuery.join([SQLParam(row[k]) for k in keys], sep=\", \", target=sql_query, prefix=\"(\",", "__repr__(self): return '<param: %s>' % repr(self.value) sqlparam = SQLParam class SQLQuery(object): \"\"\" You", "t in [int, float, bool]: return unicode(obj) elif hasattr(obj, '__unicode__') or isinstance(obj, unicode):", "list): return _sqllist(a) else: return sqlparam(a).sqlquery() def _interpolate(sformat): \"\"\" Takes a format string", "None: svars = {} sql_clauses = self.sql_clauses(what, tables, where, group, order, limit, offset)", "elif isinstance(val, (list, tuple)) and len(val) == 2: nout = SQLQuery(val[0], val[1]) #", "+ sqllist(using) if where: q += ' WHERE ' + where return q", "return len(self.query()) def query(self, paramstyle=None): \"\"\" Returns the query part of the sql", "in sql_clauses if val is not None] qout = SQLQuery.join(clauses) if _test: return", "* FROM foo'> >>> db.query(\"SELECT * FROM foo WHERE x = $x\", vars=dict(x='f'),", "VALUES ('foo', '<EMAIL>'), ('bar', '<EMAIL>')\"> \"\"\" if not values: return [] if not", ">>> safeunicode(2) u'2' >>> safeunicode('\\xe1\\x88\\xb4') u'\\u1234' \"\"\" t = type(obj) if t is", "there isn't one. >>> db = DB(None, {}) >>> db.supports_multiple_insert = True >>>", "a dictionary and interpolates the string using values from the dictionary. Returns an", "eval mucks with it result = [] for live, chunk in _interpolate(string_): if", "if not self.ctx.transactions: self.ctx.commit() return db_cursor.rowcount def delete(self, table, where, using=None, svars=None, _test=False):", "where = self._where(where, svars) query = ( \"UPDATE \" + sqllist(tables) + \"", "items.append(sqlparam(v)) items.append(')') return SQLQuery(items) def sqlquote(a): \"\"\" Ensures `a` is quoted properly for", "'order_id = 3, cust_id = 2'> >>> sqlwhere({'a': 'a', 'b': 'b'}).query() 'a =", "`tablename`. Returns current sequence ID. Set `seqname` to the ID if it's not", "\"\"\" if target is None: target = SQLQuery() target_items = target.items if prefix:", "= sformat[dollar + 1] if nextchar == \"{\": chunks.append((0, sformat[pos:dollar])) pos, level =", "sformat[dollar + 2:pos - 1])) elif nextchar in namechars: chunks.append((0, sformat[pos:dollar])) match, pos", "a SQLQuery. >>> db = DB(None, {}) >>> db.select('foo', _test=True) <sql: 'SELECT *", "'): \"\"\" Converts a `dictionary` to an SQL WHERE clause `SQLQuery`. >>> sqlwhere({'cust_id':", "\"\"\" Returns the values of the parameters used in the sql query. >>>", "a and b: return a + ' ' + b else: return a", "False: return \"'f'\" elif datetime and isinstance(obj, datetime.datetime): return repr(obj.isoformat()) else: if isinstance(obj,", "[] if not self.supports_multiple_insert: out = [self.insert(tablename, seqname=seqname, _test=_test, **v) for v in", "''' import itertools import datetime def safeunicode(obj, encoding='utf-8'): r\"\"\" Converts any given object", "token = sformat[tstart:tend] if token == \"{\": level = level + 1 elif", "<sql: '(1, 2, 3)'> \"\"\" items = [] items.append('(') for i, v in", ">>> q.query(paramstyle='qmark') 'SELECT * FROM test WHERE name=?' \"\"\" s = [] for", "where, group, order, limit, offset) clauses = [self.gen_clause(sql, val, svars) for sql, val", "None: svars = {} where = self._where(where, svars) query = ( \"UPDATE \"", "Converts a `dictionary` to an SQL WHERE clause `SQLQuery`. >>> sqlwhere({'cust_id': 2, 'order_id':3})", "reparam(\"s = $s\", dict(s=True)) <sql: \"s = 't'\"> >>> reparam(\"s IN $s\", dict(s=[1,", "if seqname is False: return None else: return out keys = values[0].keys() #@@", "have same keys. for v in values: if v.keys() != keys: raise ValueError,", "!= keys: raise ValueError, 'Bad data' sql_query = SQLQuery('INSERT INTO %s (%s) VALUES", "sqllist(lst): \"\"\" Converts the arguments for use in something like a WHERE clause.", ">>> q.values() [2, 'bob', 'Joseph'] \"\"\" if svars is None: svars = {}", "return NotImplemented return self def __len__(self): return len(self.query()) def query(self, paramstyle=None): \"\"\" Returns", "SQLQuery. \"\"\" if target is None: target = SQLQuery() target_items = target.items if", "\"'NOW()'\"> >>> sqlquote(SQLLiteral('NOW()')) <sql: 'NOW()'> \"\"\" def __init__(self, v): self.v = v def", "svars) return where def select(self, tables, svars=None, what='*', where=None, order=None, group=None, limit=None, offset=None,", "string. >>> safeunicode('hello') u'hello' >>> safeunicode(2) u'2' >>> safeunicode('\\xe1\\x88\\xb4') u'\\u1234' \"\"\" t =", "SQLQuery): self.items.extend(other.items) else: return NotImplemented return self def __len__(self): return len(self.query()) def query(self,", "a dictionary to the keyword argument `vars` and the function will call reparam", "__slots__ = [\"value\"] def __init__(self, value): self.value = value def get_marker(self, paramstyle='pyformat'): if", "1 chunks.append((1, sformat[dollar + 2:pos - 1])) elif nextchar in namechars: chunks.append((0, sformat[pos:dollar]))", "target=None): \"\"\" Joins multiple queries. >>> SQLQuery.join(['a', 'b'], ', ') <sql: 'a, b'>", "the function will call reparam for you. Internally, consists of `items`, which is", "WHERE clause. >>> sqllist(['a', 'b']) 'a, b' >>> sqllist('a') 'a' >>> sqllist(u'abc') u'abc'", "\"<EMAIL>\"}, {\"name\": \"bar\", \"email\": \"<EMAIL>\"}] >>> db.multiple_insert('person', values=values, _test=True) <sql: \"INSERT INTO person", "('LIMIT', limit), ('OFFSET', offset)) def gen_clause(self, sql, val, svars): if isinstance(val, (int, long)):", "prefix=\"(\", suffix=\")\") if _test: return sql_query db_cursor = self._db_cursor() if seqname is not", "in something like a WHERE clause. >>> sqllist(['a', 'b']) 'a, b' >>> sqllist('a')", "proper SQL version >>> sqlify(None) 'NULL' >>> sqlify(True) \"'t'\" >>> sqlify(3) '3' \"\"\"", "Takes a string and a dictionary and interpolates the string using values from", "def select(self, tables, svars=None, what='*', where=None, order=None, group=None, limit=None, offset=None, _test=False): \"\"\" Selects", "svars is None: svars = {} where = self._where(where, svars) q = 'DELETE", "out def update(self, tables, where, svars=None, _test=False, **values): \"\"\" Update `tables` with clause", "\"SELECT * FROM test WHERE name='joe'\"> >>> q.query() 'SELECT * FROM test WHERE", "WHERE foo.bar_id = bar.id LIMIT 5'> \"\"\" if svars is None: svars =", "mucks with it result = [] for live, chunk in _interpolate(string_): if live:", "tend = match.regs[3] token = sformat[tstart:tend] if token[0] in \"([\": level = level", "prefix and suffix arguments can be provided. >>> SQLQuery.join(['a', 'b'], ', ', prefix='(',", "= pos + 1, 1 while level: match, pos = matchorfail(sformat, pos) tstart,", ">>> q.values() [2, 'bob'] \"\"\" def q(x): return \"(\" + x + \")\"", "bar.id\", limit=5, _test=True) <sql: 'SELECT * FROM foo, bar WHERE foo.bar_id = bar.id", "query looks already escaped if paramstyle in ['format', 'pyformat']: if '%' in x", "isinstance(item, SQLParam) and isinstance(item.value, SQLLiteral): self.items[i] = item.value.v def append(self, value): self.items.append(value) def", "$x\", vars=dict(x='f'), _test=True) <sql: \"SELECT * FROM foo WHERE x = 'f'\"> >>>", "converts `obj` to its proper SQL version >>> sqlify(None) 'NULL' >>> sqlify(True) \"'t'\"", "is False: return \"'f'\" elif datetime and isinstance(obj, datetime.datetime): return repr(obj.isoformat()) else: if", "\"\"\" def __init__(self, v): self.v = v def __repr__(self): return self.v class SQLProducer:", "dictionary `vars` to interpolate it. If `processed=True`, `vars` is a `reparam`-style list to", "SQLQuery.join(values.keys(), ', ') _values = SQLQuery.join([sqlparam(v) for v in values.values()], ', ') sql_query", "the dictionary. Returns an `SQLQuery` for the result. >>> reparam(\"s = $s\", dict(s=True))", "if using: q += ' USING ' + sqllist(using) if where: q +=", "self.items = [items] elif isinstance(items, SQLQuery): self.items = list(items.items) else: self.items = [items]", "', ', prefix='(', suffix=')') <sql: '(a, b)'> If target argument is provided, the", "sqlparam(v) for k, v in dictionary.items()], grouping) def reparam(string_, dictionary): \"\"\" Takes a", "`SQLQuery`. >>> sqlwhere({'cust_id': 2, 'order_id':3}) <sql: 'order_id = 3 AND cust_id = 2'>", "sqlwhere({'cust_id': 2, 'order_id':3}, grouping=', ') <sql: 'order_id = 3, cust_id = 2'> >>>", "'SELECT * FROM test WHERE x=1'> >>> q.query(), q.values() ('SELECT * FROM test", "None] qout = SQLQuery.join(clauses) if _test: return qout return self.query(qout, processed=True) def insert(self,", "q2 = sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor, sql_query) try: out =", "(2, 'bob', NOW())\"> >>> q.query() 'INSERT INTO foo (age, name, created) VALUES (%s,", "None: raise _ItplError(text, pos) return match, match.end() namechars = \"abcdefghijklmnopqrstuvwxyz\" \\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks", "made to find # the id of the inserted row. q1, q2 =", "safestr('hello') 'hello' >>> safestr(u'\\u1234') '\\xe1\\x88\\xb4' >>> safestr(2) '2' \"\"\" if isinstance(obj, unicode): return", "= eval(chunk, dictionary) result.append(sqlquote(v)) else: result.append(chunk) return SQLQuery.join(result, '') class UnknownParamstyle(Exception): \"\"\" raised", "ids of the inserted rows. Set `seqname` to the ID if it's not", "None: target = SQLQuery() target_items = target.items if prefix: target_items.append(prefix) for i, item", "out = db_cursor.fetchone()[0] out = range(out-len(values)+1, out+1) except Exception: out = None if", "def __init__(self, v): self.v = v def __repr__(self): return self.v class SQLProducer: \"\"\"Database\"\"\"", "%s DEFAULT VALUES\" % table def multiple_insert(self, tablename, values, seqname=None, _test=False): \"\"\" Inserts", "tablename, seqname) if isinstance(sql_query, tuple): # for some databases, a separate query has", "= \"INSERT INTO %s \" % tablename + q(_keys) + ' VALUES '", "def _str(self): try: return self.query() % tuple([sqlify(x) for x in self.values()]) except (ValueError,", "svars) return sql_query def sql_clauses(self, what, tables, where, group, order, limit, offset): return", "return SQLQuery(self.items + items) def __radd__(self, other): if isinstance(other, basestring): items = [other]", "other def __radd__(self, other): return other + self.sqlquery() def __str__(self): return str(self.value) def", "x=%s', [1]) >>> SQLQuery(SQLParam(1)) <sql: '1'> \"\"\" if items is None: self.items =", "= reparam(sql_query, svars) return sql_query def sql_clauses(self, what, tables, where, group, order, limit,", "escape % characters in the query # For backward compatability, ignore escaping when", "**values): \"\"\" Update `tables` with clause `where` (interpolated using `vars`) and setting `values`.", "escaping when the query looks already escaped if paramstyle in ['format', 'pyformat']: if", "sqllist(u'abc') u'abc' \"\"\" if isinstance(lst, basestring): return lst else: return ', '.join(lst) def", "WHERE \" + where) if _test: return query db_cursor = self._db_cursor() self._db_execute(db_cursor, query)", "<sql: 'a, b'> Optinally, prefix and suffix arguments can be provided. >>> SQLQuery.join(['a',", "sqllist(['a', 'b']) 'a, b' >>> sqllist('a') 'a' >>> sqllist(u'abc') u'abc' \"\"\" if isinstance(lst,", "dictioanries, one for each row to be inserted, each with the same set", "self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor, sql_query) try: out = db_cursor.fetchone()[0] out = range(out-len(values)+1, out+1)", "WHERE x = $x\", vars=dict(x='f'), _test=True) <sql: \"SELECT * FROM foo WHERE x", "is a `reparam`-style list to use instead of interpolating. >>> db = DB(None,", "'<EMAIL>'), ('bar', '<EMAIL>')\"> \"\"\" if not values: return [] if not self.supports_multiple_insert: out", "the parameters used in the sql query. >>> q = SQLQuery([\"SELECT * FROM", "('FROM', sqllist(tables)), ('WHERE', where), ('GROUP BY', group), ('ORDER BY', order), ('LIMIT', limit), ('OFFSET',", "interpolating. >>> db = DB(None, {}) >>> db.query(\"SELECT * FROM foo\", _test=True) <sql:", "return where def select(self, tables, svars=None, what='*', where=None, order=None, group=None, limit=None, offset=None, _test=False):", "where) if _test: return query db_cursor = self._db_cursor() self._db_execute(db_cursor, query) if not self.ctx.transactions:", "= DB(None, {}) >>> q = db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'), _test=True) >>> q", "= matchorfail(sformat, dollar + 1) while pos < len(sformat): if sformat[pos] == \".\"", "BY', order), ('LIMIT', limit), ('OFFSET', offset)) def gen_clause(self, sql, val, svars): if isinstance(val,", "compatability, ignore escaping when the query looks already escaped if paramstyle in ['format',", "sql_query def sql_clauses(self, what, tables, where, group, order, limit, offset): return ( ('SELECT',", "def __repr__(self): return self.v class SQLProducer: \"\"\"Database\"\"\" def __init__(self): \"\"\"Creates a database. \"\"\"", "match is None: raise _ItplError(text, pos) return match, match.end() namechars = \"abcdefghijklmnopqrstuvwxyz\" \\", "return \"(\" + x + \")\" if values: _keys = SQLQuery.join(values.keys(), ', ')", ">>> q = SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam(\"joe\")]) >>> q <sql:", "# eval mucks with it result = [] for live, chunk in _interpolate(string_):", "order, limit, offset) clauses = [self.gen_clause(sql, val, svars) for sql, val in sql_clauses", "safeunicode('\\xe1\\x88\\xb4') u'\\u1234' \"\"\" t = type(obj) if t is unicode: return obj elif", "x in self.values()]) except (ValueError, TypeError): return self.query() def __str__(self): return safestr(self._str()) def", "... created=SQLLiteral('NOW()'), vars=locals(), _test=True) >>> q <sql: \"UPDATE foo SET age = 2,", ">>> safeunicode('hello') u'hello' >>> safeunicode(2) u'2' >>> safeunicode('\\xe1\\x88\\xb4') u'\\u1234' \"\"\" t = type(obj)", "is None or paramstyle in ['format', 'pyformat']: return '%s' raise UnknownParamstyle, paramstyle def", "%d\" % ( repr(self.text), self.pos) class SQLParam(object): \"\"\" Parameter in SQLQuery. >>> q", "be inserted, each with the same set of keys. Returns the list of", "* FROM foo WHERE x = \" + sqlquote('f'), _test=True) <sql: \"SELECT *", "sqlwhere({'cust_id': 2, 'order_id':3}) <sql: 'order_id = 3 AND cust_id = 2'> >>> sqlwhere({'cust_id':", "`vars` is a `reparam`-style list to use instead of interpolating. >>> db =", "\" % tablename + q(_keys) + ' VALUES ' + q(_values) else: sql_query", "suffix=None, target=None): \"\"\" Joins multiple queries. >>> SQLQuery.join(['a', 'b'], ', ') <sql: 'a,", "SQLQuery('INSERT INTO %s (%s) VALUES ' % (tablename, ', '.join(keys))) for i, row", "return SQLQuery([self]) def __add__(self, other): return self.sqlquery() + other def __radd__(self, other): return", "self._process_insert_query(sql_query, tablename, seqname) if isinstance(sql_query, tuple): # for some databases, a separate query", "the default, or to `False` if there isn't one. >>> db = DB(None,", "%s, NOW())' >>> q.values() [2, 'bob'] \"\"\" def q(x): return \"(\" + x", "def sqlquote(a): \"\"\" Ensures `a` is quoted properly for use in a SQL", "where), ('GROUP BY', group), ('ORDER BY', order), ('LIMIT', limit), ('OFFSET', offset)) def gen_clause(self,", "a SQL query. >>> 'WHERE x = ' + sqlquote(True) + ' AND", "_test=True) <sql: \"INSERT INTO person (name, email) VALUES ('foo', '<EMAIL>'), ('bar', '<EMAIL>')\"> \"\"\"", "out = [self.insert(tablename, seqname=seqname, _test=_test, **v) for v in values] if seqname is", "For backward compatability, ignore escaping when the query looks already escaped if paramstyle", "x and '%%' not in x: x = x.replace('%', '%%') s.append(x) return \"\".join(s)", "SQLQuery. >>> SQLQuery(\"x\") <sql: 'x'> >>> q = SQLQuery(['SELECT * FROM ', 'test',", "if paramstyle == 'qmark': return '?' elif paramstyle == 'numeric': return ':1' elif", "is None: svars = {} if not processed and not isinstance(sql_query, SQLQuery): sql_query", "\"\".join(s) def values(self): \"\"\" Returns the values of the parameters used in the", "0: break nextchar = sformat[dollar + 1] if nextchar == \"{\": chunks.append((0, sformat[pos:dollar]))", "[] elif isinstance(items, list): self.items = items elif isinstance(items, SQLParam): self.items = [items]", "<sql: \"SELECT * FROM foo WHERE x = 'f'\"> >>> db.query(\"SELECT * FROM", "in values: if v.keys() != keys: raise ValueError, 'Bad data' sql_query = SQLQuery('INSERT", "svars=None, what='*', where=None, order=None, group=None, limit=None, offset=None, _test=False): \"\"\" Selects `what` from `tables`", "its proper SQL version >>> sqlify(None) 'NULL' >>> sqlify(True) \"'t'\" >>> sqlify(3) '3'", "tstart, tend = match.regs[3] token = sformat[tstart:tend] if token == \"{\": level =", "(basestring, SQLParam)): self.items.append(other) elif isinstance(other, SQLQuery): self.items.extend(other.items) else: return NotImplemented return self def", "created = NOW() WHERE name = %s' >>> q.values() [2, 'bob', 'Joseph'] \"\"\"", "if live: v = eval(chunk, dictionary) result.append(sqlquote(v)) else: result.append(chunk) return SQLQuery.join(result, '') class", "test WHERE name='joe'\"> >>> q.query() 'SELECT * FROM test WHERE name=%s' >>> q.values()", "isinstance(obj, unicode): return unicode(obj) else: return str(obj).decode(encoding) def safestr(obj, encoding='utf-8'): r\"\"\" Converts any", "= [{\"name\": \"foo\", \"email\": \"<EMAIL>\"}, {\"name\": \"bar\", \"email\": \"<EMAIL>\"}] >>> db.multiple_insert('person', values=values, _test=True)", "in [int, float, bool]: return unicode(obj) elif hasattr(obj, '__unicode__') or isinstance(obj, unicode): return", "i, v in enumerate(values): if i != 0: items.append(', ') items.append(sqlparam(v)) items.append(')') return", "the ID if it's not the default, or to `False` if there isn't", "= SQLQuery() target_items = target.items if prefix: target_items.append(prefix) for i, item in enumerate(items):", "level + 1 elif token == \"}\": level = level - 1 chunks.append((1,", "if suffix: target_items.append(suffix) return target join = staticmethod(join) def _str(self): try: return self.query()", "self.pos = pos def __str__(self): return \"unfinished expression in %s at char %d\"", "'WHERE x = ' + sqlquote(True) + ' AND y = ' +", "same set of keys. Returns the list of ids of the inserted rows.", "out keys = values[0].keys() #@@ make sure all keys are valid # make", "pos, level = dollar + 2, 1 while level: match, pos = matchorfail(sformat,", "x = x.get_marker(paramstyle) s.append(safestr(x)) else: x = safestr(x) # automatically escape % characters", "sqlquote(SQLLiteral('NOW()')) <sql: 'NOW()'> \"\"\" def __init__(self, v): self.v = v def __repr__(self): return", "`dictionary` to an SQL WHERE clause `SQLQuery`. >>> sqlwhere({'cust_id': 2, 'order_id':3}) <sql: 'order_id", "'b'], ', ') <sql: 'a, b'> Optinally, prefix and suffix arguments can be", "items=None): r\"\"\"Creates a new SQLQuery. >>> SQLQuery(\"x\") <sql: 'x'> >>> q = SQLQuery(['SELECT", "= SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query def _get_insert_default_values_query(self, table): return \"INSERT INTO %s DEFAULT VALUES\"", "if isinstance(other, basestring): items = [other] else: return NotImplemented return SQLQuery(items + self.items)", "except Exception: out = None if not self.ctx.transactions: self.ctx.commit() return out def update(self,", "q = db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'), _test=True) >>> q <sql: \"INSERT INTO foo", "**values): \"\"\" Inserts `values` into `tablename`. Returns current sequence ID. Set `seqname` to", "def sqlwhere(dictionary, grouping=' AND '): \"\"\" Converts a `dictionary` to an SQL WHERE", "<sql: \"SELECT * FROM test WHERE name='joe'\"> >>> q.query() 'SELECT * FROM test", "sql_query,processed=False, svars=None): \"\"\" Execute SQL query `sql_query` using dictionary `vars` to interpolate it.", "x = $x\", vars=dict(x='f'), _test=True) <sql: \"SELECT * FROM foo WHERE x =", "seqname=None, _test=False): \"\"\" Inserts multiple rows into `tablename`. The `values` must be a", "SQLQuery. >>> db = DB(None, {}) >>> db.select('foo', _test=True) <sql: 'SELECT * FROM", "SQLQuery(items + self.items) def __iadd__(self, other): if isinstance(other, (basestring, SQLParam)): self.items.append(other) elif isinstance(other,", "\\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks = [] pos = 0 while 1: dollar = sformat.find(\"$\",", "= self._db_cursor() if seqname is not False: sql_query = self._process_insert_query(sql_query, tablename, seqname) if", "<sql: 'SELECT * FROM foo'> >>> db.select(['foo', 'bar'], where=\"foo.bar_id = bar.id\", limit=5, _test=True)", "\"\"\" # because `1 == True and hash(1) == hash(True)` # we have" ]
[ "'<KEY> # SECURITY WARNING: don't run with debug turned on in production! DEBUG", "= [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dddp', 'dddp.server', 'dddp.accounts', 'dddppp.slides', ]", "'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files", "= { 'LOGNAME': 'pw_name', 'USER': 'pw_name', 'USERNAME': 'pw_name', 'UID': 'pw_uid', 'GID': 'pw_gid', 'HOME':", "continue INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware',", "None: _PW_CACHE = pwd.getpwuid(os.getuid()) os.environ[_missing_env] = str(getattr(_PW_CACHE, _PW_MAP[_missing_env])) del _PW_CACHE, _PW_MAP, pwd BASE_DIR", "{ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('PGDATABASE', PROJECT_NAME), 'USER': os.environ.get('PGUSER', os.environ['LOGNAME']), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', ''), 'HOST':", "# Enforce a valid POSIX environment # Get missing environment variables via call", "# Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import", "], }, }, ] WSGI_APPLICATION = 'dddppp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES =", "if _PW_CACHE is None: _PW_CACHE = pwd.getpwuid(os.getuid()) os.environ[_missing_env] = str(getattr(_PW_CACHE, _PW_MAP[_missing_env])) del _PW_CACHE,", "('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_FRAME_DENY = True SESSION_COOKIE_SECURE =", "_PW_MAP, pwd BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production", "1.8.2. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list", "by 'django-admin startproject' using Django 1.8.2. For more information on this file, see", "Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dddp', 'dddp.server',", "True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True DDDPPP_CONTENT_TYPES = [] PROJ_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__),", "# django-secure # see: https://github.com/carljm/django-secure/ for more options SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT", "paths inside the project like this: os.path.join(BASE_DIR, ...) import os import pkg_resources import", "os.environ.get('DJANGO_DATABASE_PASSWORD', ''), 'HOST': os.environ.get('PGHOST', ''), 'PORT': os.environ.get('PGPORT', ''), } } # Internationalization #", "None _PW_MAP = { 'LOGNAME': 'pw_name', 'USER': 'pw_name', 'USERNAME': 'pw_name', 'UID': 'pw_uid', 'GID':", "django-secure # see: https://github.com/carljm/django-secure/ for more options SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT =", "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dddp',", "STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # django-secure #", "'dddppp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME':", "https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-au' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True", "variables via call to pwd.getpwuid(...) _PW_CACHE = None _PW_MAP = { 'LOGNAME': 'pw_name',", "settings for dddppp project. Generated by 'django-admin startproject' using Django 1.8.2. For more", "'dddppp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': {", "os.environ.get('PGUSER', os.environ['LOGNAME']), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', ''), 'HOST': os.environ.get('PGHOST', ''), 'PORT': os.environ.get('PGPORT', ''), } }", "# Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-au' TIME_ZONE = 'UTC' USE_I18N = True", "file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see", "[], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], },", "'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages',", "USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) #", "for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used", "= os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/", "'pw_gid', 'HOME': 'pw_dir', 'SHELL': 'pw_shell', } for _missing_env in set(_PW_MAP).difference(os.environ): if _PW_CACHE is", "pwd BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production #", "for dddppp project. Generated by 'django-admin startproject' using Django 1.8.2. For more information", "see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/", "# Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('PGDATABASE',", "run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [", "secret! SECRET_KEY = '<KEY> # SECURITY WARNING: don't run with debug turned on", "[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug',", "= True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True DDDPPP_CONTENT_TYPES = [] PROJ_ROOT =", "valid POSIX environment # Get missing environment variables via call to pwd.getpwuid(...) _PW_CACHE", "for _missing_env in set(_PW_MAP).difference(os.environ): if _PW_CACHE is None: _PW_CACHE = pwd.getpwuid(os.getuid()) os.environ[_missing_env] =", "Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,", "inside the project like this: os.path.join(BASE_DIR, ...) import os import pkg_resources import pwd", "'pw_name', 'USERNAME': 'pw_name', 'UID': 'pw_uid', 'GID': 'pw_gid', 'HOME': 'pw_dir', 'SHELL': 'pw_shell', } for", "True ALLOWED_HOSTS = [ 'localhost', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin',", "'django-admin startproject' using Django 1.8.2. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/", "[ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'dddppp.wsgi.application' #", "= True SECURE_FRAME_DENY = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True DDDPPP_CONTENT_TYPES =", "True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT", "STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # django-secure # see: https://github.com/carljm/django-secure/ for more options SECURE_PROXY_SSL_HEADER =", "'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dddp', 'dddp.server', 'dddp.accounts', 'dddppp.slides', ] for (requirement, pth) in", "}, }, ] WSGI_APPLICATION = 'dddppp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = {", "Django 1.8.2. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full", "import pwd PROJECT_NAME = 'dddppp' # Enforce a valid POSIX environment # Get", "STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # django-secure # see: https://github.com/carljm/django-secure/ for", "'django.contrib.staticfiles', 'dddp', 'dddp.server', 'dddp.accounts', 'dddppp.slides', ] for (requirement, pth) in [ ('django-extensions', 'django_extensions'),", "'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # django-secure # see: https://github.com/carljm/django-secure/ for more options SECURE_PROXY_SSL_HEADER", "SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<KEY>", "key used in production secret! SECRET_KEY = '<KEY> # SECURITY WARNING: don't run", "# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production", "True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images)", "keep the secret key used in production secret! SECRET_KEY = '<KEY> # SECURITY", "For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of", "= 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static", "= True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/'", "ROOT_URLCONF = 'dddppp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True,", "dddppp project. Generated by 'django-admin startproject' using Django 1.8.2. For more information on", "Get missing environment variables via call to pwd.getpwuid(...) _PW_CACHE = None _PW_MAP =", "except ( pkg_resources.DistributionNotFound, pkg_resources.VersionConflict, ): continue INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',", "https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\" # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import", "'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'dddppp.wsgi.application' # Database", "- unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret", "more options SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_FRAME_DENY", "pwd PROJECT_NAME = 'dddppp' # Enforce a valid POSIX environment # Get missing", "For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\" #", "SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True DDDPPP_CONTENT_TYPES = [] PROJ_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))", "'pw_dir', 'SHELL': 'pw_shell', } for _missing_env in set(_PW_MAP).difference(os.environ): if _PW_CACHE is None: _PW_CACHE", "''), 'HOST': os.environ.get('PGHOST', ''), 'PORT': os.environ.get('PGPORT', ''), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/", "'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF = 'dddppp.urls' TEMPLATES = [ { 'BACKEND':", "'pw_name', 'UID': 'pw_uid', 'GID': 'pw_gid', 'HOME': 'pw_dir', 'SHELL': 'pw_shell', } for _missing_env in", "'PORT': os.environ.get('PGPORT', ''), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-au' TIME_ZONE", "_PW_CACHE is None: _PW_CACHE = pwd.getpwuid(os.getuid()) os.environ[_missing_env] = str(getattr(_PW_CACHE, _PW_MAP[_missing_env])) del _PW_CACHE, _PW_MAP,", "'dddppp' # Enforce a valid POSIX environment # Get missing environment variables via", "'LOGNAME': 'pw_name', 'USER': 'pw_name', 'USERNAME': 'pw_name', 'UID': 'pw_uid', 'GID': 'pw_gid', 'HOME': 'pw_dir', 'SHELL':", "call to pwd.getpwuid(...) _PW_CACHE = None _PW_MAP = { 'LOGNAME': 'pw_name', 'USER': 'pw_name',", "DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('PGDATABASE', PROJECT_NAME), 'USER': os.environ.get('PGUSER', os.environ['LOGNAME']),", "'SHELL': 'pw_shell', } for _missing_env in set(_PW_MAP).difference(os.environ): if _PW_CACHE is None: _PW_CACHE =", "] ROOT_URLCONF = 'dddppp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS':", "Django settings for dddppp project. Generated by 'django-admin startproject' using Django 1.8.2. For", "# Get missing environment variables via call to pwd.getpwuid(...) _PW_CACHE = None _PW_MAP", "# see: https://github.com/carljm/django-secure/ for more options SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT = True", "''), 'PORT': os.environ.get('PGPORT', ''), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-au'", "in [ ('django-extensions', 'django_extensions'), ]: try: pkg_resources.get_distribution(requirement) except ( pkg_resources.DistributionNotFound, pkg_resources.VersionConflict, ): continue", "using Django 1.8.2. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the", "): continue INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',", "import pkg_resources import pwd PROJECT_NAME = 'dddppp' # Enforce a valid POSIX environment", "in production secret! SECRET_KEY = '<KEY> # SECURITY WARNING: don't run with debug", "'django.contrib.messages', 'django.contrib.staticfiles', 'dddp', 'dddp.server', 'dddp.accounts', 'dddppp.slides', ] for (requirement, pth) in [ ('django-extensions',", "like this: os.path.join(BASE_DIR, ...) import os import pkg_resources import pwd PROJECT_NAME = 'dddppp'", "WARNING: keep the secret key used in production secret! SECRET_KEY = '<KEY> #", "environment # Get missing environment variables via call to pwd.getpwuid(...) _PW_CACHE = None", "'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'dddppp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases", "'django_extensions'), ]: try: pkg_resources.get_distribution(requirement) except ( pkg_resources.DistributionNotFound, pkg_resources.VersionConflict, ): continue INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES =", "= True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/", "project like this: os.path.join(BASE_DIR, ...) import os import pkg_resources import pwd PROJECT_NAME =", "os.environ.get('PGPORT', ''), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-au' TIME_ZONE =", "'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF = 'dddppp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS':", "settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the", "'USERNAME': 'pw_name', 'UID': 'pw_uid', 'GID': 'pw_gid', 'HOME': 'pw_dir', 'SHELL': 'pw_shell', } for _missing_env", "'https') #SECURE_SSL_REDIRECT = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_FRAME_DENY = True SESSION_COOKIE_SECURE = True", "('django-extensions', 'django_extensions'), ]: try: pkg_resources.get_distribution(requirement) except ( pkg_resources.DistributionNotFound, pkg_resources.VersionConflict, ): continue INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES", "True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL", "os.environ.get('PGDATABASE', PROJECT_NAME), 'USER': os.environ.get('PGUSER', os.environ['LOGNAME']), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', ''), 'HOST': os.environ.get('PGHOST', ''), 'PORT': os.environ.get('PGPORT',", "= 'dddppp' # Enforce a valid POSIX environment # Get missing environment variables", "\"\"\" # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os", "for (requirement, pth) in [ ('django-extensions', 'django_extensions'), ]: try: pkg_resources.get_distribution(requirement) except ( pkg_resources.DistributionNotFound,", "set(_PW_MAP).difference(os.environ): if _PW_CACHE is None: _PW_CACHE = pwd.getpwuid(os.getuid()) os.environ[_missing_env] = str(getattr(_PW_CACHE, _PW_MAP[_missing_env])) del", "...) import os import pkg_resources import pwd PROJECT_NAME = 'dddppp' # Enforce a", "'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF = 'dddppp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates',", "'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ],", "del _PW_CACHE, _PW_MAP, pwd BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable", "(requirement, pth) in [ ('django-extensions', 'django_extensions'), ]: try: pkg_resources.get_distribution(requirement) except ( pkg_resources.DistributionNotFound, pkg_resources.VersionConflict,", "#'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF = 'dddppp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [],", "'pw_shell', } for _missing_env in set(_PW_MAP).difference(os.environ): if _PW_CACHE is None: _PW_CACHE = pwd.getpwuid(os.getuid())", "a valid POSIX environment # Get missing environment variables via call to pwd.getpwuid(...)", "of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\" # Build paths inside the", "list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\" # Build paths inside", "PROJECT_NAME), 'USER': os.environ.get('PGUSER', os.environ['LOGNAME']), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', ''), 'HOST': os.environ.get('PGHOST', ''), 'PORT': os.environ.get('PGPORT', ''),", "WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS", "= [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF =", "'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF = 'dddppp.urls' TEMPLATES =", "don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS =", "unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key", "[ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dddp', 'dddp.server', 'dddp.accounts', 'dddppp.slides', ] for", "} # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-au' TIME_ZONE = 'UTC' USE_I18N =", "'HOST': os.environ.get('PGHOST', ''), 'PORT': os.environ.get('PGPORT', ''), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE", "'/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # django-secure # see: https://github.com/carljm/django-secure/", "pkg_resources.get_distribution(requirement) except ( pkg_resources.DistributionNotFound, pkg_resources.VersionConflict, ): continue INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware',", "missing environment variables via call to pwd.getpwuid(...) _PW_CACHE = None _PW_MAP = {", "]: try: pkg_resources.get_distribution(requirement) except ( pkg_resources.DistributionNotFound, pkg_resources.VersionConflict, ): continue INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES = [", "with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [ 'localhost',", "development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep", "https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY", "https://github.com/carljm/django-secure/ for more options SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT = True SECURE_CONTENT_TYPE_NOSNIFF =", "JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE =", "pkg_resources import pwd PROJECT_NAME = 'dddppp' # Enforce a valid POSIX environment #", "}, ] WSGI_APPLICATION = 'dddppp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default':", "'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth',", "WSGI_APPLICATION = 'dddppp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE':", "= 'dddppp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS':", "(CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE", "'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('PGDATABASE', PROJECT_NAME), 'USER': os.environ.get('PGUSER', os.environ['LOGNAME']), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', ''),", "'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },", "Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING:", "see: https://github.com/carljm/django-secure/ for more options SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT = True SECURE_CONTENT_TYPE_NOSNIFF", "= os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # django-secure # see: https://github.com/carljm/django-secure/ for more", "more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings", "TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True #", "the secret key used in production secret! SECRET_KEY = '<KEY> # SECURITY WARNING:", "LANGUAGE_CODE = 'en-au' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ", "[ 'localhost', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions',", "this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values,", "[ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF = 'dddppp.urls'", "'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'dddppp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES", "try: pkg_resources.get_distribution(requirement) except ( pkg_resources.DistributionNotFound, pkg_resources.VersionConflict, ): continue INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware',", "see https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\" # Build paths inside the project like this: os.path.join(BASE_DIR, ...)", "{ 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('PGDATABASE', PROJECT_NAME), 'USER': os.environ.get('PGUSER', os.environ['LOGNAME']), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD',", "= [ 'localhost', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes',", "= '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # django-secure # see:", "project. Generated by 'django-admin startproject' using Django 1.8.2. For more information on this", "# https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('PGDATABASE', PROJECT_NAME), 'USER':", "options SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_FRAME_DENY =", "'pw_name', 'USER': 'pw_name', 'USERNAME': 'pw_name', 'UID': 'pw_uid', 'GID': 'pw_gid', 'HOME': 'pw_dir', 'SHELL': 'pw_shell',", "debug turned on in production! DEBUG = True ALLOWED_HOSTS = [ 'localhost', ]", "= 'en-au' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ =", "Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'", "'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF = 'dddppp.urls' TEMPLATES = [", "Enforce a valid POSIX environment # Get missing environment variables via call to", "pwd.getpwuid(os.getuid()) os.environ[_missing_env] = str(getattr(_PW_CACHE, _PW_MAP[_missing_env])) del _PW_CACHE, _PW_MAP, pwd BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #", "= ('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_FRAME_DENY = True SESSION_COOKIE_SECURE", "'HOME': 'pw_dir', 'SHELL': 'pw_shell', } for _missing_env in set(_PW_MAP).difference(os.environ): if _PW_CACHE is None:", "SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_FRAME_DENY = True", "SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_FRAME_DENY = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True DDDPPP_CONTENT_TYPES", "= [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [", "Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import pkg_resources", "_PW_CACHE = pwd.getpwuid(os.getuid()) os.environ[_missing_env] = str(getattr(_PW_CACHE, _PW_MAP[_missing_env])) del _PW_CACHE, _PW_MAP, pwd BASE_DIR =", "'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', ''), 'HOST': os.environ.get('PGHOST', ''), 'PORT': os.environ.get('PGPORT', ''), } } # Internationalization", "'en-au' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True", "{ 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION =", "pth) in [ ('django-extensions', 'django_extensions'), ]: try: pkg_resources.get_distribution(requirement) except ( pkg_resources.DistributionNotFound, pkg_resources.VersionConflict, ):", "= pwd.getpwuid(os.getuid()) os.environ[_missing_env] = str(getattr(_PW_CACHE, _PW_MAP[_missing_env])) del _PW_CACHE, _PW_MAP, pwd BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))", "'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'dddppp.wsgi.application'", "'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('PGDATABASE', PROJECT_NAME), 'USER': os.environ.get('PGUSER', os.environ['LOGNAME']), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', ''), 'HOST': os.environ.get('PGHOST', ''),", "] for (requirement, pth) in [ ('django-extensions', 'django_extensions'), ]: try: pkg_resources.get_distribution(requirement) except (", "settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\" # Build paths inside the project", "'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF = 'dddppp.urls' TEMPLATES", "via call to pwd.getpwuid(...) _PW_CACHE = None _PW_MAP = { 'LOGNAME': 'pw_name', 'USER':", "for more options SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT = True SECURE_CONTENT_TYPE_NOSNIFF = True", "on in production! DEBUG = True ALLOWED_HOSTS = [ 'localhost', ] # Application", "'GID': 'pw_gid', 'HOME': 'pw_dir', 'SHELL': 'pw_shell', } for _missing_env in set(_PW_MAP).difference(os.environ): if _PW_CACHE", "# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT =", "_PW_MAP[_missing_env])) del _PW_CACHE, _PW_MAP, pwd BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings -", "_PW_CACHE = None _PW_MAP = { 'LOGNAME': 'pw_name', 'USER': 'pw_name', 'USERNAME': 'pw_name', 'UID':", "full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\" # Build paths", "] WSGI_APPLICATION = 'dddppp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': {", "values, see https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\" # Build paths inside the project like this: os.path.join(BASE_DIR,", "USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS,", "= { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('PGDATABASE', PROJECT_NAME), 'USER': os.environ.get('PGUSER', os.environ['LOGNAME']), 'PASSWORD':", "and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\" # Build paths inside the project like", "( pkg_resources.DistributionNotFound, pkg_resources.VersionConflict, ): continue INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',", "information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and", "'whitenoise.django.GzipManifestStaticFilesStorage' # django-secure # see: https://github.com/carljm/django-secure/ for more options SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')", "definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dddp', 'dddp.server', 'dddp.accounts',", "True SECURE_FRAME_DENY = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True DDDPPP_CONTENT_TYPES = []", "'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION", "INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dddp', 'dddp.server', 'dddp.accounts', 'dddppp.slides',", "'dddp.server', 'dddp.accounts', 'dddppp.slides', ] for (requirement, pth) in [ ('django-extensions', 'django_extensions'), ]: try:", "'USER': os.environ.get('PGUSER', os.environ['LOGNAME']), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', ''), 'HOST': os.environ.get('PGHOST', ''), 'PORT': os.environ.get('PGPORT', ''), }", "See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret!", "= None _PW_MAP = { 'LOGNAME': 'pw_name', 'USER': 'pw_name', 'USERNAME': 'pw_name', 'UID': 'pw_uid',", "'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('PGDATABASE', PROJECT_NAME), 'USER': os.environ.get('PGUSER', os.environ['LOGNAME']), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', ''), 'HOST': os.environ.get('PGHOST',", "'NAME': os.environ.get('PGDATABASE', PROJECT_NAME), 'USER': os.environ.get('PGUSER', os.environ['LOGNAME']), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', ''), 'HOST': os.environ.get('PGHOST', ''), 'PORT':", "# SECURITY WARNING: don't run with debug turned on in production! DEBUG =", "in production! DEBUG = True ALLOWED_HOSTS = [ 'localhost', ] # Application definition", "'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'dddppp.wsgi.application' # Database #", "= True ALLOWED_HOSTS = [ 'localhost', ] # Application definition INSTALLED_APPS = [", "is None: _PW_CACHE = pwd.getpwuid(os.getuid()) os.environ[_missing_env] = str(getattr(_PW_CACHE, _PW_MAP[_missing_env])) del _PW_CACHE, _PW_MAP, pwd", "'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dddp', 'dddp.server', 'dddp.accounts', 'dddppp.slides', ] for (requirement, pth)", "turned on in production! DEBUG = True ALLOWED_HOSTS = [ 'localhost', ] #", "_PW_CACHE, _PW_MAP, pwd BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for", "'dddp', 'dddp.server', 'dddp.accounts', 'dddppp.slides', ] for (requirement, pth) in [ ('django-extensions', 'django_extensions'), ]:", "str(getattr(_PW_CACHE, _PW_MAP[_missing_env])) del _PW_CACHE, _PW_MAP, pwd BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings", "} } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-au' TIME_ZONE = 'UTC' USE_I18N", "secret key used in production secret! SECRET_KEY = '<KEY> # SECURITY WARNING: don't", "SECRET_KEY = '<KEY> # SECURITY WARNING: don't run with debug turned on in", "'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dddp', 'dddp.server', 'dddp.accounts', 'dddppp.slides', ] for (requirement, pth) in [", "in set(_PW_MAP).difference(os.environ): if _PW_CACHE is None: _PW_CACHE = pwd.getpwuid(os.getuid()) os.environ[_missing_env] = str(getattr(_PW_CACHE, _PW_MAP[_missing_env]))", "os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ #", "production! DEBUG = True ALLOWED_HOSTS = [ 'localhost', ] # Application definition INSTALLED_APPS", "PROJECT_NAME = 'dddppp' # Enforce a valid POSIX environment # Get missing environment", "their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\" # Build paths inside the project like this:", "https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\"", "files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static')", "os.path.join(BASE_DIR, ...) import os import pkg_resources import pwd PROJECT_NAME = 'dddppp' # Enforce", "used in production secret! SECRET_KEY = '<KEY> # SECURITY WARNING: don't run with", "_missing_env in set(_PW_MAP).difference(os.environ): if _PW_CACHE is None: _PW_CACHE = pwd.getpwuid(os.getuid()) os.environ[_missing_env] = str(getattr(_PW_CACHE,", "USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL =", "'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dddp', 'dddp.server', 'dddp.accounts', 'dddppp.slides', ] for (requirement,", "'UID': 'pw_uid', 'GID': 'pw_gid', 'HOME': 'pw_dir', 'SHELL': 'pw_shell', } for _missing_env in set(_PW_MAP).difference(os.environ):", "= 'whitenoise.django.GzipManifestStaticFilesStorage' # django-secure # see: https://github.com/carljm/django-secure/ for more options SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO',", "SECURE_FRAME_DENY = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True DDDPPP_CONTENT_TYPES = [] PROJ_ROOT", "{ 'LOGNAME': 'pw_name', 'USER': 'pw_name', 'USERNAME': 'pw_name', 'UID': 'pw_uid', 'GID': 'pw_gid', 'HOME': 'pw_dir',", "os import pkg_resources import pwd PROJECT_NAME = 'dddppp' # Enforce a valid POSIX", "os.environ.get('PGHOST', ''), 'PORT': os.environ.get('PGPORT', ''), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE =", "\"\"\" Django settings for dddppp project. Generated by 'django-admin startproject' using Django 1.8.2.", "True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_FRAME_DENY = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True", "} for _missing_env in set(_PW_MAP).difference(os.environ): if _PW_CACHE is None: _PW_CACHE = pwd.getpwuid(os.getuid()) os.environ[_missing_env]", "# https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' #", "pkg_resources.VersionConflict, ): continue INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',", "ALLOWED_HOSTS = [ 'localhost', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth',", "'localhost', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages',", "Generated by 'django-admin startproject' using Django 1.8.2. For more information on this file,", "# https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-au' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N =", "BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See", "= '<KEY> # SECURITY WARNING: don't run with debug turned on in production!", "= True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript,", "https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # django-secure", "] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',", "_PW_MAP = { 'LOGNAME': 'pw_name', 'USER': 'pw_name', 'USERNAME': 'pw_name', 'UID': 'pw_uid', 'GID': 'pw_gid',", "# Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY", "Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-au' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N", "this: os.path.join(BASE_DIR, ...) import os import pkg_resources import pwd PROJECT_NAME = 'dddppp' #", "production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in", "https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('PGDATABASE', PROJECT_NAME), 'USER': os.environ.get('PGUSER',", "'dddppp.slides', ] for (requirement, pth) in [ ('django-extensions', 'django_extensions'), ]: try: pkg_resources.get_distribution(requirement) except", "os.environ['LOGNAME']), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', ''), 'HOST': os.environ.get('PGHOST', ''), 'PORT': os.environ.get('PGPORT', ''), } } #", "= 'dddppp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2',", "'dddp.accounts', 'dddppp.slides', ] for (requirement, pth) in [ ('django-extensions', 'django_extensions'), ]: try: pkg_resources.get_distribution(requirement)", "DEBUG = True ALLOWED_HOSTS = [ 'localhost', ] # Application definition INSTALLED_APPS =", "startproject' using Django 1.8.2. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For", "POSIX environment # Get missing environment variables via call to pwd.getpwuid(...) _PW_CACHE =", "#SECURE_SSL_REDIRECT = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_FRAME_DENY = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY", "True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]", "'pw_uid', 'GID': 'pw_gid', 'HOME': 'pw_dir', 'SHELL': 'pw_shell', } for _missing_env in set(_PW_MAP).difference(os.environ): if", "os.environ[_missing_env] = str(getattr(_PW_CACHE, _PW_MAP[_missing_env])) del _PW_CACHE, _PW_MAP, pwd BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start", "the project like this: os.path.join(BASE_DIR, ...) import os import pkg_resources import pwd PROJECT_NAME", "TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors':", "production secret! SECRET_KEY = '<KEY> # SECURITY WARNING: don't run with debug turned", "pwd.getpwuid(...) _PW_CACHE = None _PW_MAP = { 'LOGNAME': 'pw_name', 'USER': 'pw_name', 'USERNAME': 'pw_name',", "environment variables via call to pwd.getpwuid(...) _PW_CACHE = None _PW_MAP = { 'LOGNAME':", "SECURITY WARNING: don't run with debug turned on in production! DEBUG = True", "on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their", "= True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_FRAME_DENY = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY =", "# SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY =", "{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request',", "pkg_resources.DistributionNotFound, pkg_resources.VersionConflict, ): continue INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',", "INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', ]", "the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\" # Build", "import os import pkg_resources import pwd PROJECT_NAME = 'dddppp' # Enforce a valid", "'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF = 'dddppp.urls' TEMPLATES = [ {", "to pwd.getpwuid(...) _PW_CACHE = None _PW_MAP = { 'LOGNAME': 'pw_name', 'USER': 'pw_name', 'USERNAME':", "[ ('django-extensions', 'django_extensions'), ]: try: pkg_resources.get_distribution(requirement) except ( pkg_resources.DistributionNotFound, pkg_resources.VersionConflict, ): continue INSTALLED_APPS.append(pth)", "Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('PGDATABASE', PROJECT_NAME),", "= str(getattr(_PW_CACHE, _PW_MAP[_missing_env])) del _PW_CACHE, _PW_MAP, pwd BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development", "os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # django-secure # see: https://github.com/carljm/django-secure/ for more options", "''), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-au' TIME_ZONE = 'UTC'", "'USER': 'pw_name', 'USERNAME': 'pw_name', 'UID': 'pw_uid', 'GID': 'pw_gid', 'HOME': 'pw_dir', 'SHELL': 'pw_shell', }", "MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF" ]
[ "python from setuptools import setup import os __doc__ = \"\"\" Command line tool", "#!/usr/bin/env python from setuptools import setup import os __doc__ = \"\"\" Command line", ":: BSD License\", \"Topic :: System :: Networking\", \"Operating System :: POSIX ::", "return open(os.path.join(os.path.dirname(__file__), fname)).read() install_requires = [ 'setuptools', 'pbkdf2', ] try: import argparse except:", "fname)).read() install_requires = [ 'setuptools', 'pbkdf2', ] try: import argparse except: install_requires.append('argparse') version", "install_requires=install_requires, classifiers=[ \"License :: OSI Approved :: BSD License\", \"Topic :: System ::", ":: Python :: 2.7\", \"Programming Language :: Python :: 3.3\", ], data_files=[ ('/etc/bash_completion.d/',", "2.6\", \"Programming Language :: Python :: 2.7\", \"Programming Language :: Python :: 3.3\",", "Networking\", \"Operating System :: POSIX :: Linux\", \"Environment :: Console\", \"Programming Language ::", "os __doc__ = \"\"\" Command line tool and library wrappers around iwlist and", "/etc/network/interfaces. \"\"\" def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() install_requires = [ 'setuptools', 'pbkdf2', ]", "version=version, author='<NAME>, <NAME>', author_email='<EMAIL>', description=__doc__, long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'], test_suite='tests', platforms=[\"Debian\"], license='BSD', install_requires=install_requires, classifiers=[", "library wrappers around iwlist and /etc/network/interfaces. \"\"\" def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() install_requires", "import os __doc__ = \"\"\" Command line tool and library wrappers around iwlist", "name='wifi', version=version, author='<NAME>, <NAME>', author_email='<EMAIL>', description=__doc__, long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'], test_suite='tests', platforms=[\"Debian\"], license='BSD', install_requires=install_requires,", "'setuptools', 'pbkdf2', ] try: import argparse except: install_requires.append('argparse') version = '1.0.0' setup( name='wifi',", "\"Programming Language :: Python :: 2.6\", \"Programming Language :: Python :: 2.7\", \"Programming", "long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'], test_suite='tests', platforms=[\"Debian\"], license='BSD', install_requires=install_requires, classifiers=[ \"License :: OSI Approved ::", "] try: import argparse except: install_requires.append('argparse') version = '1.0.0' setup( name='wifi', version=version, author='<NAME>,", "version = '1.0.0' setup( name='wifi', version=version, author='<NAME>, <NAME>', author_email='<EMAIL>', description=__doc__, long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'],", "Python :: 2.7\", \"Programming Language :: Python :: 3.3\", ], data_files=[ ('/etc/bash_completion.d/', ['extras/wifi-completion.bash']),", "and /etc/network/interfaces. \"\"\" def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() install_requires = [ 'setuptools', 'pbkdf2',", ":: Linux\", \"Environment :: Console\", \"Programming Language :: Python\", \"Programming Language :: Python", ":: Console\", \"Programming Language :: Python\", \"Programming Language :: Python :: 2.6\", \"Programming", "and library wrappers around iwlist and /etc/network/interfaces. \"\"\" def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read()", "wrappers around iwlist and /etc/network/interfaces. \"\"\" def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() install_requires =", "setup import os __doc__ = \"\"\" Command line tool and library wrappers around", "packages=['wifi'], scripts=['bin/wifi'], test_suite='tests', platforms=[\"Debian\"], license='BSD', install_requires=install_requires, classifiers=[ \"License :: OSI Approved :: BSD", "Language :: Python :: 2.6\", \"Programming Language :: Python :: 2.7\", \"Programming Language", "= \"\"\" Command line tool and library wrappers around iwlist and /etc/network/interfaces. \"\"\"", "\"Operating System :: POSIX :: Linux\", \"Environment :: Console\", \"Programming Language :: Python\",", "description=__doc__, long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'], test_suite='tests', platforms=[\"Debian\"], license='BSD', install_requires=install_requires, classifiers=[ \"License :: OSI Approved", "argparse except: install_requires.append('argparse') version = '1.0.0' setup( name='wifi', version=version, author='<NAME>, <NAME>', author_email='<EMAIL>', description=__doc__,", "BSD License\", \"Topic :: System :: Networking\", \"Operating System :: POSIX :: Linux\",", "Console\", \"Programming Language :: Python\", \"Programming Language :: Python :: 2.6\", \"Programming Language", "System :: Networking\", \"Operating System :: POSIX :: Linux\", \"Environment :: Console\", \"Programming", "Approved :: BSD License\", \"Topic :: System :: Networking\", \"Operating System :: POSIX", "license='BSD', install_requires=install_requires, classifiers=[ \"License :: OSI Approved :: BSD License\", \"Topic :: System", "Language :: Python\", \"Programming Language :: Python :: 2.6\", \"Programming Language :: Python", "License\", \"Topic :: System :: Networking\", \"Operating System :: POSIX :: Linux\", \"Environment", "[ 'setuptools', 'pbkdf2', ] try: import argparse except: install_requires.append('argparse') version = '1.0.0' setup(", "Python :: 2.6\", \"Programming Language :: Python :: 2.7\", \"Programming Language :: Python", "try: import argparse except: install_requires.append('argparse') version = '1.0.0' setup( name='wifi', version=version, author='<NAME>, <NAME>',", "install_requires.append('argparse') version = '1.0.0' setup( name='wifi', version=version, author='<NAME>, <NAME>', author_email='<EMAIL>', description=__doc__, long_description=read('README.rst'), packages=['wifi'],", "test_suite='tests', platforms=[\"Debian\"], license='BSD', install_requires=install_requires, classifiers=[ \"License :: OSI Approved :: BSD License\", \"Topic", ":: Networking\", \"Operating System :: POSIX :: Linux\", \"Environment :: Console\", \"Programming Language", "<filename>setup.py #!/usr/bin/env python from setuptools import setup import os __doc__ = \"\"\" Command", "__doc__ = \"\"\" Command line tool and library wrappers around iwlist and /etc/network/interfaces.", "\"License :: OSI Approved :: BSD License\", \"Topic :: System :: Networking\", \"Operating", "\"Environment :: Console\", \"Programming Language :: Python\", \"Programming Language :: Python :: 2.6\",", "tool and library wrappers around iwlist and /etc/network/interfaces. \"\"\" def read(fname): return open(os.path.join(os.path.dirname(__file__),", ":: POSIX :: Linux\", \"Environment :: Console\", \"Programming Language :: Python\", \"Programming Language", "except: install_requires.append('argparse') version = '1.0.0' setup( name='wifi', version=version, author='<NAME>, <NAME>', author_email='<EMAIL>', description=__doc__, long_description=read('README.rst'),", "import argparse except: install_requires.append('argparse') version = '1.0.0' setup( name='wifi', version=version, author='<NAME>, <NAME>', author_email='<EMAIL>',", ":: System :: Networking\", \"Operating System :: POSIX :: Linux\", \"Environment :: Console\",", "Linux\", \"Environment :: Console\", \"Programming Language :: Python\", \"Programming Language :: Python ::", "Language :: Python :: 2.7\", \"Programming Language :: Python :: 3.3\", ], data_files=[", ":: OSI Approved :: BSD License\", \"Topic :: System :: Networking\", \"Operating System", "def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() install_requires = [ 'setuptools', 'pbkdf2', ] try: import", "author_email='<EMAIL>', description=__doc__, long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'], test_suite='tests', platforms=[\"Debian\"], license='BSD', install_requires=install_requires, classifiers=[ \"License :: OSI", "import setup import os __doc__ = \"\"\" Command line tool and library wrappers", ":: Python\", \"Programming Language :: Python :: 2.6\", \"Programming Language :: Python ::", "2.7\", \"Programming Language :: Python :: 3.3\", ], data_files=[ ('/etc/bash_completion.d/', ['extras/wifi-completion.bash']), ] )", "\"\"\" def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() install_requires = [ 'setuptools', 'pbkdf2', ] try:", ":: Python :: 2.6\", \"Programming Language :: Python :: 2.7\", \"Programming Language ::", ":: 2.6\", \"Programming Language :: Python :: 2.7\", \"Programming Language :: Python ::", "System :: POSIX :: Linux\", \"Environment :: Console\", \"Programming Language :: Python\", \"Programming", "author='<NAME>, <NAME>', author_email='<EMAIL>', description=__doc__, long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'], test_suite='tests', platforms=[\"Debian\"], license='BSD', install_requires=install_requires, classifiers=[ \"License", "line tool and library wrappers around iwlist and /etc/network/interfaces. \"\"\" def read(fname): return", "= '1.0.0' setup( name='wifi', version=version, author='<NAME>, <NAME>', author_email='<EMAIL>', description=__doc__, long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'], test_suite='tests',", "setup( name='wifi', version=version, author='<NAME>, <NAME>', author_email='<EMAIL>', description=__doc__, long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'], test_suite='tests', platforms=[\"Debian\"], license='BSD',", "platforms=[\"Debian\"], license='BSD', install_requires=install_requires, classifiers=[ \"License :: OSI Approved :: BSD License\", \"Topic ::", "<NAME>', author_email='<EMAIL>', description=__doc__, long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'], test_suite='tests', platforms=[\"Debian\"], license='BSD', install_requires=install_requires, classifiers=[ \"License ::", "read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() install_requires = [ 'setuptools', 'pbkdf2', ] try: import argparse", "'pbkdf2', ] try: import argparse except: install_requires.append('argparse') version = '1.0.0' setup( name='wifi', version=version,", "\"\"\" Command line tool and library wrappers around iwlist and /etc/network/interfaces. \"\"\" def", "from setuptools import setup import os __doc__ = \"\"\" Command line tool and", "scripts=['bin/wifi'], test_suite='tests', platforms=[\"Debian\"], license='BSD', install_requires=install_requires, classifiers=[ \"License :: OSI Approved :: BSD License\",", "iwlist and /etc/network/interfaces. \"\"\" def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() install_requires = [ 'setuptools',", "'1.0.0' setup( name='wifi', version=version, author='<NAME>, <NAME>', author_email='<EMAIL>', description=__doc__, long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'], test_suite='tests', platforms=[\"Debian\"],", "= [ 'setuptools', 'pbkdf2', ] try: import argparse except: install_requires.append('argparse') version = '1.0.0'", "\"Programming Language :: Python\", \"Programming Language :: Python :: 2.6\", \"Programming Language ::", "POSIX :: Linux\", \"Environment :: Console\", \"Programming Language :: Python\", \"Programming Language ::", ":: 2.7\", \"Programming Language :: Python :: 3.3\", ], data_files=[ ('/etc/bash_completion.d/', ['extras/wifi-completion.bash']), ]", "around iwlist and /etc/network/interfaces. \"\"\" def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() install_requires = [", "open(os.path.join(os.path.dirname(__file__), fname)).read() install_requires = [ 'setuptools', 'pbkdf2', ] try: import argparse except: install_requires.append('argparse')", "install_requires = [ 'setuptools', 'pbkdf2', ] try: import argparse except: install_requires.append('argparse') version =", "Python\", \"Programming Language :: Python :: 2.6\", \"Programming Language :: Python :: 2.7\",", "Command line tool and library wrappers around iwlist and /etc/network/interfaces. \"\"\" def read(fname):", "\"Topic :: System :: Networking\", \"Operating System :: POSIX :: Linux\", \"Environment ::", "\"Programming Language :: Python :: 2.7\", \"Programming Language :: Python :: 3.3\", ],", "classifiers=[ \"License :: OSI Approved :: BSD License\", \"Topic :: System :: Networking\",", "setuptools import setup import os __doc__ = \"\"\" Command line tool and library", "OSI Approved :: BSD License\", \"Topic :: System :: Networking\", \"Operating System ::" ]
[ "auth_api.utils.util import cors_preflight API = Namespace('products', description='Endpoints for products management') TRACER = Tracer.get_instance()", "endpoints for managing an Org resource.\"\"\" from flask import request from flask_restplus import", "Namespace('products', description='Endpoints for products management') TRACER = Tracer.get_instance() _JWT = JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS') @API.route('',", "KIND, either express or implied. # See the License for the specific language", "schema_utils.validate(request_json, 'org_product_subscription') if not valid_format: return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try: subscriptions = ProductService.create_product_subscription(org_id,", "Unless required by applicable law or agreed to in writing, software # distributed", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "# See the License for the specific language governing permissions and # limitations", "Tracer.get_instance() _JWT = JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS') @API.route('', methods=['GET', 'POST', 'OPTIONS']) class OrgProducts(Resource): \"\"\"Resource for", "specific language governing permissions and # limitations under the License. \"\"\"API endpoints for", "License. # You may obtain a copy of the License at # #", "auth_api import status as http_status from auth_api.exceptions import BusinessException from auth_api.jwt_wrapper import JWTWrapper", "management') TRACER = Tracer.get_instance() _JWT = JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS') @API.route('', methods=['GET', 'POST', 'OPTIONS']) class", "valid_format: return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try: subscriptions = ProductService.create_product_subscription(org_id, request_json) if subscriptions is", "= Namespace('products', description='Endpoints for products management') TRACER = Tracer.get_instance() _JWT = JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS')", "import Role from auth_api.utils.util import cors_preflight API = Namespace('products', description='Endpoints for products management')", "distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "else: response, status = {'subscriptions': ProductSubscriptionSchema().dump(subscriptions, many=True)}, \\ http_status.HTTP_201_CREATED except BusinessException as exception:", "'License'); # you may not use this file except in compliance with the", "the License. \"\"\"API endpoints for managing an Org resource.\"\"\" from flask import request", "law or agreed to in writing, software # distributed under the License is", "auth_api.schemas import ProductSubscriptionSchema from auth_api.schemas import utils as schema_utils from auth_api.services import Product", "= JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS') @API.route('', methods=['GET', 'POST', 'OPTIONS']) class OrgProducts(Resource): \"\"\"Resource for managing product", "the License for the specific language governing permissions and # limitations under the", "Apache License, Version 2.0 (the 'License'); # you may not use this file", "compliance with the License. # You may obtain a copy of the License", "import JWTWrapper from auth_api.schemas import ProductSubscriptionSchema from auth_api.schemas import utils as schema_utils from", "the org using the request body.\"\"\" request_json = request.get_json() valid_format, errors = schema_utils.validate(request_json,", "Role from auth_api.utils.util import cors_preflight API = Namespace('products', description='Endpoints for products management') TRACER", "@_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def post(org_id): \"\"\"Post a new product subscription to the org using the", "authorized to perform this action'}, \\ http_status.HTTP_401_UNAUTHORIZED else: response, status = {'subscriptions': ProductSubscriptionSchema().dump(subscriptions,", "Province of British Columbia # # Licensed under the Apache License, Version 2.0", "Licensed under the Apache License, Version 2.0 (the 'License'); # you may not", "this file except in compliance with the License. # You may obtain a", "products management') TRACER = Tracer.get_instance() _JWT = JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS') @API.route('', methods=['GET', 'POST', 'OPTIONS'])", "import cors_preflight API = Namespace('products', description='Endpoints for products management') TRACER = Tracer.get_instance() _JWT", "under the Apache License, Version 2.0 (the 'License'); # you may not use", "managing an Org resource.\"\"\" from flask import request from flask_restplus import Namespace, Resource,", "you may not use this file except in compliance with the License. #", "British Columbia # # Licensed under the Apache License, Version 2.0 (the 'License');", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "ProductService from auth_api.tracer import Tracer from auth_api.utils.roles import Role from auth_api.utils.util import cors_preflight", "\"\"\"Resource for managing product subscriptions.\"\"\" @staticmethod @TRACER.trace() @cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def post(org_id): \"\"\"Post a", "resource.\"\"\" from flask import request from flask_restplus import Namespace, Resource, cors from auth_api", "ProductService.create_product_subscription(org_id, request_json) if subscriptions is None: response, status = {'message': 'Not authorized to", "request body.\"\"\" request_json = request.get_json() valid_format, errors = schema_utils.validate(request_json, 'org_product_subscription') if not valid_format:", "request_json = request.get_json() valid_format, errors = schema_utils.validate(request_json, 'org_product_subscription') if not valid_format: return {'message':", "© 2019 Province of British Columbia # # Licensed under the Apache License,", "new product subscription to the org using the request body.\"\"\" request_json = request.get_json()", "# Copyright © 2019 Province of British Columbia # # Licensed under the", "ANY KIND, either express or implied. # See the License for the specific", "import BusinessException from auth_api.jwt_wrapper import JWTWrapper from auth_api.schemas import ProductSubscriptionSchema from auth_api.schemas import", "from auth_api.schemas import ProductSubscriptionSchema from auth_api.schemas import utils as schema_utils from auth_api.services import", "auth_api.schemas import utils as schema_utils from auth_api.services import Product as ProductService from auth_api.tracer", "_JWT = JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS') @API.route('', methods=['GET', 'POST', 'OPTIONS']) class OrgProducts(Resource): \"\"\"Resource for managing", "@TRACER.trace() @cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def post(org_id): \"\"\"Post a new product subscription to the org", "except BusinessException as exception: response, status = {'code': exception.code, 'message': exception.message}, exception.status_code return", "import utils as schema_utils from auth_api.services import Product as ProductService from auth_api.tracer import", "an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "in compliance with the License. # You may obtain a copy of the", "{'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try: subscriptions = ProductService.create_product_subscription(org_id, request_json) if subscriptions is None: response,", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "product subscription to the org using the request body.\"\"\" request_json = request.get_json() valid_format,", "'Not authorized to perform this action'}, \\ http_status.HTTP_401_UNAUTHORIZED else: response, status = {'subscriptions':", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "post(org_id): \"\"\"Post a new product subscription to the org using the request body.\"\"\"", "use this file except in compliance with the License. # You may obtain", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "http_status.HTTP_201_CREATED except BusinessException as exception: response, status = {'code': exception.code, 'message': exception.message}, exception.status_code", "as exception: response, status = {'code': exception.code, 'message': exception.message}, exception.status_code return response, status", "many=True)}, \\ http_status.HTTP_201_CREATED except BusinessException as exception: response, status = {'code': exception.code, 'message':", "from auth_api import status as http_status from auth_api.exceptions import BusinessException from auth_api.jwt_wrapper import", "(the 'License'); # you may not use this file except in compliance with", "not use this file except in compliance with the License. # You may", "as http_status from auth_api.exceptions import BusinessException from auth_api.jwt_wrapper import JWTWrapper from auth_api.schemas import", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "'org_product_subscription') if not valid_format: return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try: subscriptions = ProductService.create_product_subscription(org_id, request_json)", "http_status.HTTP_401_UNAUTHORIZED else: response, status = {'subscriptions': ProductSubscriptionSchema().dump(subscriptions, many=True)}, \\ http_status.HTTP_201_CREATED except BusinessException as", "response, status = {'message': 'Not authorized to perform this action'}, \\ http_status.HTTP_401_UNAUTHORIZED else:", "Resource, cors from auth_api import status as http_status from auth_api.exceptions import BusinessException from", "See the License for the specific language governing permissions and # limitations under", "ProductSubscriptionSchema().dump(subscriptions, many=True)}, \\ http_status.HTTP_201_CREATED except BusinessException as exception: response, status = {'code': exception.code,", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"\"\"API endpoints for managing an Org resource.\"\"\" from flask import request from flask_restplus", "import Tracer from auth_api.utils.roles import Role from auth_api.utils.util import cors_preflight API = Namespace('products',", "schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try: subscriptions = ProductService.create_product_subscription(org_id, request_json) if subscriptions is None: response, status", "import status as http_status from auth_api.exceptions import BusinessException from auth_api.jwt_wrapper import JWTWrapper from", "from flask_restplus import Namespace, Resource, cors from auth_api import status as http_status from", "auth_api.jwt_wrapper import JWTWrapper from auth_api.schemas import ProductSubscriptionSchema from auth_api.schemas import utils as schema_utils", "License, Version 2.0 (the 'License'); # you may not use this file except", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "None: response, status = {'message': 'Not authorized to perform this action'}, \\ http_status.HTTP_401_UNAUTHORIZED", "= {'message': 'Not authorized to perform this action'}, \\ http_status.HTTP_401_UNAUTHORIZED else: response, status", "2019 Province of British Columbia # # Licensed under the Apache License, Version", "cors from auth_api import status as http_status from auth_api.exceptions import BusinessException from auth_api.jwt_wrapper", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "writing, software # distributed under the License is distributed on an 'AS IS'", "under the License. \"\"\"API endpoints for managing an Org resource.\"\"\" from flask import", "org using the request body.\"\"\" request_json = request.get_json() valid_format, errors = schema_utils.validate(request_json, 'org_product_subscription')", "ProductSubscriptionSchema from auth_api.schemas import utils as schema_utils from auth_api.services import Product as ProductService", "OF ANY KIND, either express or implied. # See the License for the", "limitations under the License. \"\"\"API endpoints for managing an Org resource.\"\"\" from flask", "status = {'message': 'Not authorized to perform this action'}, \\ http_status.HTTP_401_UNAUTHORIZED else: response,", "from auth_api.tracer import Tracer from auth_api.utils.roles import Role from auth_api.utils.util import cors_preflight API", "from flask import request from flask_restplus import Namespace, Resource, cors from auth_api import", "@staticmethod @TRACER.trace() @cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def post(org_id): \"\"\"Post a new product subscription to the", "of British Columbia # # Licensed under the Apache License, Version 2.0 (the", "to perform this action'}, \\ http_status.HTTP_401_UNAUTHORIZED else: response, status = {'subscriptions': ProductSubscriptionSchema().dump(subscriptions, many=True)},", "status = {'subscriptions': ProductSubscriptionSchema().dump(subscriptions, many=True)}, \\ http_status.HTTP_201_CREATED except BusinessException as exception: response, status", "not valid_format: return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try: subscriptions = ProductService.create_product_subscription(org_id, request_json) if subscriptions", "# you may not use this file except in compliance with the License.", "subscriptions is None: response, status = {'message': 'Not authorized to perform this action'},", "@cors_preflight('GET,POST,OPTIONS') @API.route('', methods=['GET', 'POST', 'OPTIONS']) class OrgProducts(Resource): \"\"\"Resource for managing product subscriptions.\"\"\" @staticmethod", "\\ http_status.HTTP_201_CREATED except BusinessException as exception: response, status = {'code': exception.code, 'message': exception.message},", "agreed to in writing, software # distributed under the License is distributed on", "valid_format, errors = schema_utils.validate(request_json, 'org_product_subscription') if not valid_format: return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try:", "{'subscriptions': ProductSubscriptionSchema().dump(subscriptions, many=True)}, \\ http_status.HTTP_201_CREATED except BusinessException as exception: response, status = {'code':", "= {'subscriptions': ProductSubscriptionSchema().dump(subscriptions, many=True)}, \\ http_status.HTTP_201_CREATED except BusinessException as exception: response, status =", "= schema_utils.validate(request_json, 'org_product_subscription') if not valid_format: return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try: subscriptions =", "= ProductService.create_product_subscription(org_id, request_json) if subscriptions is None: response, status = {'message': 'Not authorized", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "OrgProducts(Resource): \"\"\"Resource for managing product subscriptions.\"\"\" @staticmethod @TRACER.trace() @cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def post(org_id): \"\"\"Post", "subscriptions = ProductService.create_product_subscription(org_id, request_json) if subscriptions is None: response, status = {'message': 'Not", "# distributed under the License is distributed on an 'AS IS' BASIS, #", "from auth_api.exceptions import BusinessException from auth_api.jwt_wrapper import JWTWrapper from auth_api.schemas import ProductSubscriptionSchema from", "for products management') TRACER = Tracer.get_instance() _JWT = JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS') @API.route('', methods=['GET', 'POST',", "distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT", "if subscriptions is None: response, status = {'message': 'Not authorized to perform this", "# Licensed under the Apache License, Version 2.0 (the 'License'); # you may", "schema_utils from auth_api.services import Product as ProductService from auth_api.tracer import Tracer from auth_api.utils.roles", "IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "auth_api.tracer import Tracer from auth_api.utils.roles import Role from auth_api.utils.util import cors_preflight API =", "from auth_api.schemas import utils as schema_utils from auth_api.services import Product as ProductService from", "# # Unless required by applicable law or agreed to in writing, software", "Tracer from auth_api.utils.roles import Role from auth_api.utils.util import cors_preflight API = Namespace('products', description='Endpoints", "import Namespace, Resource, cors from auth_api import status as http_status from auth_api.exceptions import", "auth_api.utils.roles import Role from auth_api.utils.util import cors_preflight API = Namespace('products', description='Endpoints for products", "the Apache License, Version 2.0 (the 'License'); # you may not use this", "express or implied. # See the License for the specific language governing permissions", "import ProductSubscriptionSchema from auth_api.schemas import utils as schema_utils from auth_api.services import Product as", "from auth_api.utils.roles import Role from auth_api.utils.util import cors_preflight API = Namespace('products', description='Endpoints for", "# Unless required by applicable law or agreed to in writing, software #", "def post(org_id): \"\"\"Post a new product subscription to the org using the request", "except in compliance with the License. # You may obtain a copy of", "utils as schema_utils from auth_api.services import Product as ProductService from auth_api.tracer import Tracer", "to the org using the request body.\"\"\" request_json = request.get_json() valid_format, errors =", "by applicable law or agreed to in writing, software # distributed under the", "is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "request from flask_restplus import Namespace, Resource, cors from auth_api import status as http_status", "return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try: subscriptions = ProductService.create_product_subscription(org_id, request_json) if subscriptions is None:", "flask_restplus import Namespace, Resource, cors from auth_api import status as http_status from auth_api.exceptions", "TRACER = Tracer.get_instance() _JWT = JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS') @API.route('', methods=['GET', 'POST', 'OPTIONS']) class OrgProducts(Resource):", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "this action'}, \\ http_status.HTTP_401_UNAUTHORIZED else: response, status = {'subscriptions': ProductSubscriptionSchema().dump(subscriptions, many=True)}, \\ http_status.HTTP_201_CREATED", "'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "@cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def post(org_id): \"\"\"Post a new product subscription to the org using", "either express or implied. # See the License for the specific language governing", "managing product subscriptions.\"\"\" @staticmethod @TRACER.trace() @cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def post(org_id): \"\"\"Post a new product", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "may not use this file except in compliance with the License. # You", "governing permissions and # limitations under the License. \"\"\"API endpoints for managing an", "# limitations under the License. \"\"\"API endpoints for managing an Org resource.\"\"\" from", "BusinessException as exception: response, status = {'code': exception.code, 'message': exception.message}, exception.status_code return response,", "import request from flask_restplus import Namespace, Resource, cors from auth_api import status as", "http_status from auth_api.exceptions import BusinessException from auth_api.jwt_wrapper import JWTWrapper from auth_api.schemas import ProductSubscriptionSchema", "request.get_json() valid_format, errors = schema_utils.validate(request_json, 'org_product_subscription') if not valid_format: return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST", "# # Licensed under the Apache License, Version 2.0 (the 'License'); # you", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "<gh_stars>0 # Copyright © 2019 Province of British Columbia # # Licensed under", "from auth_api.utils.util import cors_preflight API = Namespace('products', description='Endpoints for products management') TRACER =", "Product as ProductService from auth_api.tracer import Tracer from auth_api.utils.roles import Role from auth_api.utils.util", "= Tracer.get_instance() _JWT = JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS') @API.route('', methods=['GET', 'POST', 'OPTIONS']) class OrgProducts(Resource): \"\"\"Resource", "file except in compliance with the License. # You may obtain a copy", "the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR", "status as http_status from auth_api.exceptions import BusinessException from auth_api.jwt_wrapper import JWTWrapper from auth_api.schemas", "errors = schema_utils.validate(request_json, 'org_product_subscription') if not valid_format: return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try: subscriptions", "using the request body.\"\"\" request_json = request.get_json() valid_format, errors = schema_utils.validate(request_json, 'org_product_subscription') if", "try: subscriptions = ProductService.create_product_subscription(org_id, request_json) if subscriptions is None: response, status = {'message':", "BusinessException from auth_api.jwt_wrapper import JWTWrapper from auth_api.schemas import ProductSubscriptionSchema from auth_api.schemas import utils", "@API.route('', methods=['GET', 'POST', 'OPTIONS']) class OrgProducts(Resource): \"\"\"Resource for managing product subscriptions.\"\"\" @staticmethod @TRACER.trace()", "auth_api.services import Product as ProductService from auth_api.tracer import Tracer from auth_api.utils.roles import Role", "as ProductService from auth_api.tracer import Tracer from auth_api.utils.roles import Role from auth_api.utils.util import", "on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "subscriptions.\"\"\" @staticmethod @TRACER.trace() @cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def post(org_id): \"\"\"Post a new product subscription to", "software # distributed under the License is distributed on an 'AS IS' BASIS,", "a new product subscription to the org using the request body.\"\"\" request_json =", "= request.get_json() valid_format, errors = schema_utils.validate(request_json, 'org_product_subscription') if not valid_format: return {'message': schema_utils.serialize(errors)},", "License for the specific language governing permissions and # limitations under the License.", "for managing product subscriptions.\"\"\" @staticmethod @TRACER.trace() @cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def post(org_id): \"\"\"Post a new", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "the specific language governing permissions and # limitations under the License. \"\"\"API endpoints", "permissions and # limitations under the License. \"\"\"API endpoints for managing an Org", "if not valid_format: return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try: subscriptions = ProductService.create_product_subscription(org_id, request_json) if", "action'}, \\ http_status.HTTP_401_UNAUTHORIZED else: response, status = {'subscriptions': ProductSubscriptionSchema().dump(subscriptions, many=True)}, \\ http_status.HTTP_201_CREATED except", "description='Endpoints for products management') TRACER = Tracer.get_instance() _JWT = JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS') @API.route('', methods=['GET',", "the License. # You may obtain a copy of the License at #", "JWTWrapper from auth_api.schemas import ProductSubscriptionSchema from auth_api.schemas import utils as schema_utils from auth_api.services", "from auth_api.services import Product as ProductService from auth_api.tracer import Tracer from auth_api.utils.roles import", "License. \"\"\"API endpoints for managing an Org resource.\"\"\" from flask import request from", "Copyright © 2019 Province of British Columbia # # Licensed under the Apache", "Columbia # # Licensed under the Apache License, Version 2.0 (the 'License'); #", "to in writing, software # distributed under the License is distributed on an", "from auth_api.jwt_wrapper import JWTWrapper from auth_api.schemas import ProductSubscriptionSchema from auth_api.schemas import utils as", "for the specific language governing permissions and # limitations under the License. \"\"\"API", "implied. # See the License for the specific language governing permissions and #", "language governing permissions and # limitations under the License. \"\"\"API endpoints for managing", "Org resource.\"\"\" from flask import request from flask_restplus import Namespace, Resource, cors from", "{'message': 'Not authorized to perform this action'}, \\ http_status.HTTP_401_UNAUTHORIZED else: response, status =", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "http_status.HTTP_400_BAD_REQUEST try: subscriptions = ProductService.create_product_subscription(org_id, request_json) if subscriptions is None: response, status =", "required by applicable law or agreed to in writing, software # distributed under", "Version 2.0 (the 'License'); # you may not use this file except in", "an Org resource.\"\"\" from flask import request from flask_restplus import Namespace, Resource, cors", "body.\"\"\" request_json = request.get_json() valid_format, errors = schema_utils.validate(request_json, 'org_product_subscription') if not valid_format: return", "perform this action'}, \\ http_status.HTTP_401_UNAUTHORIZED else: response, status = {'subscriptions': ProductSubscriptionSchema().dump(subscriptions, many=True)}, \\", "applicable law or agreed to in writing, software # distributed under the License", "class OrgProducts(Resource): \"\"\"Resource for managing product subscriptions.\"\"\" @staticmethod @TRACER.trace() @cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def post(org_id):", "auth_api.exceptions import BusinessException from auth_api.jwt_wrapper import JWTWrapper from auth_api.schemas import ProductSubscriptionSchema from auth_api.schemas", "under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES", "methods=['GET', 'POST', 'OPTIONS']) class OrgProducts(Resource): \"\"\"Resource for managing product subscriptions.\"\"\" @staticmethod @TRACER.trace() @cors.crossdomain(origin='*')", "\\ http_status.HTTP_401_UNAUTHORIZED else: response, status = {'subscriptions': ProductSubscriptionSchema().dump(subscriptions, many=True)}, \\ http_status.HTTP_201_CREATED except BusinessException", "flask import request from flask_restplus import Namespace, Resource, cors from auth_api import status", "for managing an Org resource.\"\"\" from flask import request from flask_restplus import Namespace,", "is None: response, status = {'message': 'Not authorized to perform this action'}, \\", "or agreed to in writing, software # distributed under the License is distributed", "\"\"\"Post a new product subscription to the org using the request body.\"\"\" request_json", "or implied. # See the License for the specific language governing permissions and", "import Product as ProductService from auth_api.tracer import Tracer from auth_api.utils.roles import Role from", "'OPTIONS']) class OrgProducts(Resource): \"\"\"Resource for managing product subscriptions.\"\"\" @staticmethod @TRACER.trace() @cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def", "response, status = {'subscriptions': ProductSubscriptionSchema().dump(subscriptions, many=True)}, \\ http_status.HTTP_201_CREATED except BusinessException as exception: response,", "as schema_utils from auth_api.services import Product as ProductService from auth_api.tracer import Tracer from", "2.0 (the 'License'); # you may not use this file except in compliance", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS') @API.route('', methods=['GET', 'POST', 'OPTIONS']) class OrgProducts(Resource): \"\"\"Resource for managing product subscriptions.\"\"\"", "API = Namespace('products', description='Endpoints for products management') TRACER = Tracer.get_instance() _JWT = JWTWrapper.get_instance()", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "the request body.\"\"\" request_json = request.get_json() valid_format, errors = schema_utils.validate(request_json, 'org_product_subscription') if not", "cors_preflight API = Namespace('products', description='Endpoints for products management') TRACER = Tracer.get_instance() _JWT =", "in writing, software # distributed under the License is distributed on an 'AS", "'POST', 'OPTIONS']) class OrgProducts(Resource): \"\"\"Resource for managing product subscriptions.\"\"\" @staticmethod @TRACER.trace() @cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value])", "with the License. # You may obtain a copy of the License at", "request_json) if subscriptions is None: response, status = {'message': 'Not authorized to perform", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "and # limitations under the License. \"\"\"API endpoints for managing an Org resource.\"\"\"", "subscription to the org using the request body.\"\"\" request_json = request.get_json() valid_format, errors", "License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Namespace, Resource, cors from auth_api import status as http_status from auth_api.exceptions import BusinessException", "product subscriptions.\"\"\" @staticmethod @TRACER.trace() @cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def post(org_id): \"\"\"Post a new product subscription" ]
[ ").count(), Application.QUESTION: all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED: all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(), } editor", "import Application from TWLight.resources.models import Partner from TWLight.applications.signals import Reminder from TWLight.users.models import", "class Command(BaseCommand): def handle(self, *args, **options): # This is not DRY. Originally, this", "deduplicated dict of coordinators from the pending app queryset, along # with a", "Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False, ) .exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\", \"partner\", \"date_created\") ) # A deduplicated dict", "status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(), } editor = Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist: logger.info( \"Editor {} does", "TWLight.applications.views.ListApplicationsView.get_queryset(). # But that now expects a request object. So, we did a", "( Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) & Q(status=Application.PENDING) | Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) & Q(status=Application.QUESTION)", "all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED: all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(), } editor = Editor.objects.get(id=coordinator[0])", "with a status of PENDING or QUESTION # or APPROVED, and their corresponding", "try: # We create a dictionary with the three status codes # we'd", "with a status of AVAILABLE. all_apps = ( Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) &", "editor = Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist: logger.info( \"Editor {} does not exist; skipping.\".format(coordinator[0]) )", "TWLight.applications.signals import Reminder from TWLight.users.models import Editor logger = logging.getLogger(__name__) class Command(BaseCommand): def", "Partner from TWLight.applications.signals import Reminder from TWLight.users.models import Editor logger = logging.getLogger(__name__) class", "\"partner__coordinator__editor__user__userprofile__lang\", ) ) for coordinator, count in list(coordinators.items()): try: # We create a", "of coordinators from the pending app queryset, along # with a count of", "} editor = Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist: logger.info( \"Editor {} does not exist; skipping.\".format(coordinator[0])", "pending apps they have coordinators = Counter( all_apps.values_list( \"partner__coordinator__editor\", \"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\", ) )", "Application from TWLight.resources.models import Partner from TWLight.applications.signals import Reminder from TWLight.users.models import Editor", "= Counter( all_apps.values_list( \"partner__coordinator__editor\", \"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\", ) ) for coordinator, count in list(coordinators.items()):", "# TWLight.applications.views.ListApplicationsView.get_queryset(). # But that now expects a request object. So, we did", "and their corresponding user preferences being True # for partners with a status", "app queryset, along # with a count of how many total pending apps", "they have coordinators = Counter( all_apps.values_list( \"partner__coordinator__editor\", \"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\", ) ) for coordinator,", ".order_by(\"status\", \"partner\", \"date_created\") ) # A deduplicated dict of coordinators from the pending", "Q from TWLight.applications.models import Application from TWLight.resources.models import Partner from TWLight.applications.signals import Reminder", "of PENDING or QUESTION # or APPROVED, and their corresponding user preferences being", "\"partner\", \"date_created\") ) # A deduplicated dict of coordinators from the pending app", "from # TWLight.applications.views.ListApplicationsView.get_queryset(). # But that now expects a request object. So, we", "Editor logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): # This is", "Application.QUESTION: all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED: all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(), } editor =", "# We're actually getting apps with a status of PENDING or QUESTION #", "to send emails for, and their corresponding # counts. app_status_and_count = { Application.PENDING:", "did a copy/paste. # We're actually getting apps with a status of PENDING", "of how many total pending apps they have coordinators = Counter( all_apps.values_list( \"partner__coordinator__editor\",", "Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) & Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False, ) .exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\", \"partner\", \"date_created\") )", "a status of PENDING or QUESTION # or APPROVED, and their corresponding user", "all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(), } editor = Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist: logger.info( \"Editor {}", "bother with the signal if we have a coordinator email. if coordinator[1]: Reminder.coordinator_reminder.send(", "status of PENDING or QUESTION # or APPROVED, and their corresponding user preferences", "or APPROVED, and their corresponding user preferences being True # for partners with", "& Q(status=Application.QUESTION) | Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) & Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False, ) .exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\",", "{} does not exist; skipping.\".format(coordinator[0]) ) break # Only bother with the signal", "getting apps with a status of PENDING or QUESTION # or APPROVED, and", "\"date_created\") ) # A deduplicated dict of coordinators from the pending app queryset,", "all_apps = ( Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) & Q(status=Application.PENDING) | Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True )", "So, we did a copy/paste. # We're actually getting apps with a status", "import Editor logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): # This", "= ( Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) & Q(status=Application.PENDING) | Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) &", "with the signal if we have a coordinator email. if coordinator[1]: Reminder.coordinator_reminder.send( sender=self.__class__,", "status of AVAILABLE. all_apps = ( Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) & Q(status=Application.PENDING) |", "coordinators = Counter( all_apps.values_list( \"partner__coordinator__editor\", \"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\", ) ) for coordinator, count in", "from collections import Counter from django.core.management.base import BaseCommand from django.db.models import Q from", "django.db.models import Q from TWLight.applications.models import Application from TWLight.resources.models import Partner from TWLight.applications.signals", "import Q from TWLight.applications.models import Application from TWLight.resources.models import Partner from TWLight.applications.signals import", "partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) & Q(status=Application.PENDING) | Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) & Q(status=Application.QUESTION) | Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True", "partner__status__in=[Partner.AVAILABLE], editor__isnull=False, ) .exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\", \"partner\", \"date_created\") ) # A deduplicated dict of", "the pending app queryset, along # with a count of how many total", "queryset from # TWLight.applications.views.ListApplicationsView.get_queryset(). # But that now expects a request object. So,", "if we have a coordinator email. if coordinator[1]: Reminder.coordinator_reminder.send( sender=self.__class__, app_status_and_count=app_status_and_count, coordinator_wp_username=editor.wp_username, coordinator_email=coordinator[1],", "corresponding user preferences being True # for partners with a status of AVAILABLE.", "all_apps.values_list( \"partner__coordinator__editor\", \"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\", ) ) for coordinator, count in list(coordinators.items()): try: #", "def handle(self, *args, **options): # This is not DRY. Originally, this pulled the", "\"partner__coordinator__editor\", \"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\", ) ) for coordinator, count in list(coordinators.items()): try: # We", "a count of how many total pending apps they have coordinators = Counter(", "logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): # This is not", "\"Editor {} does not exist; skipping.\".format(coordinator[0]) ) break # Only bother with the", "partners with a status of AVAILABLE. all_apps = ( Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True )", "*args, **options): # This is not DRY. Originally, this pulled the queryset from", "the queryset from # TWLight.applications.views.ListApplicationsView.get_queryset(). # But that now expects a request object.", "Originally, this pulled the queryset from # TWLight.applications.views.ListApplicationsView.get_queryset(). # But that now expects", ").count(), } editor = Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist: logger.info( \"Editor {} does not exist;", "AVAILABLE. all_apps = ( Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) & Q(status=Application.PENDING) | Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True", "now expects a request object. So, we did a copy/paste. # We're actually", "# We create a dictionary with the three status codes # we'd want", "have coordinators = Counter( all_apps.values_list( \"partner__coordinator__editor\", \"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\", ) ) for coordinator, count", "app_status_and_count = { Application.PENDING: all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION: all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(),", "from the pending app queryset, along # with a count of how many", "= { Application.PENDING: all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION: all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED:", "django.core.management.base import BaseCommand from django.db.models import Q from TWLight.applications.models import Application from TWLight.resources.models", "along # with a count of how many total pending apps they have", ") # A deduplicated dict of coordinators from the pending app queryset, along", "how many total pending apps they have coordinators = Counter( all_apps.values_list( \"partner__coordinator__editor\", \"partner__coordinator__email\",", "total pending apps they have coordinators = Counter( all_apps.values_list( \"partner__coordinator__editor\", \"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\", )", "collections import Counter from django.core.management.base import BaseCommand from django.db.models import Q from TWLight.applications.models", "TWLight.users.models import Editor logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): #", "QUESTION # or APPROVED, and their corresponding user preferences being True # for", "many total pending apps they have coordinators = Counter( all_apps.values_list( \"partner__coordinator__editor\", \"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\",", "dictionary with the three status codes # we'd want to send emails for,", "status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED: all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(), } editor = Editor.objects.get(id=coordinator[0]) except", "skipping.\".format(coordinator[0]) ) break # Only bother with the signal if we have a", "Q(status=Application.QUESTION) | Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) & Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False, ) .exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\", \"partner\",", "= Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist: logger.info( \"Editor {} does not exist; skipping.\".format(coordinator[0]) ) break", "PENDING or QUESTION # or APPROVED, and their corresponding user preferences being True", "partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) & Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False, ) .exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\", \"partner\", \"date_created\") ) #", "this pulled the queryset from # TWLight.applications.views.ListApplicationsView.get_queryset(). # But that now expects a", "a status of AVAILABLE. all_apps = ( Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) & Q(status=Application.PENDING)", "object. So, we did a copy/paste. # We're actually getting apps with a", "# But that now expects a request object. So, we did a copy/paste.", "create a dictionary with the three status codes # we'd want to send", "copy/paste. # We're actually getting apps with a status of PENDING or QUESTION", "with a count of how many total pending apps they have coordinators =", "we'd want to send emails for, and their corresponding # counts. app_status_and_count =", "# or APPROVED, and their corresponding user preferences being True # for partners", "user preferences being True # for partners with a status of AVAILABLE. all_apps", "in list(coordinators.items()): try: # We create a dictionary with the three status codes", "dict of coordinators from the pending app queryset, along # with a count", "a request object. So, we did a copy/paste. # We're actually getting apps", "Q(status=Application.PENDING) | Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) & Q(status=Application.QUESTION) | Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) & Q(status=Application.APPROVED),", "we did a copy/paste. # We're actually getting apps with a status of", "partner__coordinator__editor=coordinator[0], ).count(), } editor = Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist: logger.info( \"Editor {} does not", ") .exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\", \"partner\", \"date_created\") ) # A deduplicated dict of coordinators from", "the three status codes # we'd want to send emails for, and their", "apps with a status of PENDING or QUESTION # or APPROVED, and their", "of AVAILABLE. all_apps = ( Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) & Q(status=Application.PENDING) | Q(", ") & Q(status=Application.QUESTION) | Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) & Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False, ) .exclude(editor__user__groups__name=\"restricted\")", "Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) & Q(status=Application.PENDING) | Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) & Q(status=Application.QUESTION) | Q(", "# we'd want to send emails for, and their corresponding # counts. app_status_and_count", "all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION: all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED: all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0],", "import Counter from django.core.management.base import BaseCommand from django.db.models import Q from TWLight.applications.models import", "Application.APPROVED: all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(), } editor = Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist: logger.info( \"Editor", "emails for, and their corresponding # counts. app_status_and_count = { Application.PENDING: all_apps.filter( status=Application.PENDING,", "three status codes # we'd want to send emails for, and their corresponding", "from TWLight.resources.models import Partner from TWLight.applications.signals import Reminder from TWLight.users.models import Editor logger", "coordinator, count in list(coordinators.items()): try: # We create a dictionary with the three", "corresponding # counts. app_status_and_count = { Application.PENDING: all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION: all_apps.filter(", "list(coordinators.items()): try: # We create a dictionary with the three status codes #", "DRY. Originally, this pulled the queryset from # TWLight.applications.views.ListApplicationsView.get_queryset(). # But that now", "| Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) & Q(status=Application.QUESTION) | Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) & Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE],", "have a coordinator email. if coordinator[1]: Reminder.coordinator_reminder.send( sender=self.__class__, app_status_and_count=app_status_and_count, coordinator_wp_username=editor.wp_username, coordinator_email=coordinator[1], coordinator_lang=coordinator[2], )", "queryset, along # with a count of how many total pending apps they", "not exist; skipping.\".format(coordinator[0]) ) break # Only bother with the signal if we", "handle(self, *args, **options): # This is not DRY. Originally, this pulled the queryset", "# for partners with a status of AVAILABLE. all_apps = ( Application.objects.filter( Q(", "Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) & Q(status=Application.PENDING) | Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) & Q(status=Application.QUESTION) |", ") break # Only bother with the signal if we have a coordinator", "or QUESTION # or APPROVED, and their corresponding user preferences being True #", "pulled the queryset from # TWLight.applications.views.ListApplicationsView.get_queryset(). # But that now expects a request", "status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION: all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED: all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(),", "Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist: logger.info( \"Editor {} does not exist; skipping.\".format(coordinator[0]) ) break #", "A deduplicated dict of coordinators from the pending app queryset, along # with", "from django.db.models import Q from TWLight.applications.models import Application from TWLight.resources.models import Partner from", "that now expects a request object. So, we did a copy/paste. # We're", "Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) & Q(status=Application.QUESTION) | Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) & Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False,", "actually getting apps with a status of PENDING or QUESTION # or APPROVED,", "being True # for partners with a status of AVAILABLE. all_apps = (", "for partners with a status of AVAILABLE. all_apps = ( Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True", "break # Only bother with the signal if we have a coordinator email.", "signal if we have a coordinator email. if coordinator[1]: Reminder.coordinator_reminder.send( sender=self.__class__, app_status_and_count=app_status_and_count, coordinator_wp_username=editor.wp_username,", "import logging from collections import Counter from django.core.management.base import BaseCommand from django.db.models import", "for coordinator, count in list(coordinators.items()): try: # We create a dictionary with the", "# This is not DRY. Originally, this pulled the queryset from # TWLight.applications.views.ListApplicationsView.get_queryset().", "except Editor.DoesNotExist: logger.info( \"Editor {} does not exist; skipping.\".format(coordinator[0]) ) break # Only", ") ) for coordinator, count in list(coordinators.items()): try: # We create a dictionary", "the signal if we have a coordinator email. if coordinator[1]: Reminder.coordinator_reminder.send( sender=self.__class__, app_status_and_count=app_status_and_count,", "logging from collections import Counter from django.core.management.base import BaseCommand from django.db.models import Q", "request object. So, we did a copy/paste. # We're actually getting apps with", "Application.PENDING: all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION: all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED: all_apps.filter( status=Application.APPROVED,", "editor__isnull=False, ) .exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\", \"partner\", \"date_created\") ) # A deduplicated dict of coordinators", "import BaseCommand from django.db.models import Q from TWLight.applications.models import Application from TWLight.resources.models import", "not DRY. Originally, this pulled the queryset from # TWLight.applications.views.ListApplicationsView.get_queryset(). # But that", "import Reminder from TWLight.users.models import Editor logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self,", "{ Application.PENDING: all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION: all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED: all_apps.filter(", "import Partner from TWLight.applications.signals import Reminder from TWLight.users.models import Editor logger = logging.getLogger(__name__)", "a copy/paste. # We're actually getting apps with a status of PENDING or", ").count(), Application.APPROVED: all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(), } editor = Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist: logger.info(", ") & Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False, ) .exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\", \"partner\", \"date_created\") ) # A", ".exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\", \"partner\", \"date_created\") ) # A deduplicated dict of coordinators from the", "**options): # This is not DRY. Originally, this pulled the queryset from #", "= logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): # This is not DRY.", "# with a count of how many total pending apps they have coordinators", "exist; skipping.\".format(coordinator[0]) ) break # Only bother with the signal if we have", "We're actually getting apps with a status of PENDING or QUESTION # or", "send emails for, and their corresponding # counts. app_status_and_count = { Application.PENDING: all_apps.filter(", "their corresponding # counts. app_status_and_count = { Application.PENDING: all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION:", "partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED: all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(), } editor = Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist:", "Reminder from TWLight.users.models import Editor logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args,", "from TWLight.applications.models import Application from TWLight.resources.models import Partner from TWLight.applications.signals import Reminder from", "& Q(status=Application.PENDING) | Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) & Q(status=Application.QUESTION) | Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) &", "# counts. app_status_and_count = { Application.PENDING: all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION: all_apps.filter( status=Application.QUESTION,", ") for coordinator, count in list(coordinators.items()): try: # We create a dictionary with", "logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): # This is not DRY. Originally,", "Editor.DoesNotExist: logger.info( \"Editor {} does not exist; skipping.\".format(coordinator[0]) ) break # Only bother", "We create a dictionary with the three status codes # we'd want to", "their corresponding user preferences being True # for partners with a status of", "But that now expects a request object. So, we did a copy/paste. #", "does not exist; skipping.\".format(coordinator[0]) ) break # Only bother with the signal if", "and their corresponding # counts. app_status_and_count = { Application.PENDING: all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(),", "partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION: all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED: all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(), }", "# Only bother with the signal if we have a coordinator email. if", "preferences being True # for partners with a status of AVAILABLE. all_apps =", "logger.info( \"Editor {} does not exist; skipping.\".format(coordinator[0]) ) break # Only bother with", "a dictionary with the three status codes # we'd want to send emails", "we have a coordinator email. if coordinator[1]: Reminder.coordinator_reminder.send( sender=self.__class__, app_status_and_count=app_status_and_count, coordinator_wp_username=editor.wp_username, coordinator_email=coordinator[1], coordinator_lang=coordinator[2],", "counts. app_status_and_count = { Application.PENDING: all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION: all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0],", "for, and their corresponding # counts. app_status_and_count = { Application.PENDING: all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0],", "TWLight.resources.models import Partner from TWLight.applications.signals import Reminder from TWLight.users.models import Editor logger =", "count in list(coordinators.items()): try: # We create a dictionary with the three status", ") & Q(status=Application.PENDING) | Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) & Q(status=Application.QUESTION) | Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True )", "True # for partners with a status of AVAILABLE. all_apps = ( Application.objects.filter(", "# A deduplicated dict of coordinators from the pending app queryset, along #", "from TWLight.users.models import Editor logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options):", "from django.core.management.base import BaseCommand from django.db.models import Q from TWLight.applications.models import Application from", "BaseCommand from django.db.models import Q from TWLight.applications.models import Application from TWLight.resources.models import Partner", "TWLight.applications.models import Application from TWLight.resources.models import Partner from TWLight.applications.signals import Reminder from TWLight.users.models", "APPROVED, and their corresponding user preferences being True # for partners with a", "from TWLight.applications.signals import Reminder from TWLight.users.models import Editor logger = logging.getLogger(__name__) class Command(BaseCommand):", "count of how many total pending apps they have coordinators = Counter( all_apps.values_list(", "Counter( all_apps.values_list( \"partner__coordinator__editor\", \"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\", ) ) for coordinator, count in list(coordinators.items()): try:", "status codes # we'd want to send emails for, and their corresponding #", "partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) & Q(status=Application.QUESTION) | Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) & Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False, )", "want to send emails for, and their corresponding # counts. app_status_and_count = {", "apps they have coordinators = Counter( all_apps.values_list( \"partner__coordinator__editor\", \"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\", ) ) for", "coordinators from the pending app queryset, along # with a count of how", "with the three status codes # we'd want to send emails for, and", "expects a request object. So, we did a copy/paste. # We're actually getting", "& Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False, ) .exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\", \"partner\", \"date_created\") ) # A deduplicated", "\"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\", ) ) for coordinator, count in list(coordinators.items()): try: # We create", "is not DRY. Originally, this pulled the queryset from # TWLight.applications.views.ListApplicationsView.get_queryset(). # But", "Only bother with the signal if we have a coordinator email. if coordinator[1]:", "Counter from django.core.management.base import BaseCommand from django.db.models import Q from TWLight.applications.models import Application", "codes # we'd want to send emails for, and their corresponding # counts.", "This is not DRY. Originally, this pulled the queryset from # TWLight.applications.views.ListApplicationsView.get_queryset(). #", "| Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) & Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False, ) .exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\", \"partner\", \"date_created\")", "pending app queryset, along # with a count of how many total pending", "Command(BaseCommand): def handle(self, *args, **options): # This is not DRY. Originally, this pulled" ]
[ "wavelength=555, polarisation=None): super(Laser, self).__init__() self.position = np.array(position) self.direction = np.array(direction) self.wavelength = wavelength", "photon.active = True return photon class RadialSource(object): \"\"\" A point source that emits", "Laser is not set.\" self.polarisation = np.array(polarisation) self.throw = 0 self.source_id = \"LaserSource_\"", "= True photon.wavelength = self.wavelength photon.polarisation = self.polarisation photon.id = self.throw self.throw =", "= self.wavelength photon.polarisation = self.polarisation photon.id = self.throw self.throw = self.throw + 1", "self.throw = 0 self.source_id = \"CylindricalSource_\" + str(id(self)) def translate(self, translation): self.shape.append_transform(tf.translation_matrix(translation)) def", "+ y**2 if s <= 1.0: LOOP = False z = -1. +", "should be perpendicular to the plane normal and aligned with the z-axis. For", "self.throw self.throw = self.throw + 1 intphi = np.random.randint(1, self.spacing+1) inttheta = np.random.randint(1,", "self.throw self.throw = self.throw + 1 # Position of emission phi = np.random.uniform(0.,", "self.wavelength photon.active = True return photon class RadialSource(object): \"\"\" A point source that", "= np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) direction = (x,y,z) transform =", "GLOBAL FRAME. # i.e. this is passed directly to the photon to set", "FinitePlane, transform_point, transform_direction, rotation_matrix_from_vector_alignment, norm from Materials import Spectrum def random_spherecial_vector(): # This", "\"\"\" def __init__(self, spectrum = None, wavelength = 555, center = (0.,0.,0.), phimin", "point if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength photon.active", "wavelength=555, use_random_polarisation=False): super(SimpleSource, self).__init__() self.position = position self.direction = direction self.wavelength = wavelength", "photon.position[2] + boost direction = focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction =", "should have received a copy of the GNU General Public License # along", "if s <= 1.0: LOOP = False z = -1. + 2. *", "+ 1 intphi = np.random.randint(1, self.spacing+1) inttheta = np.random.randint(1, self.spacing+1) phi = intphi*(self.phimax-self.phimin)/self.spacing", "x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) direction = (x,y,z) transform", "this program. If not, see <http://www.gnu.org/licenses/>. import numpy as np from external.transformations import", "(-1,1,1)): super(LensSourceAngle, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.planeorigin = planeorigin self.planeextent", "= spectrum self.wavelength = wavelength self.planeorigin = planeorigin self.planeextent = planeextent self.linepoint =", "PointSource(object): \"\"\" A point source that emits randomly in solid angle specified by", "thetamax self.throw = 0 self.source_id = \"PointSource_\" + str(id(self)) def photon(self): photon =", "length self.width = width # direction is the direction that photons are fired", "Set wavelength of photon if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength", "= (x,y,z) transform = tf.translation_matrix((0,0,0)) point = transform_point(self.center, transform) photon.direction = direction photon.position", "+ np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] direction = focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5", "x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position = np.array((x,y,z)) #", "= 0 self.source_id = \"RadialSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source", "return photon class CylindricalSource(object): \"\"\" A source for photons emitted in a random", "FRAME. # i.e. this is passed directly to the photon to set is's", "= None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), focussize = 0, planeorigin = (-1,-1,-1),", "version. # # pvtrace is distributed in the hope that it will be", "For this lense an additional z-boost is added (Angle of incidence in z-direction).", "angle specified by phimin, ..., thetamax \"\"\" def __init__(self, spectrum = None, wavelength", "z = np.cos(theta) local_direction = (x,y,z) photon.direction = local_direction # Set wavelength of", "= np.random.uniform(0.,self.length) local_center = (x,y,z) photon.position = transform_point(local_center, self.shape.transform) # Direction of emission", "Cylinder(radius = radius, length = length) self.radius = radius self.length = length self.throw", "photon.id = self.throw self.throw = self.throw + 1 return photon class Laser(object): \"\"\"A", "self.throw + 1 return photon class Laser(object): \"\"\"A light source that will generate", "thetamax self.spacing = spacing self.throw = 0 self.source_id = \"RadialSource_\" + str(id(self)) def", "point which is on the surface of the finite plane in it's local", "# You should have received a copy of the GNU General Public License", "angle self.throw = 0 self.source_id = \"LensSourceAngle_\" + str(id(self)) def photon(self): photon =", "= angle self.throw = 0 self.source_id = \"LensSourceAngle_\" + str(id(self)) def photon(self): photon", "\"focussize\". The focus line should be perpendicular to the plane normal and aligned", "# Position of emission phi = np.random.uniform(0., 2*np.pi) r = np.random.uniform(0.,self.radius) x =", "= np.random.randint(1, self.spacing+1) inttheta = np.random.randint(1, self.spacing+1) phi = intphi*(self.phimax-self.phimin)/self.spacing if self.thetamin ==", "with space tolerance given by variable \"focussize\". The focus line should be perpendicular", "0, thetamax = np.pi, spacing=20): super(RadialSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength", "3 of the License, or # (at your option) any later version. #", "self.source_id = \"RadialSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id", "translate(self, translation): self.shape.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.shape.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon =", "= self.throw self.throw = self.throw + 1 return photon class Laser(object): \"\"\"A light", "= thetamax self.spacing = spacing self.throw = 0 self.source_id = \"RadialSource_\" + str(id(self))", "# i.e. this is passed directly to the photon to set is's direction", "self.throw + 1 # Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost =", "GNU General Public License as published by # the Free Software Foundation; either", "self.source_id = \"LaserSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id", "= self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class LensSource(object): \"\"\" A source", "local_point = (x, y, 0.) # Transform the direciton photon.position = transform_point(local_point, self.plane.transform)", "\"SimpleSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id photon.position =", "rotation angle around xy-plane, the transform from +z to the direction of the", "None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class LensSource(object): \"\"\"", "random_spherecial_vector(): # This method of calculating isotropic vectors is taken from GNU Scientific", "randomly in solid angle specified by phimin, ..., thetamax \"\"\" def __init__(self, spectrum", "of calculating isotropic vectors is taken from GNU Scientific Library LOOP = True", "length=0.05, width=0.05): super(PlanarSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.plane = FinitePlane(length=length,", "super(PointSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.center = center self.phimin =", "= wavelength self.plane = FinitePlane(length=length, width=width) self.length = length self.width = width #", "= 0, thetamax = np.pi, spacing=20): super(RadialSource, self).__init__() self.spectrum = spectrum self.wavelength =", "= self.throw + 1 # Position of emission phi = np.random.uniform(0., 2*np.pi) r", "+ str(id(self)) def translate(self, translation): self.plane.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.plane.append_transform(tf.rotation_matrix(angle, axis)) def", "self.throw + 1 return photon class PlanarSource(object): \"\"\"A box that emits photons from", "self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength photon.active = True", "fired out of the plane in the GLOBAL FRAME. # i.e. this is", "wavelength assert polarisation != None, \"Polarisation of the Laser is not set.\" self.polarisation", "# it under the terms of the GNU General Public License as published", "direction that photons are fired out of the plane in the GLOBAL FRAME.", "photon.wavelength = self.wavelength return photon class CylindricalSource(object): \"\"\" A source for photons emitted", "tf from Trace import Photon from Geometry import Box, Cylinder, FinitePlane, transform_point, transform_direction,", "Geometry import Box, Cylinder, FinitePlane, transform_point, transform_direction, rotation_matrix_from_vector_alignment, norm from Materials import Spectrum", "= (0.,0.,0.), phimin = 0, phimax = 2*np.pi, thetamin = 0, thetamax =", "direction and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, use_random_polarisation=False): super(SimpleSource, self).__init__() self.position =", "# # pvtrace is distributed in the hope that it will be useful,", "= use_random_polarisation self.throw = 0 self.source_id = \"SimpleSource_\" + str(id(self)) def photon(self): photon", "direction is the direction that photons are fired out of the plane in", "spacing self.throw = 0 self.source_id = \"RadialSource_\" + str(id(self)) def photon(self): photon =", "+ np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] direction = focuspoint", "np.cos(theta) direction = (x,y,z) transform = tf.translation_matrix((0,0,0)) point = transform_point(self.center, transform) photon.direction =", "def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, use_random_polarisation=False): super(SimpleSource, self).__init__() self.position = position self.direction =", "photon class LensSource(object): \"\"\" A source where photons generated in a plane are", "additional z-boost is added (Angle of incidence in z-direction). \"\"\" def __init__(self, spectrum", "= phimin self.phimax = phimax self.thetamin = thetamin self.thetamax = thetamax self.spacing =", "= self.throw self.throw = self.throw + 1 # Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y", "to the photon to set is's direction self.direction = direction self.throw = 0", "that emits randomly in solid angle specified by phimin, ..., thetamax \"\"\" def", "transform_point(local_center, self.shape.transform) # Direction of emission (no need to transform if meant to", "= 555, linepoint=(0,0,0), linedirection=(0,0,1), angle = 0, focussize = 0, planeorigin = (-1,-1,-1),", "spacing=20): super(RadialSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.center = center self.phimin", "in a random direction and position inside a cylinder(radius, length) \"\"\" def __init__(self,", "direction=[0,0,1], wavelength=555, use_random_polarisation=False): super(SimpleSource, self).__init__() self.position = position self.direction = direction self.wavelength =", "+ str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id photon.id = self.throw", "self.wavelength = wavelength self.shape = Cylinder(radius = radius, length = length) self.radius =", "warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #", "A point source that emits at discrete angles theta(i) and phi(i) \"\"\" def", "self.phimin = phimin self.phimax = phimax self.thetamin = thetamin self.thetamax = thetamax self.spacing", "angle around xy-plane, the transform from +z to the direction of the photon", "self.wavelength = wavelength self.use_random_polarisation = use_random_polarisation self.throw = 0 self.source_id = \"SimpleSource_\" +", "np.random.uniform(self.thetamin, self.thetamax) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) direction =", "local frame x = np.random.uniform(0., self.length) y = np.random.uniform(0., self.width) local_point = (x,", "if self.thetamin == self.thetamax: theta = self.thetamin else: theta = inttheta*(self.thetamax-self.thetamin)/self.spacing x =", "photon.position = transform_point(local_center, self.shape.transform) # Direction of emission (no need to transform if", "= direction photon.position = point if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else:", "= 0 self.source_id = \"PlanarSource_\" + str(id(self)) def translate(self, translation): self.plane.append_transform(tf.translation_matrix(translation)) def rotate(self,", "emitted in a random direction and position inside a cylinder(radius, length) \"\"\" def", "self.radius = radius self.length = length self.throw = 0 self.source_id = \"CylindricalSource_\" +", "import translation_matrix, rotation_matrix import external.transformations as tf from Trace import Photon from Geometry", "= self.wavelength return photon class LensSourceAngle(object): \"\"\" A source where photons generated in", "np.random.uniform(0.,2*np.pi) theta = np.random.uniform(0.,np.pi) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta)", "photon class PointSource(object): \"\"\" A point source that emits randomly in solid angle", "def photon(self): photon = Photon() photon.source = self.source_id photon.position = np.array(self.position) photon.direction =", "True while LOOP: x = -1. + 2. * np.random.uniform() y = -1.", "= \"RadialSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id photon.id", "+ 2. * np.random.uniform() y = -1. + 2. * np.random.uniform() s =", "* np.random.uniform() s = x**2 + y**2 if s <= 1.0: LOOP =", "-1. + 2. * np.random.uniform() y = -1. + 2. * np.random.uniform() s", "+ 1 return photon class PlanarSource(object): \"\"\"A box that emits photons from the", "an additional z-boost is added (Angle of incidence in z-direction). \"\"\" def __init__(self,", "theta = np.random.uniform(self.thetamin, self.thetamax) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta)", "= transform_direction(vec, R) else: photon.polarisation = None photon.id = self.throw self.throw = self.throw", "z-axis. For this lense an additional z-boost is added (Angle of incidence in", "= 0 self.source_id = \"CylindricalSource_\" + str(id(self)) def translate(self, translation): self.shape.append_transform(tf.translation_matrix(translation)) def rotate(self,", "program. If not, see <http://www.gnu.org/licenses/>. import numpy as np from external.transformations import translation_matrix,", "LensSource(object): \"\"\" A source where photons generated in a plane are focused on", "for more details. # # You should have received a copy of the", "translation_matrix, rotation_matrix import external.transformations as tf from Trace import Photon from Geometry import", "= transform_point(local_center, self.shape.transform) # Direction of emission (no need to transform if meant", "self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class LensSourceAngle(object): \"\"\" A source where", "position self.direction = direction self.wavelength = wavelength self.use_random_polarisation = use_random_polarisation self.throw = 0", "2*np.pi, thetamin = 0, thetamax = np.pi): super(PointSource, self).__init__() self.spectrum = spectrum self.wavelength", "of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU", "photon.wavelength = self.wavelength return photon class LensSourceAngle(object): \"\"\" A source where photons generated", "= 10): super(CylindricalSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.shape = Cylinder(radius", "def photon(self): photon = Photon() photon.id = self.throw self.throw = self.throw + 1", "= intphi*(self.phimax-self.phimin)/self.spacing if self.thetamin == self.thetamax: theta = self.thetamin else: theta = inttheta*(self.thetamax-self.thetamin)/self.spacing", "(normal), sampled from the spectrum.\"\"\" def __init__(self, spectrum=None, wavelength=555, direction=(0,0,1), length=0.05, width=0.05): super(PlanarSource,", "self.throw = self.throw + 1 # Create a point which is on the", "source that emits randomly in solid angle specified by phimin, ..., thetamax \"\"\"", "s a = 2 * np.sqrt(1 - s) x = a * x", "or # (at your option) any later version. # # pvtrace is distributed", "!= None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class LensSource(object):", "photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class LensSourceAngle(object): \"\"\" A", "self.throw + 1 # Position of emission phi = np.random.uniform(0., 2*np.pi) r =", "of the photon vec = random_spherecial_vector() vec[2] = 0. vec = norm(vec) R", "(0.,0.,0.), phimin = 0, phimax = 2*np.pi, thetamin = 0, thetamax = np.pi):", "Photon() photon.source = self.source_id photon.position = np.array(self.position) photon.direction = np.array(self.direction) photon.active = True", "y = -1. + 2. * np.random.uniform() s = x**2 + y**2 if", "Scientific Library LOOP = True while LOOP: x = -1. + 2. *", "photon.id = self.throw self.throw = self.throw + 1 # Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0])", "tolerance given by variable \"focussize\". The focus line should be perpendicular to the", "np.random.randint(1, self.spacing+1) phi = intphi*(self.phimax-self.phimin)/self.spacing if self.thetamin == self.thetamax: theta = self.thetamin else:", "Randomise rotation angle around xy-plane, the transform from +z to the direction of", "0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSource, self).__init__() self.spectrum = spectrum self.wavelength", "= self.throw + 1 intphi = np.random.randint(1, self.spacing+1) inttheta = np.random.randint(1, self.spacing+1) phi", "self.use_random_polarisation: # Randomise rotation angle around xy-plane, the transform from +z to the", "of the GNU General Public License as published by # the Free Software", "np.random.uniform(0., self.width) local_point = (x, y, 0.) # Transform the direciton photon.position =", "\"\"\" A point source that emits at discrete angles theta(i) and phi(i) \"\"\"", "!= None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength # Further initialisation photon.active", "Transform the direciton photon.position = transform_point(local_point, self.plane.transform) photon.direction = self.direction photon.active = True", "translation): self.shape.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.shape.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon()", "self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] direction = focuspoint - photon.position modulus =", "= (x,y,z) photon.direction = local_direction # Set wavelength of photon if self.spectrum !=", "inttheta*(self.thetamax-self.thetamin)/self.spacing x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) direction = (x,y,z)", "the direction of the photon vec = random_spherecial_vector() vec[2] = 0. vec =", "photon = Photon() photon.id = self.throw self.throw = self.throw + 1 # Position", "= 0, phimax = 2*np.pi, thetamin = 0, thetamax = np.pi): super(PointSource, self).__init__()", "self.source_id photon.id = self.throw self.throw = self.throw + 1 # Position of emission", "a * x y = a * y return np.array([x,y,z]) class SimpleSource(object): \"\"\"A", "= phimax self.thetamin = thetamin self.thetamax = thetamax self.spacing = spacing self.throw =", "self.shape = Cylinder(radius = radius, length = length) self.radius = radius self.length =", "+ 1 # Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) z = np.random.uniform(self.planeorigin[2],self.planeextent[2])", "later version. # # pvtrace is distributed in the hope that it will", "= direction self.throw = 0 self.source_id = \"PlanarSource_\" + str(id(self)) def translate(self, translation):", "phi = intphi*(self.phimax-self.phimin)/self.spacing if self.thetamin == self.thetamax: theta = self.thetamin else: theta =", "theta = inttheta*(self.thetamax-self.thetamin)/self.spacing x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) direction", "meant to be isotropic) phi = np.random.uniform(0.,2*np.pi) theta = np.random.uniform(0.,np.pi) x = np.cos(phi)*np.sin(theta)", "photon.direction = local_direction # Set wavelength of photon if self.spectrum != None: photon.wavelength", "transform = tf.translation_matrix((0,0,0)) point = transform_point(self.center, transform) photon.direction = direction photon.position = point", "received a copy of the GNU General Public License # along with this", "Box, Cylinder, FinitePlane, transform_point, transform_direction, rotation_matrix_from_vector_alignment, norm from Materials import Spectrum def random_spherecial_vector():", "\"\"\"A box that emits photons from the top surface (normal), sampled from the", "by # the Free Software Foundation; either version 3 of the License, or", "2*np.pi, thetamin = 0, thetamax = np.pi, spacing=20): super(RadialSource, self).__init__() self.spectrum = spectrum", "= wavelength self.center = center self.phimin = phimin self.phimax = phimax self.thetamin =", "copy of the GNU General Public License # along with this program. If", "the photon to set is's direction self.direction = direction self.throw = 0 self.source_id", "\"\"\" A source where photons generated in a plane are focused on a", "import Photon from Geometry import Box, Cylinder, FinitePlane, transform_point, transform_direction, rotation_matrix_from_vector_alignment, norm from", "LOOP = False z = -1. + 2. * s a = 2", "= self.direction photon.active = True if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else:", "class CylindricalSource(object): \"\"\" A source for photons emitted in a random direction and", "axis)) def photon(self): photon = Photon() photon.source = self.source_id photon.id = self.throw self.throw", "str(id(self)) def translate(self, translation): self.plane.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.plane.append_transform(tf.rotation_matrix(angle, axis)) def photon(self):", "self.linedirection = np.array(linedirection) self.focussize = focussize self.angle = angle self.throw = 0 self.source_id", "photon(self): photon = Photon() photon.source = self.source_id photon.id = self.throw self.throw = self.throw", "= None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), angle = 0, focussize = 0,", "self.throw + 1 # Create a point which is on the surface of", "self.wavelength photon.polarisation = self.polarisation photon.id = self.throw self.throw = self.throw + 1 return", "self.source_id = \"CylindricalSource_\" + str(id(self)) def translate(self, translation): self.shape.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis):", "photon.wavelength = self.wavelength return photon class LensSource(object): \"\"\" A source where photons generated", "is distributed in the hope that it will be useful, # but WITHOUT", "in it's local frame x = np.random.uniform(0., self.length) y = np.random.uniform(0., self.width) local_point", "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public", "random_spherecial_vector() vec[2] = 0. vec = norm(vec) R = rotation_matrix_from_vector_alignment(self.direction, [0,0,1]) photon.polarisation =", "in the hope that it will be useful, # but WITHOUT ANY WARRANTY;", "= (-1,-1,-1), planeextent = (-1,1,1)): super(LensSourceAngle, self).__init__() self.spectrum = spectrum self.wavelength = wavelength", "class SimpleSource(object): \"\"\"A light source that will generate photons of a single colour,", "from the spectrum.\"\"\" def __init__(self, spectrum=None, wavelength=555, direction=(0,0,1), length=0.05, width=0.05): super(PlanarSource, self).__init__() self.spectrum", "FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for", "License, or # (at your option) any later version. # # pvtrace is", "= thetamin self.thetamax = thetamax self.spacing = spacing self.throw = 0 self.source_id =", "555, linepoint=(0,0,0), linedirection=(0,0,1), angle = 0, focussize = 0, planeorigin = (-1,-1,-1), planeextent", "= np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize self.throw = 0 self.source_id =", "+ str(id(self)) def translate(self, translation): self.shape.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.shape.append_transform(tf.rotation_matrix(angle, axis)) def", "# Direction of emission (no need to transform if meant to be isotropic)", "if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon", "Materials import Spectrum def random_spherecial_vector(): # This method of calculating isotropic vectors is", "= local_direction # Set wavelength of photon if self.spectrum != None: photon.wavelength =", "angle = 0, focussize = 0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSourceAngle,", "initialisation photon.active = True return photon class PointSource(object): \"\"\" A point source that", "intphi = np.random.randint(1, self.spacing+1) inttheta = np.random.randint(1, self.spacing+1) phi = intphi*(self.phimax-self.phimin)/self.spacing if self.thetamin", "can redistribute it and/or modify # it under the terms of the GNU", "+ 1 return photon class Laser(object): \"\"\"A light source that will generate photons", "version 3 of the License, or # (at your option) any later version.", "None, \"Polarisation of the Laser is not set.\" self.polarisation = np.array(polarisation) self.throw =", "-1. + 2. * np.random.uniform() s = x**2 + y**2 if s <=", "def translate(self, translation): self.shape.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.shape.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon", "= np.array(self.position) photon.direction = np.array(self.direction) photon.active = True photon.wavelength = self.wavelength # If", "self.wavelength # If use_polarisation is set generate a random polarisation vector of the", "= np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost = y*np.tan(self.angle) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) - boost", "radius self.length = length self.throw = 0 self.source_id = \"CylindricalSource_\" + str(id(self)) def", "phimax = 2*np.pi, thetamin = 0, thetamax = np.pi): super(PointSource, self).__init__() self.spectrum =", "of the GNU General Public License # along with this program. If not,", "2. * s a = 2 * np.sqrt(1 - s) x = a", "License for more details. # # You should have received a copy of", "length = length) self.radius = radius self.length = length self.throw = 0 self.source_id", "rotation_matrix import external.transformations as tf from Trace import Photon from Geometry import Box,", "* y return np.array([x,y,z]) class SimpleSource(object): \"\"\"A light source that will generate photons", "= np.cos(theta) direction = (x,y,z) transform = tf.translation_matrix((0,0,0)) point = transform_point(self.center, transform) photon.direction", "redistribute it and/or modify # it under the terms of the GNU General", "should be perpendicular to the plane normal and aligned with the z-axis. \"\"\"", "= 2*np.pi, thetamin = 0, thetamax = np.pi, spacing=20): super(RadialSource, self).__init__() self.spectrum =", "Foundation; either version 3 of the License, or # (at your option) any", "photon.id = self.throw self.throw = self.throw + 1 return photon class PlanarSource(object): \"\"\"A", "r*np.cos(phi) y = r*np.sin(phi) z = np.random.uniform(0.,self.length) local_center = (x,y,z) photon.position = transform_point(local_center,", "self).__init__() self.position = np.array(position) self.direction = np.array(direction) self.wavelength = wavelength assert polarisation !=", "of the Laser is not set.\" self.polarisation = np.array(polarisation) self.throw = 0 self.source_id", "self.wavelength = wavelength assert polarisation != None, \"Polarisation of the Laser is not", "tf.translation_matrix((0,0,0)) point = transform_point(self.center, transform) photon.direction = direction photon.position = point if self.spectrum", "boost direction = focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction = direction/modulus #", "0.) # Transform the direciton photon.position = transform_point(local_point, self.plane.transform) photon.direction = self.direction photon.active", "= np.array(polarisation) self.throw = 0 self.source_id = \"LaserSource_\" + str(id(self)) def photon(self): photon", "class RadialSource(object): \"\"\" A point source that emits at discrete angles theta(i) and", "= self.throw self.throw = self.throw + 1 # Create a point which is", "= focussize self.throw = 0 self.source_id = \"LensSource_\" + str(id(self)) def photon(self): photon", "True return photon class RadialSource(object): \"\"\" A point source that emits at discrete", "photon class PlanarSource(object): \"\"\"A box that emits photons from the top surface (normal),", "the License, or # (at your option) any later version. # # pvtrace", "np.array(self.direction) photon.active = True photon.wavelength = self.wavelength # If use_polarisation is set generate", "self.direction = direction self.wavelength = wavelength self.use_random_polarisation = use_random_polarisation self.throw = 0 self.source_id", "y = np.random.uniform(0., self.width) local_point = (x, y, 0.) # Transform the direciton", "angle, axis): self.plane.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon() photon.source = self.source_id photon.id", "of incidence in z-direction). \"\"\" def __init__(self, spectrum = None, wavelength = 555,", "class PointSource(object): \"\"\" A point source that emits randomly in solid angle specified", "thetamax \"\"\" def __init__(self, spectrum = None, wavelength = 555, center = (0.,0.,0.),", "= 0 self.source_id = \"LaserSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source", "with this program. If not, see <http://www.gnu.org/licenses/>. import numpy as np from external.transformations", "self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.center = center self.phimin = phimin", "self.throw self.throw = self.throw + 1 phi = np.random.uniform(self.phimin, self.phimax) theta = np.random.uniform(self.thetamin,", "None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class LensSourceAngle(object): \"\"\"", "to the plane normal and aligned with the z-axis. \"\"\" def __init__(self, spectrum", "position inside a cylinder(radius, length) \"\"\" def __init__(self, spectrum = None, wavelength =", "self.wavelength = wavelength self.planeorigin = planeorigin self.planeextent = planeextent self.linepoint = np.array(linepoint) self.linedirection", "focused on a line with space tolerance given by variable \"focussize\". The focus", "= np.array(self.position) photon.direction = np.array(self.direction) photon.active = True photon.wavelength = self.wavelength photon.polarisation =", "linepoint=(0,0,0), linedirection=(0,0,1), focussize = 0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSource, self).__init__()", "photon.direction = direction/modulus # Wavelength if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else:", "True photon.wavelength = self.wavelength # If use_polarisation is set generate a random polarisation", "of the finite plane in it's local frame x = np.random.uniform(0., self.length) y", "np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) local_direction = (x,y,z) photon.direction = local_direction", "= width # direction is the direction that photons are fired out of", "position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, polarisation=None): super(Laser, self).__init__() self.position = np.array(position) self.direction", "+ np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] + boost direction = focuspoint - photon.position modulus", "lense an additional z-boost is added (Angle of incidence in z-direction). \"\"\" def", "= 0 self.source_id = \"PointSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source", "a * y return np.array([x,y,z]) class SimpleSource(object): \"\"\"A light source that will generate", "\"\"\"A light source that will generate photons of a single colour, direction and", "from external.transformations import translation_matrix, rotation_matrix import external.transformations as tf from Trace import Photon", "self.source_id photon.position = np.array(self.position) photon.direction = np.array(self.direction) photon.active = True photon.wavelength = self.wavelength", "= self.wavelength return photon class LensSource(object): \"\"\" A source where photons generated in", "will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty", "= (-1,1,1)): super(LensSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.planeorigin = planeorigin", "cylinder(radius, length) \"\"\" def __init__(self, spectrum = None, wavelength = 555, radius =", "= np.array(self.direction) photon.active = True photon.wavelength = self.wavelength # If use_polarisation is set", "str(id(self)) def photon(self): photon = Photon() photon.id = self.throw self.throw = self.throw +", "= np.random.uniform(0.,2*np.pi) theta = np.random.uniform(0.,np.pi) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z =", "class PlanarSource(object): \"\"\"A box that emits photons from the top surface (normal), sampled", "- boost photon.position = np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0] = self.linepoint[0]", "transform) photon.direction = direction photon.position = point if self.spectrum != None: photon.wavelength =", "= np.sin(phi)*np.sin(theta) z = np.cos(theta) direction = (x,y,z) transform = tf.translation_matrix((0,0,0)) point =", "your option) any later version. # # pvtrace is distributed in the hope", "focussize self.angle = angle self.throw = 0 self.source_id = \"LensSourceAngle_\" + str(id(self)) def", "else: photon.wavelength = self.wavelength return photon class LensSourceAngle(object): \"\"\" A source where photons", "plane in the GLOBAL FRAME. # i.e. this is passed directly to the", "str(id(self)) def translate(self, translation): self.shape.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.shape.append_transform(tf.rotation_matrix(angle, axis)) def photon(self):", "super(Laser, self).__init__() self.position = np.array(position) self.direction = np.array(direction) self.wavelength = wavelength assert polarisation", "= self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength photon.active = True return photon class RadialSource(object):", "normal and aligned with the z-axis. For this lense an additional z-boost is", "wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), focussize = 0, planeorigin = (-1,-1,-1), planeextent =", "2*np.pi) r = np.random.uniform(0.,self.radius) x = r*np.cos(phi) y = r*np.sin(phi) z = np.random.uniform(0.,self.length)", "photon.wavelength = self.wavelength photon.polarisation = self.polarisation photon.id = self.throw self.throw = self.throw +", "spectrum self.wavelength = wavelength self.planeorigin = planeorigin self.planeextent = planeextent self.linepoint = np.array(linepoint)", "__init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, polarisation=None): super(Laser, self).__init__() self.position = np.array(position) self.direction = np.array(direction)", "is taken from GNU Scientific Library LOOP = True while LOOP: x =", "np.random.uniform() y = -1. + 2. * np.random.uniform() s = x**2 + y**2", "x = np.random.uniform(0., self.length) y = np.random.uniform(0., self.width) local_point = (x, y, 0.)", "on a line with space tolerance given by variable \"focussize\". The focus line", "phimax = 2*np.pi, thetamin = 0, thetamax = np.pi, spacing=20): super(RadialSource, self).__init__() self.spectrum", "photon.source = self.source_id photon.id = self.throw self.throw = self.throw + 1 # Position", "= spacing self.throw = 0 self.source_id = \"RadialSource_\" + str(id(self)) def photon(self): photon", "photon.position[2] direction = focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction = direction/modulus #", "self.source_id = \"LensSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id", "without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR", "wavelength=555, direction=(0,0,1), length=0.05, width=0.05): super(PlanarSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.plane", "transform if meant to be isotropic) phi = np.random.uniform(0.,2*np.pi) theta = np.random.uniform(0.,np.pi) x", "y = np.sin(phi)*np.sin(theta) z = np.cos(theta) direction = (x,y,z) transform = tf.translation_matrix((0,0,0)) point", "\"PlanarSource_\" + str(id(self)) def translate(self, translation): self.plane.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.plane.append_transform(tf.rotation_matrix(angle, axis))", "length self.throw = 0 self.source_id = \"CylindricalSource_\" + str(id(self)) def translate(self, translation): self.shape.append_transform(tf.translation_matrix(translation))", "self.source_id photon.id = self.throw self.throw = self.throw + 1 # Position x =", "a cylinder(radius, length) \"\"\" def __init__(self, spectrum = None, wavelength = 555, radius", "1 phi = np.random.uniform(self.phimin, self.phimax) theta = np.random.uniform(self.thetamin, self.thetamax) x = np.cos(phi)*np.sin(theta) y", "center = (0.,0.,0.), phimin = 0, phimax = 2*np.pi, thetamin = 0, thetamax", "photon.id = self.throw self.throw = self.throw + 1 intphi = np.random.randint(1, self.spacing+1) inttheta", "self.plane.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon() photon.source = self.source_id photon.id = self.throw", "= Cylinder(radius = radius, length = length) self.radius = radius self.length = length", "photon.position = np.array(self.position) photon.direction = np.array(self.direction) photon.active = True photon.wavelength = self.wavelength #", "You should have received a copy of the GNU General Public License #", "= norm(vec) R = rotation_matrix_from_vector_alignment(self.direction, [0,0,1]) photon.polarisation = transform_direction(vec, R) else: photon.polarisation =", "return photon class RadialSource(object): \"\"\" A point source that emits at discrete angles", "self.spectrum = spectrum self.wavelength = wavelength self.shape = Cylinder(radius = radius, length =", "None photon.id = self.throw self.throw = self.throw + 1 return photon class Laser(object):", "the terms of the GNU General Public License as published by # the", "photon.active = True return photon class PointSource(object): \"\"\" A point source that emits", "np.array((0.,0.,0.)) focuspoint[0] = self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] =", "None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), focussize = 0, planeorigin = (-1,-1,-1), planeextent", "= self.source_id photon.id = self.throw self.throw = self.throw + 1 phi = np.random.uniform(self.phimin,", "use_random_polarisation self.throw = 0 self.source_id = \"SimpleSource_\" + str(id(self)) def photon(self): photon =", "wavelength = 555, center = (0.,0.,0.), phimin = 0, phimax = 2*np.pi, thetamin", "= 2*np.pi, thetamin = 0, thetamax = np.pi): super(PointSource, self).__init__() self.spectrum = spectrum", "self.thetamax = thetamax self.spacing = spacing self.throw = 0 self.source_id = \"RadialSource_\" +", "aligned with the z-axis. For this lense an additional z-boost is added (Angle", "0. vec = norm(vec) R = rotation_matrix_from_vector_alignment(self.direction, [0,0,1]) photon.polarisation = transform_direction(vec, R) else:", "= thetamax self.throw = 0 self.source_id = \"PointSource_\" + str(id(self)) def photon(self): photon", "photon.direction = np.array(self.direction) photon.active = True photon.wavelength = self.wavelength photon.polarisation = self.polarisation photon.id", "self.thetamax) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) direction = (x,y,z)", "rotation_matrix_from_vector_alignment, norm from Materials import Spectrum def random_spherecial_vector(): # This method of calculating", "the surface of the finite plane in it's local frame x = np.random.uniform(0.,", "LensSourceAngle(object): \"\"\" A source where photons generated in a plane are focused on", "= np.random.uniform(self.thetamin, self.thetamax) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) direction", "photon class Laser(object): \"\"\"A light source that will generate photons of a single", "self.plane.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.plane.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon() photon.source", "= 0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSourceAngle, self).__init__() self.spectrum = spectrum", "finite plane in it's local frame x = np.random.uniform(0., self.length) y = np.random.uniform(0.,", "the top surface (normal), sampled from the spectrum.\"\"\" def __init__(self, spectrum=None, wavelength=555, direction=(0,0,1),", "self.phimin = phimin self.phimax = phimax self.thetamin = thetamin self.thetamax = thetamax self.throw", "np from external.transformations import translation_matrix, rotation_matrix import external.transformations as tf from Trace import", "in solid angle specified by phimin, ..., thetamax \"\"\" def __init__(self, spectrum =", "FinitePlane(length=length, width=width) self.length = length self.width = width # direction is the direction", "np.random.uniform(0., self.length) y = np.random.uniform(0., self.width) local_point = (x, y, 0.) # Transform", "set generate a random polarisation vector of the photon if self.use_random_polarisation: # Randomise", "photon.direction = direction photon.position = point if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform())", "self.plane.transform) photon.direction = self.direction photon.active = True if self.spectrum != None: photon.wavelength =", "with the z-axis. For this lense an additional z-boost is added (Angle of", "inttheta = np.random.randint(1, self.spacing+1) phi = intphi*(self.phimax-self.phimin)/self.spacing if self.thetamin == self.thetamax: theta =", "super(RadialSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.center = center self.phimin =", "self.source_id photon.id = self.throw self.throw = self.throw + 1 intphi = np.random.randint(1, self.spacing+1)", "= Photon() photon.source = self.source_id photon.id = self.throw self.throw = self.throw + 1", "along with this program. If not, see <http://www.gnu.org/licenses/>. import numpy as np from", "it's local frame x = np.random.uniform(0., self.length) y = np.random.uniform(0., self.width) local_point =", "Photon() photon.id = self.throw self.throw = self.throw + 1 # Position x =", "direction = (x,y,z) transform = tf.translation_matrix((0,0,0)) point = transform_point(self.center, transform) photon.direction = direction", "= np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0] = self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize) focuspoint[1]", "be isotropic) phi = np.random.uniform(0.,2*np.pi) theta = np.random.uniform(0.,np.pi) x = np.cos(phi)*np.sin(theta) y =", "= self.throw + 1 # Create a point which is on the surface", "(no need to transform if meant to be isotropic) phi = np.random.uniform(0.,2*np.pi) theta", "self.shape.transform) # Direction of emission (no need to transform if meant to be", "r = np.random.uniform(0.,self.radius) x = r*np.cos(phi) y = r*np.sin(phi) z = np.random.uniform(0.,self.length) local_center", "0, phimax = 2*np.pi, thetamin = 0, thetamax = np.pi, spacing=20): super(RadialSource, self).__init__()", "focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] direction = focuspoint - photon.position", "planeextent = (-1,1,1)): super(LensSourceAngle, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.planeorigin =", "solid angle specified by phimin, ..., thetamax \"\"\" def __init__(self, spectrum = None,", "General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import", "of the plane in the GLOBAL FRAME. # i.e. this is passed directly", "np.array([x,y,z]) class SimpleSource(object): \"\"\"A light source that will generate photons of a single", "(Angle of incidence in z-direction). \"\"\" def __init__(self, spectrum = None, wavelength =", "self.planeorigin = planeorigin self.planeextent = planeextent self.linepoint = np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize", "super(LensSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.planeorigin = planeorigin self.planeextent =", "\"LensSourceAngle_\" + str(id(self)) def photon(self): photon = Photon() photon.id = self.throw self.throw =", "# Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position =", "vectors is taken from GNU Scientific Library LOOP = True while LOOP: x", "photon if self.use_random_polarisation: # Randomise rotation angle around xy-plane, the transform from +z", "boost = y*np.tan(self.angle) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) - boost photon.position = np.array((x,y,z)) # Direction", "the GNU General Public License as published by # the Free Software Foundation;", "vec = random_spherecial_vector() vec[2] = 0. vec = norm(vec) R = rotation_matrix_from_vector_alignment(self.direction, [0,0,1])", "in a plane are focused on a line with space tolerance given by", "= np.array(self.direction) photon.active = True photon.wavelength = self.wavelength photon.polarisation = self.polarisation photon.id =", "self.spacing+1) inttheta = np.random.randint(1, self.spacing+1) phi = intphi*(self.phimax-self.phimin)/self.spacing if self.thetamin == self.thetamax: theta", "str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id photon.position = np.array(self.position) photon.direction", "photons generated in a plane are focused on a line with space tolerance", "= self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class CylindricalSource(object): \"\"\" A source", "and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, use_random_polarisation=False): super(SimpleSource, self).__init__() self.position = position", "wavelength = 555, radius = 1, length = 10): super(CylindricalSource, self).__init__() self.spectrum =", "self.use_random_polarisation = use_random_polarisation self.throw = 0 self.source_id = \"SimpleSource_\" + str(id(self)) def photon(self):", "+ boost direction = focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction = direction/modulus", "by phimin, ..., thetamax \"\"\" def __init__(self, spectrum = None, wavelength = 555,", "= length) self.radius = radius self.length = length self.throw = 0 self.source_id =", "not set.\" self.polarisation = np.array(polarisation) self.throw = 0 self.source_id = \"LaserSource_\" + str(id(self))", "= 0, thetamax = np.pi): super(PointSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength", "= position self.direction = direction self.wavelength = wavelength self.use_random_polarisation = use_random_polarisation self.throw =", "self.plane = FinitePlane(length=length, width=width) self.length = length self.width = width # direction is", "of a single colour, direction and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, use_random_polarisation=False):", "the plane normal and aligned with the z-axis. For this lense an additional", "= np.array(linedirection) self.focussize = focussize self.throw = 0 self.source_id = \"LensSource_\" + str(id(self))", "generate photons of a single colour, direction and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1],", "phimin = 0, phimax = 2*np.pi, thetamin = 0, thetamax = np.pi): super(PointSource,", "else: photon.wavelength = self.wavelength # Further initialisation photon.active = True return photon class", "= self.source_id photon.position = np.array(self.position) photon.direction = np.array(self.direction) photon.active = True photon.wavelength =", "direction photon.position = point if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength", "y = a * y return np.array([x,y,z]) class SimpleSource(object): \"\"\"A light source that", "# Further initialisation photon.active = True return photon class PointSource(object): \"\"\" A point", "direction self.wavelength = wavelength self.use_random_polarisation = use_random_polarisation self.throw = 0 self.source_id = \"SimpleSource_\"", "= (x, y, 0.) # Transform the direciton photon.position = transform_point(local_point, self.plane.transform) photon.direction", "transform_direction(vec, R) else: photon.polarisation = None photon.id = self.throw self.throw = self.throw +", "self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class LensSource(object): \"\"\" A source where", "the spectrum.\"\"\" def __init__(self, spectrum=None, wavelength=555, direction=(0,0,1), length=0.05, width=0.05): super(PlanarSource, self).__init__() self.spectrum =", "it will be useful, # but WITHOUT ANY WARRANTY; without even the implied", "\"\"\" A source for photons emitted in a random direction and position inside", "photon.source = self.source_id photon.id = self.throw self.throw = self.throw + 1 phi =", "Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import numpy", "xy-plane, the transform from +z to the direction of the photon vec =", "self.throw = 0 self.source_id = \"PointSource_\" + str(id(self)) def photon(self): photon = Photon()", "a point which is on the surface of the finite plane in it's", "return photon class Laser(object): \"\"\"A light source that will generate photons of a", "y**2 if s <= 1.0: LOOP = False z = -1. + 2.", "555, radius = 1, length = 10): super(CylindricalSource, self).__init__() self.spectrum = spectrum self.wavelength", "a single colour, direction and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, use_random_polarisation=False): super(SimpleSource,", "= np.array(direction) self.wavelength = wavelength assert polarisation != None, \"Polarisation of the Laser", "be perpendicular to the plane normal and aligned with the z-axis. For this", "i.e. this is passed directly to the photon to set is's direction self.direction", "= np.pi, spacing=20): super(RadialSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.center =", "if self.use_random_polarisation: # Randomise rotation angle around xy-plane, the transform from +z to", "10): super(CylindricalSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.shape = Cylinder(radius =", "the # GNU General Public License for more details. # # You should", "..., thetamax \"\"\" def __init__(self, spectrum = None, wavelength = 555, center =", "True photon.wavelength = self.wavelength photon.polarisation = self.polarisation photon.id = self.throw self.throw = self.throw", "external.transformations import translation_matrix, rotation_matrix import external.transformations as tf from Trace import Photon from", "transform_direction, rotation_matrix_from_vector_alignment, norm from Materials import Spectrum def random_spherecial_vector(): # This method of", "def __init__(self, spectrum=None, wavelength=555, direction=(0,0,1), length=0.05, width=0.05): super(PlanarSource, self).__init__() self.spectrum = spectrum self.wavelength", "= np.random.uniform(0., self.width) local_point = (x, y, 0.) # Transform the direciton photon.position", "= spectrum self.wavelength = wavelength self.shape = Cylinder(radius = radius, length = length)", "super(LensSourceAngle, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.planeorigin = planeorigin self.planeextent =", "555, center = (0.,0.,0.), phimin = 0, phimax = 2*np.pi, thetamin = 0,", "else: photon.polarisation = None photon.id = self.throw self.throw = self.throw + 1 return", "__init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, use_random_polarisation=False): super(SimpleSource, self).__init__() self.position = position self.direction = direction", "generate a random polarisation vector of the photon if self.use_random_polarisation: # Randomise rotation", "# the Free Software Foundation; either version 3 of the License, or #", "super(PlanarSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.plane = FinitePlane(length=length, width=width) self.length", "Free Software Foundation; either version 3 of the License, or # (at your", "photons of a single colour, direction and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555,", "specified by phimin, ..., thetamax \"\"\" def __init__(self, spectrum = None, wavelength =", "and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, polarisation=None): super(Laser, self).__init__() self.position = np.array(position)", "self.throw = self.throw + 1 # Position of emission phi = np.random.uniform(0., 2*np.pi)", "wavelength self.planeorigin = planeorigin self.planeextent = planeextent self.linepoint = np.array(linepoint) self.linedirection = np.array(linedirection)", "plane are focused on a line with space tolerance given by variable \"focussize\".", "norm from Materials import Spectrum def random_spherecial_vector(): # This method of calculating isotropic", "PARTICULAR PURPOSE. See the # GNU General Public License for more details. #", "a random polarisation vector of the photon if self.use_random_polarisation: # Randomise rotation angle", "2. * np.random.uniform() y = -1. + 2. * np.random.uniform() s = x**2", "PlanarSource(object): \"\"\"A box that emits photons from the top surface (normal), sampled from", "= np.cos(theta) local_direction = (x,y,z) photon.direction = local_direction # Set wavelength of photon", "width # direction is the direction that photons are fired out of the", "free software; you can redistribute it and/or modify # it under the terms", "focussize = 0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSource, self).__init__() self.spectrum =", "0, focussize = 0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSourceAngle, self).__init__() self.spectrum", "useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of #", "axis): self.plane.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon() photon.source = self.source_id photon.id =", "x = r*np.cos(phi) y = r*np.sin(phi) z = np.random.uniform(0.,self.length) local_center = (x,y,z) photon.position", "on the surface of the finite plane in it's local frame x =", "the GLOBAL FRAME. # i.e. this is passed directly to the photon to", "even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", "= \"PointSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id photon.id", "self.thetamin == self.thetamax: theta = self.thetamin else: theta = inttheta*(self.thetamax-self.thetamin)/self.spacing x = np.cos(phi)*np.sin(theta)", "= spectrum self.wavelength = wavelength self.center = center self.phimin = phimin self.phimax =", "photon.source = self.source_id photon.id = self.throw self.throw = self.throw + 1 intphi =", "direction = focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction = direction/modulus # Wavelength", "= phimax self.thetamin = thetamin self.thetamax = thetamax self.throw = 0 self.source_id =", "from Geometry import Box, Cylinder, FinitePlane, transform_point, transform_direction, rotation_matrix_from_vector_alignment, norm from Materials import", "1 # Create a point which is on the surface of the finite", "= False z = -1. + 2. * s a = 2 *", "phi = np.random.uniform(0., 2*np.pi) r = np.random.uniform(0.,self.radius) x = r*np.cos(phi) y = r*np.sin(phi)", "None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength # Further initialisation photon.active =", "photon = Photon() photon.source = self.source_id photon.position = np.array(self.position) photon.direction = np.array(self.direction) photon.active", "incidence in z-direction). \"\"\" def __init__(self, spectrum = None, wavelength = 555, linepoint=(0,0,0),", "__init__(self, spectrum = None, wavelength = 555, center = (0.,0.,0.), phimin = 0,", "y return np.array([x,y,z]) class SimpleSource(object): \"\"\"A light source that will generate photons of", "discrete angles theta(i) and phi(i) \"\"\" def __init__(self, spectrum = None, wavelength =", "added (Angle of incidence in z-direction). \"\"\" def __init__(self, spectrum = None, wavelength", "focuspoint[2] = photon.position[2] direction = focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction =", "colour, direction and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, use_random_polarisation=False): super(SimpleSource, self).__init__() self.position", "vec[2] = 0. vec = norm(vec) R = rotation_matrix_from_vector_alignment(self.direction, [0,0,1]) photon.polarisation = transform_direction(vec,", "pvtrace is distributed in the hope that it will be useful, # but", "= photon.position[2] + boost direction = focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction", "np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] direction = focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction", "polarisation vector of the photon if self.use_random_polarisation: # Randomise rotation angle around xy-plane,", "local_direction = (x,y,z) photon.direction = local_direction # Set wavelength of photon if self.spectrum", "translation): self.plane.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.plane.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon()", "photon.source = self.source_id photon.id = self.throw self.throw = self.throw + 1 # Create", "to the plane normal and aligned with the z-axis. For this lense an", "photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength # Further initialisation photon.active = True", "= 0 self.source_id = \"SimpleSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source", "= length self.throw = 0 self.source_id = \"CylindricalSource_\" + str(id(self)) def translate(self, translation):", "= radius self.length = length self.throw = 0 self.source_id = \"CylindricalSource_\" + str(id(self))", "radius = 1, length = 10): super(CylindricalSource, self).__init__() self.spectrum = spectrum self.wavelength =", "at discrete angles theta(i) and phi(i) \"\"\" def __init__(self, spectrum = None, wavelength", "photon.active = True photon.wavelength = self.wavelength # If use_polarisation is set generate a", "np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position = np.array((x,y,z)) # Direction focuspoint", "import external.transformations as tf from Trace import Photon from Geometry import Box, Cylinder,", "r*np.sin(phi) z = np.random.uniform(0.,self.length) local_center = (x,y,z) photon.position = transform_point(local_center, self.shape.transform) # Direction", "is not set.\" self.polarisation = np.array(polarisation) self.throw = 0 self.source_id = \"LaserSource_\" +", "planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSource, self).__init__() self.spectrum = spectrum self.wavelength =", "self.throw = self.throw + 1 intphi = np.random.randint(1, self.spacing+1) inttheta = np.random.randint(1, self.spacing+1)", "= self.throw + 1 return photon class PlanarSource(object): \"\"\"A box that emits photons", "Cylinder, FinitePlane, transform_point, transform_direction, rotation_matrix_from_vector_alignment, norm from Materials import Spectrum def random_spherecial_vector(): #", "= wavelength self.use_random_polarisation = use_random_polarisation self.throw = 0 self.source_id = \"SimpleSource_\" + str(id(self))", "= focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction = direction/modulus # Wavelength if", "terms of the GNU General Public License as published by # the Free", "Trace import Photon from Geometry import Box, Cylinder, FinitePlane, transform_point, transform_direction, rotation_matrix_from_vector_alignment, norm", "self.spectrum = spectrum self.wavelength = wavelength self.center = center self.phimin = phimin self.phimax", "emits randomly in solid angle specified by phimin, ..., thetamax \"\"\" def __init__(self,", "Create a point which is on the surface of the finite plane in", "aligned with the z-axis. \"\"\" def __init__(self, spectrum = None, wavelength = 555,", "as tf from Trace import Photon from Geometry import Box, Cylinder, FinitePlane, transform_point,", "source that emits at discrete angles theta(i) and phi(i) \"\"\" def __init__(self, spectrum", "return photon class PointSource(object): \"\"\" A point source that emits randomly in solid", "<http://www.gnu.org/licenses/>. import numpy as np from external.transformations import translation_matrix, rotation_matrix import external.transformations as", "thetamax = np.pi): super(PointSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.center =", "x = -1. + 2. * np.random.uniform() y = -1. + 2. *", "with the z-axis. \"\"\" def __init__(self, spectrum = None, wavelength = 555, linepoint=(0,0,0),", "= True if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength", "= 1, length = 10): super(CylindricalSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength", "# Create a point which is on the surface of the finite plane", "\"LensSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id photon.id =", "space tolerance given by variable \"focussize\". The focus line should be perpendicular to", "= FinitePlane(length=length, width=width) self.length = length self.width = width # direction is the", "= True while LOOP: x = -1. + 2. * np.random.uniform() y =", "self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.plane = FinitePlane(length=length, width=width) self.length =", "self.angle = angle self.throw = 0 self.source_id = \"LensSourceAngle_\" + str(id(self)) def photon(self):", "photon.polarisation = transform_direction(vec, R) else: photon.polarisation = None photon.id = self.throw self.throw =", "phimin, ..., thetamax \"\"\" def __init__(self, spectrum = None, wavelength = 555, center", "True return photon class PointSource(object): \"\"\" A point source that emits randomly in", "that emits at discrete angles theta(i) and phi(i) \"\"\" def __init__(self, spectrum =", "self.source_id photon.id = self.throw self.throw = self.throw + 1 phi = np.random.uniform(self.phimin, self.phimax)", "surface of the finite plane in it's local frame x = np.random.uniform(0., self.length)", "x**2 + y**2 if s <= 1.0: LOOP = False z = -1.", "np.random.uniform(0.,np.pi) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) local_direction = (x,y,z)", "The focus line should be perpendicular to the plane normal and aligned with", "= self.source_id photon.id = self.throw self.throw = self.throw + 1 intphi = np.random.randint(1,", "and aligned with the z-axis. \"\"\" def __init__(self, spectrum = None, wavelength =", "wavelength of photon if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength =", "= np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize self.angle = angle self.throw =", "= self.wavelength # If use_polarisation is set generate a random polarisation vector of", "self.wavelength = wavelength self.plane = FinitePlane(length=length, width=width) self.length = length self.width = width", "ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR", "= self.throw + 1 # Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost", "the plane in the GLOBAL FRAME. # i.e. this is passed directly to", "source where photons generated in a plane are focused on a line with", "self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength # Further initialisation", "WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS", "photon if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength #", "# # You should have received a copy of the GNU General Public", "source that will generate photons of a single colour, direction and position.\"\"\" def", "= planeextent self.linepoint = np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize self.throw =", "2. * np.random.uniform() s = x**2 + y**2 if s <= 1.0: LOOP", "and aligned with the z-axis. For this lense an additional z-boost is added", "modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction = direction/modulus # Wavelength if self.spectrum != None: photon.wavelength", "a random direction and position inside a cylinder(radius, length) \"\"\" def __init__(self, spectrum", "else: photon.wavelength = self.wavelength photon.active = True return photon class RadialSource(object): \"\"\" A", "Public License for more details. # # You should have received a copy", "direciton photon.position = transform_point(local_point, self.plane.transform) photon.direction = self.direction photon.active = True if self.spectrum", "self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.planeorigin = planeorigin self.planeextent = planeextent", "self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength photon.active = True return photon class RadialSource(object): \"\"\"", "photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class CylindricalSource(object): \"\"\" A", "= self.throw self.throw = self.throw + 1 return photon class PlanarSource(object): \"\"\"A box", "self.direction photon.active = True if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength", "set.\" self.polarisation = np.array(polarisation) self.throw = 0 self.source_id = \"LaserSource_\" + str(id(self)) def", "line should be perpendicular to the plane normal and aligned with the z-axis.", "self.length = length self.width = width # direction is the direction that photons", "photon class RadialSource(object): \"\"\" A point source that emits at discrete angles theta(i)", "for photons emitted in a random direction and position inside a cylinder(radius, length)", "np.sin(phi)*np.sin(theta) z = np.cos(theta) direction = (x,y,z) transform = tf.translation_matrix((0,0,0)) point = transform_point(self.center,", "+ np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] + boost direction", "self.shape.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.shape.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon() photon.source", "= True return photon class RadialSource(object): \"\"\" A point source that emits at", "out of the plane in the GLOBAL FRAME. # i.e. this is passed", "return np.array([x,y,z]) class SimpleSource(object): \"\"\"A light source that will generate photons of a", "= 2 * np.sqrt(1 - s) x = a * x y =", "rotation_matrix_from_vector_alignment(self.direction, [0,0,1]) photon.polarisation = transform_direction(vec, R) else: photon.polarisation = None photon.id = self.throw", "that will generate photons of a single colour, direction and position.\"\"\" def __init__(self,", "colour, direction and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, polarisation=None): super(Laser, self).__init__() self.position", "self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.shape = Cylinder(radius = radius, length", "= \"SimpleSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id photon.position", "rotate(self, angle, axis): self.plane.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon() photon.source = self.source_id", "= \"CylindricalSource_\" + str(id(self)) def translate(self, translation): self.shape.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.shape.append_transform(tf.rotation_matrix(angle,", "phi = np.random.uniform(self.phimin, self.phimax) theta = np.random.uniform(self.thetamin, self.thetamax) x = np.cos(phi)*np.sin(theta) y =", "1 return photon class PlanarSource(object): \"\"\"A box that emits photons from the top", "np.random.uniform(0., 2*np.pi) r = np.random.uniform(0.,self.radius) x = r*np.cos(phi) y = r*np.sin(phi) z =", "else: photon.wavelength = self.wavelength return photon class CylindricalSource(object): \"\"\" A source for photons", "None, wavelength = 555, radius = 1, length = 10): super(CylindricalSource, self).__init__() self.spectrum", "= self.throw + 1 phi = np.random.uniform(self.phimin, self.phimax) theta = np.random.uniform(self.thetamin, self.thetamax) x", "self.direction = np.array(direction) self.wavelength = wavelength assert polarisation != None, \"Polarisation of the", "focussize = 0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSourceAngle, self).__init__() self.spectrum =", "from the top surface (normal), sampled from the spectrum.\"\"\" def __init__(self, spectrum=None, wavelength=555,", "else: photon.wavelength = self.wavelength return photon class LensSource(object): \"\"\" A source where photons", "= 0 self.source_id = \"LensSourceAngle_\" + str(id(self)) def photon(self): photon = Photon() photon.id", "top surface (normal), sampled from the spectrum.\"\"\" def __init__(self, spectrum=None, wavelength=555, direction=(0,0,1), length=0.05,", "np.array(linedirection) self.focussize = focussize self.throw = 0 self.source_id = \"LensSource_\" + str(id(self)) def", "= rotation_matrix_from_vector_alignment(self.direction, [0,0,1]) photon.polarisation = transform_direction(vec, R) else: photon.polarisation = None photon.id =", "= (x,y,z) photon.position = transform_point(local_center, self.shape.transform) # Direction of emission (no need to", "= x**2 + y**2 if s <= 1.0: LOOP = False z =", "self.throw = 0 self.source_id = \"RadialSource_\" + str(id(self)) def photon(self): photon = Photon()", "phi = np.random.uniform(0.,2*np.pi) theta = np.random.uniform(0.,np.pi) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z", "focussize self.throw = 0 self.source_id = \"LensSource_\" + str(id(self)) def photon(self): photon =", "that emits photons from the top surface (normal), sampled from the spectrum.\"\"\" def", "not, see <http://www.gnu.org/licenses/>. import numpy as np from external.transformations import translation_matrix, rotation_matrix import", "\"\"\" def __init__(self, spectrum = None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), focussize =", "length) \"\"\" def __init__(self, spectrum = None, wavelength = 555, radius = 1,", "vec = norm(vec) R = rotation_matrix_from_vector_alignment(self.direction, [0,0,1]) photon.polarisation = transform_direction(vec, R) else: photon.polarisation", "transform_point, transform_direction, rotation_matrix_from_vector_alignment, norm from Materials import Spectrum def random_spherecial_vector(): # This method", "None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class CylindricalSource(object): \"\"\"", "numpy as np from external.transformations import translation_matrix, rotation_matrix import external.transformations as tf from", "0 self.source_id = \"LaserSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source =", "0 self.source_id = \"PointSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source =", "!= None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength photon.active = True return", "photon.wavelength = self.wavelength photon.active = True return photon class RadialSource(object): \"\"\" A point", "focus line should be perpendicular to the plane normal and aligned with the", "photon.source = self.source_id photon.position = np.array(self.position) photon.direction = np.array(self.direction) photon.active = True photon.wavelength", "is on the surface of the finite plane in it's local frame x", "WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A", "z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) - boost photon.position = np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.))", "that it will be useful, # but WITHOUT ANY WARRANTY; without even the", "= np.pi): super(PointSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.center = center", "the finite plane in it's local frame x = np.random.uniform(0., self.length) y =", "be perpendicular to the plane normal and aligned with the z-axis. \"\"\" def", "wavelength self.plane = FinitePlane(length=length, width=width) self.length = length self.width = width # direction", "photon.wavelength = self.wavelength # Further initialisation photon.active = True return photon class PointSource(object):", "+ str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id photon.position = np.array(self.position)", "implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the", "\"RadialSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id photon.id =", "= np.random.uniform(self.phimin, self.phimax) theta = np.random.uniform(self.thetamin, self.thetamax) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta)", "+ 1 # Position of emission phi = np.random.uniform(0., 2*np.pi) r = np.random.uniform(0.,self.radius)", "def photon(self): photon = Photon() photon.source = self.source_id photon.id = self.throw self.throw =", "radius, length = length) self.radius = radius self.length = length self.throw = 0", "This method of calculating isotropic vectors is taken from GNU Scientific Library LOOP", "the hope that it will be useful, # but WITHOUT ANY WARRANTY; without", "np.cos(theta) local_direction = (x,y,z) photon.direction = local_direction # Set wavelength of photon if", "True if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return", "planeorigin self.planeextent = planeextent self.linepoint = np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize", "= self.throw + 1 return photon class Laser(object): \"\"\"A light source that will", "source for photons emitted in a random direction and position inside a cylinder(radius,", "\"\"\" A point source that emits randomly in solid angle specified by phimin,", "+ 1 phi = np.random.uniform(self.phimin, self.phimax) theta = np.random.uniform(self.thetamin, self.thetamax) x = np.cos(phi)*np.sin(theta)", "= np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position = np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0] = self.linepoint[0]", "photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class LensSource(object): \"\"\" A", "linedirection=(0,0,1), focussize = 0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSource, self).__init__() self.spectrum", "np.sin(phi)*np.sin(theta) z = np.cos(theta) local_direction = (x,y,z) photon.direction = local_direction # Set wavelength", "!= None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class CylindricalSource(object):", "a copy of the GNU General Public License # along with this program.", "self.linepoint = np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize self.throw = 0 self.source_id", "x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) local_direction = (x,y,z) photon.direction", "= a * x y = a * y return np.array([x,y,z]) class SimpleSource(object):", "A PARTICULAR PURPOSE. See the # GNU General Public License for more details.", "Position of emission phi = np.random.uniform(0., 2*np.pi) r = np.random.uniform(0.,self.radius) x = r*np.cos(phi)", "0 self.source_id = \"LensSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source =", "# This method of calculating isotropic vectors is taken from GNU Scientific Library", "RadialSource(object): \"\"\" A point source that emits at discrete angles theta(i) and phi(i)", "polarisation != None, \"Polarisation of the Laser is not set.\" self.polarisation = np.array(polarisation)", "the Free Software Foundation; either version 3 of the License, or # (at", "y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position = np.array((x,y,z)) # Direction focuspoint =", "return photon class LensSourceAngle(object): \"\"\" A source where photons generated in a plane", "photon(self): photon = Photon() photon.source = self.source_id photon.position = np.array(self.position) photon.direction = np.array(self.direction)", "= self.polarisation photon.id = self.throw self.throw = self.throw + 1 return photon class", "frame x = np.random.uniform(0., self.length) y = np.random.uniform(0., self.width) local_point = (x, y,", "class LensSource(object): \"\"\" A source where photons generated in a plane are focused", "(x,y,z) transform = tf.translation_matrix((0,0,0)) point = transform_point(self.center, transform) photon.direction = direction photon.position =", "point = transform_point(self.center, transform) photon.direction = direction photon.position = point if self.spectrum !=", "published by # the Free Software Foundation; either version 3 of the License,", "= -1. + 2. * np.random.uniform() y = -1. + 2. * np.random.uniform()", "the Laser is not set.\" self.polarisation = np.array(polarisation) self.throw = 0 self.source_id =", "self.wavelength # Further initialisation photon.active = True return photon class PointSource(object): \"\"\" A", "False z = -1. + 2. * s a = 2 * np.sqrt(1", "self.source_id = \"PointSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id", "= planeextent self.linepoint = np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize self.angle =", "License # along with this program. If not, see <http://www.gnu.org/licenses/>. import numpy as", "= r*np.cos(phi) y = r*np.sin(phi) z = np.random.uniform(0.,self.length) local_center = (x,y,z) photon.position =", "width=0.05): super(PlanarSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.plane = FinitePlane(length=length, width=width)", "= 555, center = (0.,0.,0.), phimin = 0, phimax = 2*np.pi, thetamin =", "0 self.source_id = \"LensSourceAngle_\" + str(id(self)) def photon(self): photon = Photon() photon.id =", "+ 1 # Create a point which is on the surface of the", "around xy-plane, the transform from +z to the direction of the photon vec", "(x,y,z) photon.position = transform_point(local_center, self.shape.transform) # Direction of emission (no need to transform", "np.array(position) self.direction = np.array(direction) self.wavelength = wavelength assert polarisation != None, \"Polarisation of", "a single colour, direction and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, polarisation=None): super(Laser,", "in z-direction). \"\"\" def __init__(self, spectrum = None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1),", "self.position = np.array(position) self.direction = np.array(direction) self.wavelength = wavelength assert polarisation != None,", "is passed directly to the photon to set is's direction self.direction = direction", "self.source_id = \"LensSourceAngle_\" + str(id(self)) def photon(self): photon = Photon() photon.id = self.throw", "= length self.width = width # direction is the direction that photons are", "= phimin self.phimax = phimax self.thetamin = thetamin self.thetamax = thetamax self.throw =", "photon.direction = np.array(self.direction) photon.active = True photon.wavelength = self.wavelength # If use_polarisation is", "software; you can redistribute it and/or modify # it under the terms of", "emits at discrete angles theta(i) and phi(i) \"\"\" def __init__(self, spectrum = None,", "photon.polarisation = None photon.id = self.throw self.throw = self.throw + 1 return photon", "np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] + boost direction = focuspoint - photon.position modulus =", "wavelength self.shape = Cylinder(radius = radius, length = length) self.radius = radius self.length", "1.0: LOOP = False z = -1. + 2. * s a =", "\"Polarisation of the Laser is not set.\" self.polarisation = np.array(polarisation) self.throw = 0", "plane normal and aligned with the z-axis. For this lense an additional z-boost", "LOOP: x = -1. + 2. * np.random.uniform() y = -1. + 2.", "self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class", "np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] direction = focuspoint -", "perpendicular to the plane normal and aligned with the z-axis. For this lense", "self.throw + 1 phi = np.random.uniform(self.phimin, self.phimax) theta = np.random.uniform(self.thetamin, self.thetamax) x =", "General Public License for more details. # # You should have received a", "np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0] = self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize) focuspoint[1] =", "self.spacing+1) phi = intphi*(self.phimax-self.phimin)/self.spacing if self.thetamin == self.thetamax: theta = self.thetamin else: theta", "external.transformations as tf from Trace import Photon from Geometry import Box, Cylinder, FinitePlane,", "CylindricalSource(object): \"\"\" A source for photons emitted in a random direction and position", "direction=(0,0,1), length=0.05, width=0.05): super(PlanarSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.plane =", "LOOP = True while LOOP: x = -1. + 2. * np.random.uniform() y", "the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See", "angle, axis): self.shape.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon() photon.source = self.source_id photon.id", "# If use_polarisation is set generate a random polarisation vector of the photon", "555, linepoint=(0,0,0), linedirection=(0,0,1), focussize = 0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSource,", "light source that will generate photons of a single colour, direction and position.\"\"\"", "passed directly to the photon to set is's direction self.direction = direction self.throw", "R = rotation_matrix_from_vector_alignment(self.direction, [0,0,1]) photon.polarisation = transform_direction(vec, R) else: photon.polarisation = None photon.id", "line with space tolerance given by variable \"focussize\". The focus line should be", "y, 0.) # Transform the direciton photon.position = transform_point(local_point, self.plane.transform) photon.direction = self.direction", "Photon() photon.source = self.source_id photon.id = self.throw self.throw = self.throw + 1 intphi", "a plane are focused on a line with space tolerance given by variable", "photon.direction = self.direction photon.active = True if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform())", "= None, wavelength = 555, center = (0.,0.,0.), phimin = 0, phimax =", "!= None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class LensSourceAngle(object):", "position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, use_random_polarisation=False): super(SimpleSource, self).__init__() self.position = position self.direction", "= direction/modulus # Wavelength if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength", "(at your option) any later version. # # pvtrace is distributed in the", "= thetamin self.thetamax = thetamax self.throw = 0 self.source_id = \"PointSource_\" + str(id(self))", "self.throw = self.throw + 1 phi = np.random.uniform(self.phimin, self.phimax) theta = np.random.uniform(self.thetamin, self.thetamax)", "more details. # # You should have received a copy of the GNU", "z = np.cos(theta) direction = (x,y,z) transform = tf.translation_matrix((0,0,0)) point = transform_point(self.center, transform)", "GNU General Public License for more details. # # You should have received", "1 intphi = np.random.randint(1, self.spacing+1) inttheta = np.random.randint(1, self.spacing+1) phi = intphi*(self.phimax-self.phimin)/self.spacing if", "under the terms of the GNU General Public License as published by #", "= self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] +", "= \"PlanarSource_\" + str(id(self)) def translate(self, translation): self.plane.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.plane.append_transform(tf.rotation_matrix(angle,", "= self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class LensSourceAngle(object): \"\"\" A source", "transform_point(self.center, transform) photon.direction = direction photon.position = point if self.spectrum != None: photon.wavelength", "def translate(self, translation): self.plane.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.plane.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon", "np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position = np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0] = self.linepoint[0] +", "self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class CylindricalSource(object): \"\"\" A source for", "it under the terms of the GNU General Public License as published by", "Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0] = self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] +", "you can redistribute it and/or modify # it under the terms of the", "transform_point(local_point, self.plane.transform) photon.direction = self.direction photon.active = True if self.spectrum != None: photon.wavelength", "np.pi, spacing=20): super(RadialSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.center = center", "of the License, or # (at your option) any later version. # #", "position=[0,0,0], direction=[0,0,1], wavelength=555, use_random_polarisation=False): super(SimpleSource, self).__init__() self.position = position self.direction = direction self.wavelength", "hope that it will be useful, # but WITHOUT ANY WARRANTY; without even", "perpendicular to the plane normal and aligned with the z-axis. \"\"\" def __init__(self,", "x = a * x y = a * y return np.array([x,y,z]) class", "is set generate a random polarisation vector of the photon if self.use_random_polarisation: #", "+ 2. * s a = 2 * np.sqrt(1 - s) x =", "# Wavelength if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength", "y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost = y*np.tan(self.angle) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) - boost photon.position =", "photon class LensSourceAngle(object): \"\"\" A source where photons generated in a plane are", "photon class CylindricalSource(object): \"\"\" A source for photons emitted in a random direction", "[0,0,1]) photon.polarisation = transform_direction(vec, R) else: photon.polarisation = None photon.id = self.throw self.throw", "see <http://www.gnu.org/licenses/>. import numpy as np from external.transformations import translation_matrix, rotation_matrix import external.transformations", "self.polarisation photon.id = self.throw self.throw = self.throw + 1 return photon class PlanarSource(object):", "= wavelength self.planeorigin = planeorigin self.planeextent = planeextent self.linepoint = np.array(linepoint) self.linedirection =", "np.array(self.position) photon.direction = np.array(self.direction) photon.active = True photon.wavelength = self.wavelength photon.polarisation = self.polarisation", "focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction = direction/modulus # Wavelength if self.spectrum", "of emission (no need to transform if meant to be isotropic) phi =", "(x, y, 0.) # Transform the direciton photon.position = transform_point(local_point, self.plane.transform) photon.direction =", "= Photon() photon.source = self.source_id photon.position = np.array(self.position) photon.direction = np.array(self.direction) photon.active =", "= wavelength assert polarisation != None, \"Polarisation of the Laser is not set.\"", "0, thetamax = np.pi): super(PointSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.center", "self.throw self.throw = self.throw + 1 return photon class PlanarSource(object): \"\"\"A box that", "self.spectrum = spectrum self.wavelength = wavelength self.plane = FinitePlane(length=length, width=width) self.length = length", "1 # Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost = y*np.tan(self.angle) z", "# direction is the direction that photons are fired out of the plane", "direction of the photon vec = random_spherecial_vector() vec[2] = 0. vec = norm(vec)", "self.throw self.throw = self.throw + 1 # Create a point which is on", "= transform_point(local_point, self.plane.transform) photon.direction = self.direction photon.active = True if self.spectrum != None:", "1 return photon class Laser(object): \"\"\"A light source that will generate photons of", "spectrum = None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), angle = 0, focussize =", "photon.wavelength = self.wavelength # If use_polarisation is set generate a random polarisation vector", "vector of the photon if self.use_random_polarisation: # Randomise rotation angle around xy-plane, the", "self.thetamax = thetamax self.throw = 0 self.source_id = \"PointSource_\" + str(id(self)) def photon(self):", "License as published by # the Free Software Foundation; either version 3 of", "* s a = 2 * np.sqrt(1 - s) x = a *", "be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of", "np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost = y*np.tan(self.angle) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) - boost photon.position", "planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSourceAngle, self).__init__() self.spectrum = spectrum self.wavelength =", "self.wavelength return photon class CylindricalSource(object): \"\"\" A source for photons emitted in a", "y = r*np.sin(phi) z = np.random.uniform(0.,self.length) local_center = (x,y,z) photon.position = transform_point(local_center, self.shape.transform)", "plane normal and aligned with the z-axis. \"\"\" def __init__(self, spectrum = None,", "import Box, Cylinder, FinitePlane, transform_point, transform_direction, rotation_matrix_from_vector_alignment, norm from Materials import Spectrum def", "spectrum self.wavelength = wavelength self.shape = Cylinder(radius = radius, length = length) self.radius", "self.width = width # direction is the direction that photons are fired out", "normal and aligned with the z-axis. \"\"\" def __init__(self, spectrum = None, wavelength", "to transform if meant to be isotropic) phi = np.random.uniform(0.,2*np.pi) theta = np.random.uniform(0.,np.pi)", "GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>.", "np.random.uniform(self.planeorigin[1],self.planeextent[1]) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position = np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0]", "boost photon.position = np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0] = self.linepoint[0] +", "directly to the photon to set is's direction self.direction = direction self.throw =", "focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] + boost direction = focuspoint", "self.throw + 1 intphi = np.random.randint(1, self.spacing+1) inttheta = np.random.randint(1, self.spacing+1) phi =", "thetamin self.thetamax = thetamax self.spacing = spacing self.throw = 0 self.source_id = \"RadialSource_\"", "= np.random.uniform(0.,self.radius) x = r*np.cos(phi) y = r*np.sin(phi) z = np.random.uniform(0.,self.length) local_center =", "thetamin = 0, thetamax = np.pi): super(PointSource, self).__init__() self.spectrum = spectrum self.wavelength =", "= -1. + 2. * s a = 2 * np.sqrt(1 - s)", "are focused on a line with space tolerance given by variable \"focussize\". The", "that photons are fired out of the plane in the GLOBAL FRAME. #", "= self.source_id photon.id = self.throw self.throw = self.throw + 1 # Position x", "Laser(object): \"\"\"A light source that will generate photons of a single colour, direction", "+ str(id(self)) def photon(self): photon = Photon() photon.id = self.throw self.throw = self.throw", "but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or", "and position inside a cylinder(radius, length) \"\"\" def __init__(self, spectrum = None, wavelength", "np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) direction = (x,y,z) transform = tf.translation_matrix((0,0,0))", "= 0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSource, self).__init__() self.spectrum = spectrum", "self.throw + 1 # Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) z =", "np.random.uniform(0.,self.radius) x = r*np.cos(phi) y = r*np.sin(phi) z = np.random.uniform(0.,self.length) local_center = (x,y,z)", "= np.array(linedirection) self.focussize = focussize self.angle = angle self.throw = 0 self.source_id =", "0 self.source_id = \"SimpleSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source =", "np.sqrt(1 - s) x = a * x y = a * y", "np.pi): super(PointSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.center = center self.phimin", "emission phi = np.random.uniform(0., 2*np.pi) r = np.random.uniform(0.,self.radius) x = r*np.cos(phi) y =", "plane in it's local frame x = np.random.uniform(0., self.length) y = np.random.uniform(0., self.width)", "direction and position inside a cylinder(radius, length) \"\"\" def __init__(self, spectrum = None,", "np.array(self.direction) photon.active = True photon.wavelength = self.wavelength photon.polarisation = self.polarisation photon.id = self.throw", "= self.throw self.throw = self.throw + 1 intphi = np.random.randint(1, self.spacing+1) inttheta =", "is free software; you can redistribute it and/or modify # it under the", "= planeorigin self.planeextent = planeextent self.linepoint = np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize =", "+ 1 # Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost = y*np.tan(self.angle)", "by variable \"focussize\". The focus line should be perpendicular to the plane normal", "self.throw = self.throw + 1 return photon class PlanarSource(object): \"\"\"A box that emits", "+ 2. * np.random.uniform() s = x**2 + y**2 if s <= 1.0:", "photon.id = self.throw self.throw = self.throw + 1 # Create a point which", "spectrum self.wavelength = wavelength self.center = center self.phimin = phimin self.phimax = phimax", "else: theta = inttheta*(self.thetamax-self.thetamin)/self.spacing x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta)", "Photon() photon.source = self.source_id photon.id = self.throw self.throw = self.throw + 1 phi", "GNU Scientific Library LOOP = True while LOOP: x = -1. + 2.", "= np.random.uniform(0.,np.pi) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) local_direction =", "\"PointSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id photon.id =", "variable \"focussize\". The focus line should be perpendicular to the plane normal and", "self.throw self.throw = self.throw + 1 return photon class Laser(object): \"\"\"A light source", "= random_spherecial_vector() vec[2] = 0. vec = norm(vec) R = rotation_matrix_from_vector_alignment(self.direction, [0,0,1]) photon.polarisation", "= self.throw self.throw = self.throw + 1 # Position of emission phi =", "s <= 1.0: LOOP = False z = -1. + 2. * s", "this is passed directly to the photon to set is's direction self.direction =", "direction/modulus # Wavelength if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength =", "None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength photon.active = True return photon", "direction self.throw = 0 self.source_id = \"PlanarSource_\" + str(id(self)) def translate(self, translation): self.plane.append_transform(tf.translation_matrix(translation))", "the direciton photon.position = transform_point(local_point, self.plane.transform) photon.direction = self.direction photon.active = True if", "theta = np.random.uniform(0.,np.pi) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) local_direction", "self.linedirection = np.array(linedirection) self.focussize = focussize self.throw = 0 self.source_id = \"LensSource_\" +", "planeextent self.linepoint = np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize self.angle = angle", "theta(i) and phi(i) \"\"\" def __init__(self, spectrum = None, wavelength = 555, center", "If not, see <http://www.gnu.org/licenses/>. import numpy as np from external.transformations import translation_matrix, rotation_matrix", "self.thetamin else: theta = inttheta*(self.thetamax-self.thetamin)/self.spacing x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z =", "= spectrum self.wavelength = wavelength self.plane = FinitePlane(length=length, width=width) self.length = length self.width", "= \"LensSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id photon.id", "self.linepoint = np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize self.angle = angle self.throw", "self.throw = 0 self.source_id = \"LensSourceAngle_\" + str(id(self)) def photon(self): photon = Photon()", "photon(self): photon = Photon() photon.id = self.throw self.throw = self.throw + 1 #", "have received a copy of the GNU General Public License # along with", "angles theta(i) and phi(i) \"\"\" def __init__(self, spectrum = None, wavelength = 555,", "= direction self.wavelength = wavelength self.use_random_polarisation = use_random_polarisation self.throw = 0 self.source_id =", "self.source_id = \"PlanarSource_\" + str(id(self)) def translate(self, translation): self.plane.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis):", "theta = self.thetamin else: theta = inttheta*(self.thetamax-self.thetamin)/self.spacing x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta)", "y*np.tan(self.angle) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) - boost photon.position = np.array((x,y,z)) # Direction focuspoint =", "self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] + boost", "0 self.source_id = \"CylindricalSource_\" + str(id(self)) def translate(self, translation): self.shape.append_transform(tf.translation_matrix(translation)) def rotate(self, angle,", "photons are fired out of the plane in the GLOBAL FRAME. # i.e.", "set is's direction self.direction = direction self.throw = 0 self.source_id = \"PlanarSource_\" +", "in the GLOBAL FRAME. # i.e. this is passed directly to the photon", "spectrum = None, wavelength = 555, center = (0.,0.,0.), phimin = 0, phimax", "wavelength self.use_random_polarisation = use_random_polarisation self.throw = 0 self.source_id = \"SimpleSource_\" + str(id(self)) def", "option) any later version. # # pvtrace is distributed in the hope that", "pvtrace is free software; you can redistribute it and/or modify # it under", "# Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0] = self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1]", "= Photon() photon.id = self.throw self.throw = self.throw + 1 # Position x", "self.length) y = np.random.uniform(0., self.width) local_point = (x, y, 0.) # Transform the", "A source where photons generated in a plane are focused on a line", "= 0, focussize = 0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSourceAngle, self).__init__()", "phimin = 0, phimax = 2*np.pi, thetamin = 0, thetamax = np.pi, spacing=20):", "is the direction that photons are fired out of the plane in the", "the z-axis. For this lense an additional z-boost is added (Angle of incidence", "focuspoint[2] = photon.position[2] + boost direction = focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5", "Software Foundation; either version 3 of the License, or # (at your option)", "photon.id = self.throw self.throw = self.throw + 1 phi = np.random.uniform(self.phimin, self.phimax) theta", "sampled from the spectrum.\"\"\" def __init__(self, spectrum=None, wavelength=555, direction=(0,0,1), length=0.05, width=0.05): super(PlanarSource, self).__init__()", "s) x = a * x y = a * y return np.array([x,y,z])", "PURPOSE. See the # GNU General Public License for more details. # #", "= 555, radius = 1, length = 10): super(CylindricalSource, self).__init__() self.spectrum = spectrum", "= self.wavelength photon.active = True return photon class RadialSource(object): \"\"\" A point source", "self.throw = 0 self.source_id = \"SimpleSource_\" + str(id(self)) def photon(self): photon = Photon()", "np.random.uniform(0.,self.length) local_center = (x,y,z) photon.position = transform_point(local_center, self.shape.transform) # Direction of emission (no", "# pvtrace is free software; you can redistribute it and/or modify # it", "self.throw = self.throw + 1 return photon class Laser(object): \"\"\"A light source that", "self.polarisation = np.array(polarisation) self.throw = 0 self.source_id = \"LaserSource_\" + str(id(self)) def photon(self):", "self.direction = direction self.throw = 0 self.source_id = \"PlanarSource_\" + str(id(self)) def translate(self,", "self.center = center self.phimin = phimin self.phimax = phimax self.thetamin = thetamin self.thetamax", "= \"LaserSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id photon.position", "random direction and position inside a cylinder(radius, length) \"\"\" def __init__(self, spectrum =", "= a * y return np.array([x,y,z]) class SimpleSource(object): \"\"\"A light source that will", "= self.throw self.throw = self.throw + 1 phi = np.random.uniform(self.phimin, self.phimax) theta =", "= \"LensSourceAngle_\" + str(id(self)) def photon(self): photon = Photon() photon.id = self.throw self.throw", "import Spectrum def random_spherecial_vector(): # This method of calculating isotropic vectors is taken", "photon to set is's direction self.direction = direction self.throw = 0 self.source_id =", "= None, wavelength = 555, radius = 1, length = 10): super(CylindricalSource, self).__init__()", "z = -1. + 2. * s a = 2 * np.sqrt(1 -", "any later version. # # pvtrace is distributed in the hope that it", "x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost = y*np.tan(self.angle) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) -", "self.thetamin = thetamin self.thetamax = thetamax self.throw = 0 self.source_id = \"PointSource_\" +", "photon.active = True photon.wavelength = self.wavelength photon.polarisation = self.polarisation photon.id = self.throw self.throw", "the GNU General Public License # along with this program. If not, see", "photons from the top surface (normal), sampled from the spectrum.\"\"\" def __init__(self, spectrum=None,", "np.array(direction) self.wavelength = wavelength assert polarisation != None, \"Polarisation of the Laser is", "Library LOOP = True while LOOP: x = -1. + 2. * np.random.uniform()", "a line with space tolerance given by variable \"focussize\". The focus line should", "photon.polarisation = self.polarisation photon.id = self.throw self.throw = self.throw + 1 return photon", "of the photon if self.use_random_polarisation: # Randomise rotation angle around xy-plane, the transform", "= self.wavelength return photon class CylindricalSource(object): \"\"\" A source for photons emitted in", "details. # # You should have received a copy of the GNU General", "single colour, direction and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, polarisation=None): super(Laser, self).__init__()", "box that emits photons from the top surface (normal), sampled from the spectrum.\"\"\"", "import numpy as np from external.transformations import translation_matrix, rotation_matrix import external.transformations as tf", "= np.sin(phi)*np.sin(theta) z = np.cos(theta) local_direction = (x,y,z) photon.direction = local_direction # Set", "self.wavelength return photon class LensSourceAngle(object): \"\"\" A source where photons generated in a", "= np.random.randint(1, self.spacing+1) phi = intphi*(self.phimax-self.phimin)/self.spacing if self.thetamin == self.thetamax: theta = self.thetamin", "class Laser(object): \"\"\"A light source that will generate photons of a single colour,", "random polarisation vector of the photon if self.use_random_polarisation: # Randomise rotation angle around", "is added (Angle of incidence in z-direction). \"\"\" def __init__(self, spectrum = None,", "= True photon.wavelength = self.wavelength # If use_polarisation is set generate a random", "length = 10): super(CylindricalSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.shape =", "(x,y,z) photon.direction = local_direction # Set wavelength of photon if self.spectrum != None:", "self.spacing = spacing self.throw = 0 self.source_id = \"RadialSource_\" + str(id(self)) def photon(self):", "= np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) local_direction = (x,y,z) photon.direction =", "np.random.randint(1, self.spacing+1) inttheta = np.random.randint(1, self.spacing+1) phi = intphi*(self.phimax-self.phimin)/self.spacing if self.thetamin == self.thetamax:", "if meant to be isotropic) phi = np.random.uniform(0.,2*np.pi) theta = np.random.uniform(0.,np.pi) x =", "point source that emits randomly in solid angle specified by phimin, ..., thetamax", "self.throw = self.throw + 1 # Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1])", "photon.position = np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0] = self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize)", "= np.random.uniform(self.planeorigin[1],self.planeextent[1]) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position = np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.))", "spectrum=None, wavelength=555, direction=(0,0,1), length=0.05, width=0.05): super(PlanarSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength", "use_random_polarisation=False): super(SimpleSource, self).__init__() self.position = position self.direction = direction self.wavelength = wavelength self.use_random_polarisation", "and phi(i) \"\"\" def __init__(self, spectrum = None, wavelength = 555, center =", "= tf.translation_matrix((0,0,0)) point = transform_point(self.center, transform) photon.direction = direction photon.position = point if", "= self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] + boost direction = focuspoint -", "self.shape.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon() photon.source = self.source_id photon.id = self.throw", "of a single colour, direction and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, polarisation=None):", "position=[0,0,0], direction=[0,0,1], wavelength=555, polarisation=None): super(Laser, self).__init__() self.position = np.array(position) self.direction = np.array(direction) self.wavelength", "__init__(self, spectrum = None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), angle = 0, focussize", "polarisation=None): super(Laser, self).__init__() self.position = np.array(position) self.direction = np.array(direction) self.wavelength = wavelength assert", "= np.array((0.,0.,0.)) focuspoint[0] = self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2]", "# GNU General Public License for more details. # # You should have", "taken from GNU Scientific Library LOOP = True while LOOP: x = -1.", "- photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction = direction/modulus # Wavelength if self.spectrum !=", "direction=[0,0,1], wavelength=555, polarisation=None): super(Laser, self).__init__() self.position = np.array(position) self.direction = np.array(direction) self.wavelength =", "self.throw = 0 self.source_id = \"LensSource_\" + str(id(self)) def photon(self): photon = Photon()", "= self.wavelength # Further initialisation photon.active = True return photon class PointSource(object): \"\"\"", "str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id photon.id = self.throw self.throw", "it and/or modify # it under the terms of the GNU General Public", "assert polarisation != None, \"Polarisation of the Laser is not set.\" self.polarisation =", "np.random.uniform() s = x**2 + y**2 if s <= 1.0: LOOP = False", "= np.random.uniform(0., 2*np.pi) r = np.random.uniform(0.,self.radius) x = r*np.cos(phi) y = r*np.sin(phi) z", "* x y = a * y return np.array([x,y,z]) class SimpleSource(object): \"\"\"A light", "def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, polarisation=None): super(Laser, self).__init__() self.position = np.array(position) self.direction =", "self.phimax = phimax self.thetamin = thetamin self.thetamax = thetamax self.spacing = spacing self.throw", "= -1. + 2. * np.random.uniform() s = x**2 + y**2 if s", "as published by # the Free Software Foundation; either version 3 of the", "= np.random.uniform(self.planeorigin[2],self.planeextent[2]) - boost photon.position = np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0]", "phi(i) \"\"\" def __init__(self, spectrum = None, wavelength = 555, center = (0.,0.,0.),", "isotropic vectors is taken from GNU Scientific Library LOOP = True while LOOP:", "the transform from +z to the direction of the photon vec = random_spherecial_vector()", "A source for photons emitted in a random direction and position inside a", "# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General", "0 self.source_id = \"PlanarSource_\" + str(id(self)) def translate(self, translation): self.plane.append_transform(tf.translation_matrix(translation)) def rotate(self, angle,", "photon.active = True if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength =", "self.spectrum = spectrum self.wavelength = wavelength self.planeorigin = planeorigin self.planeextent = planeextent self.linepoint", "self.phimax = phimax self.thetamin = thetamin self.thetamax = thetamax self.throw = 0 self.source_id", "direction self.direction = direction self.throw = 0 self.source_id = \"PlanarSource_\" + str(id(self)) def", "norm(vec) R = rotation_matrix_from_vector_alignment(self.direction, [0,0,1]) photon.polarisation = transform_direction(vec, R) else: photon.polarisation = None", "If use_polarisation is set generate a random polarisation vector of the photon if", "local_center = (x,y,z) photon.position = transform_point(local_center, self.shape.transform) # Direction of emission (no need", "intphi*(self.phimax-self.phimin)/self.spacing if self.thetamin == self.thetamax: theta = self.thetamin else: theta = inttheta*(self.thetamax-self.thetamin)/self.spacing x", "= center self.phimin = phimin self.phimax = phimax self.thetamin = thetamin self.thetamax =", "self).__init__() self.position = position self.direction = direction self.wavelength = wavelength self.use_random_polarisation = use_random_polarisation", "are fired out of the plane in the GLOBAL FRAME. # i.e. this", "the photon vec = random_spherecial_vector() vec[2] = 0. vec = norm(vec) R =", "thetamin = 0, thetamax = np.pi, spacing=20): super(RadialSource, self).__init__() self.spectrum = spectrum self.wavelength", "Direction of emission (no need to transform if meant to be isotropic) phi", "np.array(self.position) photon.direction = np.array(self.direction) photon.active = True photon.wavelength = self.wavelength # If use_polarisation", "= self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength # Further initialisation photon.active = True return", "= (-1,1,1)): super(LensSourceAngle, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.planeorigin = planeorigin", "= 0. vec = norm(vec) R = rotation_matrix_from_vector_alignment(self.direction, [0,0,1]) photon.polarisation = transform_direction(vec, R)", "self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] direction =", "x y = a * y return np.array([x,y,z]) class SimpleSource(object): \"\"\"A light source", "# Set wavelength of photon if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else:", "= (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction = direction/modulus # Wavelength if self.spectrum != None: photon.wavelength =", "np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] + boost direction =", "= 0 self.source_id = \"LensSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source", "Wavelength if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return", "z-boost is added (Angle of incidence in z-direction). \"\"\" def __init__(self, spectrum =", "np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost = y*np.tan(self.angle) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) - boost photon.position = np.array((x,y,z)) #", "= self.source_id photon.id = self.throw self.throw = self.throw + 1 # Position of", "focuspoint[0] = self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2]", "np.array(polarisation) self.throw = 0 self.source_id = \"LaserSource_\" + str(id(self)) def photon(self): photon =", "__init__(self, spectrum=None, wavelength=555, direction=(0,0,1), length=0.05, width=0.05): super(PlanarSource, self).__init__() self.spectrum = spectrum self.wavelength =", "* np.random.uniform() y = -1. + 2. * np.random.uniform() s = x**2 +", "def __init__(self, spectrum = None, wavelength = 555, radius = 1, length =", "will generate photons of a single colour, direction and position.\"\"\" def __init__(self, position=[0,0,0],", "s = x**2 + y**2 if s <= 1.0: LOOP = False z", "the plane normal and aligned with the z-axis. \"\"\" def __init__(self, spectrum =", "translate(self, translation): self.plane.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.plane.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon =", "length) self.radius = radius self.length = length self.throw = 0 self.source_id = \"CylindricalSource_\"", "surface (normal), sampled from the spectrum.\"\"\" def __init__(self, spectrum=None, wavelength=555, direction=(0,0,1), length=0.05, width=0.05):", "spectrum = None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), focussize = 0, planeorigin =", "0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSourceAngle, self).__init__() self.spectrum = spectrum self.wavelength", "emission (no need to transform if meant to be isotropic) phi = np.random.uniform(0.,2*np.pi)", "self.throw = 0 self.source_id = \"LaserSource_\" + str(id(self)) def photon(self): photon = Photon()", "wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), angle = 0, focussize = 0, planeorigin =", "spectrum self.wavelength = wavelength self.plane = FinitePlane(length=length, width=width) self.length = length self.width =", "= np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position = np.array((x,y,z)) # Direction", "np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize self.throw = 0 self.source_id = \"LensSource_\"", "spectrum.\"\"\" def __init__(self, spectrum=None, wavelength=555, direction=(0,0,1), length=0.05, width=0.05): super(PlanarSource, self).__init__() self.spectrum = spectrum", "or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License", "self.phimax) theta = np.random.uniform(self.thetamin, self.thetamax) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z =", "photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction = direction/modulus # Wavelength if self.spectrum != None:", "np.random.uniform(self.phimin, self.phimax) theta = np.random.uniform(self.thetamin, self.thetamax) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z", "\"CylindricalSource_\" + str(id(self)) def translate(self, translation): self.shape.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.shape.append_transform(tf.rotation_matrix(angle, axis))", "linepoint=(0,0,0), linedirection=(0,0,1), angle = 0, focussize = 0, planeorigin = (-1,-1,-1), planeextent =", "photon.position = transform_point(local_point, self.plane.transform) photon.direction = self.direction photon.active = True if self.spectrum !=", "if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength # Further", "def __init__(self, spectrum = None, wavelength = 555, center = (0.,0.,0.), phimin =", "distributed in the hope that it will be useful, # but WITHOUT ANY", "either version 3 of the License, or # (at your option) any later", "self.focussize = focussize self.angle = angle self.throw = 0 self.source_id = \"LensSourceAngle_\" +", "from Trace import Photon from Geometry import Box, Cylinder, FinitePlane, transform_point, transform_direction, rotation_matrix_from_vector_alignment,", "use_polarisation is set generate a random polarisation vector of the photon if self.use_random_polarisation:", "def rotate(self, angle, axis): self.plane.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon() photon.source =", "of emission phi = np.random.uniform(0., 2*np.pi) r = np.random.uniform(0.,self.radius) x = r*np.cos(phi) y", "photon = Photon() photon.source = self.source_id photon.id = self.throw self.throw = self.throw +", "of photon if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength", "# Transform the direciton photon.position = transform_point(local_point, self.plane.transform) photon.direction = self.direction photon.active =", "Photon() photon.source = self.source_id photon.id = self.throw self.throw = self.throw + 1 #", "if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength photon.active =", "need to transform if meant to be isotropic) phi = np.random.uniform(0.,2*np.pi) theta =", "np.random.uniform(self.planeorigin[2],self.planeextent[2]) - boost photon.position = np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0] =", "calculating isotropic vectors is taken from GNU Scientific Library LOOP = True while", "while LOOP: x = -1. + 2. * np.random.uniform() y = -1. +", "= 555, linepoint=(0,0,0), linedirection=(0,0,1), focussize = 0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)):", "thetamax = np.pi, spacing=20): super(RadialSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.center", "\"LaserSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id photon.position =", "= (-1,-1,-1), planeextent = (-1,1,1)): super(LensSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength", "== self.thetamax: theta = self.thetamin else: theta = inttheta*(self.thetamax-self.thetamin)/self.spacing x = np.cos(phi)*np.sin(theta) y", "emits photons from the top surface (normal), sampled from the spectrum.\"\"\" def __init__(self,", "0, phimax = 2*np.pi, thetamin = 0, thetamax = np.pi): super(PointSource, self).__init__() self.spectrum", "self.position = position self.direction = direction self.wavelength = wavelength self.use_random_polarisation = use_random_polarisation self.throw", "= self.throw + 1 # Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) z", "* np.sqrt(1 - s) x = a * x y = a *", "= self.source_id photon.id = self.throw self.throw = self.throw + 1 # Create a", "= np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost = y*np.tan(self.angle) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) - boost photon.position = np.array((x,y,z))", "is's direction self.direction = direction self.throw = 0 self.source_id = \"PlanarSource_\" + str(id(self))", "Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position = np.array((x,y,z))", "self.thetamin = thetamin self.thetamax = thetamax self.spacing = spacing self.throw = 0 self.source_id", "the photon if self.use_random_polarisation: # Randomise rotation angle around xy-plane, the transform from", "= None photon.id = self.throw self.throw = self.throw + 1 return photon class", "photon.position = point if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength =", "2 * np.sqrt(1 - s) x = a * x y = a", "width=width) self.length = length self.width = width # direction is the direction that", "self.source_id photon.id = self.throw self.throw = self.throw + 1 # Create a point", "self.throw = 0 self.source_id = \"PlanarSource_\" + str(id(self)) def translate(self, translation): self.plane.append_transform(tf.translation_matrix(translation)) def", "General Public License as published by # the Free Software Foundation; either version", "self.source_id = \"SimpleSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id", "self.focussize = focussize self.throw = 0 self.source_id = \"LensSource_\" + str(id(self)) def photon(self):", "return photon class LensSource(object): \"\"\" A source where photons generated in a plane", "def __init__(self, spectrum = None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), focussize = 0,", "np.array(linedirection) self.focussize = focussize self.angle = angle self.throw = 0 self.source_id = \"LensSourceAngle_\"", "as np from external.transformations import translation_matrix, rotation_matrix import external.transformations as tf from Trace", "= self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] direction = focuspoint - photon.position modulus", "class LensSourceAngle(object): \"\"\" A source where photons generated in a plane are focused", "rotate(self, angle, axis): self.shape.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon() photon.source = self.source_id", "(0.,0.,0.), phimin = 0, phimax = 2*np.pi, thetamin = 0, thetamax = np.pi,", "= point if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength", "photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength photon.active = True return photon class", "\"\"\" def __init__(self, spectrum = None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), angle =", "planeextent self.linepoint = np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize self.throw = 0", "self.wavelength return photon class LensSource(object): \"\"\" A source where photons generated in a", "axis): self.shape.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon() photon.source = self.source_id photon.id =", "from GNU Scientific Library LOOP = True while LOOP: x = -1. +", "a = 2 * np.sqrt(1 - s) x = a * x y", "A point source that emits randomly in solid angle specified by phimin, ...,", "\"\"\" def __init__(self, spectrum = None, wavelength = 555, radius = 1, length", "self.width) local_point = (x, y, 0.) # Transform the direciton photon.position = transform_point(local_point,", "from +z to the direction of the photon vec = random_spherecial_vector() vec[2] =", "def rotate(self, angle, axis): self.shape.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon() photon.source =", "wavelength self.center = center self.phimin = phimin self.phimax = phimax self.thetamin = thetamin", "1 # Position of emission phi = np.random.uniform(0., 2*np.pi) r = np.random.uniform(0.,self.radius) x", "= np.array(position) self.direction = np.array(direction) self.wavelength = wavelength assert polarisation != None, \"Polarisation", "phimax self.thetamin = thetamin self.thetamax = thetamax self.throw = 0 self.source_id = \"PointSource_\"", "and/or modify # it under the terms of the GNU General Public License", "Spectrum def random_spherecial_vector(): # This method of calculating isotropic vectors is taken from", "z-axis. \"\"\" def __init__(self, spectrum = None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), focussize", "= focussize self.angle = angle self.throw = 0 self.source_id = \"LensSourceAngle_\" + str(id(self))", "z = np.random.uniform(0.,self.length) local_center = (x,y,z) photon.position = transform_point(local_center, self.shape.transform) # Direction of", "super(CylindricalSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.shape = Cylinder(radius = radius,", "single colour, direction and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, use_random_polarisation=False): super(SimpleSource, self).__init__()", "= photon.position[2] direction = focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction = direction/modulus", "spectrum = None, wavelength = 555, radius = 1, length = 10): super(CylindricalSource,", "1 # Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position", "local_direction # Set wavelength of photon if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform())", "point source that emits at discrete angles theta(i) and phi(i) \"\"\" def __init__(self,", "where photons generated in a plane are focused on a line with space", "phimin self.phimax = phimax self.thetamin = thetamin self.thetamax = thetamax self.throw = 0", "(-1,-1,-1), planeextent = (-1,1,1)): super(LensSourceAngle, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.planeorigin", "# pvtrace is distributed in the hope that it will be useful, #", "self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength # Further initialisation photon.active = True return photon", "self.thetamax: theta = self.thetamin else: theta = inttheta*(self.thetamax-self.thetamin)/self.spacing x = np.cos(phi)*np.sin(theta) y =", "np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize self.angle = angle self.throw = 0", "-1. + 2. * s a = 2 * np.sqrt(1 - s) x", "planeextent = (-1,1,1)): super(LensSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.planeorigin =", "z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position = np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0] =", "direction and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, polarisation=None): super(Laser, self).__init__() self.position =", "= wavelength self.shape = Cylinder(radius = radius, length = length) self.radius = radius", "focuspoint = np.array((0.,0.,0.)) focuspoint[0] = self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize)", "method of calculating isotropic vectors is taken from GNU Scientific Library LOOP =", "modify # it under the terms of the GNU General Public License as", "Further initialisation photon.active = True return photon class PointSource(object): \"\"\" A point source", "= inttheta*(self.thetamax-self.thetamin)/self.spacing x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) direction =", "!= None, \"Polarisation of the Laser is not set.\" self.polarisation = np.array(polarisation) self.throw", "= transform_point(self.center, transform) photon.direction = direction photon.position = point if self.spectrum != None:", "the direction that photons are fired out of the plane in the GLOBAL", "given by variable \"focussize\". The focus line should be perpendicular to the plane", "linedirection=(0,0,1), angle = 0, focussize = 0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)):", "0 self.source_id = \"RadialSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source =", "phimax self.thetamin = thetamin self.thetamax = thetamax self.spacing = spacing self.throw = 0", "generated in a plane are focused on a line with space tolerance given", "= 0, phimax = 2*np.pi, thetamin = 0, thetamax = np.pi, spacing=20): super(RadialSource,", "z-direction). \"\"\" def __init__(self, spectrum = None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), angle", "return photon class PlanarSource(object): \"\"\"A box that emits photons from the top surface", "the z-axis. \"\"\" def __init__(self, spectrum = None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1),", "phimin self.phimax = phimax self.thetamin = thetamin self.thetamax = thetamax self.spacing = spacing", "See the # GNU General Public License for more details. # # You", "- s) x = a * x y = a * y return", "isotropic) phi = np.random.uniform(0.,2*np.pi) theta = np.random.uniform(0.,np.pi) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta)", "to set is's direction self.direction = direction self.throw = 0 self.source_id = \"PlanarSource_\"", "photon.position = np.array(self.position) photon.direction = np.array(self.direction) photon.active = True photon.wavelength = self.wavelength photon.polarisation", "__init__(self, spectrum = None, wavelength = 555, radius = 1, length = 10):", "self.planeextent = planeextent self.linepoint = np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize self.angle", "None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), angle = 0, focussize = 0, planeorigin", "super(SimpleSource, self).__init__() self.position = position self.direction = direction self.wavelength = wavelength self.use_random_polarisation =", "(-1,1,1)): super(LensSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.planeorigin = planeorigin self.planeextent", "__init__(self, spectrum = None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), focussize = 0, planeorigin", "photon vec = random_spherecial_vector() vec[2] = 0. vec = norm(vec) R = rotation_matrix_from_vector_alignment(self.direction,", "self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] + boost direction = focuspoint - photon.position", "Public License as published by # the Free Software Foundation; either version 3", "<= 1.0: LOOP = False z = -1. + 2. * s a", "to the direction of the photon vec = random_spherecial_vector() vec[2] = 0. vec", "= True return photon class PointSource(object): \"\"\" A point source that emits randomly", "transform from +z to the direction of the photon vec = random_spherecial_vector() vec[2]", "R) else: photon.polarisation = None photon.id = self.throw self.throw = self.throw + 1", "center self.phimin = phimin self.phimax = phimax self.thetamin = thetamin self.thetamax = thetamax", "= y*np.tan(self.angle) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) - boost photon.position = np.array((x,y,z)) # Direction focuspoint", "Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost = y*np.tan(self.angle) z = np.random.uniform(self.planeorigin[2],self.planeextent[2])", "thetamin self.thetamax = thetamax self.throw = 0 self.source_id = \"PointSource_\" + str(id(self)) def", "FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more", "(-1,-1,-1), planeextent = (-1,1,1)): super(LensSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.planeorigin", "inside a cylinder(radius, length) \"\"\" def __init__(self, spectrum = None, wavelength = 555,", "self.throw self.throw = self.throw + 1 # Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y =", "= self.thetamin else: theta = inttheta*(self.thetamax-self.thetamin)/self.spacing x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z", "to be isotropic) phi = np.random.uniform(0.,2*np.pi) theta = np.random.uniform(0.,np.pi) x = np.cos(phi)*np.sin(theta) y", "= r*np.sin(phi) z = np.random.uniform(0.,self.length) local_center = (x,y,z) photon.position = transform_point(local_center, self.shape.transform) #", "def random_spherecial_vector(): # This method of calculating isotropic vectors is taken from GNU", "Photon from Geometry import Box, Cylinder, FinitePlane, transform_point, transform_direction, rotation_matrix_from_vector_alignment, norm from Materials", "photons emitted in a random direction and position inside a cylinder(radius, length) \"\"\"", "photon.id = self.throw self.throw = self.throw + 1 # Position of emission phi", "self.wavelength = wavelength self.center = center self.phimin = phimin self.phimax = phimax self.thetamin", "y = np.sin(phi)*np.sin(theta) z = np.cos(theta) local_direction = (x,y,z) photon.direction = local_direction #", "= self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] direction", "(direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction = direction/modulus # Wavelength if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform())", "# along with this program. If not, see <http://www.gnu.org/licenses/>. import numpy as np", "= radius, length = length) self.radius = radius self.length = length self.throw =", "from Materials import Spectrum def random_spherecial_vector(): # This method of calculating isotropic vectors", "# Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost = y*np.tan(self.angle) z =", "# (at your option) any later version. # # pvtrace is distributed in", "None, wavelength = 555, center = (0.,0.,0.), phimin = 0, phimax = 2*np.pi,", "= np.random.uniform(0., self.length) y = np.random.uniform(0., self.width) local_point = (x, y, 0.) #", "SimpleSource(object): \"\"\"A light source that will generate photons of a single colour, direction", "1, length = 10): super(CylindricalSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.shape", "def __init__(self, spectrum = None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), angle = 0,", "# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY", "this lense an additional z-boost is added (Angle of incidence in z-direction). \"\"\"", "which is on the surface of the finite plane in it's local frame", "self.length = length self.throw = 0 self.source_id = \"CylindricalSource_\" + str(id(self)) def translate(self,", "self.planeextent = planeextent self.linepoint = np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize self.throw", "# Randomise rotation angle around xy-plane, the transform from +z to the direction", "+z to the direction of the photon vec = random_spherecial_vector() vec[2] = 0." ]
[ "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) @ input(y)) ... results.append(int(b)", "other)]) def nand_(self: bits, other) -> bits: \"\"\" >>> results = [] >>>", "== c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.imp_(y)", "of logic circuits and synthesizing circuits from those definitions. \"\"\" from __future__ import", "bits(result) def __pow__(self: bits, other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\" return self", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nimp_, self, other) def __gt__(self, other):", "in f.__annotations__.items() if k != 'return' } type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit = bit.circuit() except: raise", "nor(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "return bits([x.nimp_(y) for (x, y) in zip(self, other)]) def nimp_(self: bits, other: bits)", "bit from the integer 1 \"\"\" if other == 1: return bit.operation(op.not_, self)", "0], [0, 0]] >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss =", "Bit that is designated an output. >>> bit.circuit(circuit()) >>> b0 = output(input(1).not_()) >>>", "zs = outputs(xs.nif(ys)) ... ns = [int(z) for z in zs] ... c", "all(results) True \"\"\" return bit.operation(op.nor_, self, other) def __mod__(self, other): \"\"\" >>> results", "... b = output(input(x).xnor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "all(results) True \"\"\" return bit.operation(op.and_, self, other) def __and__(self, other): \"\"\" >>> results", "output(input(x).nimp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nimp_, self, other)", "in zip(self, other)]) def xor(self: bits, other: bits) -> bits: \"\"\" >>> results", "for b in bss[1]]) ([1, 1, 1, 1], [0, 0, 0, 0]) >>>", "input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_, self, other)", "y Traceback (most recent call last): ... RuntimeError: automated circuit synthesis failed \"\"\"", "in zip(self, other)]) def or_(self: bits, other: bits) -> bits: \"\"\" >>> results", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp(input(y))) ... results.append(int(b) ==", "signature class bit(): \"\"\" Class for representing an abstract bit. Such a bit", "for (x, y) in zip(self, other)]) def xnor(self: bits, other: bits) -> bits:", "\"\"\" return bits([x.if_(y) for (x, y) in zip(self, other)]) def imp(self: bits, other:", ">>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / [1, 3, 4])", "a variable input from one source.\"\"\" class input_two(input): \"\"\"Bit that is designated as", "bits: \"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs", "the original function. return f if __name__ == \"__main__\": doctest.testmod() # pragma: no", "keep track of relationships between operators and to represent the wires within a", "pylint: disable=R0903 \"\"\" Class for representing an input or output type of a", "self.value = value self.gate = bit._circuit.gate(op.id_, is_input=True) class input_one(input): \"\"\"Bit that is designated", "inputs([y, y, y])) ... zs = outputs(xs.or_(ys)) ... ns = [int(z) for z", "# it returns an output. if bit._hook_operation is not None: r = bit._hook_operation(o,", "bits: \"\"\" Return bits object given the supplied argument. \"\"\" return bits_type(argument)\\ if", "** bits([constant(0) for _ in range(other)]) def __truediv__(self: bits, other) -> Sequence[bits]: \"\"\"", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) >=", "\"\"\" return bit.operation(op.imp_, self, other) def nand(self, other): \"\"\" >>> results = []", ">>> b0 = output(input(1).not_()) >>> b1 = output(b0.not_()) >>> b2 = output(b0) >>>", "return bits([x.nimp_(y) for (x, y) in zip(self, other)]) def nif(self: bits, other: bits)", "1], [0, 0, 0, 0]] \"\"\" if isinstance(other, list) and len(other) > 0", "bit.operation(op.and_, self, other) def __and__(self, other): \"\"\" >>> results = [] >>> for", "is `other`. def __add__(self: bits, other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\" result", "= output(input(1).not_()) >>> b1 = output(b0.not_()) >>> b2 = output(b0) >>> [b0.value, b1.value,", "other)]) def __xor__(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "of abstract bits. \"\"\" @staticmethod def from_byte(byte_: int, constructor=bit) -> bits: return bits([", "bit.circuit(circuit()) ... b = output(~input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\"", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nor(ys)) ... ns", "Return output from hook if it exists and if # it returns an", "y])) ... zs = outputs(xs.imp_(ys)) ... ns = [int(z) for z in zs]", "c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nand_(y) for", "outputs(xs > ys) ... ns = [int(z) for z in zs] ... c", "-> Sequence[bits]: \"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss =", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.nif_(ys)) ... ns = [int(z)", "in [0, 1]: ... bit.circuit(circuit()) ... b = output(1 - input(x)) ... results.append(int(b)", "is not None: return r return bit.constructor(*args)(v, bit.gate(o, [a.gate for a in args]))", "= outputs(xs.not_()) >>> int(ys) 7 \"\"\" return sum(int(b)*(2**i) for (i, b) in zip(range(len(self)),", "0), (1, 1)]: ... bit.circuit(circuit()) ... (xs, ys) = (inputs([x, x, x]), inputs([y,", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self, other) class constant(bit): \"\"\"Bit that", "the bit by copying it to a new wire. self.value = b.value self.gate", "bss[0]], [b.value for b in bss[1]]) ([1, 1, 1, 1], [0, 0, 0,", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_, self, other) def __rxor__(self, other): \"\"\"", "all(results) True \"\"\" return bit.operation(op.nimp_, self, other) def nimp_(self, other): \"\"\" >>> results", ">>> all(results) True \"\"\" return bit.operation(op.or_, self, other) def __ror__(self, other): \"\"\" >>>", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "circuits from those definitions. \"\"\" from __future__ import annotations from typing import Sequence", "True \"\"\" return bit.operation(op.nor_, self, other) def xnor(self, other): \"\"\" >>> results =", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "as final output or whether there are others dependent on it. if len(b.gate.outputs)", "y, y, y])) >>> all(results) True \"\"\" return bits([x.xor_(y) for (x, y) in", "x]), inputs([y, y, y])) ... zs = outputs(xs.or_(ys)) ... ns = [int(z) for", "outputs(xs.if_(ys)) ... ns = [int(z) for z in zs] ... c = bit.circuit()", "= lambda a: output if a is bit else outputs # For forward-compatibility", "be interpreted concretely as a value, but it is also used to keep", "> ys) ... ns = [int(z) for z in zs] ... c =", "output(1 - input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True >>> bit.circuit(circuit()) >>>", "bit.circuit(circuit()) ... b = output(input(x).imp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "b = output(input(x) <= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "representing a vector of abstract bits. \"\"\" @staticmethod def from_byte(byte_: int, constructor=bit) ->", "annotations from typing import Sequence import doctest from parts import parts from circuit", "zs = outputs(xs.nif_(ys)) ... ns = [int(z) for z in zs] ... c", "= { k: type_in(eval_(a)) for (k, a) in f.__annotations__.items() if k != 'return'", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp_(input(y)))", "other) def __xor__(self, other): \"\"\" >>> results = [] >>> for (x, y)", "(x, y) in zip(self, other)]) def nand(self: bits, other) -> bits: \"\"\" >>>", "igs): return bit._circuit.gate(operation, igs) def __init__(self, value, gate_=None): self.value = value self.gate =", "1: return bit.operation(op.not_, self) raise ValueError('can only subtract a bit from the integer", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self, other) def nand_(self,", "outputs(xs.imp(ys)) ... ns = [int(z) for z in zs] ... c = bit.circuit()", "other)) # Number of parts is `other`. def __add__(self: bits, other) -> bits:", "... b = output(input(x).nif(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "designated as a variable input from a second source.\"\"\" class output(bit): \"\"\" Bit", "type_out = lambda a: output if a is bit else outputs # For", "(input_one, input_two)) and b2 is None: return type(b1) else: return bit \"\"\" return", "self ^ (constant(other) if isinstance(other, int) else other) def or_(self, other): \"\"\" >>>", "for b in bs] [1, 1, 1, 0, 0, 0, 0, 1] \"\"\"", "= output(input(0).and_(input(0))) >>> b.value == bit.circuit().evaluate([0,0])[0] True \"\"\" _circuit = None _hook_operation =", "y) in zip(self, other)]) def xnor(self: bits, other: bits) -> bits: \"\"\" >>>", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_, self, other) def __rxor__(self,", "inputs([y, y, y])) ... zs = outputs(xs.imp(ys)) ... ns = [int(z) for z", "... zs = outputs(xs.nand(ys)) ... ns = [int(z) for z in zs] ...", "bss[1]]) ([1, 1, 1, 1], [0, 0, 0, 0]) >>> bit.circuit(circuit()) >>> bs", "in bits.from_byte(byte_, constructor) ]) @staticmethod def zeros(n: int) -> bits: \"\"\" >>> bit.circuit(circuit())", "bs] for bs in bss] [[1, 1], [1, 1], [0, 0], [0, 0]]", "combinator library for assembling abstract definitions of logic circuits and synthesizing circuits from", "b2=None): # The inference code below is not currently in use. \"\"\" if", "y) in zip(self, other)]) def nand(self: bits, other) -> bits: \"\"\" >>> results", "0, 0, 0, 0, 0] \"\"\" return bits([ bit_ for byte_ in bytes_", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs < ys) ...", "results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True >>> bit.circuit(circuit()) >>> 2 - input(0) Traceback", "(xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.and_(ys))", "returns an output. if bit._hook_operation is not None: r = bit._hook_operation(o, v, *args)", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs ^ ys) ...", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nor_(ys)) ... ns =", "inputs(l): return bits(map(input, l)) def outputs(l): return bits(map(output, l)) def synthesize(f): \"\"\" Decorator", "from those definitions. \"\"\" from __future__ import annotations from typing import Sequence import", "bit.circuit().evaluate([1,1])[0] True >>> def make_hook(bit_): ... def hook(o, v, *args): ... return bit_.constructor(*args)(v,", "True \"\"\" return bit.operation(op.not_, self) def __invert__(self): \"\"\" >>> results = [] >>>", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs &", "x]), inputs([y, y, y])) ... zs = outputs(xs.nimp(ys)) ... ns = [int(z) for", "zip(self, other)]) def __lt__(self: bits, other: bits) -> bits: \"\"\" >>> results =", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_, self, other) def xnor(self, other):", "[b.value for b in bss[1]]) ([1, 1, 1, 1], [0, 0, 0, 0])", "other) def imp_(self, other): \"\"\" >>> results = [] >>> for (x, y)", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nif_(ys)) ... ns", "x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.xor_(y) for (x,", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs <= ys)", "def imp_(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "outputs(xs.nif_(ys)) ... ns = [int(z) for z in zs] ... c = bit.circuit()", "return bits([x.nif_(y) for (x, y) in zip(self, other)]) def nif_(self: bits, other: bits)", ">>> all(results) True \"\"\" return bit.operation(op.not_, self) def __rsub__(self, other): \"\"\" >>> results", "y, y, y])) >>> all(results) True \"\"\" return bits([x.and_(y) for (x, y) in", "\"\"\" return bits([x.xor_(y) for (x, y) in zip(self, other)]) def __xor__(self: bits, other:", "bit, y: bit) -> bit: ... return (x & y) | ((1 -", ">>> results = [] >>> for (x, y) in [(0, 0), (0, 1),", "representing an abstract bit. Such a bit can be interpreted concretely as a", "y, y])) ... zs = outputs(xs.nor_(ys)) ... ns = [int(z) for z in", "bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs << 3 >>>", "Sequence of lengths. elif isinstance(other, set) and len(other) == 1 and isinstance(list(other)[0], int):", "Sequence import doctest from parts import parts from circuit import op, gate, circuit,", "bits: \"\"\" >>> bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([255]))] [1, 1, 1,", "return bits([x.nand_(y) for (x, y) in zip(self, other)]) def nand_(self: bits, other) ->", "synthesis failed') from None # Return the original function. return f if __name__", "other)]) def nimp_(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "b = output(input(x).imp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_,", "output(input(x) <= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_,", "= None @staticmethod def circuit(circuit_=None): if circuit_ is not None: bit._circuit = circuit_", "} type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit = bit.circuit() except: raise RuntimeError('automated circuit synthesis failed') from None", "\"\"\" Decorator for automatically synthesizing a circuit from a function that takes only", "0, 0, 0, 0, 0, 0] \"\"\" return bits([ bit_ for byte_ in", "type annotation of the decorated function. type_in = lambda a: input(0) if a", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xor_(ys)) ... ns =", "__add__(self: bits, other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\" result = list(self) result.extend(list(other))", "input from one source.\"\"\" class input_two(input): \"\"\"Bit that is designated as a variable", "the wires within a circuit built up out of those operators. >>> bit.hook_operation(lambda", "for (x, y) in zip(self, other)]) def imp_(self: bits, other: bits) -> bits:", "bs in bss] [[1], [1, 1, 1], [0, 0, 0, 0]] \"\"\" if", "bits([x.nor_(y) for (x, y) in zip(self, other)]) def nor_(self: bits, other: bits) ->", "x])) >>> all(results) True \"\"\" return bits([x.not_() for x in self]) def and_(self:", "y])) ... zs = outputs(xs == ys) ... ns = [int(z) for z", "used to keep track of relationships between operators and to represent the wires", "... bit.circuit(circuit()) ... b = output(input(x).nimp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "xor(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "for a in args])) @staticmethod def constructor(b1, b2=None): # The inference code below", "\"\"\" return bit.operation(op.or_, self, other) def __or__(self, other): \"\"\" >>> results = []", "to a new wire. self.value = b.value self.gate = bit._circuit.gate(op.id_, [b.gate], is_output=True) class", "return bits([ bit_ for byte_ in bytes_ for bit_ in bits.from_byte(byte_, constructor) ])", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.xnor(ys)) ... ns = [int(z)", "def and_(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "bits([x.nor_(y) for (x, y) in zip(self, other)]) def xnor(self: bits, other: bits) ->", "constant input.\"\"\" class input(bit): \"\"\"Bit that is designated as a variable input.\"\"\" def", "1, 1, 1], [0, 0, 0, 0]) >>> bit.circuit(circuit()) >>> bs = bits(map(bit,", "bit_ for byte_ in bytes_ for bit_ in bits.from_byte(byte_, constructor) ]) @staticmethod def", "interpreted concretely as a value, but it is also used to keep track", "Decorator for automatically synthesizing a circuit from a function that takes only `bit`", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) &", "for (x, y) in zip(self, other)]) def nand(self: bits, other) -> bits: \"\"\"", ">>> bit.circuit(circuit()) >>> b = 0 & constant(1) >>> b.value 0 \"\"\" return", "bit.operation(op.if_, self, other) def __ge__(self, other): \"\"\" >>> results = [] >>> for", "zip(self, other)]) def __ge__(self: bits, other: bits) -> bits: \"\"\" >>> results =", "zs = outputs(xs.and_(ys)) ... ns = [int(z) for z in zs] ... c", "\"\"\" return bits([x.nif_(y) for (x, y) in zip(self, other)]) def nif_(self: bits, other:", "for i in range(8)]) ]) @staticmethod def from_bytes(bytes_, constructor=bit) -> bits: \"\"\" >>>", "on it. if len(b.gate.outputs) > 0: b = ~(~b) # Preserve the bit", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) < input(y)) ...", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nimp(other) def nif(self, other): \"\"\" >>> results", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor(input(y)))", "1, 0, 0, 0, 0, 1] \"\"\" if isinstance(other, set) and isinstance(list(other)[0], int):", "bit._circuit.gate(operation, igs) def __init__(self, value, gate_=None): self.value = value self.gate = bit._circuit.gate() if", "bit.circuit(circuit()) >>> b0 = output(input(1).not_()) >>> b1 = output(b0.not_()) >>> b2 = output(b0)", "= output(input(x).xor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_, self,", "return bits([x.xnor_(y) for (x, y) in zip(self, other)]) def xnor_(self: bits, other: bits)", "(0, 1)] >>> [conjunction.circuit.evaluate(xy) for xy in xys] [[0, 0], [0, 0], [1,", "abstract definitions of logic circuits and synthesizing circuits from those definitions. \"\"\" from", "def __eq__(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "call last): ... RuntimeError: automated circuit synthesis failed \"\"\" # Functions for determining", "in use. \"\"\" if isinstance(b1, input_one) and isinstance(b2, input_one): return input_one elif isinstance(b1,", "@synthesize ... def conjunction(xy: bits(2)) -> bits(2): ... return (xy[0], xy[0] & xy[1])", "op, gate, circuit, signature class bit(): \"\"\" Class for representing an abstract bit.", "from parts import parts from circuit import op, gate, circuit, signature class bit():", "zs = outputs(xs.nor(ys)) ... ns = [int(z) for z in zs] ... c", "quantity = list(other)[0] return bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity]) else: # Shift return bits([constant(0)]*other) **", "= output(input(x).xnor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_, self,", "other) def __and__(self, other): \"\"\" >>> results = [] >>> for (x, y)", "for representing a vector of abstract bits. \"\"\" @staticmethod def from_byte(byte_: int, constructor=bit)", "other)]) def nor_(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "determining types/signature from # the type annotation of the decorated function. type_in =", "a is bit else inputs([0] * a) type_out = lambda a: output if", "ys) ... ns = [int(z) for z in zs] ... c = bit.circuit()", "% input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_, self,", "... zs = outputs(xs.nor(ys)) ... ns = [int(z) for z in zs] ...", "bit.operation(op.imp_, self, other) def imp_(self, other): \"\"\" >>> results = [] >>> for", "if # it returns an output. if bit._hook_operation is not None: r =", "= outputs(xs.xnor(ys)) ... ns = [int(z) for z in zs] ... c =", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) % input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "for (x, y) in zip(self, other)]) def __le__(self: bits, other: bits) -> bits:", "== 1: return bit.operation(op.not_, self) raise ValueError('can only subtract a bit from the", "only `bit` and/or `bits` objects as its arguments and returns an output of", "(x, y) in zip(self, other)]) def __le__(self: bits, other: bits) -> bits: \"\"\"", "bit._circuit.gate(op.id_, is_input=True) class input_one(input): \"\"\"Bit that is designated as a variable input from", "\"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs <<", "y]) for x in (0, 1) for y in (0, 1)] >>> [conjunction.circuit.evaluate(xy)", "other) def __lt__(self, other): \"\"\" >>> results = [] >>> for (x, y)", "xy in xys] [[1], [0], [0], [1]] >>> @synthesize ... def conjunction(xy: bits(2))", "others dependent on it. if len(b.gate.outputs) > 0: b = ~(~b) # Preserve", "other): \"\"\" >>> results = [] >>> for x in [0, 1]: ...", "other)]) def imp(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "bit.hook_operation(make_hook(bit)) >>> bit.circuit(circuit()) >>> b = output(input(0).and_(input(0))) >>> b.value == bit.circuit().evaluate([0,0])[0] True \"\"\"", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... (xs, ys) = (inputs([x, x, x]),", "in (0, 1) for y in (0, 1)] >>> [equal.circuit.evaluate(xy) for xy in", "other) def __mod__(self, other): \"\"\" >>> results = [] >>> for (x, y)", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs <= ys) ...", "for b in bits.from_bytes(bytes([11, 0]))] [0, 0, 0, 0, 1, 0, 1, 1,", "... return bit_.constructor(*args)(v, bit_.gate(o, [a.gate for a in args])) ... return hook >>>", "... def hook(o, v, *args): ... return bit_.constructor(*args)(v, bit_.gate(o, [a.gate for a in", "igs) def __init__(self, value, gate_=None): self.value = value self.gate = bit._circuit.gate() if gate_", "bits.zeros(3) >>> ys = outputs(xs.not_()) >>> [y.value for y in ys] [1, 1,", "else other) def nimp(self, other): \"\"\" >>> results = [] >>> for (x,", "bit.operation(op.xnor_, self, other) def __eq__(self, other): \"\"\" >>> results = [] >>> for", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.or_(ys)) ... ns", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nimp_, self, other) def nimp_(self, other): \"\"\"", "1, 1, 1, 1, 1] >>> bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([11,", "b = output(input(x).nimp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nimp_,", "** bits(self[0:len(self)-other]) def __lshift__(self: bits, other) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> bs", "True \"\"\" return bits([x.nif_(y) for (x, y) in zip(self, other)]) def xor(self: bits,", "True \"\"\" return bit.operation(op.if_, self, other) def __ge__(self, other): \"\"\" >>> results =", ">>> b = output(input(0).and_(input(0))) >>> b.value == bit.circuit().evaluate([0,0])[0] True \"\"\" _circuit = None", "input_two)) and b2 is None: return type(b1) else: return bit \"\"\" return bit", "\"\"\"Concatenation of bit vectors.\"\"\" return self + other def constants(l): return bits(map(constant, l))", ">>> all(results) True \"\"\" return bits([x.xnor_(y) for (x, y) in zip(self, other)]) def", "bit.circuit(circuit()) ... b = output(input(x).nimp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "... b = output(~input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self, other) def nand_(self, other):", "automated synthesis. \"\"\" class bits(list): \"\"\" Class for representing a vector of abstract", "# Number of parts is `other`. def __add__(self: bits, other) -> bits: \"\"\"Concatenation", "circuit from a function that takes only `bit` and/or `bits` objects as its", "return bits([x.or_(y) for (x, y) in zip(self, other)]) def __or__(self: bits, other: bits)", "in zip(self, other)]) def __rshift__(self: bits, other) -> bits: \"\"\" Overloaded operator: rotation", "return bits([x.nor_(y) for (x, y) in zip(self, other)]) def nor_(self: bits, other: bits)", ">>> bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([255]))] [1, 1, 1, 1, 1,", "(xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xor(ys))", "True \"\"\" return bits([x.not_() for x in self]) def and_(self: bits, other: bits)", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.or_, self, other) def __ror__(self, other):", "outputs(xs.nimp(ys)) ... ns = [int(z) for z in zs] ... c = bit.circuit()", "True \"\"\" return bits([x.imp_(y) for (x, y) in zip(self, other)]) def nand(self: bits,", "(0, 1) for y in (0, 1)] >>> [conjunction.circuit.evaluate(xy) for xy in xys]", "= hook @staticmethod def operation(o, *args): # Ensure second argument is a `bit`.", "bit.circuit(circuit()) ... b = output(input(x) % input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "def nif_(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "inputs([y, y, y])) ... zs = outputs(xs.xor(ys)) ... ns = [int(z) for z", "map(bits, parts(self, length=other)) # Sequence of lengths. elif isinstance(other, set) and len(other) ==", "output(input(x).if_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.if_, self, other)", "self, other) def imp(self, other): \"\"\" >>> results = [] >>> for (x,", "\"\"\" return bits([x.or_(y) for (x, y) in zip(self, other)]) def __or__(self: bits, other:", "b in bits.from_bytes(bytes([255]))] [1, 1, 1, 1, 1, 1, 1, 1] >>> bit.circuit(circuit())", "bits([x.xnor_(y) for (x, y) in zip(self, other)]) def if_(self: bits, other: bits) ->", "= bs >> 3 >>> [b.value for b in bs] [0, 0, 0,", "bit is ready as final output or whether there are others dependent on", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.imp_(y) for (x, y)", "a bit from the integer 1') def and_(self, other): \"\"\" >>> results =", "& input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.and_, self,", "| constant(0) >>> b.value 1 \"\"\" return self | (constant(other) if isinstance(other, int)", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_, self, other) def nor_(self, other): \"\"\"", "bit.circuit(circuit()) ... b = output(input(x) & input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "def if_(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "an output. if bit._hook_operation is not None: r = bit._hook_operation(o, v, *args) if", "__new__(cls, argument = None) -> bits: \"\"\" Return bits object given the supplied", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nor(ys)) ...", "b = output(input(x) ^ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "... b = output(input(x).imp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_, self, other) def __le__(self, other):", "self.gate = bit._circuit.gate(op.id_, [b.gate], is_output=True) class bits_type(int): # pylint: disable=R0903 \"\"\" Class for", "other) def imp(self, other): \"\"\" >>> results = [] >>> for (x, y)", "y, y])) ... zs = outputs(xs % ys) ... ns = [int(z) for", "3, 4]) >>> [[b.value for b in bs] for bs in bss] [[1],", "y, y])) >>> all(results) True \"\"\" return bits([x.imp_(y) for (x, y) in zip(self,", "bs = bits(map(bit, [0,0,0,0,1,1,1,1])) >>> bs = bs >> {3} >>> [b.value for", "make_hook(bit_): ... def hook(o, v, *args): ... return bit_.constructor(*args)(v, bit_.gate(o, [a.gate for a", "... bit.circuit(circuit()) ... b = output(input(x).or_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "return bit.operation(op.nand_, self, other) def nand_(self, other): \"\"\" >>> results = [] >>>", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) @ input(y)) ... results.append(int(b) ==", "0, 0]) >>> ys = outputs(xs.not_()) >>> int(ys) 7 \"\"\" return sum(int(b)*(2**i) for", "bits(map(constant, l)) def inputs(l): return bits(map(input, l)) def outputs(l): return bits(map(output, l)) def", "in (0, 1)] >>> [conjunction.circuit.evaluate(xy) for xy in xys] [[0, 0], [0, 0],", ">>> [b.value for b in bs] [1, 1, 1, 0, 0, 0, 0,", "0, 0]) >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs", "b: bit): # Check if bit is ready as final output or whether", "= bit.circuit() ... results.append(ns == c.evaluate([x, x, x, y, y, y])) >>> all(results)", "bits. \"\"\" @staticmethod def from_byte(byte_: int, constructor=bit) -> bits: return bits([ constructor(bit_) for", "in [(0, 0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b", "args])) ... return hook >>> bit.hook_operation(make_hook(bit)) >>> bit.circuit(circuit()) >>> b = output(input(0).and_(input(0))) >>>", "b in bs] [0, 0, 0, 1, 1, 1, 1, 0] >>> bit.circuit(circuit())", ">>> b2 = output(b0) >>> [b0.value, b1.value, b2.value] [0, 1, 0] \"\"\" def", "... b = output(input(x).xnor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "str) else a # pylint: disable=W0123 try: # Construct the circuit and add", "output(input(x).nand(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self, other)", "output(input(x).xnor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other)", "x, x]), inputs([y, y, y])) ... zs = outputs(xs ^ ys) ... ns", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp(input(y))) ... results.append(int(b)", "1, 0] \"\"\" def __init__(self: bit, b: bit): # Check if bit is", "x, x]), inputs([y, y, y])) ... zs = outputs(xs >= ys) ... ns", "zs = outputs(xs.nor_(ys)) ... ns = [int(z) for z in zs] ... c", "1] \"\"\" return bits([constant(0)]*n) def __new__(cls, argument = None) -> bits: \"\"\" Return", "0, 1] \"\"\" if isinstance(other, set) and isinstance(list(other)[0], int): # Rotation. quantity =", "other)]) def xnor_(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "True \"\"\" return bit.operation(op.imp_, self, other) def imp_(self, other): \"\"\" >>> results =", "x]) ... ys = outputs(~xs) ... ns = [int(y) for y in ys]", "relationships between operators and to represent the wires within a circuit built up", "__init__(self: bit, value: int): self.value = value self.gate = bit._circuit.gate(op.id_, is_input=True) class input_one(input):", ">>> bit.circuit(circuit()) >>> 2 - input(0) Traceback (most recent call last): ... ValueError:", "for x in [0, 1]: ... bit.circuit(circuit()) ... b = output(1 - input(x))", "vectors.\"\"\" result = list(self) result.extend(list(other)) return bits(result) def __pow__(self: bits, other) -> bits:", "code below is not currently in use. \"\"\" if isinstance(b1, input_one) and isinstance(b2,", "... xs = inputs([x, x, x]) ... ys = outputs(~xs) ... ns =", "b = output(input(x) >= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", ">>> xs = bits.zeros(3) >>> ys = outputs(xs.not_()) >>> [y.value for y in", "(constant(other) if isinstance(other, int) else other) def or_(self, other): \"\"\" >>> results =", "def nor_(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "bytes_ for bit_ in bits.from_byte(byte_, constructor) ]) @staticmethod def zeros(n: int) -> bits:", "for b in bs] for bs in bss] [[1, 1], [1, 1], [0,", "bits([x.nand_(y) for (x, y) in zip(self, other)]) def __rshift__(self: bits, other) -> bits:", "not_(self): \"\"\" >>> results = [] >>> for x in [0, 1]: ...", ">>> all(results) True \"\"\" return bits([x.nif_(y) for (x, y) in zip(self, other)]) def", "True \"\"\" return bit.operation(op.xor_, self, other) def xor_(self, other): \"\"\" >>> results =", "input_two): return input_two elif isinstance(b1, (input_one, input_two)) and b2 is None: return type(b1)", "= output(b0.not_()) >>> b2 = output(b0) >>> [b0.value, b1.value, b2.value] [0, 1, 0]", "bits([x.nif_(y) for (x, y) in zip(self, other)]) def __lt__(self: bits, other: bits) ->", "other) def xnor_(self, other): \"\"\" >>> results = [] >>> for (x, y)", "y]) for x in (0, 1) for y in (0, 1)] >>> [equal.circuit.evaluate(xy)", "= outputs(xs ^ ys) ... ns = [int(z) for z in zs] ...", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def __eq__(self, other): \"\"\"", "\"\"\" return bits([x.if_(y) for (x, y) in zip(self, other)]) def __ge__(self: bits, other:", "\"\"\" Return bits object given the supplied argument. \"\"\" return bits_type(argument)\\ if isinstance(argument,", "bits([x.nor_(y) for (x, y) in zip(self, other)]) def __mod__(self, other) -> bits: \"\"\"", "in range(other)]) def __truediv__(self: bits, other) -> Sequence[bits]: \"\"\" >>> bit.circuit(circuit()) >>> bs", "zip(self, other)]) def __mod__(self, other) -> bits: \"\"\" >>> results = [] >>>", "]) @staticmethod def from_bytes(bytes_, constructor=bit) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> [b.value for", "__gt__(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.if_(y) for (x, y)", "== c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nimp_(y)", "... zs = outputs(xs.nif(ys)) ... ns = [int(z) for z in zs] ...", "zs = outputs(xs.nand(ys)) ... ns = [int(z) for z in zs] ... c", "bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / 2) >>>", "... ns = [int(z) for z in zs] ... c = bit.circuit() ...", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.and_(y) for (x, y)", "Embedded domain-specific combinator library for assembling abstract definitions of logic circuits and synthesizing", "for b in bits.from_bytes(bytes([255]))] [1, 1, 1, 1, 1, 1, 1, 1] >>>", "bit._hook_operation(o, v, *args) if r is not None: return r return bit.constructor(*args)(v, bit.gate(o,", "[1, 3, 4]) >>> [[b.value for b in bs] for bs in bss]", ">>> all(results) True \"\"\" return bit.operation(op.nand_, self, other) def nand_(self, other): \"\"\" >>>", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xnor_(ys)) ... ns =", "self, other) def __eq__(self, other): \"\"\" >>> results = [] >>> for (x,", "== input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_, self,", "[a.gate for a in args])) @staticmethod def constructor(b1, b2=None): # The inference code", "other): \"\"\" >>> bit.circuit(circuit()) >>> b = 1 | constant(0) >>> b.value 1", "nimp_(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "\"\"\" >>> bit.circuit(circuit()) >>> xs = constants([0, 0, 0]) >>> ys = outputs(xs.not_())", "bit.operation(op.xor_, self, other) def __xor__(self, other): \"\"\" >>> results = [] >>> for", "a function that takes only `bit` and/or `bits` objects as its arguments and", "RuntimeError: automated circuit synthesis failed \"\"\" # Functions for determining types/signature from #", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.if_(ys)) ... ns", "(x, y) in zip(self, other)]) def __ge__(self: bits, other: bits) -> bits: \"\"\"", "for byte_ in bytes_ for bit_ in bits.from_byte(byte_, constructor) ]) @staticmethod def zeros(n:", "1] >>> bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([11, 0]))] [0, 0, 0,", "x, x]), inputs([y, y, y])) ... zs = outputs(xs < ys) ... ns", "circuit and add it to the function as an attribute. bit.circuit(circuit()) args_in =", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nimp_, self, other) def nimp_(self,", "v, *args) if r is not None: return r return bit.constructor(*args)(v, bit.gate(o, [a.gate", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp(input(y)))", "\"\"\" return self.nimp(other) def nif(self, other): \"\"\" >>> results = [] >>> for", "\"\"\" return bits([x.imp_(y) for (x, y) in zip(self, other)]) def __le__(self: bits, other:", "1)] >>> [equal.circuit.evaluate(xy) for xy in xys] [[1], [0], [0], [1]] >>> @synthesize", "... zs = outputs(xs > ys) ... ns = [int(z) for z in", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs >= ys) ...", "parts(self, other)) # Number of parts is `other`. def __add__(self: bits, other) ->", "return sum(int(b)*(2**i) for (i, b) in zip(range(len(self)), reversed(self))) def not_(self: bits) -> bits:", "== 2: args[1] = constant(args[1]) if isinstance(args[1], int) else args[1] # Compute the", "all(results) True \"\"\" return bits([x.nor_(y) for (x, y) in zip(self, other)]) def __mod__(self,", "outputs(xs <= ys) ... ns = [int(z) for z in zs] ... c", "attribute. bit.circuit(circuit()) args_in = { k: type_in(eval_(a)) for (k, a) in f.__annotations__.items() if", "as a variable input.\"\"\" def __init__(self: bit, value: int): self.value = value self.gate", "0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0,", "1, 1, 0, 0, 0, 0, 1] \"\"\" if isinstance(other, set) and isinstance(list(other)[0],", "# Preserve the bit by copying it to a new wire. self.value =", "bits([x.not_() for x in self]) def __invert__(self: bits) -> bits: \"\"\" >>> results", "__and__(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "0, 0, 0, 0, 0, 0, 0, 0] \"\"\" return bits([ bit_ for", "y, y])) ... zs = outputs(xs.xor(ys)) ... ns = [int(z) for z in", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) | input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "for (x, y) in zip(self, other)]) def nif_(self: bits, other: bits) -> bits:", "4]) >>> [[b.value for b in bs] for bs in bss] [[1], [1,", "the value of the result of the operation on the arguments. v =", "v = o(*[a.value for a in args]) # Return output from hook if", "inputs([y, y, y])) ... zs = outputs(xs & ys) ... ns = [int(z)", "1 | constant(0) >>> b.value 1 \"\"\" return self | (constant(other) if isinstance(other,", ">>> int(ys) 7 \"\"\" return sum(int(b)*(2**i) for (i, b) in zip(range(len(self)), reversed(self))) def", "= bit._hook_operation(o, v, *args) if r is not None: return r return bit.constructor(*args)(v,", "... b = output(input(x) == input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "DSL for assembling logic circuits. Embedded domain-specific combinator library for assembling abstract definitions", "| ys) ... ns = [int(z) for z in zs] ... c =", "bits.from_bytes(bytes([11, 0]))] [0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0,", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).and_(input(y))) ...", "[1,1,1,1,0,0,0,0])) >>> bss = list(bs / 2) >>> ([b.value for b in bss[0]],", "def hook_operation(hook=None): bit._hook_operation = hook @staticmethod def operation(o, *args): # Ensure second argument", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) & input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", ">>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def __eq__(self, other): \"\"\" >>>", "in zip(self, other)]) def imp(self: bits, other: bits) -> bits: \"\"\" >>> results", "... return x & y Traceback (most recent call last): ... RuntimeError: automated", "= outputs(xs.not_()) >>> [y.value for y in ys] [1, 1, 1] \"\"\" return", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "\"\"\" return bit.operation(op.nand_, self, other) def nand_(self, other): \"\"\" >>> results = []", "y, y, y])) >>> all(results) True \"\"\" return bits([x.nand_(y) for (x, y) in", "zs = outputs(xs.nimp_(ys)) ... ns = [int(z) for z in zs] ... c", "for (x, y) in zip(self, other)]) def or_(self: bits, other: bits) -> bits:", "= output(input(x).nimp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nimp_, self,", "__rxor__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 1 ^ constant(0) >>> b.value", "-> bits: \"\"\" >>> results = [] >>> for (x, y) in [(0,", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp(input(y))) ... results.append(int(b) ==", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_, self, other) def __le__(self,", "... b = output(input(x) @ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", ">>> bit.circuit(circuit()) >>> bs = bits(map(bit, [0,0,0,0,1,1,1,1])) >>> bs = bs >> {3}", "x]), inputs([y, y, y])) ... zs = outputs(xs.xor(ys)) ... ns = [int(z) for", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) > input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "and isinstance(list(other)[0], int): # Rotation. quantity = list(other)[0] return bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity]) else:", "b = output(input(x).nand(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_,", "constructor) ]) @staticmethod def zeros(n: int) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> xs", "self) raise ValueError('can only subtract a bit from the integer 1') def and_(self,", "self, other) def nimp_(self, other): \"\"\" >>> results = [] >>> for (x,", "x in [0, 1]: ... bit.circuit(circuit()) ... b = output(~input(x)) ... results.append(int(b) ==", "automated circuit synthesis failed \"\"\" # Functions for determining types/signature from # the", "True \"\"\" return bits([x.or_(y) for (x, y) in zip(self, other)]) def __or__(self: bits,", "\"\"\"Embedded DSL for assembling logic circuits. Embedded domain-specific combinator library for assembling abstract", "\"\"\" Class for representing an abstract bit. Such a bit can be interpreted", "bit. Such a bit can be interpreted concretely as a value, but it", "def __ge__(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nand_(y) for (x, y)", "& (constant(other) if isinstance(other, int) else other) def nimp(self, other): \"\"\" >>> results", "(xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nor(ys))", "not None: bit._circuit = circuit_ return None else: bit._circuit.prune_and_topological_sort_stable() return bit._circuit @staticmethod def", "b = output(input(x) | input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operation(op.not_, self) def __rsub__(self, other):", "bs] for bs in bss] [[1], [1, 1, 1], [0, 0, 0, 0]]", "# pylint: disable=R0903 \"\"\" Class for representing an input or output type of", "None else gate_ def __int__(self): return self.value def not_(self): \"\"\" >>> results =", "def __or__(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "a: eval(a) if isinstance(a, str) else a # pylint: disable=W0123 try: # Construct", "lambda a: output if a is bit else outputs # For forward-compatibility with", "bit_.constructor(*args)(v, bit_.gate(o, [a.gate for a in args])) ... return hook >>> bit.hook_operation(make_hook(bit)) >>>", "= output(~input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operation(op.not_, self)", "= output(input(x) % input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "1, 1] \"\"\" return bits([constant(0)]*n) def __new__(cls, argument = None) -> bits: \"\"\"", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nimp_(ys)) ... ns", "zip(self, other)]) def nif(self: bits, other: bits) -> bits: \"\"\" >>> results =", "bits: \"\"\"Concatenation of bit vectors.\"\"\" result = list(self) result.extend(list(other)) return bits(result) def __pow__(self:", "bit: ... return (x & y) | ((1 - x) & (1 -", "True \"\"\" return bits([x.xor_(y) for (x, y) in zip(self, other)]) def __xor__(self: bits,", "bit.circuit(circuit()) ... b = output(input(x) <= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp_(input(y))) ...", "other)]) def xnor(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "1, 1, 1, 1, 1, 1, 1] >>> bit.circuit(circuit()) >>> [b.value for b", "y])) ... zs = outputs(xs.if_(ys)) ... ns = [int(z) for z in zs]", "all(results) True \"\"\" return bits([x.nand_(y) for (x, y) in zip(self, other)]) def nand_(self:", "\"\"\" def __init__(self: bit, b: bit): # Check if bit is ready as", "zip(self, other)]) def __gt__(self: bits, other: bits) -> bits: \"\"\" >>> results =", "bit._circuit.prune_and_topological_sort_stable() return bit._circuit @staticmethod def hook_operation(hook=None): bit._hook_operation = hook @staticmethod def operation(o, *args):", "return bit.operation(op.not_, self) raise ValueError('can only subtract a bit from the integer 1')", "= constant(args[1]) if isinstance(args[1], int) else args[1] # Compute the value of the", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.if_, self, other) def imp(self, other): \"\"\"", "= list(args) if len(args) == 2: args[1] = constant(args[1]) if isinstance(args[1], int) else", "one source.\"\"\" class input_two(input): \"\"\"Bit that is designated as a variable input from", "function. type_in = lambda a: input(0) if a is bit else inputs([0] *", "zip(self, other)]) def nif_(self: bits, other: bits) -> bits: \"\"\" >>> results =", "zs = outputs(xs < ys) ... ns = [int(z) for z in zs]", "int): # Rotation. quantity = list(other)[0] return bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity]) else: # Shift", "to keep track of relationships between operators and to represent the wires within", "for automated synthesis. \"\"\" class bits(list): \"\"\" Class for representing a vector of", "[1, 1, 1], [0, 0, 0, 0]] \"\"\" if isinstance(other, list) and len(other)", "0, 0, 0, 0, 0, 0, 0] \"\"\" return bits(self[other:]) ** bits([constant(0) for", "list(args) if len(args) == 2: args[1] = constant(args[1]) if isinstance(args[1], int) else args[1]", "input.\"\"\" def __init__(self: bit, value: int): self.value = value self.gate = bit._circuit.gate(op.id_, is_input=True)", "domain-specific combinator library for assembling abstract definitions of logic circuits and synthesizing circuits", "all(results) True \"\"\" return bits([x.nif_(y) for (x, y) in zip(self, other)]) def nif_(self:", "if it exists and if # it returns an output. if bit._hook_operation is", "Preserve the bit by copying it to a new wire. self.value = b.value", "bits(self[0:len(self)-quantity]) else: # Shift return bits([constant(0)]*other) ** bits(self[0:len(self)-other]) def __lshift__(self: bits, other) ->", "return bits(map(constant, l)) def inputs(l): return bits(map(input, l)) def outputs(l): return bits(map(output, l))", ">>> def make_hook(bit_): ... def hook(o, v, *args): ... return bit_.constructor(*args)(v, bit_.gate(o, [a.gate", "True \"\"\" return bits([x.xnor_(y) for (x, y) in zip(self, other)]) def xnor_(self: bits,", "class bit(): \"\"\" Class for representing an abstract bit. Such a bit can", "= bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / [1, 3, 4]) >>> [[b.value", "\"\"\"Bit that is designated as a variable input from a second source.\"\"\" class", "other) def nimp(self, other): \"\"\" >>> results = [] >>> for (x, y)", "in [(0, 0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... (xs,", "outputs(xs >= ys) ... ns = [int(z) for z in zs] ... c", "= output(input(x).imp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_, self,", "input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True >>> bit.circuit(circuit()) >>> 2 -", "copying it to a new wire. self.value = b.value self.gate = bit._circuit.gate(op.id_, [b.gate],", ">>> all(results) True \"\"\" return bit.operation(op.nimp_, self, other) def nimp_(self, other): \"\"\" >>>", "constant(args[1]) if isinstance(args[1], int) else args[1] # Compute the value of the result", "built up out of those operators. >>> bit.hook_operation(lambda o, v, *args: None) >>>", "def nand_(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "that takes only `bit` and/or `bits` objects as its arguments and returns an", "x) & (1 - y)) >>> xys = [bits([x, y]) for x in", "for determining types/signature from # the type annotation of the decorated function. type_in", "(xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nand_(ys))", "xnor(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "else inputs([0] * a) type_out = lambda a: output if a is bit", "and isinstance(list(other)[0], int): return self / (len(self)//list(other)[0]) # Parts of length `other`. else:", "(xy[0], xy[0] & xy[1]) >>> xys = [bits([x, y]) for x in (0,", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nimp_, self, other) def __gt__(self, other): \"\"\"", "b = output(input(1).and_(input(1))) >>> b.value == bit.circuit().evaluate([1,1])[0] True >>> def make_hook(bit_): ... def", "self, other) def __matmul__(self, other): \"\"\" >>> results = [] >>> for (x,", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xnor(ys)) ...", "[[0, 0], [0, 0], [1, 0], [1, 1]] >>> @synthesize ... def equal(x,", "type_in(eval_(a)) for (k, a) in f.__annotations__.items() if k != 'return' } type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit", "self, other) def xnor(self, other): \"\"\" >>> results = [] >>> for (x,", "f.__annotations__.items() if k != 'return' } type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit = bit.circuit() except: raise RuntimeError('automated", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "y, y])) >>> all(results) True \"\"\" return bits([x.nand_(y) for (x, y) in zip(self,", "... b = output(input(x).nand(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "- input(0) Traceback (most recent call last): ... ValueError: can only subtract a", "x]), inputs([y, y, y])) ... zs = outputs(xs.xnor_(ys)) ... ns = [int(z) for", "and isinstance(b2, input_two): return input_two elif isinstance(b1, (input_one, input_two)) and b2 is None:", "= output(input(x) @ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "... bit.circuit(circuit()) ... b = output(input(x).nand_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "last): ... ValueError: can only subtract a bit from the integer 1 \"\"\"", "... zs = outputs(xs.imp_(ys)) ... ns = [int(z) for z in zs] ...", "[0, 0, 0, 1, 1, 1, 1, 0] >>> bit.circuit(circuit()) >>> bs =", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs >=", "input_one(input): \"\"\"Bit that is designated as a variable input from one source.\"\"\" class", "value self.gate = bit._circuit.gate(op.id_, is_input=True) class input_one(input): \"\"\"Bit that is designated as a", "a in args]) # Return output from hook if it exists and if", "= [int(y) for y in ys] ... c = bit.circuit() ... results.append(ns ==", "b = output(input(x).xnor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_,", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "in bss[0]], [b.value for b in bss[1]]) ([1, 1, 1, 1], [0, 0,", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.imp_(ys)) ... ns = [int(z)", ">>> ys = outputs(xs.not_()) >>> [y.value for y in ys] [1, 1, 1]", "isinstance(b2, input_two): return input_two elif isinstance(b1, (input_one, input_two)) and b2 is None: return", "c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nimp_(y) for", "output(input(x).or_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.or_, self, other)", "results = [] >>> for x in [0, 1]: ... bit.circuit(circuit()) ... b", "= output(input(x) >= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "... zs = outputs(xs | ys) ... ns = [int(z) for z in", "y, y])) ... zs = outputs(xs == ys) ... ns = [int(z) for", "for assembling logic circuits. Embedded domain-specific combinator library for assembling abstract definitions of", "= value self.gate = bit._circuit.gate(op.id_, is_input=True) class input_one(input): \"\"\"Bit that is designated as", "def __and__(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "y])) ... zs = outputs(xs < ys) ... ns = [int(z) for z", "definitions of logic circuits and synthesizing circuits from those definitions. \"\"\" from __future__", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) | input(y)) ...", "all(results) True \"\"\" return bit.operation(op.if_, self, other) def imp(self, other): \"\"\" >>> results", "constant(1) >>> b.value 0 \"\"\" return self & (constant(other) if isinstance(other, int) else", "synthesizing circuits from those definitions. \"\"\" from __future__ import annotations from typing import", "are others dependent on it. if len(b.gate.outputs) > 0: b = ~(~b) #", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xnor(ys)) ... ns =", "{ k: type_in(eval_(a)) for (k, a) in f.__annotations__.items() if k != 'return' }", "def __init__(self: bit, value: int): self.value = value self.gate = bit._circuit.gate(op.id_, is_input=True) class", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.nor(ys)) ... ns = [int(z)", "def and_(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "bss = list(bs / 2) >>> ([b.value for b in bss[0]], [b.value for", "True \"\"\" return bit.operation(op.nor_, self, other) def __mod__(self, other): \"\"\" >>> results =", ">>> @synthesize ... def conjunction(xy: bits(2)) -> bits(2): ... return (xy[0], xy[0] &", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) == input(y)) ...", "= output(input(x) < input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.if_, self, other) def imp(self,", "x in [0, 1]: ... bit.circuit(circuit()) ... xs = inputs([x, x, x]) ...", "self, other) def __le__(self, other): \"\"\" >>> results = [] >>> for (x,", "y, y])) ... zs = outputs(xs.imp_(ys)) ... ns = [int(z) for z in", "(xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nif(ys))", "\"\"\" return self & (constant(other) if isinstance(other, int) else other) def nimp(self, other):", "bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs >> 3 >>> [b.value for b in", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nor_(y) for (x, y)", "x]), inputs([y, y, y])) ... zs = outputs(xs.imp(ys)) ... ns = [int(z) for", "in args])) @staticmethod def constructor(b1, b2=None): # The inference code below is not", "xys = [bits([x, y]) for x in (0, 1) for y in (0,", "int): self.value = value self.gate = bit._circuit.gate(op.id_, is_input=True) class input_one(input): \"\"\"Bit that is", "(most recent call last): ... ValueError: can only subtract a bit from the", "b.value == bit.circuit().evaluate([0,0])[0] True \"\"\" _circuit = None _hook_operation = None @staticmethod def", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self, other) class", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) <= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "def conjunction(xy: bits(2)) -> bits(2): ... return (xy[0], xy[0] & xy[1]) >>> xys", "y])) >>> all(results) True \"\"\" return bits([x.nimp_(y) for (x, y) in zip(self, other)])", "the type annotation of the decorated function. type_in = lambda a: input(0) if", "for z in zs] ... c = bit.circuit() ... results.append(ns == c.evaluate([x, x,", "for (x, y) in zip(self, other)]) def nif(self: bits, other: bits) -> bits:", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.or_(ys)) ...", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).if_(input(y))) ... results.append(int(b)", "True \"\"\" return bit.operation(op.xor_, self, other) def __xor__(self, other): \"\"\" >>> results =", "bits) -> bits: \"\"\" >>> results = [] >>> for (x, y) in", "else\\ list.__new__(cls, argument) def __int__(self: bits) -> int: \"\"\" >>> bit.circuit(circuit()) >>> xs", "all(results) True \"\"\" return bits([x.and_(y) for (x, y) in zip(self, other)]) def __and__(self:", "bits([x.xor_(y) for (x, y) in zip(self, other)]) def __xor__(self: bits, other: bits) ->", "return map(bits, parts(self, other)) # Number of parts is `other`. def __add__(self: bits,", "*args) if r is not None: return r return bit.constructor(*args)(v, bit.gate(o, [a.gate for", "from a second source.\"\"\" class output(bit): \"\"\" Bit that is designated an output.", "synthesize(f): \"\"\" Decorator for automatically synthesizing a circuit from a function that takes", "on the arguments. v = o(*[a.value for a in args]) # Return output", "other) def nimp_(self, other): \"\"\" >>> results = [] >>> for (x, y)", "bit.operation(op.xor_, self, other) def xor_(self, other): \"\"\" >>> results = [] >>> for", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.imp_(ys)) ...", "bss = list(bs / [1, 3, 4]) >>> [[b.value for b in bs]", "PEP 563. eval_ = lambda a: eval(a) if isinstance(a, str) else a #", "y)) >>> xys = [bits([x, y]) for x in (0, 1) for y", "other) def __gt__(self, other): \"\"\" >>> results = [] >>> for (x, y)", "1 \"\"\" return self | (constant(other) if isinstance(other, int) else other) def nor(self,", ">>> [[b.value for b in bs] for bs in bss] [[1, 1], [1,", "output(input(x) == input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_,", "y) in zip(self, other)]) def if_(self: bits, other: bits) -> bits: \"\"\" >>>", "input or output type of a function decorated for automated synthesis. \"\"\" class", "that is designated as a constant input.\"\"\" class input(bit): \"\"\"Bit that is designated", "args])) @staticmethod def constructor(b1, b2=None): # The inference code below is not currently", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_, self, other) def xnor(self, other): \"\"\"", "bits([x.not_() for x in self]) def and_(self: bits, other: bits) -> bits: \"\"\"", "bits([x.and_(y) for (x, y) in zip(self, other)]) def nimp(self: bits, other: bits) ->", "for (x, y) in zip(self, other)]) def __mod__(self, other) -> bits: \"\"\" >>>", "for x in (0, 1) for y in (0, 1)] >>> [conjunction.circuit.evaluate(xy) for", "outputs(xs ^ ys) ... ns = [int(z) for z in zs] ... c", "other) def __eq__(self, other): \"\"\" >>> results = [] >>> for (x, y)", "> 0 and isinstance(other[0], int): return map(bits, parts(self, length=other)) # Sequence of lengths.", "2 - input(0) Traceback (most recent call last): ... ValueError: can only subtract", "all(results) True \"\"\" return bit.operation(op.nif_, self, other) def nif_(self, other): \"\"\" >>> results", "@staticmethod def hook_operation(hook=None): bit._hook_operation = hook @staticmethod def operation(o, *args): # Ensure second", "(xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nand(ys))", ">>> for x in [0, 1]: ... bit.circuit(circuit()) ... xs = inputs([x, x,", ">>> all(results) True \"\"\" return bit.operation(op.nimp_, self, other) def __gt__(self, other): \"\"\" >>>", "True \"\"\" return bit.operation(op.if_, self, other) def imp(self, other): \"\"\" >>> results =", "# For forward-compatibility with PEP 563. eval_ = lambda a: eval(a) if isinstance(a,", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nif_(ys)) ... ns =", "if isinstance(args[1], int) else args[1] # Compute the value of the result of", "\"\"\" return self.nif(other) def xor(self, other): \"\"\" >>> results = [] >>> for", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.if_(ys)) ... ns =", "bit.operation(op.imp_, self, other) def __le__(self, other): \"\"\" >>> results = [] >>> for", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor(input(y))) ... results.append(int(b) ==", "for y in ys] [1, 1, 1] \"\"\" return bits([constant(0)]*n) def __new__(cls, argument", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).if_(input(y))) ... results.append(int(b) ==", "c.evaluate([x, x, x])) >>> all(results) True \"\"\" return bits([x.not_() for x in self])", "return bits([x.nif_(y) for (x, y) in zip(self, other)]) def __lt__(self: bits, other: bits)", "/ {2}) >>> [[b.value for b in bs] for bs in bss] [[1,", "__ror__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 1 | constant(0) >>> b.value", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nimp_, self, other) def __gt__(self,", "\"\"\" return bit.operation(op.xor_, self, other) def xor_(self, other): \"\"\" >>> results = []", "xys] [[1], [0], [0], [1]] >>> @synthesize ... def conjunction(xy: bits(2)) -> bits(2):", "bit.circuit(circuit()) ... b = output(input(x).nimp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "def __eq__(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "inputs([y, y, y])) ... zs = outputs(xs | ys) ... ns = [int(z)", ">>> [conjunction.circuit.evaluate(xy) for xy in xys] [[0, 0], [0, 0], [1, 0], [1,", "pylint: disable=W0123 try: # Construct the circuit and add it to the function", "x, x]) ... ys = outputs(xs.not_()) ... ns = [int(y) for y in", "return bit.operation(op.and_, self, other) def __and__(self, other): \"\"\" >>> results = [] >>>", "__matmul__(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "bits([x.if_(y) for (x, y) in zip(self, other)]) def __ge__(self: bits, other: bits) ->", "other)]) def __eq__(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "int) else other) def or_(self, other): \"\"\" >>> results = [] >>> for", "c = bit.circuit() ... results.append(ns == c.evaluate([x, x, x, y, y, y])) >>>", "last): ... RuntimeError: automated circuit synthesis failed \"\"\" # Functions for determining types/signature", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).or_(input(y)))", "output(input(x).nor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_, self, other)", "input_one): return input_one elif isinstance(b1, input_two) and isinstance(b2, input_two): return input_two elif isinstance(b1,", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) ^ input(y))", "> 0: b = ~(~b) # Preserve the bit by copying it to", "(x, y) in zip(self, other)]) def __gt__(self: bits, other: bits) -> bits: \"\"\"", ">>> 2 - input(0) Traceback (most recent call last): ... ValueError: can only", "zs = outputs(xs.xor_(ys)) ... ns = [int(z) for z in zs] ... c", "y])) >>> all(results) True \"\"\" return bits([x.if_(y) for (x, y) in zip(self, other)])", "def __le__(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "bit.circuit(circuit()) ... b = output(input(x) > input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "bit.operation(op.or_, self, other) def __or__(self, other): \"\"\" >>> results = [] >>> for", "x]), inputs([y, y, y])) ... zs = outputs(xs.xnor(ys)) ... ns = [int(z) for", "bits(2): ... return (xy[0], xy[0] & xy[1]) >>> xys = [bits([x, y]) for", "y, y])) >>> all(results) True \"\"\" return bits([x.xor_(y) for (x, y) in zip(self,", "for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]: ...", ">>> bit.hook_operation(lambda o, v, *args: None) >>> bit.circuit(circuit()) >>> b = output(input(1).and_(input(1))) >>>", "output(input(x) @ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_,", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs == ys)", ">>> results = [] >>> for x in [0, 1]: ... bit.circuit(circuit()) ...", "__gt__(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "bit.circuit(circuit()) ... b = output(input(x) ^ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) <=", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) < input(y)) ... results.append(int(b) ==", "input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_, self, other)", "ys = outputs(~xs) ... ns = [int(y) for y in ys] ... c", "all(results) True \"\"\" return bits([x.xnor_(y) for (x, y) in zip(self, other)]) def __eq__(self:", "bit vectors.\"\"\" return self + other def constants(l): return bits(map(constant, l)) def inputs(l):", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs ==", "b = output(input(x).and_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.and_,", "x, x]), inputs([y, y, y])) ... zs = outputs(xs & ys) ... ns", "def constants(l): return bits(map(constant, l)) def inputs(l): return bits(map(input, l)) def outputs(l): return", "y, y])) ... zs = outputs(xs ^ ys) ... ns = [int(z) for", "\"\"\" return bits([x.nand_(y) for (x, y) in zip(self, other)]) def __rshift__(self: bits, other)", "is not None: bit._circuit = circuit_ return None else: bit._circuit.prune_and_topological_sort_stable() return bit._circuit @staticmethod", "= outputs(xs.imp(ys)) ... ns = [int(z) for z in zs] ... c =", "zip(self, other)]) def imp_(self: bits, other: bits) -> bits: \"\"\" >>> results =", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif_(input(y))) ... results.append(int(b)", "= outputs(xs <= ys) ... ns = [int(z) for z in zs] ...", "= constants([0, 0, 0]) >>> ys = outputs(xs.not_()) >>> int(ys) 7 \"\"\" return", "designated as a variable input from one source.\"\"\" class input_two(input): \"\"\"Bit that is", "zs = outputs(xs.xor(ys)) ... ns = [int(z) for z in zs] ... c", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xnor_(ys)) ...", "class input(bit): \"\"\"Bit that is designated as a variable input.\"\"\" def __init__(self: bit,", "# Rotation. quantity = list(other)[0] return bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity]) else: # Shift return", "for b in bs] for bs in bss] [[1], [1, 1, 1], [0,", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).or_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor_(input(y))) ... results.append(int(b)", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.or_(ys)) ... ns =", "& xy[1]) >>> xys = [bits([x, y]) for x in (0, 1) for", "y) | ((1 - x) & (1 - y)) >>> xys = [bits([x,", "return r return bit.constructor(*args)(v, bit.gate(o, [a.gate for a in args])) @staticmethod def constructor(b1,", "... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operation(op.not_, self) def __invert__(self):", "bit.operation(op.and_, self, other) def __rand__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 0", "subtract a bit from the integer 1') def and_(self, other): \"\"\" >>> results", "== c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.xor_(y)", "self, other) def if_(self, other): \"\"\" >>> results = [] >>> for (x,", "type `bit` or `bits`. >>> @synthesize ... def equal(x: bit, y: bit) ->", "all(results) True \"\"\" return bits([x.xor_(y) for (x, y) in zip(self, other)]) def xor_(self:", "None: r = bit._hook_operation(o, v, *args) if r is not None: return r", "input_one elif isinstance(b1, input_two) and isinstance(b2, input_two): return input_two elif isinstance(b1, (input_one, input_two))", "bit.operation(op.xor_, self, other) def __rxor__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 1", "vectors.\"\"\" return self + other def constants(l): return bits(map(constant, l)) def inputs(l): return", "args[1] # Compute the value of the result of the operation on the", "b = output(input(x).nimp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nimp_,", "other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\" return self + other def constants(l):", "and len(other) > 0 and isinstance(other[0], int): return map(bits, parts(self, length=other)) # Sequence", "y in (0, 1)] >>> [conjunction.circuit.evaluate(xy) for xy in xys] [[0, 0], [0,", "type(b1) else: return bit \"\"\" return bit @staticmethod def gate(operation, igs): return bit._circuit.gate(operation,", "if len(args) == 2: args[1] = constant(args[1]) if isinstance(args[1], int) else args[1] #", "reversed([(byte_>>i)%2 for i in range(8)]) ]) @staticmethod def from_bytes(bytes_, constructor=bit) -> bits: \"\"\"", "ys = outputs(xs.not_()) ... ns = [int(y) for y in ys] ... c", "for bs in bss] [[1, 1], [1, 1], [0, 0], [0, 0]] >>>", "operators. >>> bit.hook_operation(lambda o, v, *args: None) >>> bit.circuit(circuit()) >>> b = output(input(1).and_(input(1)))", "in args])) ... return hook >>> bit.hook_operation(make_hook(bit)) >>> bit.circuit(circuit()) >>> b = output(input(0).and_(input(0)))", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.imp(ys)) ... ns = [int(z)", "automatically synthesizing a circuit from a function that takes only `bit` and/or `bits`", "-> bits: \"\"\" Return bits object given the supplied argument. \"\"\" return bits_type(argument)\\", "c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.xnor_(y) for", "return bit.operation(op.nimp_, self, other) def __gt__(self, other): \"\"\" >>> results = [] >>>", "is bit else outputs # For forward-compatibility with PEP 563. eval_ = lambda", "\"\"\" return bits([x.nif_(y) for (x, y) in zip(self, other)]) def xor(self: bits, other:", "0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0] \"\"\" return", "bits([ bit_ for byte_ in bytes_ for bit_ in bits.from_byte(byte_, constructor) ]) @staticmethod", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nif_, self, other) def nif_(self,", "and/or `bits` objects as its arguments and returns an output of type `bit`", "*args): ... return bit_.constructor(*args)(v, bit_.gate(o, [a.gate for a in args])) ... return hook", "result.extend(list(other)) return bits(result) def __pow__(self: bits, other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\"", "def __lshift__(self: bits, other) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit,", "self & (constant(other) if isinstance(other, int) else other) def nimp(self, other): \"\"\" >>>", "zip(self, other)]) def __eq__(self: bits, other: bits) -> bits: \"\"\" >>> results =", "output(b0.not_()) >>> b2 = output(b0) >>> [b0.value, b1.value, b2.value] [0, 1, 0] \"\"\"", "in xys] [[0, 0], [0, 0], [1, 0], [1, 1]] >>> @synthesize ...", "inputs([y, y, y])) ... zs = outputs(xs.nand_(ys)) ... ns = [int(z) for z", "class output(bit): \"\"\" Bit that is designated an output. >>> bit.circuit(circuit()) >>> b0", "[equal.circuit.evaluate(xy) for xy in xys] [[1], [0], [0], [1]] >>> @synthesize ... def", "bit.operation(op.xnor_, self, other) def xnor_(self, other): \"\"\" >>> results = [] >>> for", "an output. >>> bit.circuit(circuit()) >>> b0 = output(input(1).not_()) >>> b1 = output(b0.not_()) >>>", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs % ys)", "inputs([y, y, y])) ... zs = outputs(xs == ys) ... ns = [int(z)", "list(other)[0] return bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity]) else: # Shift return bits([constant(0)]*other) ** bits(self[0:len(self)-other]) def", "b = 1 ^ constant(0) >>> b.value 1 \"\"\" return self ^ (constant(other)", "gate_ def __int__(self): return self.value def not_(self): \"\"\" >>> results = [] >>>", ">>> all(results) True \"\"\" return bit.operation(op.xor_, self, other) def xor_(self, other): \"\"\" >>>", "y, y])) >>> all(results) True \"\"\" return bits([x.nif_(y) for (x, y) in zip(self,", "x]), inputs([y, y, y])) ... zs = outputs(xs.nimp_(ys)) ... ns = [int(z) for", "... bit.circuit(circuit()) ... b = output(input(x).nif_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "gate_=None): self.value = value self.gate = bit._circuit.gate() if gate_ is None else gate_", "bit.circuit(circuit()) ... b = output(input(x) >= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "arguments. v = o(*[a.value for a in args]) # Return output from hook", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nand_(ys)) ... ns =", "@synthesize ... def equal(x: bit, y: bit) -> bit: ... return (x &", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.nimp_(ys)) ... ns = [int(z)", "... b = output(1 - input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True", "(0, 1) for y in (0, 1)] >>> [equal.circuit.evaluate(xy) for xy in xys]", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.or_(y) for (x, y)", "[[1], [1, 1, 1], [0, 0, 0, 0]] \"\"\" if isinstance(other, list) and", "return bit.operation(op.xor_, self, other) def xor_(self, other): \"\"\" >>> results = [] >>>", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def", "that is designated as a variable input from one source.\"\"\" class input_two(input): \"\"\"Bit", "x, x]), inputs([y, y, y])) ... zs = outputs(xs <= ys) ... ns", "== 1 and isinstance(list(other)[0], int): return self / (len(self)//list(other)[0]) # Parts of length", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) @ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "bits([constant(0) for _ in range(other)]) def __truediv__(self: bits, other) -> Sequence[bits]: \"\"\" >>>", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).if_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "assembling logic circuits. Embedded domain-specific combinator library for assembling abstract definitions of logic", "all(results) True \"\"\" return bits([x.nimp_(y) for (x, y) in zip(self, other)]) def nimp_(self:", "bits: \"\"\" >>> results = [] >>> for x in [0, 1]: ...", "input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nimp(other) def nif(self,", "None: return r return bit.constructor(*args)(v, bit.gate(o, [a.gate for a in args])) @staticmethod def", "None @staticmethod def circuit(circuit_=None): if circuit_ is not None: bit._circuit = circuit_ return", "y, y])) ... zs = outputs(xs > ys) ... ns = [int(z) for", ">>> [b.value for b in bs] [0, 0, 0, 1, 1, 1, 1,", "all(results) True \"\"\" return bit.operation(op.nor_, self, other) def xnor(self, other): \"\"\" >>> results", "return bit.operation(op.if_, self, other) def __ge__(self, other): \"\"\" >>> results = [] >>>", "y, y])) ... zs = outputs(xs.xnor_(ys)) ... ns = [int(z) for z in", "if a is bit else inputs([0] * a) type_out = lambda a: output", "other) def nand(self, other): \"\"\" >>> results = [] >>> for (x, y)", "@staticmethod def constructor(b1, b2=None): # The inference code below is not currently in", "bits) -> int: \"\"\" >>> bit.circuit(circuit()) >>> xs = constants([0, 0, 0]) >>>", "all(results) True \"\"\" return bit.operation(op.not_, self) def __invert__(self): \"\"\" >>> results = []", "... bit.circuit(circuit()) ... b = output(input(x) < input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "other)]) def __or__(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "b = output(input(x).imp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_,", "def __le__(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operation(op.not_, self) def __rsub__(self, other): \"\"\" >>>", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif(input(y))) ... results.append(int(b) ==", "imp_(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) @ input(y)) ...", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self, other) class constant(bit): \"\"\"Bit", "1, 1] >>> bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([11, 0]))] [0, 0,", "# Return the original function. return f if __name__ == \"__main__\": doctest.testmod() #", "1], [0, 0, 0, 0]) >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>>", "1]: ... bit.circuit(circuit()) ... xs = inputs([x, x, x]) ... ys = outputs(xs.not_())", "True \"\"\" return bits([x.nimp_(y) for (x, y) in zip(self, other)]) def nimp_(self: bits,", "to represent the wires within a circuit built up out of those operators.", "for b in bs] [1, 0, 0, 0, 0, 0, 0, 0] \"\"\"", "= bs >> {3} >>> [b.value for b in bs] [1, 1, 1,", "Check if bit is ready as final output or whether there are others", "circuit_ is not None: bit._circuit = circuit_ return None else: bit._circuit.prune_and_topological_sort_stable() return bit._circuit", "for (i, b) in zip(range(len(self)), reversed(self))) def not_(self: bits) -> bits: \"\"\" >>>", "True \"\"\" return bits([x.nand_(y) for (x, y) in zip(self, other)]) def nand_(self: bits,", "else other) def nor(self, other): \"\"\" >>> results = [] >>> for (x,", "(k, a) in f.__annotations__.items() if k != 'return' } type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit = bit.circuit()", "import annotations from typing import Sequence import doctest from parts import parts from", "bits.from_bytes(bytes([255]))] [1, 1, 1, 1, 1, 1, 1, 1] >>> bit.circuit(circuit()) >>> [b.value", "isinstance(b1, input_one) and isinstance(b2, input_one): return input_one elif isinstance(b1, input_two) and isinstance(b2, input_two):", "-> int: \"\"\" >>> bit.circuit(circuit()) >>> xs = constants([0, 0, 0]) >>> ys", "> input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nimp(other) def", "all(results) True \"\"\" return self.nimp(other) def nif(self, other): \"\"\" >>> results = []", "bits.from_byte(byte_, constructor) ]) @staticmethod def zeros(n: int) -> bits: \"\"\" >>> bit.circuit(circuit()) >>>", "= output(input(x) & input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operation(op.not_, self) def __rsub__(self,", "bit.operation(op.nand_, self, other) def __matmul__(self, other): \"\"\" >>> results = [] >>> for", "other) def nand_(self, other): \"\"\" >>> results = [] >>> for (x, y)", "argument. \"\"\" return bits_type(argument)\\ if isinstance(argument, int) else\\ list.__new__(cls, argument) def __int__(self: bits)", "output(input(1).not_()) >>> b1 = output(b0.not_()) >>> b2 = output(b0) >>> [b0.value, b1.value, b2.value]", "= bit._circuit.gate(op.id_, [b.gate], is_output=True) class bits_type(int): # pylint: disable=R0903 \"\"\" Class for representing", "bit.circuit(circuit()) >>> b = output(input(0).and_(input(0))) >>> b.value == bit.circuit().evaluate([0,0])[0] True \"\"\" _circuit =", "x])) >>> all(results) True \"\"\" return bits([x.not_() for x in self]) def __invert__(self:", "f.circuit = bit.circuit() except: raise RuntimeError('automated circuit synthesis failed') from None # Return", "inputs([x, x, x]) ... ys = outputs(~xs) ... ns = [int(y) for y", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs < ys)", "def __new__(cls, argument = None) -> bits: \"\"\" Return bits object given the", "return bits([x.and_(y) for (x, y) in zip(self, other)]) def __and__(self: bits, other: bits)", ">>> all(results) True \"\"\" return self.nif(other) def xor(self, other): \"\"\" >>> results =", "def synthesize(f): \"\"\" Decorator for automatically synthesizing a circuit from a function that", "bit.operation(op.or_, self, other) def __ror__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 1", "bit.circuit().evaluate([x])[0]) >>> all(results) True >>> bit.circuit(circuit()) >>> 2 - input(0) Traceback (most recent", "int): return map(bits, parts(self, length=other)) # Sequence of lengths. elif isinstance(other, set) and", "other)]) def __le__(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "[] >>> for x in [0, 1]: ... bit.circuit(circuit()) ... b = output(~input(x))", "bit, value: int): self.value = value self.gate = bit._circuit.gate(op.id_, is_input=True) class input_one(input): \"\"\"Bit", "(xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.imp(ys))", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nif_, self, other) def __lt__(self,", "def __mod__(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "zip(range(len(self)), reversed(self))) def not_(self: bits) -> bits: \"\"\" >>> results = [] >>>", "set) and isinstance(list(other)[0], int): # Rotation. quantity = list(other)[0] return bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity])", "__future__ import annotations from typing import Sequence import doctest from parts import parts", "= None _hook_operation = None @staticmethod def circuit(circuit_=None): if circuit_ is not None:", "nimp_(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "True \"\"\" return bit.operation(op.nand_, self, other) def __matmul__(self, other): \"\"\" >>> results =", "def nif(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", ">>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / {2})", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "self, other) def nif_(self, other): \"\"\" >>> results = [] >>> for (x,", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_, self, other) def __xor__(self, other): \"\"\"", "exists and if # it returns an output. if bit._hook_operation is not None:", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "self.gate = bit._circuit.gate() if gate_ is None else gate_ def __int__(self): return self.value", "that is designated as a variable input.\"\"\" def __init__(self: bit, value: int): self.value", "\"\"\" return bits([x.nor_(y) for (x, y) in zip(self, other)]) def nor_(self: bits, other:", "/ [1, 3, 4]) >>> [[b.value for b in bs] for bs in", "def gate(operation, igs): return bit._circuit.gate(operation, igs) def __init__(self, value, gate_=None): self.value = value", "\"\"\" return bits_type(argument)\\ if isinstance(argument, int) else\\ list.__new__(cls, argument) def __int__(self: bits) ->", ">>> all(results) True \"\"\" return bits([x.not_() for x in self]) def __invert__(self: bits)", "isinstance(a, str) else a # pylint: disable=W0123 try: # Construct the circuit and", "output(input(x) | input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.or_,", "self, other) def nor_(self, other): \"\"\" >>> results = [] >>> for (x,", "Overloaded operator: rotation and shift operations. >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0]))", "... b = output(input(x).nimp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "try: # Construct the circuit and add it to the function as an", "input_two) and isinstance(b2, input_two): return input_two elif isinstance(b1, (input_one, input_two)) and b2 is", "y) in zip(self, other)]) def nor_(self: bits, other: bits) -> bits: \"\"\" >>>", "it returns an output. if bit._hook_operation is not None: r = bit._hook_operation(o, v,", "else gate_ def __int__(self): return self.value def not_(self): \"\"\" >>> results = []", "bits, other) -> Sequence[bits]: \"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>>", "inputs([y, y, y])) ... zs = outputs(xs < ys) ... ns = [int(z)", "return bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity]) else: # Shift return bits([constant(0)]*other) ** bits(self[0:len(self)-other]) def __lshift__(self:", "x, x]), inputs([y, y, y])) ... zs = outputs(xs | ys) ... ns", "1, 1, 1, 1, 1, 1] >>> bit.circuit(circuit()) >>> [b.value for b in", "def nimp(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "logic circuits and synthesizing circuits from those definitions. \"\"\" from __future__ import annotations", "inputs([y, y, y])) ... zs = outputs(xs.xor_(ys)) ... ns = [int(z) for z", "y])) ... zs = outputs(xs.nor_(ys)) ... ns = [int(z) for z in zs]", "= output(input(x).nif(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nif_, self,", "[b0.value, b1.value, b2.value] [0, 1, 0] \"\"\" def __init__(self: bit, b: bit): #", "\"\"\" return bits([x.nimp_(y) for (x, y) in zip(self, other)]) def nimp_(self: bits, other:", "definitions. \"\"\" from __future__ import annotations from typing import Sequence import doctest from", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "class input_one(input): \"\"\"Bit that is designated as a variable input from one source.\"\"\"", "in range(8)]) ]) @staticmethod def from_bytes(bytes_, constructor=bit) -> bits: \"\"\" >>> bit.circuit(circuit()) >>>", "gate(operation, igs): return bit._circuit.gate(operation, igs) def __init__(self, value, gate_=None): self.value = value self.gate", "xy[1]) >>> xys = [bits([x, y]) for x in (0, 1) for y", "all(results) True \"\"\" return bits([x.nand_(y) for (x, y) in zip(self, other)]) def __rshift__(self:", "output or whether there are others dependent on it. if len(b.gate.outputs) > 0:", "True \"\"\" return self.nif(other) def xor(self, other): \"\"\" >>> results = [] >>>", "b = ~(~b) # Preserve the bit by copying it to a new", ">>> all(results) True \"\"\" return bit.operation(op.imp_, self, other) def nand(self, other): \"\"\" >>>", "(1 - y)) >>> xys = [bits([x, y]) for x in (0, 1)", "also used to keep track of relationships between operators and to represent the", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs %", "other) def xnor(self, other): \"\"\" >>> results = [] >>> for (x, y)", "[a.gate for a in args])) ... return hook >>> bit.hook_operation(make_hook(bit)) >>> bit.circuit(circuit()) >>>", "outputs(xs == ys) ... ns = [int(z) for z in zs] ... c", "type_in = lambda a: input(0) if a is bit else inputs([0] * a)", "*args): # Ensure second argument is a `bit`. args = list(args) if len(args)", "r = bit._hook_operation(o, v, *args) if r is not None: return r return", "x in self]) def __invert__(self: bits) -> bits: \"\"\" >>> results = []", "def nif_(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "True \"\"\" return bits([x.xor_(y) for (x, y) in zip(self, other)]) def xor_(self: bits,", "def or_(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "self, other) def __rxor__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 1 ^", "return bit \"\"\" return bit @staticmethod def gate(operation, igs): return bit._circuit.gate(operation, igs) def", "in xys] [[1], [0], [0], [1]] >>> @synthesize ... def conjunction(xy: bits(2)) ->", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) <= input(y)) ... results.append(int(b) ==", "b in bits.from_bytes(bytes([11, 0]))] [0, 0, 0, 0, 1, 0, 1, 1, 0,", "outputs(xs | ys) ... ns = [int(z) for z in zs] ... c", "y])) ... zs = outputs(xs.nimp(ys)) ... ns = [int(z) for z in zs]", "\"\"\" return bit.operation(op.imp_, self, other) def imp_(self, other): \"\"\" >>> results = []", "input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_, self, other)", "abstract bits. \"\"\" @staticmethod def from_byte(byte_: int, constructor=bit) -> bits: return bits([ constructor(bit_)", ">>> all(results) True \"\"\" return bit.operation(op.nif_, self, other) def nif_(self, other): \"\"\" >>>", ">>> [b.value for b in bits.from_bytes(bytes([255]))] [1, 1, 1, 1, 1, 1, 1,", "b.value 0 \"\"\" return self & (constant(other) if isinstance(other, int) else other) def", "all(results) True \"\"\" return self.nif(other) def xor(self, other): \"\"\" >>> results = []", "results = [] >>> for (x, y) in [(0, 0), (0, 1), (1,", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) ^ input(y)) ... results.append(int(b)", "len(b.gate.outputs) > 0: b = ~(~b) # Preserve the bit by copying it", "y])) ... zs = outputs(xs.nif_(ys)) ... ns = [int(z) for z in zs]", "y])) >>> all(results) True \"\"\" return bits([x.xor_(y) for (x, y) in zip(self, other)])", "x]), inputs([y, y, y])) ... zs = outputs(xs.if_(ys)) ... ns = [int(z) for", "bits) -> bits: \"\"\" >>> results = [] >>> for x in [0,", "not None: r = bit._hook_operation(o, v, *args) if r is not None: return", "nor(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "bs >> {3} >>> [b.value for b in bs] [1, 1, 1, 0,", "-> bits: \"\"\" >>> bit.circuit(circuit()) >>> xs = bits.zeros(3) >>> ys = outputs(xs.not_())", "self, other) def __or__(self, other): \"\"\" >>> results = [] >>> for (x,", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) > input(y)) ... results.append(int(b) ==", "zs = outputs(xs | ys) ... ns = [int(z) for z in zs]", "as a variable input from a second source.\"\"\" class output(bit): \"\"\" Bit that", "(x & y) | ((1 - x) & (1 - y)) >>> xys", "from a function that takes only `bit` and/or `bits` objects as its arguments", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.xnor_(y) for (x, y)", "\"\"\" return bit.operation(op.nimp_, self, other) def nimp_(self, other): \"\"\" >>> results = []", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nimp(ys)) ...", "in (0, 1) for y in (0, 1)] >>> [conjunction.circuit.evaluate(xy) for xy in", "zs = outputs(xs.xnor_(ys)) ... ns = [int(z) for z in zs] ... c", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nif_, self, other) def nif_(self, other): \"\"\"", "return bit.operation(op.nand_, self, other) class constant(bit): \"\"\"Bit that is designated as a constant", "for b in bs] [0, 0, 0, 1, 1, 1, 1, 0] >>>", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) ==", "ys] [1, 1, 1] \"\"\" return bits([constant(0)]*n) def __new__(cls, argument = None) ->", "in zip(self, other)]) def __le__(self: bits, other: bits) -> bits: \"\"\" >>> results", "def circuit(circuit_=None): if circuit_ is not None: bit._circuit = circuit_ return None else:", "output(input(x).imp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_, self, other)", "** bits(self[0:len(self)-quantity]) else: # Shift return bits([constant(0)]*other) ** bits(self[0:len(self)-other]) def __lshift__(self: bits, other)", "y, y])) ... zs = outputs(xs.nimp_(ys)) ... ns = [int(z) for z in", "\"\"\" return bits([x.xor_(y) for (x, y) in zip(self, other)]) def or_(self: bits, other:", "-> bits: \"\"\" >>> results = [] >>> for x in [0, 1]:", "is bit else inputs([0] * a) type_out = lambda a: output if a", "result of the operation on the arguments. v = o(*[a.value for a in", "isinstance(other, int) else other) def nor(self, other): \"\"\" >>> results = [] >>>", "return bits([constant(0)]*n) def __new__(cls, argument = None) -> bits: \"\"\" Return bits object", "and to represent the wires within a circuit built up out of those", "c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nif_(y) for", "# Functions for determining types/signature from # the type annotation of the decorated", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) >= input(y))", "for x in [0, 1]: ... bit.circuit(circuit()) ... b = output(input(x).not_()) ... results.append(int(b)", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xor(ys)) ... ns", "gate_ is None else gate_ def __int__(self): return self.value def not_(self): \"\"\" >>>", "\"\"\" return bit.operation(op.or_, self, other) def __ror__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b", "y) in zip(self, other)]) def imp(self: bits, other: bits) -> bits: \"\"\" >>>", "outputs(xs.xor_(ys)) ... ns = [int(z) for z in zs] ... c = bit.circuit()", "{3} >>> [b.value for b in bs] [1, 1, 1, 0, 0, 0,", "(x, y) in zip(self, other)]) def nif(self: bits, other: bits) -> bits: \"\"\"", "For forward-compatibility with PEP 563. eval_ = lambda a: eval(a) if isinstance(a, str)", "... b = output(input(x).nor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "a value, but it is also used to keep track of relationships between", "__invert__(self: bits) -> bits: \"\"\" >>> results = [] >>> for x in", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).and_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "the decorated function. type_in = lambda a: input(0) if a is bit else", "1') def and_(self, other): \"\"\" >>> results = [] >>> for (x, y)", "\"\"\" Class for representing a vector of abstract bits. \"\"\" @staticmethod def from_byte(byte_:", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) |", "= outputs(xs & ys) ... ns = [int(z) for z in zs] ...", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "is not currently in use. \"\"\" if isinstance(b1, input_one) and isinstance(b2, input_one): return", "if len(b.gate.outputs) > 0: b = ~(~b) # Preserve the bit by copying", "[0, 1]: ... bit.circuit(circuit()) ... b = output(1 - input(x)) ... results.append(int(b) ==", ">>> all(results) True \"\"\" return bit.operation(op.and_, self, other) def __and__(self, other): \"\"\" >>>", "x]), inputs([y, y, y])) ... zs = outputs(xs ^ ys) ... ns =", "y) in zip(self, other)]) def nand_(self: bits, other) -> bits: \"\"\" >>> results", "else args[1] # Compute the value of the result of the operation on", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) == input(y))", "None # Return the original function. return f if __name__ == \"__main__\": doctest.testmod()", "bits(list): \"\"\" Class for representing a vector of abstract bits. \"\"\" @staticmethod def", "bits([x.imp_(y) for (x, y) in zip(self, other)]) def imp_(self: bits, other: bits) ->", "all(results) True \"\"\" return bits([x.xnor_(y) for (x, y) in zip(self, other)]) def xnor_(self:", "all(results) True \"\"\" return bit.operation(op.and_, self, other) def __rand__(self, other): \"\"\" >>> bit.circuit(circuit())", "... zs = outputs(xs >= ys) ... ns = [int(z) for z in", "output(input(1).and_(input(1))) >>> b.value == bit.circuit().evaluate([1,1])[0] True >>> def make_hook(bit_): ... def hook(o, v,", "the result of the operation on the arguments. v = o(*[a.value for a", "bit._circuit = circuit_ return None else: bit._circuit.prune_and_topological_sort_stable() return bit._circuit @staticmethod def hook_operation(hook=None): bit._hook_operation", "outputs(xs.nor(ys)) ... ns = [int(z) for z in zs] ... c = bit.circuit()", "(xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.if_(ys))", "and synthesizing circuits from those definitions. \"\"\" from __future__ import annotations from typing", "y])) ... zs = outputs(xs.xor_(ys)) ... ns = [int(z) for z in zs]", "if_(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "in zip(self, other)]) def nimp(self: bits, other: bits) -> bits: \"\"\" >>> results", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nand_(ys)) ... ns", "def xor_(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "import doctest from parts import parts from circuit import op, gate, circuit, signature", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_, self, other) def xor_(self, other): \"\"\"", "bits([x.nimp_(y) for (x, y) in zip(self, other)]) def nif(self: bits, other: bits) ->", "value: int): self.value = value self.gate = bit._circuit.gate(op.id_, is_input=True) class input_one(input): \"\"\"Bit that", "raise RuntimeError('automated circuit synthesis failed') from None # Return the original function. return", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nimp_, self, other) def", "... b = output(input(x) > input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs == ys) ...", "outputs(xs.nand(ys)) ... ns = [int(z) for z in zs] ... c = bit.circuit()", "... bit.circuit(circuit()) ... b = output(input(x) >= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", ">>> [b.value for b in bs] [1, 0, 0, 0, 0, 0, 0,", "subtract a bit from the integer 1 \"\"\" if other == 1: return", "bs = bs >> {3} >>> [b.value for b in bs] [1, 1,", "eval_ = lambda a: eval(a) if isinstance(a, str) else a # pylint: disable=W0123", "True \"\"\" return bit.operation(op.and_, self, other) def __and__(self, other): \"\"\" >>> results =", "y) in [(0, 0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ...", "... zs = outputs(xs <= ys) ... ns = [int(z) for z in", "__xor__(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "a) in f.__annotations__.items() if k != 'return' } type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit = bit.circuit() except:", "designated an output. >>> bit.circuit(circuit()) >>> b0 = output(input(1).not_()) >>> b1 = output(b0.not_())", "zip(self, other)]) def xnor(self: bits, other: bits) -> bits: \"\"\" >>> results =", "all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def __eq__(self, other): \"\"\" >>> results", "constructor=bit) -> bits: return bits([ constructor(bit_) for bit_ in reversed([(byte_>>i)%2 for i in", "bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / [1, 3,", "output(input(x).xnor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other)", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_, self, other) def __xor__(self,", ">>> @synthesize ... def equal(x, y): ... return x & y Traceback (most", "# Return output from hook if it exists and if # it returns", "bit.operation(op.nimp_, self, other) def nimp_(self, other): \"\"\" >>> results = [] >>> for", "y])) ... zs = outputs(xs.xnor_(ys)) ... ns = [int(z) for z in zs]", "y])) ... zs = outputs(xs.nif(ys)) ... ns = [int(z) for z in zs]", "... def equal(x, y): ... return x & y Traceback (most recent call", "bit by copying it to a new wire. self.value = b.value self.gate =", "\"\"\" return bit.operation(op.nand_, self, other) def __matmul__(self, other): \"\"\" >>> results = []", "bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / [1, 3, 4]) >>> [[b.value for", "b = output(input(x) @ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "y, y])) >>> all(results) True \"\"\" return bits([x.nor_(y) for (x, y) in zip(self,", "= list(bs / {2}) >>> [[b.value for b in bs] for bs in", "\"\"\" return bit.operation(op.nor_, self, other) def __mod__(self, other): \"\"\" >>> results = []", "in zip(self, other)]) def imp_(self: bits, other: bits) -> bits: \"\"\" >>> results", "return bits(map(input, l)) def outputs(l): return bits(map(output, l)) def synthesize(f): \"\"\" Decorator for", "r is not None: return r return bit.constructor(*args)(v, bit.gate(o, [a.gate for a in", ">>> all(results) True \"\"\" return bit.operation(op.xor_, self, other) def __xor__(self, other): \"\"\" >>>", "(xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nor_(ys))", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self, other) def", "constant(0) >>> b.value 1 \"\"\" return self | (constant(other) if isinstance(other, int) else", "True \"\"\" return bit.operation(op.nand_, self, other) class constant(bit): \"\"\"Bit that is designated as", "hook(o, v, *args): ... return bit_.constructor(*args)(v, bit_.gate(o, [a.gate for a in args])) ...", "\"\"\"Bit that is designated as a variable input.\"\"\" def __init__(self: bit, value: int):", "def nor(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "value self.gate = bit._circuit.gate() if gate_ is None else gate_ def __int__(self): return", "all(results) True \"\"\" return bit.operation(op.nor_, self, other) def nor_(self, other): \"\"\" >>> results", "y])) ... zs = outputs(xs.nimp_(ys)) ... ns = [int(z) for z in zs]", "__ge__(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "y])) >>> all(results) True \"\"\" return bits([x.and_(y) for (x, y) in zip(self, other)])", "[1]] >>> @synthesize ... def conjunction(xy: bits(2)) -> bits(2): ... return (xy[0], xy[0]", "input_two elif isinstance(b1, (input_one, input_two)) and b2 is None: return type(b1) else: return", ">>> all(results) True >>> bit.circuit(circuit()) >>> 2 - input(0) Traceback (most recent call", "y) in zip(self, other)]) def __xor__(self: bits, other: bits) -> bits: \"\"\" >>>", "def __xor__(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def if_(self, other): \"\"\"", "outputs(xs.not_()) >>> int(ys) 7 \"\"\" return sum(int(b)*(2**i) for (i, b) in zip(range(len(self)), reversed(self)))", "bits([constant(0)]*n) def __new__(cls, argument = None) -> bits: \"\"\" Return bits object given", "\"\"\" return bit.operation(op.nif_, self, other) def nif_(self, other): \"\"\" >>> results = []", "input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.if_, self, other)", "= outputs(xs.xnor_(ys)) ... ns = [int(z) for z in zs] ... c =", "list) and len(other) > 0 and isinstance(other[0], int): return map(bits, parts(self, length=other)) #", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nimp_(ys)) ...", "x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nif_(y) for (x,", "... b = output(input(x).or_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "1], [1, 1], [0, 0], [0, 0]] >>> bit.circuit(circuit()) >>> bs = bits(map(bit,", "== c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.xnor_(y)", "... ns = [int(y) for y in ys] ... c = bit.circuit() ...", "all(results) True \"\"\" return bits([x.imp_(y) for (x, y) in zip(self, other)]) def nand(self:", "isinstance(other, int) else other) def or_(self, other): \"\"\" >>> results = [] >>>", "bits([x.xor_(y) for (x, y) in zip(self, other)]) def or_(self: bits, other: bits) ->", "else: return bit \"\"\" return bit @staticmethod def gate(operation, igs): return bit._circuit.gate(operation, igs)", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "ns = [int(y) for y in ys] ... c = bit.circuit() ... results.append(ns", "x]), inputs([y, y, y])) ... zs = outputs(xs.and_(ys)) ... ns = [int(z) for", "a is bit else outputs # For forward-compatibility with PEP 563. eval_ =", ">>> bit.circuit(circuit()) >>> b = output(input(0).and_(input(0))) >>> b.value == bit.circuit().evaluate([0,0])[0] True \"\"\" _circuit", "def nand(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "__mod__(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "return bit.operation(op.and_, self, other) def __rand__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b =", "-> bits: \"\"\" >>> bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([255]))] [1, 1,", "x, x]), inputs([y, y, y])) ... zs = outputs(xs % ys) ... ns", "1, 0, 0, 0, 0, 0, 0, 0, 0] \"\"\" return bits([ bit_", "@staticmethod def operation(o, *args): # Ensure second argument is a `bit`. args =", "1, 1], [0, 0, 0, 0]) >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0]))", "__eq__(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "= output(1 - input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True >>> bit.circuit(circuit())", "parts from circuit import op, gate, circuit, signature class bit(): \"\"\" Class for", "xs = inputs([x, x, x]) ... ys = outputs(xs.not_()) ... ns = [int(y)", "in zip(self, other)]) def __gt__(self: bits, other: bits) -> bits: \"\"\" >>> results", "bs >> 3 >>> [b.value for b in bs] [0, 0, 0, 1,", "(0, 1)] >>> [equal.circuit.evaluate(xy) for xy in xys] [[1], [0], [0], [1]] >>>", "a `bit`. args = list(args) if len(args) == 2: args[1] = constant(args[1]) if", "[b.value for b in bs] [0, 0, 0, 1, 1, 1, 1, 0]", "for a in args])) ... return hook >>> bit.hook_operation(make_hook(bit)) >>> bit.circuit(circuit()) >>> b", "b = output(input(x).if_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.if_,", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif(input(y)))", ">>> all(results) True \"\"\" return bits([x.nimp_(y) for (x, y) in zip(self, other)]) def", "[1,1,1,1,0,0,0,0])) >>> bss = list(bs / [1, 3, 4]) >>> [[b.value for b", "`bits` objects as its arguments and returns an output of type `bit` or", ">>> bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([11, 0]))] [0, 0, 0, 0,", "map(bits, parts(self, other)) # Number of parts is `other`. def __add__(self: bits, other)", "of lengths. elif isinstance(other, set) and len(other) == 1 and isinstance(list(other)[0], int): return", "y) in zip(self, other)]) def __mod__(self, other) -> bits: \"\"\" >>> results =", "(xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nimp(ys))", "[[b.value for b in bs] for bs in bss] [[1, 1], [1, 1],", "1] \"\"\" if isinstance(other, set) and isinstance(list(other)[0], int): # Rotation. quantity = list(other)[0]", "inputs([0] * a) type_out = lambda a: output if a is bit else", "all(results) True \"\"\" return bit.operation(op.xor_, self, other) def __rxor__(self, other): \"\"\" >>> bit.circuit(circuit())", ">>> b = output(input(1).and_(input(1))) >>> b.value == bit.circuit().evaluate([1,1])[0] True >>> def make_hook(bit_): ...", "/ 2) >>> ([b.value for b in bss[0]], [b.value for b in bss[1]])", "bss] [[1], [1, 1, 1], [0, 0, 0, 0]] \"\"\" if isinstance(other, list)", "an attribute. bit.circuit(circuit()) args_in = { k: type_in(eval_(a)) for (k, a) in f.__annotations__.items()", "k: type_in(eval_(a)) for (k, a) in f.__annotations__.items() if k != 'return' } type_out(eval_(f.__annotations__['return']))(f(**args_in))", "inputs([y, y, y])) ... zs = outputs(xs.nif(ys)) ... ns = [int(z) for z", "parts is `other`. def __add__(self: bits, other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\"", "zs = outputs(xs <= ys) ... ns = [int(z) for z in zs]", "b = output(1 - input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True >>>", ">>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def if_(self, other): \"\"\" >>>", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs <", ">= ys) ... ns = [int(z) for z in zs] ... c =", "in zip(self, other)]) def __lt__(self: bits, other: bits) -> bits: \"\"\" >>> results", "logic circuits. Embedded domain-specific combinator library for assembling abstract definitions of logic circuits", "... zs = outputs(xs.xor(ys)) ... ns = [int(z) for z in zs] ...", "\"\"\" Overloaded operator: rotation and shift operations. >>> bit.circuit(circuit()) >>> bs = bits(map(bit,", "an input or output type of a function decorated for automated synthesis. \"\"\"", "self.value = b.value self.gate = bit._circuit.gate(op.id_, [b.gate], is_output=True) class bits_type(int): # pylint: disable=R0903", "isinstance(other, set) and isinstance(list(other)[0], int): # Rotation. quantity = list(other)[0] return bits(self[len(self)-quantity:]) **", "inputs([y, y, y])) ... zs = outputs(xs.nif_(ys)) ... ns = [int(z) for z", "(x, y) in zip(self, other)]) def imp(self: bits, other: bits) -> bits: \"\"\"", "zip(self, other)]) def xor(self: bits, other: bits) -> bits: \"\"\" >>> results =", "Functions for determining types/signature from # the type annotation of the decorated function.", "if bit._hook_operation is not None: r = bit._hook_operation(o, v, *args) if r is", "return bits([x.if_(y) for (x, y) in zip(self, other)]) def imp(self: bits, other: bits)", "True \"\"\" return bits([x.nimp_(y) for (x, y) in zip(self, other)]) def nif(self: bits,", "b.value == bit.circuit().evaluate([1,1])[0] True >>> def make_hook(bit_): ... def hook(o, v, *args): ...", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nor_(ys)) ...", "bits(map(output, l)) def synthesize(f): \"\"\" Decorator for automatically synthesizing a circuit from a", "other def constants(l): return bits(map(constant, l)) def inputs(l): return bits(map(input, l)) def outputs(l):", "b = output(input(x).xor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_,", "True \"\"\" return bits([x.if_(y) for (x, y) in zip(self, other)]) def __ge__(self: bits,", "nand_(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "True \"\"\" return bit.operation(op.xnor_, self, other) def xnor_(self, other): \"\"\" >>> results =", ">>> xys = [bits([x, y]) for x in (0, 1) for y in", "def __pow__(self: bits, other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\" return self +", "__lshift__(self: bits, other) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0]))", "bit.operation(op.nimp_, self, other) def __gt__(self, other): \"\"\" >>> results = [] >>> for", ">>> all(results) True \"\"\" return bits([x.if_(y) for (x, y) in zip(self, other)]) def", "def not_(self: bits) -> bits: \"\"\" >>> results = [] >>> for x", "a circuit from a function that takes only `bit` and/or `bits` objects as", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs > ys)", "(xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.or_(ys))", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.imp_(ys)) ... ns =", "(x, y) in zip(self, other)]) def __or__(self: bits, other: bits) -> bits: \"\"\"", "y])) ... zs = outputs(xs > ys) ... ns = [int(z) for z", "bit.circuit() ... results.append(ns == c.evaluate([x, x, x])) >>> all(results) True \"\"\" return bits([x.not_()", "self]) def and_(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "elif isinstance(b1, (input_one, input_two)) and b2 is None: return type(b1) else: return bit", "... zs = outputs(xs.nor_(ys)) ... ns = [int(z) for z in zs] ...", "k != 'return' } type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit = bit.circuit() except: raise RuntimeError('automated circuit synthesis", "[[1], [0], [0], [1]] >>> @synthesize ... def conjunction(xy: bits(2)) -> bits(2): ...", "bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs << 3 >>> [b.value for b in", "^ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_, self,", ">>> all(results) True \"\"\" return bit.operation(op.nor_, self, other) def nor_(self, other): \"\"\" >>>", "\"\"\" return bits([x.nif_(y) for (x, y) in zip(self, other)]) def __lt__(self: bits, other:", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.if_, self, other) def __ge__(self, other):", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "inference code below is not currently in use. \"\"\" if isinstance(b1, input_one) and", "isinstance(other, int) else other) def nimp(self, other): \"\"\" >>> results = [] >>>", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nimp(ys)) ... ns", "... zs = outputs(xs == ys) ... ns = [int(z) for z in", "is None else gate_ def __int__(self): return self.value def not_(self): \"\"\" >>> results", "| ((1 - x) & (1 - y)) >>> xys = [bits([x, y])", "x in self]) def and_(self: bits, other: bits) -> bits: \"\"\" >>> results", "0, 0, 0] \"\"\" return bits(self[other:]) ** bits([constant(0) for _ in range(other)]) def", "output. >>> bit.circuit(circuit()) >>> b0 = output(input(1).not_()) >>> b1 = output(b0.not_()) >>> b2", "y) in zip(self, other)]) def nor(self: bits, other: bits) -> bits: \"\"\" >>>", "if other == 1: return bit.operation(op.not_, self) raise ValueError('can only subtract a bit", "True \"\"\" return bit.operation(op.imp_, self, other) def __le__(self, other): \"\"\" >>> results =", "xor_(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit = bit.circuit() except: raise RuntimeError('automated circuit synthesis failed') from None #", "xy in xys] [[0, 0], [0, 0], [1, 0], [1, 1]] >>> @synthesize", ">>> [[b.value for b in bs] for bs in bss] [[1], [1, 1,", "_circuit = None _hook_operation = None @staticmethod def circuit(circuit_=None): if circuit_ is not", ">>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / 2)", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) >= input(y)) ...", "in zip(self, other)]) def xnor(self: bits, other: bits) -> bits: \"\"\" >>> results", "return x & y Traceback (most recent call last): ... RuntimeError: automated circuit", "`bit` and/or `bits` objects as its arguments and returns an output of type", "[(0, 0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b =", ">>> all(results) True \"\"\" return bits([x.not_() for x in self]) def and_(self: bits,", "... bit.circuit(circuit()) ... b = output(1 - input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>>", "[0,0,0,0,1,1,1,1])) >>> bs = bs >> {3} >>> [b.value for b in bs]", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor(input(y))) ... results.append(int(b) ==", "(x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit())", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp(input(y))) ...", "y])) >>> all(results) True \"\"\" return bits([x.nor_(y) for (x, y) in zip(self, other)])", "it to the function as an attribute. bit.circuit(circuit()) args_in = { k: type_in(eval_(a))", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xor_(ys)) ...", "outputs(xs.or_(ys)) ... ns = [int(z) for z in zs] ... c = bit.circuit()", "synthesis failed \"\"\" # Functions for determining types/signature from # the type annotation", ">>> bit.circuit(circuit()) >>> xs = bits.zeros(3) >>> ys = outputs(xs.not_()) >>> [y.value for", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) ^", "bits([x.imp_(y) for (x, y) in zip(self, other)]) def __le__(self: bits, other: bits) ->", "bits([x.nand_(y) for (x, y) in zip(self, other)]) def nand_(self: bits, other) -> bits:", "l)) def synthesize(f): \"\"\" Decorator for automatically synthesizing a circuit from a function", "isinstance(b1, (input_one, input_two)) and b2 is None: return type(b1) else: return bit \"\"\"", "def __int__(self): return self.value def not_(self): \"\"\" >>> results = [] >>> for", "[1,1,1,1,0,0,0,0])) >>> bs = bs >> 3 >>> [b.value for b in bs]", "0, 0, 0, 0] \"\"\" return bits(self[other:]) ** bits([constant(0) for _ in range(other)])", "[y.value for y in ys] [1, 1, 1] \"\"\" return bits([constant(0)]*n) def __new__(cls,", "... bit.circuit(circuit()) ... xs = inputs([x, x, x]) ... ys = outputs(xs.not_()) ...", "b = 0 & constant(1) >>> b.value 0 \"\"\" return self & (constant(other)", "library for assembling abstract definitions of logic circuits and synthesizing circuits from those", "[[b.value for b in bs] for bs in bss] [[1], [1, 1, 1],", "input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other)", "... bit.circuit(circuit()) ... b = output(input(x).xnor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "def not_(self): \"\"\" >>> results = [] >>> for x in [0, 1]:", "xnor(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "True \"\"\" return bits([x.xor_(y) for (x, y) in zip(self, other)]) def or_(self: bits,", "rotation and shift operations. >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs", "bit.operation(op.imp_, self, other) def nand(self, other): \"\"\" >>> results = [] >>> for", "\"\"\"Concatenation of bit vectors.\"\"\" result = list(self) result.extend(list(other)) return bits(result) def __pow__(self: bits,", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs & ys)", "True \"\"\" return bit.operation(op.xnor_, self, other) def if_(self, other): \"\"\" >>> results =", "bits([ constructor(bit_) for bit_ in reversed([(byte_>>i)%2 for i in range(8)]) ]) @staticmethod def", "inputs([y, y, y])) ... zs = outputs(xs > ys) ... ns = [int(z)", "... zs = outputs(xs < ys) ... ns = [int(z) for z in", "imp(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "a variable input from a second source.\"\"\" class output(bit): \"\"\" Bit that is", "\"\"\" return bits([x.nor_(y) for (x, y) in zip(self, other)]) def xnor(self: bits, other:", "bit.circuit(circuit()) ... b = output(input(x).nand_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "return bits([x.xor_(y) for (x, y) in zip(self, other)]) def or_(self: bits, other: bits)", "* a) type_out = lambda a: output if a is bit else outputs", "function decorated for automated synthesis. \"\"\" class bits(list): \"\"\" Class for representing a", "circuit import op, gate, circuit, signature class bit(): \"\"\" Class for representing an", "b = output(input(x).nif(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nif_,", "(len(self)//list(other)[0]) # Parts of length `other`. else: return map(bits, parts(self, other)) # Number", "a constant input.\"\"\" class input(bit): \"\"\"Bit that is designated as a variable input.\"\"\"", "for xy in xys] [[1], [0], [0], [1]] >>> @synthesize ... def conjunction(xy:", "def __init__(self, value, gate_=None): self.value = value self.gate = bit._circuit.gate() if gate_ is", "bits([x.xnor_(y) for (x, y) in zip(self, other)]) def __eq__(self: bits, other: bits) ->", "== bit.circuit().evaluate([1,1])[0] True >>> def make_hook(bit_): ... def hook(o, v, *args): ... return", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) @ input(y))", "= outputs(xs.or_(ys)) ... ns = [int(z) for z in zs] ... c =", "for representing an input or output type of a function decorated for automated", "bit.circuit(circuit()) ... b = output(input(x) @ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "up out of those operators. >>> bit.hook_operation(lambda o, v, *args: None) >>> bit.circuit(circuit())", "for (x, y) in zip(self, other)]) def __lt__(self: bits, other: bits) -> bits:", "-> bits: \"\"\"Concatenation of bit vectors.\"\"\" result = list(self) result.extend(list(other)) return bits(result) def", "output if a is bit else outputs # For forward-compatibility with PEP 563.", "in [0, 1]: ... bit.circuit(circuit()) ... b = output(~input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0])", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_, self, other) def", "y])) >>> all(results) True \"\"\" return bits([x.or_(y) for (x, y) in zip(self, other)])", ">>> all(results) True \"\"\" return bits([x.nor_(y) for (x, y) in zip(self, other)]) def", "in bss] [[1, 1], [1, 1], [0, 0], [0, 0]] >>> bit.circuit(circuit()) >>>", "inputs([y, y, y])) ... zs = outputs(xs <= ys) ... ns = [int(z)", "bits, other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\" return self + other def", "to the function as an attribute. bit.circuit(circuit()) args_in = { k: type_in(eval_(a)) for", "bit.circuit(circuit()) ... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs", "other)]) def __lt__(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "True \"\"\" return bits([x.nimp_(y) for (x, y) in zip(self, other)]) def __gt__(self: bits,", "True \"\"\" return bits([x.or_(y) for (x, y) in zip(self, other)]) def nor(self: bits,", "__xor__(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "- x) & (1 - y)) >>> xys = [bits([x, y]) for x", "0, 0, 1, 1, 1, 1, 0] >>> bit.circuit(circuit()) >>> bs = bits(map(bit,", ">>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / 2) >>> ([b.value", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) | input(y))", "for (x, y) in zip(self, other)]) def __eq__(self: bits, other: bits) -> bits:", "x in (0, 1) for y in (0, 1)] >>> [conjunction.circuit.evaluate(xy) for xy", "self, other) def imp_(self, other): \"\"\" >>> results = [] >>> for (x,", "else outputs # For forward-compatibility with PEP 563. eval_ = lambda a: eval(a)", "y, y])) ... zs = outputs(xs < ys) ... ns = [int(z) for", "from_byte(byte_: int, constructor=bit) -> bits: return bits([ constructor(bit_) for bit_ in reversed([(byte_>>i)%2 for", "2) >>> ([b.value for b in bss[0]], [b.value for b in bss[1]]) ([1,", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.and_, self, other) def __and__(self, other): \"\"\"", "inputs([y, y, y])) ... zs = outputs(xs.nimp_(ys)) ... ns = [int(z) for z", "all(results) True \"\"\" return bits([x.if_(y) for (x, y) in zip(self, other)]) def imp(self:", "b in bs] [1, 0, 0, 0, 0, 0, 0, 0] \"\"\" return", "for bit_ in reversed([(byte_>>i)%2 for i in range(8)]) ]) @staticmethod def from_bytes(bytes_, constructor=bit)", "[b.value for b in bs] [1, 1, 1, 0, 0, 0, 0, 1]", "a circuit built up out of those operators. >>> bit.hook_operation(lambda o, v, *args:", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor_(input(y))) ... results.append(int(b)", "__init__(self, value, gate_=None): self.value = value self.gate = bit._circuit.gate() if gate_ is None", "if gate_ is None else gate_ def __int__(self): return self.value def not_(self): \"\"\"", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "bit.operation(op.not_, self) def __rsub__(self, other): \"\"\" >>> results = [] >>> for x", "bs in bss] [[1, 1], [1, 1], [0, 0], [0, 0]] >>> bit.circuit(circuit())", ">>> all(results) True \"\"\" return bits([x.and_(y) for (x, y) in zip(self, other)]) def", "x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nimp_(y) for (x,", "True \"\"\" return bits([x.xnor_(y) for (x, y) in zip(self, other)]) def if_(self: bits,", "reversed(self))) def not_(self: bits) -> bits: \"\"\" >>> results = [] >>> for", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.xor_(y) for (x, y)", "bit.circuit(circuit()) >>> b = 1 | constant(0) >>> b.value 1 \"\"\" return self", "b in bss[1]]) ([1, 1, 1, 1], [0, 0, 0, 0]) >>> bit.circuit(circuit())", "0]) >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs /", "= outputs(xs.nif(ys)) ... ns = [int(z) for z in zs] ... c =", "x]), inputs([y, y, y])) ... zs = outputs(xs.nor(ys)) ... ns = [int(z) for", "concretely as a value, but it is also used to keep track of", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.and_(ys)) ... ns =", "x]), inputs([y, y, y])) ... zs = outputs(xs < ys) ... ns =", "Shift return bits([constant(0)]*other) ** bits(self[0:len(self)-other]) def __lshift__(self: bits, other) -> bits: \"\"\" >>>", ">>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs << 3 >>> [b.value", "... return (xy[0], xy[0] & xy[1]) >>> xys = [bits([x, y]) for x", "represent the wires within a circuit built up out of those operators. >>>", "bit.circuit(circuit()) ... b = output(input(x).nor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.if_, self, other) def imp(self, other):", "bits([x.imp_(y) for (x, y) in zip(self, other)]) def nand(self: bits, other) -> bits:", "a: output if a is bit else outputs # For forward-compatibility with PEP", "Parts of length `other`. else: return map(bits, parts(self, other)) # Number of parts", "return bit.operation(op.nor_, self, other) def xnor(self, other): \"\"\" >>> results = [] >>>", "constructor=bit) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([255]))] [1,", "isinstance(args[1], int) else args[1] # Compute the value of the result of the", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) == input(y)) ... results.append(int(b)", "[0, 0, 0, 0]] \"\"\" if isinstance(other, list) and len(other) > 0 and", "other): \"\"\" >>> bit.circuit(circuit()) >>> b = 1 ^ constant(0) >>> b.value 1", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor(input(y))) ...", "bits([x.nimp_(y) for (x, y) in zip(self, other)]) def __gt__(self: bits, other: bits) ->", "== c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nif_(y)", "for y in ys] ... c = bit.circuit() ... results.append(ns == c.evaluate([x, x,", "returns an output of type `bit` or `bits`. >>> @synthesize ... def equal(x:", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "imp(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor(input(y))) ...", "inputs([y, y, y])) ... zs = outputs(xs.and_(ys)) ... ns = [int(z) for z", "bits([x.nimp_(y) for (x, y) in zip(self, other)]) def nimp_(self: bits, other: bits) ->", "y) in zip(self, other)]) def xor_(self: bits, other: bits) -> bits: \"\"\" >>>", "as a variable input from one source.\"\"\" class input_two(input): \"\"\"Bit that is designated", "... b = output(input(x) <= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "for y in (0, 1)] >>> [conjunction.circuit.evaluate(xy) for xy in xys] [[0, 0],", "== c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nand_(y)", "y])) ... zs = outputs(xs.and_(ys)) ... ns = [int(z) for z in zs]", "... zs = outputs(xs.nif_(ys)) ... ns = [int(z) for z in zs] ...", "lambda a: input(0) if a is bit else inputs([0] * a) type_out =", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nand(ys)) ... ns", "... bit.circuit(circuit()) ... b = output(input(x) | input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "(x, y) in zip(self, other)]) def __rshift__(self: bits, other) -> bits: \"\"\" Overloaded", "== bit.circuit().evaluate([x])[0]) >>> all(results) True >>> bit.circuit(circuit()) >>> 2 - input(0) Traceback (most", "return bits([x.if_(y) for (x, y) in zip(self, other)]) def __ge__(self: bits, other: bits)", "x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nor_(y) for (x,", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor(input(y))) ... results.append(int(b)", "list(bs / {2}) >>> [[b.value for b in bs] for bs in bss]", "other)]) def __gt__(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "all(results) True \"\"\" return bits([x.not_() for x in self]) def __invert__(self: bits) ->", "int) else\\ list.__new__(cls, argument) def __int__(self: bits) -> int: \"\"\" >>> bit.circuit(circuit()) >>>", "... bit.circuit(circuit()) ... b = output(input(x).nimp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "\"\"\" return bits([x.nimp_(y) for (x, y) in zip(self, other)]) def __gt__(self: bits, other:", "other)]) def __ge__(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "= output(input(x) ^ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "bit) -> bit: ... return (x & y) | ((1 - x) &", "inputs([y, y, y])) ... zs = outputs(xs ^ ys) ... ns = [int(z)", "results.append(ns == c.evaluate([x, x, x])) >>> all(results) True \"\"\" return bits([x.not_() for x", "circuit(circuit_=None): if circuit_ is not None: bit._circuit = circuit_ return None else: bit._circuit.prune_and_topological_sort_stable()", ">>> all(results) True \"\"\" return bit.operation(op.if_, self, other) def imp(self, other): \"\"\" >>>", "y) in zip(self, other)]) def xor(self: bits, other: bits) -> bits: \"\"\" >>>", "in zip(self, other)]) def __mod__(self, other) -> bits: \"\"\" >>> results = []", "all(results) True \"\"\" return bits([x.nif_(y) for (x, y) in zip(self, other)]) def __lt__(self:", "def __lt__(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "bit.circuit(circuit()) ... b = output(input(x).nor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "y, y])) ... zs = outputs(xs.imp(ys)) ... ns = [int(z) for z in", "\"\"\" return bits([x.xnor_(y) for (x, y) in zip(self, other)]) def if_(self: bits, other:", "self.nif(other) def xor(self, other): \"\"\" >>> results = [] >>> for (x, y)", "a new wire. self.value = b.value self.gate = bit._circuit.gate(op.id_, [b.gate], is_output=True) class bits_type(int):", "recent call last): ... RuntimeError: automated circuit synthesis failed \"\"\" # Functions for", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) <", "0, 0, 0, 0, 0, 0, 0] \"\"\" return bits([ bit_ for byte_", "x, x])) >>> all(results) True \"\"\" return bits([x.not_() for x in self]) def", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand_(input(y))) ...", "sum(int(b)*(2**i) for (i, b) in zip(range(len(self)), reversed(self))) def not_(self: bits) -> bits: \"\"\"", "& (1 - y)) >>> xys = [bits([x, y]) for x in (0,", "# Sequence of lengths. elif isinstance(other, set) and len(other) == 1 and isinstance(list(other)[0],", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).or_(input(y))) ... results.append(int(b)", "... zs = outputs(xs.nimp(ys)) ... ns = [int(z) for z in zs] ...", "= list(self) result.extend(list(other)) return bits(result) def __pow__(self: bits, other) -> bits: \"\"\"Concatenation of", "0, 0] \"\"\" return bits(self[other:]) ** bits([constant(0) for _ in range(other)]) def __truediv__(self:", "output(input(x) & input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.and_,", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.or_, self, other) def __or__(self, other):", "by copying it to a new wire. self.value = b.value self.gate = bit._circuit.gate(op.id_,", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... (xs, ys) =", "y, y])) ... zs = outputs(xs | ys) ... ns = [int(z) for", "^ ys) ... ns = [int(z) for z in zs] ... c =", "b.value self.gate = bit._circuit.gate(op.id_, [b.gate], is_output=True) class bits_type(int): # pylint: disable=R0903 \"\"\" Class", "other) def nor_(self, other): \"\"\" >>> results = [] >>> for (x, y)", "wire. self.value = b.value self.gate = bit._circuit.gate(op.id_, [b.gate], is_output=True) class bits_type(int): # pylint:", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nimp(ys)) ... ns =", "return bits([x.xnor_(y) for (x, y) in zip(self, other)]) def __eq__(self: bits, other: bits)", "1]: ... bit.circuit(circuit()) ... b = output(1 - input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0])", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) >= input(y)) ... results.append(int(b) ==", "... b = output(input(x) ^ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "return bits([x.nor_(y) for (x, y) in zip(self, other)]) def __mod__(self, other) -> bits:", "(most recent call last): ... RuntimeError: automated circuit synthesis failed \"\"\" # Functions", "hook @staticmethod def operation(o, *args): # Ensure second argument is a `bit`. args", "self, other) def nand_(self, other): \"\"\" >>> results = [] >>> for (x,", "... zs = outputs(xs ^ ys) ... ns = [int(z) for z in", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).if_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "__pow__(self: bits, other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\" return self + other", "return bit.operation(op.not_, self) def __invert__(self): \"\"\" >>> results = [] >>> for x", "is designated as a variable input from a second source.\"\"\" class output(bit): \"\"\"", "\"\"\" return self | (constant(other) if isinstance(other, int) else other) def nor(self, other):", "-> bits(2): ... return (xy[0], xy[0] & xy[1]) >>> xys = [bits([x, y])", "o(*[a.value for a in args]) # Return output from hook if it exists", "return bit.operation(op.if_, self, other) def imp(self, other): \"\"\" >>> results = [] >>>", "i in range(8)]) ]) @staticmethod def from_bytes(bytes_, constructor=bit) -> bits: \"\"\" >>> bit.circuit(circuit())", "= list(bs / 2) >>> ([b.value for b in bss[0]], [b.value for b", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).or_(input(y))) ...", "y) in zip(self, other)]) def nif_(self: bits, other: bits) -> bits: \"\"\" >>>", ">>> all(results) True \"\"\" return bits([x.xor_(y) for (x, y) in zip(self, other)]) def", "True \"\"\" return bit.operation(op.imp_, self, other) def nand(self, other): \"\"\" >>> results =", "bit @staticmethod def gate(operation, igs): return bit._circuit.gate(operation, igs) def __init__(self, value, gate_=None): self.value", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs ^", "self, other) def __ge__(self, other): \"\"\" >>> results = [] >>> for (x,", "in bs] for bs in bss] [[1, 1], [1, 1], [0, 0], [0,", "# Shift return bits([constant(0)]*other) ** bits(self[0:len(self)-other]) def __lshift__(self: bits, other) -> bits: \"\"\"", "zip(self, other)]) def nor_(self: bits, other: bits) -> bits: \"\"\" >>> results =", "inputs([y, y, y])) ... zs = outputs(xs >= ys) ... ns = [int(z)", "if isinstance(other, int) else other) def nor(self, other): \"\"\" >>> results = []", "operations. >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs >>", "int(ys) 7 \"\"\" return sum(int(b)*(2**i) for (i, b) in zip(range(len(self)), reversed(self))) def not_(self:", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "outputs(xs.xnor(ys)) ... ns = [int(z) for z in zs] ... c = bit.circuit()", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor_(input(y)))", "of the decorated function. type_in = lambda a: input(0) if a is bit", "... bit.circuit(circuit()) ... b = output(input(x).xnor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "\"\"\" return bit.operation(op.if_, self, other) def __ge__(self, other): \"\"\" >>> results = []", "and isinstance(b2, input_one): return input_one elif isinstance(b1, input_two) and isinstance(b2, input_two): return input_two", "bits: \"\"\" >>> results = [] >>> for (x, y) in [(0, 0),", ">>> all(results) True \"\"\" return self.nimp(other) def nif(self, other): \"\"\" >>> results =", "y) in zip(self, other)]) def xnor_(self: bits, other: bits) -> bits: \"\"\" >>>", "0, 0]] \"\"\" if isinstance(other, list) and len(other) > 0 and isinstance(other[0], int):", "in self]) def __invert__(self: bits) -> bits: \"\"\" >>> results = [] >>>", "disable=R0903 \"\"\" Class for representing an input or output type of a function", "Construct the circuit and add it to the function as an attribute. bit.circuit(circuit())", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs | ys) ...", "designated as a constant input.\"\"\" class input(bit): \"\"\"Bit that is designated as a", "= output(input(x).or_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.or_, self,", "in bytes_ for bit_ in bits.from_byte(byte_, constructor) ]) @staticmethod def zeros(n: int) ->", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "import parts from circuit import op, gate, circuit, signature class bit(): \"\"\" Class", "bit.operation(op.nor_, self, other) def __mod__(self, other): \"\"\" >>> results = [] >>> for", "b = output(input(x) % input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", ">>> all(results) True \"\"\" return bit.operation(op.and_, self, other) def __rand__(self, other): \"\"\" >>>", "for (x, y) in zip(self, other)]) def __and__(self: bits, other: bits) -> bits:", "None _hook_operation = None @staticmethod def circuit(circuit_=None): if circuit_ is not None: bit._circuit", "isinstance(other[0], int): return map(bits, parts(self, length=other)) # Sequence of lengths. elif isinstance(other, set)", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_, self, other) def nand(self, other): \"\"\"", "outputs # For forward-compatibility with PEP 563. eval_ = lambda a: eval(a) if", "y, y])) ... zs = outputs(xs.or_(ys)) ... ns = [int(z) for z in", "disable=W0123 try: # Construct the circuit and add it to the function as", "for _ in range(other)]) def __truediv__(self: bits, other) -> Sequence[bits]: \"\"\" >>> bit.circuit(circuit())", "from hook if it exists and if # it returns an output. if", "True >>> bit.circuit(circuit()) >>> 2 - input(0) Traceback (most recent call last): ...", "as its arguments and returns an output of type `bit` or `bits`. >>>", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.and_, self, other) def __rand__(self, other): \"\"\"", "... b = output(input(x).and_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "Rotation. quantity = list(other)[0] return bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity]) else: # Shift return bits([constant(0)]*other)", "| input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.or_, self,", "b = output(input(x).xnor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_,", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nif(other) def xor(self, other): \"\"\" >>> results", "inputs([y, y, y])) ... zs = outputs(xs.imp_(ys)) ... ns = [int(z) for z", "bs = bs << 3 >>> [b.value for b in bs] [1, 0,", "circuit, signature class bit(): \"\"\" Class for representing an abstract bit. Such a", "b = output(input(x).nand_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_,", "all(results) True \"\"\" return bits([x.nimp_(y) for (x, y) in zip(self, other)]) def __gt__(self:", "zs = outputs(xs % ys) ... ns = [int(z) for z in zs]", "def __or__(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "int) else other) def nor(self, other): \"\"\" >>> results = [] >>> for", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "def imp_(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "source.\"\"\" class output(bit): \"\"\" Bit that is designated an output. >>> bit.circuit(circuit()) >>>", "bs] [1, 0, 0, 0, 0, 0, 0, 0] \"\"\" return bits(self[other:]) **", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).or_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self, other)", "return bit.operation(op.imp_, self, other) def imp_(self, other): \"\"\" >>> results = [] >>>", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xor_(ys)) ... ns", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nor(ys)) ... ns =", "= list(other)[0] return bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity]) else: # Shift return bits([constant(0)]*other) ** bits(self[0:len(self)-other])", "bit.circuit(circuit()) ... b = output(input(x).xor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.nand_(ys)) ... ns = [int(z)", "inputs([y, y, y])) ... zs = outputs(xs.xnor(ys)) ... ns = [int(z) for z", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nand(ys)) ... ns =", "def xnor(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "= bit._circuit.gate(op.id_, is_input=True) class input_one(input): \"\"\"Bit that is designated as a variable input", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) & input(y))", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs > ys) ...", "args = list(args) if len(args) == 2: args[1] = constant(args[1]) if isinstance(args[1], int)", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_, self, other) def nor_(self, other):", "1, 0] >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [0,0,0,0,1,1,1,1])) >>> bs = bs", "(xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nif_(ys))", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.xor_(ys)) ... ns = [int(z)", "b = output(input(x) < input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "__lt__(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "x]), inputs([y, y, y])) ... zs = outputs(xs.xor_(ys)) ... ns = [int(z) for", "\"\"\" Class for representing an input or output type of a function decorated", "annotation of the decorated function. type_in = lambda a: input(0) if a is", "or whether there are others dependent on it. if len(b.gate.outputs) > 0: b", "all(results) True \"\"\" return bit.operation(op.xor_, self, other) def xor_(self, other): \"\"\" >>> results", "bit.circuit(circuit()) ... b = output(input(x).xnor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "def make_hook(bit_): ... def hook(o, v, *args): ... return bit_.constructor(*args)(v, bit_.gate(o, [a.gate for", "return bit.operation(op.or_, self, other) def __ror__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b =", "bit._hook_operation = hook @staticmethod def operation(o, *args): # Ensure second argument is a", "\"\"\" return bits([x.imp_(y) for (x, y) in zip(self, other)]) def imp_(self: bits, other:", "def nimp_(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "0: b = ~(~b) # Preserve the bit by copying it to a", "1 ^ constant(0) >>> b.value 1 \"\"\" return self ^ (constant(other) if isinstance(other,", "bit.circuit(circuit()) ... b = output(input(x).not_()) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\"", "self, other) def nand(self, other): \"\"\" >>> results = [] >>> for (x,", ">>> bs = bs >> {3} >>> [b.value for b in bs] [1,", "output(input(x) ^ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_,", "ready as final output or whether there are others dependent on it. if", "as a value, but it is also used to keep track of relationships", "argument = None) -> bits: \"\"\" Return bits object given the supplied argument.", "self + other def constants(l): return bits(map(constant, l)) def inputs(l): return bits(map(input, l))", "(x, y) in zip(self, other)]) def nimp(self: bits, other: bits) -> bits: \"\"\"", "of those operators. >>> bit.hook_operation(lambda o, v, *args: None) >>> bit.circuit(circuit()) >>> b", "for (x, y) in zip(self, other)]) def __xor__(self: bits, other: bits) -> bits:", "0]] \"\"\" if isinstance(other, list) and len(other) > 0 and isinstance(other[0], int): return", "all(results) True \"\"\" return bit.operation(op.imp_, self, other) def imp_(self, other): \"\"\" >>> results", "all(results) True \"\"\" return bit.operation(op.nand_, self, other) def __matmul__(self, other): \"\"\" >>> results", "0], [0, 0], [1, 0], [1, 1]] >>> @synthesize ... def equal(x, y):", "else: return map(bits, parts(self, other)) # Number of parts is `other`. def __add__(self:", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor(input(y))) ... results.append(int(b)", "args_in = { k: type_in(eval_(a)) for (k, a) in f.__annotations__.items() if k !=", "y) in zip(self, other)]) def __or__(self: bits, other: bits) -> bits: \"\"\" >>>", "y, y])) ... zs = outputs(xs.nand_(ys)) ... ns = [int(z) for z in", "-> bits: \"\"\"Concatenation of bit vectors.\"\"\" return self + other def constants(l): return", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) > input(y)) ...", "== c.evaluate([x, x, x])) >>> all(results) True \"\"\" return bits([x.not_() for x in", "zeros(n: int) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> xs = bits.zeros(3) >>> ys", "\"\"\" # Functions for determining types/signature from # the type annotation of the", "from typing import Sequence import doctest from parts import parts from circuit import", "& y Traceback (most recent call last): ... RuntimeError: automated circuit synthesis failed", "== ys) ... ns = [int(z) for z in zs] ... c =", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "isinstance(b2, input_one): return input_one elif isinstance(b1, input_two) and isinstance(b2, input_two): return input_two elif", "... b = output(input(x).imp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "= output(input(x).xnor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_, self,", "bits_type(argument)\\ if isinstance(argument, int) else\\ list.__new__(cls, argument) def __int__(self: bits) -> int: \"\"\"", ">>> bit.hook_operation(make_hook(bit)) >>> bit.circuit(circuit()) >>> b = output(input(0).and_(input(0))) >>> b.value == bit.circuit().evaluate([0,0])[0] True", "0]] >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs /", "or `bits`. >>> @synthesize ... def equal(x: bit, y: bit) -> bit: ...", "outputs(xs.nor_(ys)) ... ns = [int(z) for z in zs] ... c = bit.circuit()", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_, self, other) def imp_(self, other): \"\"\"", "y])) ... zs = outputs(xs.or_(ys)) ... ns = [int(z) for z in zs]", "all(results) True \"\"\" return bits([x.imp_(y) for (x, y) in zip(self, other)]) def imp_(self:", "([b.value for b in bss[0]], [b.value for b in bss[1]]) ([1, 1, 1,", "bit.operation(op.xnor_, self, other) def if_(self, other): \"\"\" >>> results = [] >>> for", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) >= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "currently in use. \"\"\" if isinstance(b1, input_one) and isinstance(b2, input_one): return input_one elif", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) @", "def xnor_(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "True \"\"\" return bits([x.nif_(y) for (x, y) in zip(self, other)]) def __lt__(self: bits,", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor(input(y))) ... results.append(int(b) ==", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) % input(y)) ... results.append(int(b)", "bit.operation(op.nand_, self, other) class constant(bit): \"\"\"Bit that is designated as a constant input.\"\"\"", "output(input(x).nif(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nif_, self, other)", "__mod__(self, other) -> bits: \"\"\" >>> results = [] >>> for (x, y)", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand(input(y))) ... results.append(int(b)", "... bit.circuit(circuit()) ... b = output(input(x).nor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "designated as a variable input.\"\"\" def __init__(self: bit, value: int): self.value = value", "1 and isinstance(list(other)[0], int): return self / (len(self)//list(other)[0]) # Parts of length `other`.", "circuits and synthesizing circuits from those definitions. \"\"\" from __future__ import annotations from", "def hook(o, v, *args): ... return bit_.constructor(*args)(v, bit_.gate(o, [a.gate for a in args]))", "bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs >> 3 >>>", "[bits([x, y]) for x in (0, 1) for y in (0, 1)] >>>", "@staticmethod def gate(operation, igs): return bit._circuit.gate(operation, igs) def __init__(self, value, gate_=None): self.value =", ">>> all(results) True \"\"\" return bit.operation(op.nor_, self, other) def xnor(self, other): \"\"\" >>>", "self.value def not_(self): \"\"\" >>> results = [] >>> for x in [0,", "x in [0, 1]: ... bit.circuit(circuit()) ... b = output(input(x).not_()) ... results.append(int(b) ==", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.and_, self, other) def __and__(self,", "dependent on it. if len(b.gate.outputs) > 0: b = ~(~b) # Preserve the", "1, 1, 0] >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [0,0,0,0,1,1,1,1])) >>> bs =", "y])) ... zs = outputs(xs & ys) ... ns = [int(z) for z", "with PEP 563. eval_ = lambda a: eval(a) if isinstance(a, str) else a", "`bit`. args = list(args) if len(args) == 2: args[1] = constant(args[1]) if isinstance(args[1],", "bits([x.nif_(y) for (x, y) in zip(self, other)]) def xor(self: bits, other: bits) ->", "\"\"\" return bit.operation(op.xnor_, self, other) def __eq__(self, other): \"\"\" >>> results = []", "... bit.circuit(circuit()) ... b = output(input(x).if_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) % input(y)) ...", "len(other) == 1 and isinstance(list(other)[0], int): return self / (len(self)//list(other)[0]) # Parts of", "results.append(ns == c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return", "nor_(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "bit.circuit(circuit()) ... b = output(input(x).if_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "from_bytes(bytes_, constructor=bit) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([255]))]", "y])) ... zs = outputs(xs | ys) ... ns = [int(z) for z", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif_(input(y))) ... results.append(int(b) ==", "length `other`. else: return map(bits, parts(self, other)) # Number of parts is `other`.", "x]), inputs([y, y, y])) ... zs = outputs(xs | ys) ... ns =", "= lambda a: input(0) if a is bit else inputs([0] * a) type_out", ">>> bit.circuit(circuit()) >>> b0 = output(input(1).not_()) >>> b1 = output(b0.not_()) >>> b2 =", "... results.append(ns == c.evaluate([x, x, x])) >>> all(results) True \"\"\" return bits([x.not_() for", ">>> b.value == bit.circuit().evaluate([0,0])[0] True \"\"\" _circuit = None _hook_operation = None @staticmethod", "nimp(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "y, y])) ... zs = outputs(xs & ys) ... ns = [int(z) for", "outputs(l): return bits(map(output, l)) def synthesize(f): \"\"\" Decorator for automatically synthesizing a circuit", "other) def nif_(self, other): \"\"\" >>> results = [] >>> for (x, y)", "True \"\"\" return bit.operation(op.nimp_, self, other) def nimp_(self, other): \"\"\" >>> results =", "`other`. def __add__(self: bits, other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\" result =", "y, y])) ... zs = outputs(xs.nif_(ys)) ... ns = [int(z) for z in", "True \"\"\" return bits([x.not_() for x in self]) def __invert__(self: bits) -> bits:", "xs = inputs([x, x, x]) ... ys = outputs(~xs) ... ns = [int(y)", "Class for representing a vector of abstract bits. \"\"\" @staticmethod def from_byte(byte_: int,", "for (x, y) in zip(self, other)]) def nimp_(self: bits, other: bits) -> bits:", "x]), inputs([y, y, y])) ... zs = outputs(xs & ys) ... ns =", "isinstance(list(other)[0], int): # Rotation. quantity = list(other)[0] return bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity]) else: #", "2: args[1] = constant(args[1]) if isinstance(args[1], int) else args[1] # Compute the value", "all(results) True \"\"\" return bit.operation(op.nimp_, self, other) def __gt__(self, other): \"\"\" >>> results", "gate, circuit, signature class bit(): \"\"\" Class for representing an abstract bit. Such", "isinstance(b1, input_two) and isinstance(b2, input_two): return input_two elif isinstance(b1, (input_one, input_two)) and b2", "return self.value def not_(self): \"\"\" >>> results = [] >>> for x in", "self | (constant(other) if isinstance(other, int) else other) def nor(self, other): \"\"\" >>>", "`bits`. >>> @synthesize ... def equal(x: bit, y: bit) -> bit: ... return", "all(results) True \"\"\" return bit.operation(op.not_, self) def __rsub__(self, other): \"\"\" >>> results =", "... ys = outputs(xs.not_()) ... ns = [int(y) for y in ys] ...", "for a in args]) # Return output from hook if it exists and", "\"\"\" return bit.operation(op.imp_, self, other) def __le__(self, other): \"\"\" >>> results = []", "all(results) True \"\"\" return bit.operation(op.nand_, self, other) class constant(bit): \"\"\"Bit that is designated", "self, other) class constant(bit): \"\"\"Bit that is designated as a constant input.\"\"\" class", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor_(input(y))) ...", "constants([0, 0, 0]) >>> ys = outputs(xs.not_()) >>> int(ys) 7 \"\"\" return sum(int(b)*(2**i)", "Sequence[bits]: \"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs", "bit._circuit.gate(op.id_, [b.gate], is_output=True) class bits_type(int): # pylint: disable=R0903 \"\"\" Class for representing an", "return bits([x.not_() for x in self]) def and_(self: bits, other: bits) -> bits:", "= output(input(x).xor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_, self,", "all(results) True \"\"\" return bits([x.nif_(y) for (x, y) in zip(self, other)]) def xor(self:", "((1 - x) & (1 - y)) >>> xys = [bits([x, y]) for", "(x, y) in zip(self, other)]) def __mod__(self, other) -> bits: \"\"\" >>> results", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) > input(y))", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "# Parts of length `other`. else: return map(bits, parts(self, other)) # Number of", "or_(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "__init__(self: bit, b: bit): # Check if bit is ready as final output", "zip(self, other)]) def nand_(self: bits, other) -> bits: \"\"\" >>> results = []", "bit.circuit(circuit()) ... b = output(1 - input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results)", "is also used to keep track of relationships between operators and to represent", "... b = output(input(x).nimp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "output(b0) >>> [b0.value, b1.value, b2.value] [0, 1, 0] \"\"\" def __init__(self: bit, b:", "\"\"\" return bits([x.xnor_(y) for (x, y) in zip(self, other)]) def xnor_(self: bits, other:", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).and_(input(y))) ... results.append(int(b) ==", "class bits(list): \"\"\" Class for representing a vector of abstract bits. \"\"\" @staticmethod", "... b = output(input(x) % input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "input.\"\"\" class input(bit): \"\"\"Bit that is designated as a variable input.\"\"\" def __init__(self:", "True \"\"\" return bit.operation(op.nif_, self, other) def __lt__(self, other): \"\"\" >>> results =", "\"\"\" if isinstance(other, list) and len(other) > 0 and isinstance(other[0], int): return map(bits,", "variable input from one source.\"\"\" class input_two(input): \"\"\"Bit that is designated as a", "r return bit.constructor(*args)(v, bit.gate(o, [a.gate for a in args])) @staticmethod def constructor(b1, b2=None):", "from circuit import op, gate, circuit, signature class bit(): \"\"\" Class for representing", "True \"\"\" return bit.operation(op.nor_, self, other) def nor_(self, other): \"\"\" >>> results =", "bit.circuit(circuit()) >>> b = output(input(1).and_(input(1))) >>> b.value == bit.circuit().evaluate([1,1])[0] True >>> def make_hook(bit_):", "= ~(~b) # Preserve the bit by copying it to a new wire.", "= output(input(x).nor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_, self,", "x]), inputs([y, y, y])) ... zs = outputs(xs == ys) ... ns =", "True \"\"\" return bit.operation(op.or_, self, other) def __ror__(self, other): \"\"\" >>> bit.circuit(circuit()) >>>", "outputs(xs.nand_(ys)) ... ns = [int(z) for z in zs] ... c = bit.circuit()", "b2 = output(b0) >>> [b0.value, b1.value, b2.value] [0, 1, 0] \"\"\" def __init__(self:", "0] \"\"\" return bits(self[other:]) ** bits([constant(0) for _ in range(other)]) def __truediv__(self: bits,", "__le__(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "in bs] [1, 0, 0, 0, 0, 0, 0, 0] \"\"\" return bits(self[other:])", "in zip(self, other)]) def nimp_(self: bits, other: bits) -> bits: \"\"\" >>> results", "def nor_(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "as a constant input.\"\"\" class input(bit): \"\"\"Bit that is designated as a variable", "bs = bs >> 3 >>> [b.value for b in bs] [0, 0,", "outputs(xs.imp_(ys)) ... ns = [int(z) for z in zs] ... c = bit.circuit()", "raise ValueError('can only subtract a bit from the integer 1') def and_(self, other):", "bit.operation(op.nor_, self, other) def xnor(self, other): \"\"\" >>> results = [] >>> for", "= [] >>> for x in [0, 1]: ... bit.circuit(circuit()) ... xs =", "= bit.circuit() except: raise RuntimeError('automated circuit synthesis failed') from None # Return the", "\"\"\" return bit.operation(op.nand_, self, other) class constant(bit): \"\"\"Bit that is designated as a", "def inputs(l): return bits(map(input, l)) def outputs(l): return bits(map(output, l)) def synthesize(f): \"\"\"", "args[1] = constant(args[1]) if isinstance(args[1], int) else args[1] # Compute the value of", "outputs(xs.xor(ys)) ... ns = [int(z) for z in zs] ... c = bit.circuit()", "return bit.operation(op.nor_, self, other) def nor_(self, other): \"\"\" >>> results = [] >>>", "b2.value] [0, 1, 0] \"\"\" def __init__(self: bit, b: bit): # Check if", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nif(ys)) ...", "for (x, y) in zip(self, other)]) def __ge__(self: bits, other: bits) -> bits:", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nimp(other) def nif(self, other): \"\"\"", "Traceback (most recent call last): ... RuntimeError: automated circuit synthesis failed \"\"\" #", "all(results) True \"\"\" return bit.operation(op.or_, self, other) def __ror__(self, other): \"\"\" >>> bit.circuit(circuit())", "def nand(self: bits, other) -> bits: \"\"\" >>> results = [] >>> for", "zs = outputs(xs == ys) ... ns = [int(z) for z in zs]", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor(input(y))) ... results.append(int(b)", "def imp(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "if a is bit else outputs # For forward-compatibility with PEP 563. eval_", "other): \"\"\" >>> results = [] >>> for (x, y) in [(0, 0),", "if isinstance(argument, int) else\\ list.__new__(cls, argument) def __int__(self: bits) -> int: \"\"\" >>>", "def if_(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "= outputs(xs.nif_(ys)) ... ns = [int(z) for z in zs] ... c =", "argument is a `bit`. args = list(args) if len(args) == 2: args[1] =", "self, other) def __xor__(self, other): \"\"\" >>> results = [] >>> for (x,", ">>> all(results) True \"\"\" return bit.operation(op.nand_, self, other) class constant(bit): \"\"\"Bit that is", "in zip(self, other)]) def nif(self: bits, other: bits) -> bits: \"\"\" >>> results", "for (x, y) in zip(self, other)]) def imp(self: bits, other: bits) -> bits:", "isinstance(other, set) and len(other) == 1 and isinstance(list(other)[0], int): return self / (len(self)//list(other)[0])", "= inputs([x, x, x]) ... ys = outputs(xs.not_()) ... ns = [int(y) for", "(x, y) in zip(self, other)]) def nor(self: bits, other: bits) -> bits: \"\"\"", "< ys) ... ns = [int(z) for z in zs] ... c =", "all(results) True >>> bit.circuit(circuit()) >>> 2 - input(0) Traceback (most recent call last):", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif(input(y))) ... results.append(int(b)", "ns = [int(z) for z in zs] ... c = bit.circuit() ... results.append(ns", "0, 0] \"\"\" return bits([ bit_ for byte_ in bytes_ for bit_ in", "zs = outputs(xs.imp(ys)) ... ns = [int(z) for z in zs] ... c", "(x, y) in zip(self, other)]) def imp_(self: bits, other: bits) -> bits: \"\"\"", "563. eval_ = lambda a: eval(a) if isinstance(a, str) else a # pylint:", "self, other) def __gt__(self, other): \"\"\" >>> results = [] >>> for (x,", "= 1 | constant(0) >>> b.value 1 \"\"\" return self | (constant(other) if", "in zip(self, other)]) def nand_(self: bits, other) -> bits: \"\"\" >>> results =", "variable input.\"\"\" def __init__(self: bit, value: int): self.value = value self.gate = bit._circuit.gate(op.id_,", "_hook_operation = None @staticmethod def circuit(circuit_=None): if circuit_ is not None: bit._circuit =", "x]) ... ys = outputs(xs.not_()) ... ns = [int(y) for y in ys]", "self.nimp(other) def nif(self, other): \"\"\" >>> results = [] >>> for (x, y)", "for x in self]) def __invert__(self: bits) -> bits: \"\"\" >>> results =", "= bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs << 3 >>> [b.value for b", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nimp(other) def nif(self, other):", ">>> bit.circuit(circuit()) >>> b = 1 ^ constant(0) >>> b.value 1 \"\"\" return", "length=other)) # Sequence of lengths. elif isinstance(other, set) and len(other) == 1 and", "bits, other) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>>", "as an attribute. bit.circuit(circuit()) args_in = { k: type_in(eval_(a)) for (k, a) in", "int) else args[1] # Compute the value of the result of the operation", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor_(input(y))) ...", "\"\"\" return bits([x.nimp_(y) for (x, y) in zip(self, other)]) def nif(self: bits, other:", "def equal(x: bit, y: bit) -> bit: ... return (x & y) |", "return map(bits, parts(self, length=other)) # Sequence of lengths. elif isinstance(other, set) and len(other)", "the arguments. v = o(*[a.value for a in args]) # Return output from", "<= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_, self,", "/ (len(self)//list(other)[0]) # Parts of length `other`. else: return map(bits, parts(self, other)) #", "y])) ... zs = outputs(xs.xnor(ys)) ... ns = [int(z) for z in zs]", "__invert__(self): \"\"\" >>> results = [] >>> for x in [0, 1]: ...", "nand(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", ">>> b = 1 | constant(0) >>> b.value 1 \"\"\" return self |", "x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.or_(y) for (x,", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... (xs, ys) = (inputs([x, x,", "bit.circuit(circuit()) ... b = output(input(x).xor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor(input(y))) ...", "= output(input(x) == input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "y in ys] ... c = bit.circuit() ... results.append(ns == c.evaluate([x, x, x]))", "y: bit) -> bit: ... return (x & y) | ((1 - x)", "xor(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "= bs << 3 >>> [b.value for b in bs] [1, 0, 0,", "... zs = outputs(xs.xor_(ys)) ... ns = [int(z) for z in zs] ...", "__rshift__(self: bits, other) -> bits: \"\"\" Overloaded operator: rotation and shift operations. >>>", "c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.or_(y) for", "return bit._circuit @staticmethod def hook_operation(hook=None): bit._hook_operation = hook @staticmethod def operation(o, *args): #", "True \"\"\" return bits([x.imp_(y) for (x, y) in zip(self, other)]) def __le__(self: bits,", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs | ys)", "zip(self, other)]) def imp(self: bits, other: bits) -> bits: \"\"\" >>> results =", "of length `other`. else: return map(bits, parts(self, other)) # Number of parts is", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nif(other) def xor(self, other): \"\"\" >>>", "for (x, y) in zip(self, other)]) def nand_(self: bits, other) -> bits: \"\"\"", "synthesis. \"\"\" class bits(list): \"\"\" Class for representing a vector of abstract bits.", "in zip(self, other)]) def if_(self: bits, other: bits) -> bits: \"\"\" >>> results", "import op, gate, circuit, signature class bit(): \"\"\" Class for representing an abstract", "\"\"\" return bits([x.xnor_(y) for (x, y) in zip(self, other)]) def __eq__(self: bits, other:", "shift operations. >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs", "return bit.operation(op.xor_, self, other) def __rxor__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b =", "a vector of abstract bits. \"\"\" @staticmethod def from_byte(byte_: int, constructor=bit) -> bits:", "Such a bit can be interpreted concretely as a value, but it is", "(xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xor_(ys))", "other)]) def __mod__(self, other) -> bits: \"\"\" >>> results = [] >>> for", "def nand_(self: bits, other) -> bits: \"\"\" >>> results = [] >>> for", "return bits([x.imp_(y) for (x, y) in zip(self, other)]) def imp_(self: bits, other: bits)", ">>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / {2}) >>> [[b.value", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand_(input(y)))", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).and_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "results = [] >>> for x in [0, 1]: ... bit.circuit(circuit()) ... xs", "operator: rotation and shift operations. >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>>", "def from_bytes(bytes_, constructor=bit) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> [b.value for b in", "imp_(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "in [0, 1]: ... bit.circuit(circuit()) ... b = output(input(x).not_()) ... results.append(int(b) == bit.circuit().evaluate([x])[0])", "y, y])) >>> all(results) True \"\"\" return bits([x.if_(y) for (x, y) in zip(self,", "class input_two(input): \"\"\"Bit that is designated as a variable input from a second", "= b.value self.gate = bit._circuit.gate(op.id_, [b.gate], is_output=True) class bits_type(int): # pylint: disable=R0903 \"\"\"", "-> bit: ... return (x & y) | ((1 - x) & (1", "= bit._circuit.gate() if gate_ is None else gate_ def __int__(self): return self.value def", "zip(self, other)]) def if_(self: bits, other: bits) -> bits: \"\"\" >>> results =", "a in args])) ... return hook >>> bit.hook_operation(make_hook(bit)) >>> bit.circuit(circuit()) >>> b =", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "of a function decorated for automated synthesis. \"\"\" class bits(list): \"\"\" Class for", "0, 0, 0, 0, 1] \"\"\" if isinstance(other, set) and isinstance(list(other)[0], int): #", ">>> all(results) True \"\"\" return bit.operation(op.if_, self, other) def __ge__(self, other): \"\"\" >>>", "bit.operation(op.not_, self) def __invert__(self): \"\"\" >>> results = [] >>> for x in", "set) and len(other) == 1 and isinstance(list(other)[0], int): return self / (len(self)//list(other)[0]) #", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.xnor_(ys)) ... ns = [int(z)", "= o(*[a.value for a in args]) # Return output from hook if it", "... b = output(input(x).xor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "b.value 1 \"\"\" return self ^ (constant(other) if isinstance(other, int) else other) def", "bit._circuit.gate() if gate_ is None else gate_ def __int__(self): return self.value def not_(self):", "v, *args): ... return bit_.constructor(*args)(v, bit_.gate(o, [a.gate for a in args])) ... return", "bit(): \"\"\" Class for representing an abstract bit. Such a bit can be", "nimp(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "... RuntimeError: automated circuit synthesis failed \"\"\" # Functions for determining types/signature from", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) ^ input(y)) ... results.append(int(b) ==", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).if_(input(y))) ...", "else: bit._circuit.prune_and_topological_sort_stable() return bit._circuit @staticmethod def hook_operation(hook=None): bit._hook_operation = hook @staticmethod def operation(o,", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) <= input(y))", "variable input from a second source.\"\"\" class output(bit): \"\"\" Bit that is designated", "b = output(~input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operation(op.not_,", "([1, 1, 1, 1], [0, 0, 0, 0]) >>> bit.circuit(circuit()) >>> bs =", "= None) -> bits: \"\"\" Return bits object given the supplied argument. \"\"\"", "xnor_(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_, self, other) def imp_(self, other):", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp_(input(y))) ... results.append(int(b) ==", "for (k, a) in f.__annotations__.items() if k != 'return' } type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit =", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "y, y, y])) >>> all(results) True \"\"\" return bits([x.nif_(y) for (x, y) in", "0] >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [0,0,0,0,1,1,1,1])) >>> bs = bs >>", "x in [0, 1]: ... bit.circuit(circuit()) ... b = output(1 - input(x)) ...", "return input_one elif isinstance(b1, input_two) and isinstance(b2, input_two): return input_two elif isinstance(b1, (input_one,", "there are others dependent on it. if len(b.gate.outputs) > 0: b = ~(~b)", "= bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / {2}) >>> [[b.value for b", "all(results) True \"\"\" return bits([x.or_(y) for (x, y) in zip(self, other)]) def __or__(self:", "@staticmethod def circuit(circuit_=None): if circuit_ is not None: bit._circuit = circuit_ return None", "1]: ... bit.circuit(circuit()) ... b = output(input(x).not_()) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results)", "bit.operation(op.nif_, self, other) def __lt__(self, other): \"\"\" >>> results = [] >>> for", "__rsub__(self, other): \"\"\" >>> results = [] >>> for x in [0, 1]:", "second source.\"\"\" class output(bit): \"\"\" Bit that is designated an output. >>> bit.circuit(circuit())", "[0], [1]] >>> @synthesize ... def conjunction(xy: bits(2)) -> bits(2): ... return (xy[0],", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor_(input(y)))", "only subtract a bit from the integer 1 \"\"\" if other == 1:", "return bit.operation(op.xor_, self, other) def __xor__(self, other): \"\"\" >>> results = [] >>>", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nif_, self, other) def nif_(self, other):", "def or_(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "True \"\"\" return bits([x.nor_(y) for (x, y) in zip(self, other)]) def nor_(self: bits,", "x]), inputs([y, y, y])) ... zs = outputs(xs > ys) ... ns =", "Class for representing an abstract bit. Such a bit can be interpreted concretely", "0, 0, 0] \"\"\" return bits([ bit_ for byte_ in bytes_ for bit_", "y) in zip(self, other)]) def __ge__(self: bits, other: bits) -> bits: \"\"\" >>>", "equal(x, y): ... return x & y Traceback (most recent call last): ...", "y])) ... zs = outputs(xs.imp(ys)) ... ns = [int(z) for z in zs]", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nif_, self, other) def __lt__(self, other):", "\"\"\" return bit @staticmethod def gate(operation, igs): return bit._circuit.gate(operation, igs) def __init__(self, value,", "return bit_.constructor(*args)(v, bit_.gate(o, [a.gate for a in args])) ... return hook >>> bit.hook_operation(make_hook(bit))", "return bit.operation(op.nimp_, self, other) def nimp_(self, other): \"\"\" >>> results = [] >>>", "% ys) ... ns = [int(z) for z in zs] ... c =", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs |", "# Check if bit is ready as final output or whether there are", "given the supplied argument. \"\"\" return bits_type(argument)\\ if isinstance(argument, int) else\\ list.__new__(cls, argument)", "b.value 1 \"\"\" return self | (constant(other) if isinstance(other, int) else other) def", "... results.append(ns == c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\"", "o, v, *args: None) >>> bit.circuit(circuit()) >>> b = output(input(1).and_(input(1))) >>> b.value ==", "def __add__(self: bits, other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\" result = list(self)", "zip(self, other)]) def __and__(self: bits, other: bits) -> bits: \"\"\" >>> results =", "return bits([x.nand_(y) for (x, y) in zip(self, other)]) def __rshift__(self: bits, other) ->", "ValueError: can only subtract a bit from the integer 1 \"\"\" if other", "forward-compatibility with PEP 563. eval_ = lambda a: eval(a) if isinstance(a, str) else", "x, x]) ... ys = outputs(~xs) ... ns = [int(y) for y in", "range(8)]) ]) @staticmethod def from_bytes(bytes_, constructor=bit) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> [b.value", "return bits([x.not_() for x in self]) def __invert__(self: bits) -> bits: \"\"\" >>>", "\"\"\" return bits([ bit_ for byte_ in bytes_ for bit_ in bits.from_byte(byte_, constructor)", "bit_ in reversed([(byte_>>i)%2 for i in range(8)]) ]) @staticmethod def from_bytes(bytes_, constructor=bit) ->", "list(bs / 2) >>> ([b.value for b in bss[0]], [b.value for b in", "0, 0, 0, 0] \"\"\" return bits([ bit_ for byte_ in bytes_ for", "inputs([y, y, y])) ... zs = outputs(xs.if_(ys)) ... ns = [int(z) for z", "only subtract a bit from the integer 1') def and_(self, other): \"\"\" >>>", "{2}) >>> [[b.value for b in bs] for bs in bss] [[1, 1],", "\"\"\" >>> bit.circuit(circuit()) >>> b = 1 | constant(0) >>> b.value 1 \"\"\"", "zip(self, other)]) def nand(self: bits, other) -> bits: \"\"\" >>> results = []", "a bit can be interpreted concretely as a value, but it is also", "\"\"\" return bits([x.imp_(y) for (x, y) in zip(self, other)]) def nand(self: bits, other)", "def xor_(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "circuit built up out of those operators. >>> bit.hook_operation(lambda o, v, *args: None)", "self, other) def xnor_(self, other): \"\"\" >>> results = [] >>> for (x,", "all(results) True \"\"\" return bit.operation(op.nif_, self, other) def __lt__(self, other): \"\"\" >>> results", "bit.circuit(circuit()) ... b = output(input(x) < input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "inputs([y, y, y])) ... zs = outputs(xs.nor_(ys)) ... ns = [int(z) for z", "for (x, y) in zip(self, other)]) def __rshift__(self: bits, other) -> bits: \"\"\"", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def __eq__(self, other):", "int) else other) def nimp(self, other): \"\"\" >>> results = [] >>> for", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.imp_(ys)) ... ns", "- y)) >>> xys = [bits([x, y]) for x in (0, 1) for", "... b = output(input(x).xor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "self, other) def __ror__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 1 |", "b = output(input(x).nor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_,", "b1.value, b2.value] [0, 1, 0] \"\"\" def __init__(self: bit, b: bit): # Check", "... bit.circuit(circuit()) ... b = output(input(x).imp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "b in bs] for bs in bss] [[1], [1, 1, 1], [0, 0,", "return (x & y) | ((1 - x) & (1 - y)) >>>", "wires within a circuit built up out of those operators. >>> bit.hook_operation(lambda o,", "0 \"\"\" return self & (constant(other) if isinstance(other, int) else other) def nimp(self,", "__and__(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", ">>> [y.value for y in ys] [1, 1, 1] \"\"\" return bits([constant(0)]*n) def", "[] >>> for x in [0, 1]: ... bit.circuit(circuit()) ... b = output(1", "below is not currently in use. \"\"\" if isinstance(b1, input_one) and isinstance(b2, input_one):", ">>> all(results) True \"\"\" return bit.operation(op.or_, self, other) def __or__(self, other): \"\"\" >>>", "outputs(xs.nimp_(ys)) ... ns = [int(z) for z in zs] ... c = bit.circuit()", "\"\"\" return bit.operation(op.not_, self) def __invert__(self): \"\"\" >>> results = [] >>> for", "for x in (0, 1) for y in (0, 1)] >>> [equal.circuit.evaluate(xy) for", "all(results) True \"\"\" return bits([x.nor_(y) for (x, y) in zip(self, other)]) def xnor(self:", "in zip(self, other)]) def __and__(self: bits, other: bits) -> bits: \"\"\" >>> results", "[0, 1]: ... bit.circuit(circuit()) ... b = output(~input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>>", "= outputs(xs.nor(ys)) ... ns = [int(z) for z in zs] ... c =", "function as an attribute. bit.circuit(circuit()) args_in = { k: type_in(eval_(a)) for (k, a)", "= output(input(x) > input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "output type of a function decorated for automated synthesis. \"\"\" class bits(list): \"\"\"", ">>> all(results) True \"\"\" return bit.operation(op.xor_, self, other) def __rxor__(self, other): \"\"\" >>>", "x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.if_(y) for (x,", "= outputs(xs.nimp(ys)) ... ns = [int(z) for z in zs] ... c =", "def __xor__(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "= bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / 2) >>> ([b.value for b", "@synthesize ... def equal(x, y): ... return x & y Traceback (most recent", "bit.circuit(circuit()) ... xs = inputs([x, x, x]) ... ys = outputs(~xs) ... ns", "= outputs(xs < ys) ... ns = [int(z) for z in zs] ...", "(xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.imp_(ys))", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.and_, self, other) def __rand__(self,", "= output(input(x).not_()) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operation(op.not_, self)", "outputs(xs.not_()) ... ns = [int(y) for y in ys] ... c = bit.circuit()", "True \"\"\" return bit.operation(op.xnor_, self, other) def __eq__(self, other): \"\"\" >>> results =", "= lambda a: eval(a) if isinstance(a, str) else a # pylint: disable=W0123 try:", "def nimp_(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "y) in zip(self, other)]) def __rshift__(self: bits, other) -> bits: \"\"\" Overloaded operator:", "(x, y) in zip(self, other)]) def nif_(self: bits, other: bits) -> bits: \"\"\"", "operation(o, *args): # Ensure second argument is a `bit`. args = list(args) if", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) < input(y))", "\"\"\" return bits([x.nand_(y) for (x, y) in zip(self, other)]) def nand_(self: bits, other)", ">>> bs = bs << 3 >>> [b.value for b in bs] [1,", "in bs] [1, 1, 1, 0, 0, 0, 0, 1] \"\"\" if isinstance(other,", "= bits(map(bit, [0,0,0,0,1,1,1,1])) >>> bs = bs >> {3} >>> [b.value for b", "y) in zip(self, other)]) def or_(self: bits, other: bits) -> bits: \"\"\" >>>", "y])) ... zs = outputs(xs ^ ys) ... ns = [int(z) for z", "def __int__(self: bits) -> int: \"\"\" >>> bit.circuit(circuit()) >>> xs = constants([0, 0,", "... bit.circuit(circuit()) ... b = output(input(x) & input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "bit.circuit(circuit()) ... b = output(input(x).nand(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "in zip(self, other)]) def nif_(self: bits, other: bits) -> bits: \"\"\" >>> results", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nif_, self, other) def __lt__(self, other): \"\"\"", "- input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True >>> bit.circuit(circuit()) >>> 2", "def outputs(l): return bits(map(output, l)) def synthesize(f): \"\"\" Decorator for automatically synthesizing a", "if k != 'return' } type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit = bit.circuit() except: raise RuntimeError('automated circuit", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.if_(ys)) ... ns = [int(z)", "bit else outputs # For forward-compatibility with PEP 563. eval_ = lambda a:", "... b = output(input(x).if_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "output(input(x).xor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_, self, other)", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp(input(y))) ...", "return bit.constructor(*args)(v, bit.gate(o, [a.gate for a in args])) @staticmethod def constructor(b1, b2=None): #", "equal(x: bit, y: bit) -> bit: ... return (x & y) | ((1", "bit else inputs([0] * a) type_out = lambda a: output if a is", ">>> [equal.circuit.evaluate(xy) for xy in xys] [[1], [0], [0], [1]] >>> @synthesize ...", "outputs(xs.nif(ys)) ... ns = [int(z) for z in zs] ... c = bit.circuit()", "in zip(self, other)]) def __eq__(self: bits, other: bits) -> bits: \"\"\" >>> results", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) == input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "... zs = outputs(xs.nimp_(ys)) ... ns = [int(z) for z in zs] ...", "True \"\"\" return self.nimp(other) def nif(self, other): \"\"\" >>> results = [] >>>", "if isinstance(a, str) else a # pylint: disable=W0123 try: # Construct the circuit", "circuit synthesis failed') from None # Return the original function. return f if", "True \"\"\" return bit.operation(op.xor_, self, other) def __rxor__(self, other): \"\"\" >>> bit.circuit(circuit()) >>>", ">>> bit.circuit(circuit()) >>> xs = constants([0, 0, 0]) >>> ys = outputs(xs.not_()) >>>", "bit.circuit(circuit()) ... b = output(input(x).nif(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "= outputs(xs.nand(ys)) ... ns = [int(z) for z in zs] ... c =", "self, other) def __mod__(self, other): \"\"\" >>> results = [] >>> for (x,", "a function decorated for automated synthesis. \"\"\" class bits(list): \"\"\" Class for representing", "add it to the function as an attribute. bit.circuit(circuit()) args_in = { k:", "nor_(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "all(results) True \"\"\" return bit.operation(op.xor_, self, other) def __xor__(self, other): \"\"\" >>> results", "constant(0) >>> b.value 1 \"\"\" return self ^ (constant(other) if isinstance(other, int) else", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_, self, other) def __rxor__(self, other):", "return bits([x.imp_(y) for (x, y) in zip(self, other)]) def __le__(self: bits, other: bits)", "output(input(x).nor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_, self, other)", "def imp(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "is None: return type(b1) else: return bit \"\"\" return bit @staticmethod def gate(operation,", "y) in zip(self, other)]) def __eq__(self: bits, other: bits) -> bits: \"\"\" >>>", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nand_(ys)) ...", "return bits(result) def __pow__(self: bits, other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\" return", "if bit is ready as final output or whether there are others dependent", "in reversed([(byte_>>i)%2 for i in range(8)]) ]) @staticmethod def from_bytes(bytes_, constructor=bit) -> bits:", "in ys] [1, 1, 1] \"\"\" return bits([constant(0)]*n) def __new__(cls, argument = None)", "zs = outputs(xs > ys) ... ns = [int(z) for z in zs]", "... zs = outputs(xs.xnor(ys)) ... ns = [int(z) for z in zs] ...", "(x, y) in zip(self, other)]) def xnor(self: bits, other: bits) -> bits: \"\"\"", "zip(self, other)]) def nor(self: bits, other: bits) -> bits: \"\"\" >>> results =", "None: bit._circuit = circuit_ return None else: bit._circuit.prune_and_topological_sort_stable() return bit._circuit @staticmethod def hook_operation(hook=None):", ">>> for x in [0, 1]: ... bit.circuit(circuit()) ... b = output(1 -", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs >", "[0, 1, 0] \"\"\" def __init__(self: bit, b: bit): # Check if bit", "in bs] [0, 0, 0, 1, 1, 1, 1, 0] >>> bit.circuit(circuit()) >>>", "nand(self: bits, other) -> bits: \"\"\" >>> results = [] >>> for (x,", "... zs = outputs(xs % ys) ... ns = [int(z) for z in", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs % ys) ...", "\"\"\" return bit.operation(op.xnor_, self, other) def if_(self, other): \"\"\" >>> results = []", "zs = outputs(xs.imp_(ys)) ... ns = [int(z) for z in zs] ... c", "... bit.circuit(circuit()) ... b = output(input(x).nor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "# Construct the circuit and add it to the function as an attribute.", "(xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xnor(ys))", "of bit vectors.\"\"\" return self + other def constants(l): return bits(map(constant, l)) def", "output of type `bit` or `bits`. >>> @synthesize ... def equal(x: bit, y:", "supplied argument. \"\"\" return bits_type(argument)\\ if isinstance(argument, int) else\\ list.__new__(cls, argument) def __int__(self:", "not_(self: bits) -> bits: \"\"\" >>> results = [] >>> for x in", "in zip(self, other)]) def __ge__(self: bits, other: bits) -> bits: \"\"\" >>> results", "bits, other) -> bits: \"\"\" Overloaded operator: rotation and shift operations. >>> bit.circuit(circuit())", "\"\"\" Bit that is designated an output. >>> bit.circuit(circuit()) >>> b0 = output(input(1).not_())", "for representing an abstract bit. Such a bit can be interpreted concretely as", "& constant(1) >>> b.value 0 \"\"\" return self & (constant(other) if isinstance(other, int)", "bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for (x,", "bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / {2}) >>> [[b.value for b in", "not currently in use. \"\"\" if isinstance(b1, input_one) and isinstance(b2, input_one): return input_one", "out of those operators. >>> bit.hook_operation(lambda o, v, *args: None) >>> bit.circuit(circuit()) >>>", "bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([11, 0]))] [0, 0, 0, 0, 1,", "value, but it is also used to keep track of relationships between operators", "def nif(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.imp(ys)) ... ns", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).or_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "bits([x.or_(y) for (x, y) in zip(self, other)]) def __or__(self: bits, other: bits) ->", "self, other) def __lt__(self, other): \"\"\" >>> results = [] >>> for (x,", "= outputs(xs.xor(ys)) ... ns = [int(z) for z in zs] ... c =", "x]), inputs([y, y, y])) ... zs = outputs(xs.imp_(ys)) ... ns = [int(z) for", "other)]) def or_(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "None: return type(b1) else: return bit \"\"\" return bit @staticmethod def gate(operation, igs):", "y, y])) >>> all(results) True \"\"\" return bits([x.xnor_(y) for (x, y) in zip(self,", "bss = list(bs / {2}) >>> [[b.value for b in bs] for bs", "an output of type `bit` or `bits`. >>> @synthesize ... def equal(x: bit,", "integer 1 \"\"\" if other == 1: return bit.operation(op.not_, self) raise ValueError('can only", "inputs([y, y, y])) ... zs = outputs(xs % ys) ... ns = [int(z)", "all(results) True \"\"\" return bits([x.or_(y) for (x, y) in zip(self, other)]) def nor(self:", "# Compute the value of the result of the operation on the arguments.", "operation on the arguments. v = o(*[a.value for a in args]) # Return", "return bits([x.xnor_(y) for (x, y) in zip(self, other)]) def if_(self: bits, other: bits)", "doctest from parts import parts from circuit import op, gate, circuit, signature class", "x]), inputs([y, y, y])) ... zs = outputs(xs.nand_(ys)) ... ns = [int(z) for", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor_(input(y))) ... results.append(int(b)", "y, y])) ... zs = outputs(xs.nor(ys)) ... ns = [int(z) for z in", ">>> bit.circuit(circuit()) >>> b = 1 | constant(0) >>> b.value 1 \"\"\" return", "[] >>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1,", "\"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs /", "bit.circuit(circuit()) ... b = output(input(x) == input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "from __future__ import annotations from typing import Sequence import doctest from parts import", "\"\"\" if other == 1: return bit.operation(op.not_, self) raise ValueError('can only subtract a", "output(input(x).nand_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self, other)", "is_output=True) class bits_type(int): # pylint: disable=R0903 \"\"\" Class for representing an input or", "arguments and returns an output of type `bit` or `bits`. >>> @synthesize ...", "zs = outputs(xs ^ ys) ... ns = [int(z) for z in zs]", "zip(self, other)]) def __or__(self: bits, other: bits) -> bits: \"\"\" >>> results =", "... b = output(input(x).nand_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "for b in bss[0]], [b.value for b in bss[1]]) ([1, 1, 1, 1],", ">> {3} >>> [b.value for b in bs] [1, 1, 1, 0, 0,", "[1, 1, 1, 1, 1, 1, 1, 1] >>> bit.circuit(circuit()) >>> [b.value for", "other == 1: return bit.operation(op.not_, self) raise ValueError('can only subtract a bit from", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "return bit.operation(op.nif_, self, other) def __lt__(self, other): \"\"\" >>> results = [] >>>", "= outputs(xs > ys) ... ns = [int(z) for z in zs] ...", "for bs in bss] [[1], [1, 1, 1], [0, 0, 0, 0]] \"\"\"", "b = output(input(0).and_(input(0))) >>> b.value == bit.circuit().evaluate([0,0])[0] True \"\"\" _circuit = None _hook_operation", "bit.hook_operation(lambda o, v, *args: None) >>> bit.circuit(circuit()) >>> b = output(input(1).and_(input(1))) >>> b.value", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_, self, other) def nand(self, other):", "c = bit.circuit() ... results.append(ns == c.evaluate([x, x, x])) >>> all(results) True \"\"\"", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nor_(ys)) ... ns", "\"\"\" if isinstance(b1, input_one) and isinstance(b2, input_one): return input_one elif isinstance(b1, input_two) and", "bit.circuit(circuit()) args_in = { k: type_in(eval_(a)) for (k, a) in f.__annotations__.items() if k", "return type(b1) else: return bit \"\"\" return bit @staticmethod def gate(operation, igs): return", "except: raise RuntimeError('automated circuit synthesis failed') from None # Return the original function.", "[1, 1], [0, 0], [0, 0]] >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0]))", "(x, y) in zip(self, other)]) def xnor_(self: bits, other: bits) -> bits: \"\"\"", "self) def __rsub__(self, other): \"\"\" >>> results = [] >>> for x in", "^ (constant(other) if isinstance(other, int) else other) def or_(self, other): \"\"\" >>> results", "y])) ... zs = outputs(xs.xor(ys)) ... ns = [int(z) for z in zs]", "... bit.circuit(circuit()) ... b = output(input(x) > input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "def __init__(self: bit, b: bit): # Check if bit is ready as final", "inputs([y, y, y])) ... zs = outputs(xs.nimp(ys)) ... ns = [int(z) for z", "zs = outputs(xs.xnor(ys)) ... ns = [int(z) for z in zs] ... c", ">>> b = 1 ^ constant(0) >>> b.value 1 \"\"\" return self ^", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) < input(y)) ... results.append(int(b)", "input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.and_, self, other)", "other) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs", ">>> bss = list(bs / {2}) >>> [[b.value for b in bs] for", "bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operation(op.not_, self) def __invert__(self): \"\"\" >>> results", "other) def __rand__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 0 & constant(1)", "bit.circuit(circuit()) ... b = output(input(x).xnor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "integer 1') def and_(self, other): \"\"\" >>> results = [] >>> for (x,", "def from_byte(byte_: int, constructor=bit) -> bits: return bits([ constructor(bit_) for bit_ in reversed([(byte_>>i)%2", "y in (0, 1)] >>> [equal.circuit.evaluate(xy) for xy in xys] [[1], [0], [0],", "... bit.circuit(circuit()) ... b = output(input(x) == input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "outputs(xs.xnor_(ys)) ... ns = [int(z) for z in zs] ... c = bit.circuit()", "and if # it returns an output. if bit._hook_operation is not None: r", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.if_(ys)) ...", "0, 0, 0, 0, 0, 0] \"\"\" return bits(self[other:]) ** bits([constant(0) for _", "`bit` or `bits`. >>> @synthesize ... def equal(x: bit, y: bit) -> bit:", ">>> bit.circuit(circuit()) >>> b = output(input(1).and_(input(1))) >>> b.value == bit.circuit().evaluate([1,1])[0] True >>> def", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) | input(y)) ... results.append(int(b) ==", "= output(input(x).nimp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nimp_, self,", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.imp(ys)) ...", "True >>> def make_hook(bit_): ... def hook(o, v, *args): ... return bit_.constructor(*args)(v, bit_.gate(o,", "is designated as a constant input.\"\"\" class input(bit): \"\"\"Bit that is designated as", "self, other) def __rand__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 0 &", "bit.gate(o, [a.gate for a in args])) @staticmethod def constructor(b1, b2=None): # The inference", "y])) ... zs = outputs(xs % ys) ... ns = [int(z) for z", "in zip(self, other)]) def nand(self: bits, other) -> bits: \"\"\" >>> results =", "v, *args: None) >>> bit.circuit(circuit()) >>> b = output(input(1).and_(input(1))) >>> b.value == bit.circuit().evaluate([1,1])[0]", "inputs([x, x, x]) ... ys = outputs(xs.not_()) ... ns = [int(y) for y", "is designated as a variable input.\"\"\" def __init__(self: bit, value: int): self.value =", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.or_, self, other) def __or__(self, other): \"\"\"", "operators and to represent the wires within a circuit built up out of", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def xnor_(self, other): \"\"\"", "x]), inputs([y, y, y])) ... zs = outputs(xs.nor_(ys)) ... ns = [int(z) for", "for (x, y) in zip(self, other)]) def xor_(self: bits, other: bits) -> bits:", "of bit vectors.\"\"\" result = list(self) result.extend(list(other)) return bits(result) def __pow__(self: bits, other)", "a # pylint: disable=W0123 try: # Construct the circuit and add it to", "zip(self, other)]) def or_(self: bits, other: bits) -> bits: \"\"\" >>> results =", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) %", "b = output(input(x).or_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.or_,", "& y) | ((1 - x) & (1 - y)) >>> xys =", "b in bs] for bs in bss] [[1, 1], [1, 1], [0, 0],", "x]), inputs([y, y, y])) ... zs = outputs(xs <= ys) ... ns =", "output(input(x).imp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_, self, other)", "a variable input.\"\"\" def __init__(self: bit, value: int): self.value = value self.gate =", "new wire. self.value = b.value self.gate = bit._circuit.gate(op.id_, [b.gate], is_output=True) class bits_type(int): #", "a bit from the integer 1 \"\"\" if other == 1: return bit.operation(op.not_,", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) >= input(y)) ... results.append(int(b)", "of the result of the operation on the arguments. v = o(*[a.value for", "types/signature from # the type annotation of the decorated function. type_in = lambda", "Return the original function. return f if __name__ == \"__main__\": doctest.testmod() # pragma:", "the integer 1') def and_(self, other): \"\"\" >>> results = [] >>> for", "... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True >>> bit.circuit(circuit()) >>> 2 - input(0)", "zs = outputs(xs.nimp(ys)) ... ns = [int(z) for z in zs] ... c", "... return (x & y) | ((1 - x) & (1 - y))", "[conjunction.circuit.evaluate(xy) for xy in xys] [[0, 0], [0, 0], [1, 0], [1, 1]]", ">>> b.value 0 \"\"\" return self & (constant(other) if isinstance(other, int) else other)", "(x, y) in zip(self, other)]) def or_(self: bits, other: bits) -> bits: \"\"\"", "bits([x.nif_(y) for (x, y) in zip(self, other)]) def nif_(self: bits, other: bits) ->", "bits(2)) -> bits(2): ... return (xy[0], xy[0] & xy[1]) >>> xys = [bits([x,", "return hook >>> bit.hook_operation(make_hook(bit)) >>> bit.circuit(circuit()) >>> b = output(input(0).and_(input(0))) >>> b.value ==", ">>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / [1,", "... ys = outputs(~xs) ... ns = [int(y) for y in ys] ...", "second argument is a `bit`. args = list(args) if len(args) == 2: args[1]", "0] \"\"\" def __init__(self: bit, b: bit): # Check if bit is ready", "bits([x.xor_(y) for (x, y) in zip(self, other)]) def xor_(self: bits, other: bits) ->", ">>> [b.value for b in bits.from_bytes(bytes([11, 0]))] [0, 0, 0, 0, 1, 0,", "an abstract bit. Such a bit can be interpreted concretely as a value,", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_, self, other) def xor_(self,", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.and_, self, other) def __and__(self, other):", "a second source.\"\"\" class output(bit): \"\"\" Bit that is designated an output. >>>", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) <= input(y)) ...", ">>> b.value 1 \"\"\" return self | (constant(other) if isinstance(other, int) else other)", "... bit.circuit(circuit()) ... b = output(input(x).xor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "xy[0] & xy[1]) >>> xys = [bits([x, y]) for x in (0, 1)", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "... bit.circuit(circuit()) ... b = output(input(x) <= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", ">>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs >> 3", "xys] [[0, 0], [0, 0], [1, 0], [1, 1]] >>> @synthesize ... def", "other) def __matmul__(self, other): \"\"\" >>> results = [] >>> for (x, y)", "all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def xnor_(self, other): \"\"\" >>> results", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) ^ input(y)) ...", "failed \"\"\" # Functions for determining types/signature from # the type annotation of", "parts import parts from circuit import op, gate, circuit, signature class bit(): \"\"\"", "bit.circuit(circuit()) ... b = output(input(x).or_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "zip(self, other)]) def xor_(self: bits, other: bits) -> bits: \"\"\" >>> results =", "return bits([x.imp_(y) for (x, y) in zip(self, other)]) def nand(self: bits, other) ->", "other)]) def __rshift__(self: bits, other) -> bits: \"\"\" Overloaded operator: rotation and shift", "outputs(~xs) ... ns = [int(y) for y in ys] ... c = bit.circuit()", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor_(input(y))) ... results.append(int(b) ==", "== c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.if_(y)", "all(results) True \"\"\" return bits([x.nimp_(y) for (x, y) in zip(self, other)]) def nif(self:", "bit.circuit() ... results.append(ns == c.evaluate([x, x, x, y, y, y])) >>> all(results) True", "bits(map(bit, [0,0,0,0,1,1,1,1])) >>> bs = bs >> {3} >>> [b.value for b in", "\"\"\" return bits([x.nor_(y) for (x, y) in zip(self, other)]) def __mod__(self, other) ->", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "== bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operation(op.not_, self) def __rsub__(self, other): \"\"\"", "nand_(self: bits, other) -> bits: \"\"\" >>> results = [] >>> for (x,", "(constant(other) if isinstance(other, int) else other) def nor(self, other): \"\"\" >>> results =", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "x]), inputs([y, y, y])) ... zs = outputs(xs.nand(ys)) ... ns = [int(z) for", "1) for y in (0, 1)] >>> [equal.circuit.evaluate(xy) for xy in xys] [[1],", "in bits.from_bytes(bytes([255]))] [1, 1, 1, 1, 1, 1, 1, 1] >>> bit.circuit(circuit()) >>>", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_, self, other) def", "= outputs(xs | ys) ... ns = [int(z) for z in zs] ...", ">>> all(results) True \"\"\" return bit.operation(op.imp_, self, other) def imp_(self, other): \"\"\" >>>", "for xy in xys] [[0, 0], [0, 0], [1, 0], [1, 1]] >>>", "return bit.operation(op.nor_, self, other) def __mod__(self, other): \"\"\" >>> results = [] >>>", "True \"\"\" return bits([x.and_(y) for (x, y) in zip(self, other)]) def __and__(self: bits,", "(x, y) in zip(self, other)]) def xor_(self: bits, other: bits) -> bits: \"\"\"", "b) in zip(range(len(self)), reversed(self))) def not_(self: bits) -> bits: \"\"\" >>> results =", "return bit._circuit.gate(operation, igs) def __init__(self, value, gate_=None): self.value = value self.gate = bit._circuit.gate()", "0, 0, 1] \"\"\" if isinstance(other, set) and isinstance(list(other)[0], int): # Rotation. quantity", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).if_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "\"\"\" return bit.operation(op.nif_, self, other) def __lt__(self, other): \"\"\" >>> results = []", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).and_(input(y)))", "c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.imp_(y) for", "*args: None) >>> bit.circuit(circuit()) >>> b = output(input(1).and_(input(1))) >>> b.value == bit.circuit().evaluate([1,1])[0] True", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif_(input(y))) ...", "bit.circuit(circuit()) >>> xs = bits.zeros(3) >>> ys = outputs(xs.not_()) >>> [y.value for y", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_, self, other) def", "def __matmul__(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "self) def __invert__(self): \"\"\" >>> results = [] >>> for x in [0,", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand(input(y)))", "in zip(self, other)]) def nor_(self: bits, other: bits) -> bits: \"\"\" >>> results", "b = output(input(x).nor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_,", "recent call last): ... ValueError: can only subtract a bit from the integer", "z in zs] ... c = bit.circuit() ... results.append(ns == c.evaluate([x, x, x,", "\"\"\" return bit.operation(op.nimp_, self, other) def __gt__(self, other): \"\"\" >>> results = []", "def operation(o, *args): # Ensure second argument is a `bit`. args = list(args)", "@ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self,", "xs = constants([0, 0, 0]) >>> ys = outputs(xs.not_()) >>> int(ys) 7 \"\"\"", "True \"\"\" return bits([x.nif_(y) for (x, y) in zip(self, other)]) def nif_(self: bits,", "bits: \"\"\" Overloaded operator: rotation and shift operations. >>> bit.circuit(circuit()) >>> bs =", "can only subtract a bit from the integer 1 \"\"\" if other ==", "return bit.operation(op.imp_, self, other) def nand(self, other): \"\"\" >>> results = [] >>>", "y) in zip(self, other)]) def __gt__(self: bits, other: bits) -> bits: \"\"\" >>>", "bits_type(int): # pylint: disable=R0903 \"\"\" Class for representing an input or output type", "= outputs(xs.imp_(ys)) ... ns = [int(z) for z in zs] ... c =", "else a # pylint: disable=W0123 try: # Construct the circuit and add it", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand(input(y))) ... results.append(int(b) ==", "== c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.and_(y)", "int): return self / (len(self)//list(other)[0]) # Parts of length `other`. else: return map(bits,", "b = output(input(x) == input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "for (x, y) in zip(self, other)]) def xor(self: bits, other: bits) -> bits:", "y])) ... zs = outputs(xs <= ys) ... ns = [int(z) for z", "def __rxor__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 1 ^ constant(0) >>>", "int: \"\"\" >>> bit.circuit(circuit()) >>> xs = constants([0, 0, 0]) >>> ys =", "bit._hook_operation is not None: r = bit._hook_operation(o, v, *args) if r is not", "from one source.\"\"\" class input_two(input): \"\"\"Bit that is designated as a variable input", "and returns an output of type `bit` or `bits`. >>> @synthesize ... def", "7 \"\"\" return sum(int(b)*(2**i) for (i, b) in zip(range(len(self)), reversed(self))) def not_(self: bits)", ">>> ys = outputs(xs.not_()) >>> int(ys) 7 \"\"\" return sum(int(b)*(2**i) for (i, b)", "\"\"\" if isinstance(other, set) and isinstance(list(other)[0], int): # Rotation. quantity = list(other)[0] return", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs ^ ys)", "all(results) True \"\"\" return bit.operation(op.imp_, self, other) def __le__(self, other): \"\"\" >>> results", "bits(map(input, l)) def outputs(l): return bits(map(output, l)) def synthesize(f): \"\"\" Decorator for automatically", "Compute the value of the result of the operation on the arguments. v", "zs = outputs(xs.if_(ys)) ... ns = [int(z) for z in zs] ... c", "def __invert__(self: bits) -> bits: \"\"\" >>> results = [] >>> for x", "b in bs] [1, 1, 1, 0, 0, 0, 0, 1] \"\"\" if", "track of relationships between operators and to represent the wires within a circuit", "\"\"\" from __future__ import annotations from typing import Sequence import doctest from parts", "bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs << 3 >>> [b.value for", "vector of abstract bits. \"\"\" @staticmethod def from_byte(byte_: int, constructor=bit) -> bits: return", "zip(self, other)]) def __rshift__(self: bits, other) -> bits: \"\"\" Overloaded operator: rotation and", "input_two(input): \"\"\"Bit that is designated as a variable input from a second source.\"\"\"", "all(results) True \"\"\" return bit.operation(op.nand_, self, other) def nand_(self, other): \"\"\" >>> results", "(x, y) in zip(self, other)]) def __lt__(self: bits, other: bits) -> bits: \"\"\"", "[0, 0, 0, 0]) >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss", "... bit.circuit(circuit()) ... b = output(input(x).imp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "... bit.circuit(circuit()) ... b = output(input(x).nif(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "is designated as a variable input from one source.\"\"\" class input_two(input): \"\"\"Bit that", "1]: ... bit.circuit(circuit()) ... b = output(~input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results)", "... b = output(input(x) | input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "__int__(self: bits) -> int: \"\"\" >>> bit.circuit(circuit()) >>> xs = constants([0, 0, 0])", "bit.circuit(circuit()) >>> b = 0 & constant(1) >>> b.value 0 \"\"\" return self", "return bit.operation(op.xnor_, self, other) def xnor_(self, other): \"\"\" >>> results = [] >>>", "list(self) result.extend(list(other)) return bits(result) def __pow__(self: bits, other) -> bits: \"\"\"Concatenation of bit", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.imp(ys)) ... ns =", "y, y])) ... zs = outputs(xs.nand(ys)) ... ns = [int(z) for z in", "-> bits: \"\"\" Overloaded operator: rotation and shift operations. >>> bit.circuit(circuit()) >>> bs", "if r is not None: return r return bit.constructor(*args)(v, bit.gate(o, [a.gate for a", "output(input(x).and_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.and_, self, other)", "in bits.from_bytes(bytes([11, 0]))] [0, 0, 0, 0, 1, 0, 1, 1, 0, 0,", "\"\"\" >>> bit.circuit(circuit()) >>> b = 0 & constant(1) >>> b.value 0 \"\"\"", "the supplied argument. \"\"\" return bits_type(argument)\\ if isinstance(argument, int) else\\ list.__new__(cls, argument) def", "the circuit and add it to the function as an attribute. bit.circuit(circuit()) args_in", "l)) def outputs(l): return bits(map(output, l)) def synthesize(f): \"\"\" Decorator for automatically synthesizing", "y, y])) ... zs = outputs(xs.and_(ys)) ... ns = [int(z) for z in", "[] >>> for x in [0, 1]: ... bit.circuit(circuit()) ... xs = inputs([x,", "and len(other) == 1 and isinstance(list(other)[0], int): return self / (len(self)//list(other)[0]) # Parts", "0] \"\"\" return bits([ bit_ for byte_ in bytes_ for bit_ in bits.from_byte(byte_,", "decorated function. type_in = lambda a: input(0) if a is bit else inputs([0]", "of type `bit` or `bits`. >>> @synthesize ... def equal(x: bit, y: bit)", "it to a new wire. self.value = b.value self.gate = bit._circuit.gate(op.id_, [b.gate], is_output=True)", "hook if it exists and if # it returns an output. if bit._hook_operation", "= inputs([x, x, x]) ... ys = outputs(~xs) ... ns = [int(y) for", "bit): # Check if bit is ready as final output or whether there", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).or_(input(y))) ... results.append(int(b) ==", "-> bits: return bits([ constructor(bit_) for bit_ in reversed([(byte_>>i)%2 for i in range(8)])", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nif_, self, other) def", "return bits_type(argument)\\ if isinstance(argument, int) else\\ list.__new__(cls, argument) def __int__(self: bits) -> int:", "output(input(x).xor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_, self, other)", "bits, other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\" result = list(self) result.extend(list(other)) return", "[b.value for b in bs] [1, 0, 0, 0, 0, 0, 0, 0]", "[1, 0], [1, 1]] >>> @synthesize ... def equal(x, y): ... return x", "use. \"\"\" if isinstance(b1, input_one) and isinstance(b2, input_one): return input_one elif isinstance(b1, input_two)", "other)]) def if_(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "input(0) if a is bit else inputs([0] * a) type_out = lambda a:", "... zs = outputs(xs.or_(ys)) ... ns = [int(z) for z in zs] ...", "== bit.circuit().evaluate([0,0])[0] True \"\"\" _circuit = None _hook_operation = None @staticmethod def circuit(circuit_=None):", "in args]) # Return output from hook if it exists and if #", "original function. return f if __name__ == \"__main__\": doctest.testmod() # pragma: no cover", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.and_(ys)) ... ns = [int(z)", "... bit.circuit(circuit()) ... b = output(input(x).nand(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "it. if len(b.gate.outputs) > 0: b = ~(~b) # Preserve the bit by", "= outputs(xs.and_(ys)) ... ns = [int(z) for z in zs] ... c =", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "other)]) def __and__(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.and_(ys)) ...", "and shift operations. >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs =", "y) in zip(self, other)]) def __lt__(self: bits, other: bits) -> bits: \"\"\" >>>", "= outputs(xs % ys) ... ns = [int(z) for z in zs] ...", "class bits_type(int): # pylint: disable=R0903 \"\"\" Class for representing an input or output", "bit.circuit(circuit()) ... b = output(input(x) | input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "output(input(x).nif_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nif_, self, other)", "all(results) True \"\"\" return bit.operation(op.if_, self, other) def __ge__(self, other): \"\"\" >>> results", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.nand(ys)) ... ns = [int(z)", "for (x, y) in zip(self, other)]) def __or__(self: bits, other: bits) -> bits:", "constant(bit): \"\"\"Bit that is designated as a constant input.\"\"\" class input(bit): \"\"\"Bit that", "bit.constructor(*args)(v, bit.gate(o, [a.gate for a in args])) @staticmethod def constructor(b1, b2=None): # The", "self.gate = bit._circuit.gate(op.id_, is_input=True) class input_one(input): \"\"\"Bit that is designated as a variable", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) >", "y, y])) ... zs = outputs(xs.nimp(ys)) ... ns = [int(z) for z in", "\"\"\" return bits([x.and_(y) for (x, y) in zip(self, other)]) def __and__(self: bits, other:", "output(input(x) % input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_,", "those definitions. \"\"\" from __future__ import annotations from typing import Sequence import doctest", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xnor(ys)) ... ns", "circuit_ return None else: bit._circuit.prune_and_topological_sort_stable() return bit._circuit @staticmethod def hook_operation(hook=None): bit._hook_operation = hook", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nimp_, self, other) def nimp_(self, other):", "... def conjunction(xy: bits(2)) -> bits(2): ... return (xy[0], xy[0] & xy[1]) >>>", "output(input(0).and_(input(0))) >>> b.value == bit.circuit().evaluate([0,0])[0] True \"\"\" _circuit = None _hook_operation = None", "if isinstance(b1, input_one) and isinstance(b2, input_one): return input_one elif isinstance(b1, input_two) and isinstance(b2,", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "\"\"\" class bits(list): \"\"\" Class for representing a vector of abstract bits. \"\"\"", "\"\"\"Bit that is designated as a constant input.\"\"\" class input(bit): \"\"\"Bit that is", "[0, 0], [0, 0]] >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss", "... b = output(input(x) & input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "\"\"\" return bits([x.and_(y) for (x, y) in zip(self, other)]) def nimp(self: bits, other:", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif_(input(y)))", "that is designated as a variable input from a second source.\"\"\" class output(bit):", "\"\"\" return bits([constant(0)]*n) def __new__(cls, argument = None) -> bits: \"\"\" Return bits", "zs = outputs(xs.nand_(ys)) ... ns = [int(z) for z in zs] ... c", "y, y])) >>> all(results) True \"\"\" return bits([x.and_(y) for (x, y) in zip(self,", "__or__(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "list(bs / [1, 3, 4]) >>> [[b.value for b in bs] for bs", "... b = output(input(x).nif_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", ">>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def xnor_(self, other): \"\"\" >>>", "def constructor(b1, b2=None): # The inference code below is not currently in use.", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) | input(y)) ... results.append(int(b)", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.or_(ys)) ... ns = [int(z)", "True \"\"\" return bits([x.if_(y) for (x, y) in zip(self, other)]) def imp(self: bits,", "1) for y in (0, 1)] >>> [conjunction.circuit.evaluate(xy) for xy in xys] [[0,", "from the integer 1') def and_(self, other): \"\"\" >>> results = [] >>>", "input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nif(other) def xor(self,", "bit.circuit(circuit()) >>> 2 - input(0) Traceback (most recent call last): ... ValueError: can", "nif(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "return bits([x.nif_(y) for (x, y) in zip(self, other)]) def xor(self: bits, other: bits)", "_ in range(other)]) def __truediv__(self: bits, other) -> Sequence[bits]: \"\"\" >>> bit.circuit(circuit()) >>>", "def __gt__(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "y, y])) >>> all(results) True \"\"\" return bits([x.or_(y) for (x, y) in zip(self,", "bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / {2}) >>>", "zip(self, other)]) def nimp(self: bits, other: bits) -> bits: \"\"\" >>> results =", ">>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... (xs, ys) = (inputs([x,", "def xnor_(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", ">>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs >> 3 >>> [b.value", "def __truediv__(self: bits, other) -> Sequence[bits]: \"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit,", "circuit synthesis failed \"\"\" # Functions for determining types/signature from # the type", "[b.gate], is_output=True) class bits_type(int): # pylint: disable=R0903 \"\"\" Class for representing an input", "len(other) > 0 and isinstance(other[0], int): return map(bits, parts(self, length=other)) # Sequence of", ">>> [b0.value, b1.value, b2.value] [0, 1, 0] \"\"\" def __init__(self: bit, b: bit):", "\"\"\" return self ^ (constant(other) if isinstance(other, int) else other) def or_(self, other):", "\"\"\" return bit.operation(op.not_, self) def __rsub__(self, other): \"\"\" >>> results = [] >>>", "= output(input(x).imp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_, self,", "\"\"\" >>> results = [] >>> for x in [0, 1]: ... bit.circuit(circuit())", "1]: ... bit.circuit(circuit()) ... xs = inputs([x, x, x]) ... ys = outputs(~xs)", "== c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nor_(y)", "y) in zip(self, other)]) def imp_(self: bits, other: bits) -> bits: \"\"\" >>>", "all(results) True \"\"\" return bits([x.and_(y) for (x, y) in zip(self, other)]) def nimp(self:", "y, y, y])) >>> all(results) True \"\"\" return bits([x.imp_(y) for (x, y) in", "x]), inputs([y, y, y])) ... zs = outputs(xs >= ys) ... ns =", "bit, b: bit): # Check if bit is ready as final output or", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_, self, other) def nor_(self,", "== c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.or_(y)", "... bit.circuit(circuit()) ... b = output(~input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True", "return bits([x.nimp_(y) for (x, y) in zip(self, other)]) def __gt__(self: bits, other: bits)", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xor(ys)) ... ns =", "def xnor(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nif_(ys)) ...", "in zip(self, other)]) def xor_(self: bits, other: bits) -> bits: \"\"\" >>> results", "bit from the integer 1') def and_(self, other): \"\"\" >>> results = []", "if isinstance(other, list) and len(other) > 0 and isinstance(other[0], int): return map(bits, parts(self,", "if_(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", ">>> bss = list(bs / 2) >>> ([b.value for b in bss[0]], [b.value", "0], [1, 0], [1, 1]] >>> @synthesize ... def equal(x, y): ... return", "abstract bit. Such a bit can be interpreted concretely as a value, but", "= output(b0) >>> [b0.value, b1.value, b2.value] [0, 1, 0] \"\"\" def __init__(self: bit,", "constructor(bit_) for bit_ in reversed([(byte_>>i)%2 for i in range(8)]) ]) @staticmethod def from_bytes(bytes_,", "in zip(self, other)]) def __or__(self: bits, other: bits) -> bits: \"\"\" >>> results", "other) def __ror__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 1 | constant(0)", "True \"\"\" return bits([x.nor_(y) for (x, y) in zip(self, other)]) def xnor(self: bits,", "bits([constant(0)]*other) ** bits(self[0:len(self)-other]) def __lshift__(self: bits, other) -> bits: \"\"\" >>> bit.circuit(circuit()) >>>", "... b = output(input(x) < input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp_(input(y))) ...", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nimp_(ys)) ... ns =", "__int__(self): return self.value def not_(self): \"\"\" >>> results = [] >>> for x", "b = 1 | constant(0) >>> b.value 1 \"\"\" return self | (constant(other)", ">>> all(results) True \"\"\" return bit.operation(op.nor_, self, other) def __mod__(self, other): \"\"\" >>>", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.if_, self, other) def __ge__(self, other): \"\"\"", "bit can be interpreted concretely as a value, but it is also used", "bits(self[0:len(self)-other]) def __lshift__(self: bits, other) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> bs =", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.or_, self, other) def __ror__(self,", "None else: bit._circuit.prune_and_topological_sort_stable() return bit._circuit @staticmethod def hook_operation(hook=None): bit._hook_operation = hook @staticmethod def", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) & input(y)) ...", "def __rsub__(self, other): \"\"\" >>> results = [] >>> for x in [0,", "= output(input(x).nand(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self,", "is designated an output. >>> bit.circuit(circuit()) >>> b0 = output(input(1).not_()) >>> b1 =", "other) class constant(bit): \"\"\"Bit that is designated as a constant input.\"\"\" class input(bit):", "y in ys] [1, 1, 1] \"\"\" return bits([constant(0)]*n) def __new__(cls, argument =", "y, y])) ... zs = outputs(xs.xor_(ys)) ... ns = [int(z) for z in", "from the integer 1 \"\"\" if other == 1: return bit.operation(op.not_, self) raise", "\"\"\" return bit.operation(op.and_, self, other) def __rand__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def if_(self,", "y, y, y])) >>> all(results) True \"\"\" return bits([x.if_(y) for (x, y) in", "outputs(xs.and_(ys)) ... ns = [int(z) for z in zs] ... c = bit.circuit()", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp_(input(y))) ... results.append(int(b) ==", "return input_two elif isinstance(b1, (input_one, input_two)) and b2 is None: return type(b1) else:", "xs = bits.zeros(3) >>> ys = outputs(xs.not_()) >>> [y.value for y in ys]", "y, y, y])) >>> all(results) True \"\"\" return bits([x.or_(y) for (x, y) in", "ys = outputs(xs.not_()) >>> int(ys) 7 \"\"\" return sum(int(b)*(2**i) for (i, b) in", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor_(input(y))) ...", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) > input(y)) ... results.append(int(b)", "= output(input(x).nif_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nif_, self,", "return bits([ constructor(bit_) for bit_ in reversed([(byte_>>i)%2 for i in range(8)]) ]) @staticmethod", "return bit.operation(op.not_, self) def __rsub__(self, other): \"\"\" >>> results = [] >>> for", "return None else: bit._circuit.prune_and_topological_sort_stable() return bit._circuit @staticmethod def hook_operation(hook=None): bit._hook_operation = hook @staticmethod", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.or_, self, other) def __ror__(self, other): \"\"\"", "... b = output(input(x) >= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "other: bits) -> bits: \"\"\" >>> results = [] >>> for (x, y)", "@staticmethod def from_byte(byte_: int, constructor=bit) -> bits: return bits([ constructor(bit_) for bit_ in", "return bits([x.and_(y) for (x, y) in zip(self, other)]) def nimp(self: bits, other: bits)", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nif(ys)) ... ns", "eval(a) if isinstance(a, str) else a # pylint: disable=W0123 try: # Construct the", "x]), inputs([y, y, y])) ... zs = outputs(xs.nif_(ys)) ... ns = [int(z) for", "isinstance(other, list) and len(other) > 0 and isinstance(other[0], int): return map(bits, parts(self, length=other))", "bit.operation(op.nif_, self, other) def nif_(self, other): \"\"\" >>> results = [] >>> for", "0, 0, 0, 0, 0] \"\"\" return bits(self[other:]) ** bits([constant(0) for _ in", "in zip(self, other)]) def __xor__(self: bits, other: bits) -> bits: \"\"\" >>> results", "__truediv__(self: bits, other) -> Sequence[bits]: \"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0]))", "<< 3 >>> [b.value for b in bs] [1, 0, 0, 0, 0,", "lambda a: eval(a) if isinstance(a, str) else a # pylint: disable=W0123 try: #", "3 >>> [b.value for b in bs] [1, 0, 0, 0, 0, 0,", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) % input(y))", "from # the type annotation of the decorated function. type_in = lambda a:", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x)", "y, y, y])) >>> all(results) True \"\"\" return bits([x.xnor_(y) for (x, y) in", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self, other) def nand_(self, other): \"\"\"", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_, self, other) def __le__(self, other): \"\"\"", "in zip(self, other)]) def xnor_(self: bits, other: bits) -> bits: \"\"\" >>> results", "else: # Shift return bits([constant(0)]*other) ** bits(self[0:len(self)-other]) def __lshift__(self: bits, other) -> bits:", "... zs = outputs(xs.and_(ys)) ... ns = [int(z) for z in zs] ...", "\"\"\" return bits([x.or_(y) for (x, y) in zip(self, other)]) def nor(self: bits, other:", "y, y])) ... zs = outputs(xs.if_(ys)) ... ns = [int(z) for z in", "b in bss[0]], [b.value for b in bss[1]]) ([1, 1, 1, 1], [0,", "bit.circuit(circuit()) ... xs = inputs([x, x, x]) ... ys = outputs(xs.not_()) ... ns", ">>> bss = list(bs / [1, 3, 4]) >>> [[b.value for b in", "other) def __or__(self, other): \"\"\" >>> results = [] >>> for (x, y)", "def __ror__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 1 | constant(0) >>>", "\"\"\" @staticmethod def from_byte(byte_: int, constructor=bit) -> bits: return bits([ constructor(bit_) for bit_", "... zs = outputs(xs.xnor_(ys)) ... ns = [int(z) for z in zs] ...", "return (xy[0], xy[0] & xy[1]) >>> xys = [bits([x, y]) for x in", "input_one) and isinstance(b2, input_one): return input_one elif isinstance(b1, input_two) and isinstance(b2, input_two): return", ">>> b.value 1 \"\"\" return self ^ (constant(other) if isinstance(other, int) else other)", "\"\"\" return bit.operation(op.nor_, self, other) def xnor(self, other): \"\"\" >>> results = []", "[0], [0], [1]] >>> @synthesize ... def conjunction(xy: bits(2)) -> bits(2): ... return", "if isinstance(other, int) else other) def or_(self, other): \"\"\" >>> results = []", "(x, y) in zip(self, other)]) def nand_(self: bits, other) -> bits: \"\"\" >>>", "hook_operation(hook=None): bit._hook_operation = hook @staticmethod def operation(o, *args): # Ensure second argument is", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nimp_(y) for (x, y)", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs & ys) ...", "__le__(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "x, x]), inputs([y, y, y])) ... zs = outputs(xs == ys) ... ns", "it exists and if # it returns an output. if bit._hook_operation is not", "can be interpreted concretely as a value, but it is also used to", "= bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs >> 3 >>> [b.value for b", "isinstance(argument, int) else\\ list.__new__(cls, argument) def __int__(self: bits) -> int: \"\"\" >>> bit.circuit(circuit())", "c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nor_(y) for", "assembling abstract definitions of logic circuits and synthesizing circuits from those definitions. \"\"\"", "not None: return r return bit.constructor(*args)(v, bit.gate(o, [a.gate for a in args])) @staticmethod", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_, self, other) def __mod__(self, other):", "return bits(self[other:]) ** bits([constant(0) for _ in range(other)]) def __truediv__(self: bits, other) ->", "self.value = value self.gate = bit._circuit.gate() if gate_ is None else gate_ def", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.if_, self, other) def __ge__(self,", "lengths. elif isinstance(other, set) and len(other) == 1 and isinstance(list(other)[0], int): return self", "of parts is `other`. def __add__(self: bits, other) -> bits: \"\"\"Concatenation of bit", "conjunction(xy: bits(2)) -> bits(2): ... return (xy[0], xy[0] & xy[1]) >>> xys =", "bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs >> 3 >>> [b.value for", "other) def xor_(self, other): \"\"\" >>> results = [] >>> for (x, y)", "input(bit): \"\"\"Bit that is designated as a variable input.\"\"\" def __init__(self: bit, value:", "1, 1, 1] >>> bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([11, 0]))] [0,", "`other`. else: return map(bits, parts(self, other)) # Number of parts is `other`. def", "bit.circuit(circuit()) >>> bs = bits(map(bit, [0,0,0,0,1,1,1,1])) >>> bs = bs >> {3} >>>", "nif(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "self, other) def __and__(self, other): \"\"\" >>> results = [] >>> for (x,", "all(results) True \"\"\" return bits([x.not_() for x in self]) def and_(self: bits, other:", "is not None: r = bit._hook_operation(o, v, *args) if r is not None:", "zip(self, other)]) def __xor__(self: bits, other: bits) -> bits: \"\"\" >>> results =", "self / (len(self)//list(other)[0]) # Parts of length `other`. else: return map(bits, parts(self, other))", "True \"\"\" return bit.operation(op.nimp_, self, other) def __gt__(self, other): \"\"\" >>> results =", "for assembling abstract definitions of logic circuits and synthesizing circuits from those definitions.", "input from a second source.\"\"\" class output(bit): \"\"\" Bit that is designated an", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs >= ys)", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_, self, other) def __mod__(self, other): \"\"\"", "bit.circuit(circuit()) ... b = output(input(x).nif_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", ">>> all(results) True \"\"\" return bits([x.nand_(y) for (x, y) in zip(self, other)]) def", "= bits.zeros(3) >>> ys = outputs(xs.not_()) >>> [y.value for y in ys] [1,", "y])) ... zs = outputs(xs.nand_(ys)) ... ns = [int(z) for z in zs]", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_, self, other) def xor_(self, other):", "bit.operation(op.nor_, self, other) def nor_(self, other): \"\"\" >>> results = [] >>> for", "... bit.circuit(circuit()) ... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ...", "[(0, 0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... (xs, ys)", "bit.operation(op.if_, self, other) def imp(self, other): \"\"\" >>> results = [] >>> for", "its arguments and returns an output of type `bit` or `bits`. >>> @synthesize", "zip(self, other)]) def __le__(self: bits, other: bits) -> bits: \"\"\" >>> results =", "__lt__(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "else other) def or_(self, other): \"\"\" >>> results = [] >>> for (x,", "zs = outputs(xs & ys) ... ns = [int(z) for z in zs]", "the integer 1 \"\"\" if other == 1: return bit.operation(op.not_, self) raise ValueError('can", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def xnor_(self, other):", ">>> bs = bs >> 3 >>> [b.value for b in bs] [0,", "other) def __le__(self, other): \"\"\" >>> results = [] >>> for (x, y)", "... bit.circuit(circuit()) ... b = output(input(x).and_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "but it is also used to keep track of relationships between operators and", "bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / 2) >>> ([b.value for b in", "other) def if_(self, other): \"\"\" >>> results = [] >>> for (x, y)", "True \"\"\" return bit.operation(op.nand_, self, other) def nand_(self, other): \"\"\" >>> results =", "= value self.gate = bit._circuit.gate() if gate_ is None else gate_ def __int__(self):", "int) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> xs = bits.zeros(3) >>> ys =", "b1 = output(b0.not_()) >>> b2 = output(b0) >>> [b0.value, b1.value, b2.value] [0, 1,", "def __lt__(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]", "bit.operation(op.not_, self) raise ValueError('can only subtract a bit from the integer 1') def", "... bit.circuit(circuit()) ... b = output(input(x) % input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "all(results) True \"\"\" return bits([x.imp_(y) for (x, y) in zip(self, other)]) def __le__(self:", "for (x, y) in zip(self, other)]) def nor(self: bits, other: bits) -> bits:", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "= [bits([x, y]) for x in (0, 1) for y in (0, 1)]", "b = output(input(x) & input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "final output or whether there are others dependent on it. if len(b.gate.outputs) >", "in self]) def and_(self: bits, other: bits) -> bits: \"\"\" >>> results =", "bits: return bits([ constructor(bit_) for bit_ in reversed([(byte_>>i)%2 for i in range(8)]) ])", ">>> for x in [0, 1]: ... bit.circuit(circuit()) ... b = output(~input(x)) ...", "y) in zip(self, other)]) def __and__(self: bits, other: bits) -> bits: \"\"\" >>>", "= outputs(xs.nand_(ys)) ... ns = [int(z) for z in zs] ... c =", "\"\"\" _circuit = None _hook_operation = None @staticmethod def circuit(circuit_=None): if circuit_ is", "nif_(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "[0, 1]: ... bit.circuit(circuit()) ... b = output(input(x).not_()) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>>", "output(input(x) >= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.if_,", "nif_(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.and_, self, other) def __rand__(self, other):", "y])) >>> all(results) True \"\"\" return bits([x.nand_(y) for (x, y) in zip(self, other)])", "True \"\"\" return bits([x.imp_(y) for (x, y) in zip(self, other)]) def imp_(self: bits,", "in zip(self, other)]) def nor(self: bits, other: bits) -> bits: \"\"\" >>> results", "def __invert__(self): \"\"\" >>> results = [] >>> for x in [0, 1]:", "True \"\"\" return bit.operation(op.or_, self, other) def __or__(self, other): \"\"\" >>> results =", "True \"\"\" return bits([x.nor_(y) for (x, y) in zip(self, other)]) def __mod__(self, other)", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "circuits. Embedded domain-specific combinator library for assembling abstract definitions of logic circuits and", "in zip(range(len(self)), reversed(self))) def not_(self: bits) -> bits: \"\"\" >>> results = []", "return bit.operation(op.nif_, self, other) def nif_(self, other): \"\"\" >>> results = [] >>>", ">>> xs = constants([0, 0, 0]) >>> ys = outputs(xs.not_()) >>> int(ys) 7", "b0 = output(input(1).not_()) >>> b1 = output(b0.not_()) >>> b2 = output(b0) >>> [b0.value,", "1, 1, 1, 1] >>> bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([11, 0]))]", "output from hook if it exists and if # it returns an output.", "... c = bit.circuit() ... results.append(ns == c.evaluate([x, x, x])) >>> all(results) True", "class constant(bit): \"\"\"Bit that is designated as a constant input.\"\"\" class input(bit): \"\"\"Bit", "y) in zip(self, other)]) def nimp(self: bits, other: bits) -> bits: \"\"\" >>>", "__or__(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "< input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nif(other) def", "other)]) def imp_(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "bits([x.and_(y) for (x, y) in zip(self, other)]) def __and__(self: bits, other: bits) ->", ">>> bs = bits(map(bit, [0,0,0,0,1,1,1,1])) >>> bs = bs >> {3} >>> [b.value", "\"\"\" return bit.operation(op.xnor_, self, other) def xnor_(self, other): \"\"\" >>> results = []", "0, 1, 1, 1, 1, 0] >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [0,0,0,0,1,1,1,1]))", "outputs(xs & ys) ... ns = [int(z) for z in zs] ... c", "def zeros(n: int) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> xs = bits.zeros(3) >>>", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xnor_(ys)) ... ns", "output(input(x) < input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nif(other)", "True \"\"\" _circuit = None _hook_operation = None @staticmethod def circuit(circuit_=None): if circuit_", "in bss] [[1], [1, 1, 1], [0, 0, 0, 0]] \"\"\" if isinstance(other,", "b = output(input(x).nif_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nif_,", "all(results) True \"\"\" return bits([x.if_(y) for (x, y) in zip(self, other)]) def __ge__(self:", "1]] >>> @synthesize ... def equal(x, y): ... return x & y Traceback", "synthesizing a circuit from a function that takes only `bit` and/or `bits` objects", "RuntimeError('automated circuit synthesis failed') from None # Return the original function. return f", "The inference code below is not currently in use. \"\"\" if isinstance(b1, input_one)", "= circuit_ return None else: bit._circuit.prune_and_topological_sort_stable() return bit._circuit @staticmethod def hook_operation(hook=None): bit._hook_operation =", "or output type of a function decorated for automated synthesis. \"\"\" class bits(list):", "for (x, y) in zip(self, other)]) def __gt__(self: bits, other: bits) -> bits:", "all(results) True \"\"\" return bits([x.xnor_(y) for (x, y) in zip(self, other)]) def if_(self:", "bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / [1, 3, 4]) >>>", "[1, 1, 1] \"\"\" return bits([constant(0)]*n) def __new__(cls, argument = None) -> bits:", "1 \"\"\" return self ^ (constant(other) if isinstance(other, int) else other) def or_(self,", "... zs = outputs(xs.if_(ys)) ... ns = [int(z) for z in zs] ...", "def equal(x, y): ... return x & y Traceback (most recent call last):", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.or_, self, other) def", "zs] ... c = bit.circuit() ... results.append(ns == c.evaluate([x, x, x, y, y,", "= outputs(~xs) ... ns = [int(y) for y in ys] ... c =", "bits: \"\"\"Concatenation of bit vectors.\"\"\" return self + other def constants(l): return bits(map(constant,", "zs = outputs(xs.or_(ys)) ... ns = [int(z) for z in zs] ... c", "[1,1,1,1,0,0,0,0])) >>> bs = bs << 3 >>> [b.value for b in bs]", ">>> all(results) True \"\"\" return bits([x.imp_(y) for (x, y) in zip(self, other)]) def", "__rand__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 0 & constant(1) >>> b.value", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) & input(y)) ... results.append(int(b) ==", "for x in [0, 1]: ... bit.circuit(circuit()) ... b = output(~input(x)) ... results.append(int(b)", "& ys) ... ns = [int(z) for z in zs] ... c =", "bit.operation(op.nand_, self, other) def nand_(self, other): \"\"\" >>> results = [] >>> for", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs <=", "\"\"\" return bit.operation(op.nor_, self, other) def nor_(self, other): \"\"\" >>> results = []", "and add it to the function as an attribute. bit.circuit(circuit()) args_in = {", "... zs = outputs(xs & ys) ... ns = [int(z) for z in", "y): ... return x & y Traceback (most recent call last): ... RuntimeError:", "whether there are others dependent on it. if len(b.gate.outputs) > 0: b =", "and_(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "bit.circuit() except: raise RuntimeError('automated circuit synthesis failed') from None # Return the original", "y, y])) ... zs = outputs(xs.xnor(ys)) ... ns = [int(z) for z in", "bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([255]))] [1, 1, 1, 1, 1, 1,", "[1,1,1,1,0,0,0,0])) >>> bss = list(bs / {2}) >>> [[b.value for b in bs]", "l)) def inputs(l): return bits(map(input, l)) def outputs(l): return bits(map(output, l)) def synthesize(f):", "(x, y) in zip(self, other)]) def if_(self: bits, other: bits) -> bits: \"\"\"", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp_(input(y))) ... results.append(int(b)", "all(results) True \"\"\" return bit.operation(op.or_, self, other) def __or__(self, other): \"\"\" >>> results", "bit.circuit(circuit()) ... b = output(input(x).imp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "return bits([x.xor_(y) for (x, y) in zip(self, other)]) def xor_(self: bits, other: bits)", ">>> b1 = output(b0.not_()) >>> b2 = output(b0) >>> [b0.value, b1.value, b2.value] [0,", "y) in zip(self, other)]) def nif(self: bits, other: bits) -> bits: \"\"\" >>>", "= output(input(x).if_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.if_, self,", "(x, y) in zip(self, other)]) def xor(self: bits, other: bits) -> bits: \"\"\"", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp_(input(y))) ... results.append(int(b)", ">>> @synthesize ... def equal(x: bit, y: bit) -> bit: ... return (x", "call last): ... ValueError: can only subtract a bit from the integer 1", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nif_(y) for (x, y)", "return bits([constant(0)]*other) ** bits(self[0:len(self)-other]) def __lshift__(self: bits, other) -> bits: \"\"\" >>> bit.circuit(circuit())", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.xor(ys)) ... ns = [int(z)", "return bits([x.nor_(y) for (x, y) in zip(self, other)]) def xnor(self: bits, other: bits)", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nif(other) def xor(self, other): \"\"\"", "other)]) def nif_(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "function that takes only `bit` and/or `bits` objects as its arguments and returns", "= output(input(x).nand_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self,", "c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.xor_(y) for", "bits, other) -> bits: \"\"\" >>> results = [] >>> for (x, y)", "y, y])) ... zs = outputs(xs <= ys) ... ns = [int(z) for", "input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.or_, self, other)", "x]), inputs([y, y, y])) ... zs = outputs(xs % ys) ... ns =", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.and_, self, other) def", "output. if bit._hook_operation is not None: r = bit._hook_operation(o, v, *args) if r", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand(input(y))) ...", "for (x, y) in zip(self, other)]) def nor_(self: bits, other: bits) -> bits:", "(1, 1)]: ... bit.circuit(circuit()) ... (xs, ys) = (inputs([x, x, x]), inputs([y, y,", "typing import Sequence import doctest from parts import parts from circuit import op,", "x in (0, 1) for y in (0, 1)] >>> [equal.circuit.evaluate(xy) for xy", "hook >>> bit.hook_operation(make_hook(bit)) >>> bit.circuit(circuit()) >>> b = output(input(0).and_(input(0))) >>> b.value == bit.circuit().evaluate([0,0])[0]", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).and_(input(y))) ... results.append(int(b)", "return bit @staticmethod def gate(operation, igs): return bit._circuit.gate(operation, igs) def __init__(self, value, gate_=None):", "@staticmethod def zeros(n: int) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> xs = bits.zeros(3)", "... bit.circuit(circuit()) ... b = output(input(x) ^ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "[int(z) for z in zs] ... c = bit.circuit() ... results.append(ns == c.evaluate([x,", "is ready as final output or whether there are others dependent on it.", "return bit.operation(op.or_, self, other) def __or__(self, other): \"\"\" >>> results = [] >>>", "y, y])) ... zs = outputs(xs.nif(ys)) ... ns = [int(z) for z in", "= [] >>> for x in [0, 1]: ... bit.circuit(circuit()) ... b =", "== bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operation(op.not_, self) def __invert__(self): \"\"\" >>>", ">> 3 >>> [b.value for b in bs] [0, 0, 0, 1, 1,", "= output(input(x).nor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_, self,", "... c = bit.circuit() ... results.append(ns == c.evaluate([x, x, x, y, y, y]))", "= outputs(xs == ys) ... ns = [int(z) for z in zs] ...", "= list(bs / [1, 3, 4]) >>> [[b.value for b in bs] for", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor_(input(y))) ... results.append(int(b) ==", "\"\"\" >>> bit.circuit(circuit()) >>> xs = bits.zeros(3) >>> ys = outputs(xs.not_()) >>> [y.value", "bits([x.if_(y) for (x, y) in zip(self, other)]) def imp(self: bits, other: bits) ->", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self, other) def __matmul__(self, other): \"\"\"", "Return bits object given the supplied argument. \"\"\" return bits_type(argument)\\ if isinstance(argument, int)", "if isinstance(other, int) else other) def nimp(self, other): \"\"\" >>> results = []", "import Sequence import doctest from parts import parts from circuit import op, gate,", "\"\"\" return bits([x.not_() for x in self]) def __invert__(self: bits) -> bits: \"\"\"", "= 1 ^ constant(0) >>> b.value 1 \"\"\" return self ^ (constant(other) if", "other)]) def xor(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "0 & constant(1) >>> b.value 0 \"\"\" return self & (constant(other) if isinstance(other,", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def if_(self, other):", "bit_ in bits.from_byte(byte_, constructor) ]) @staticmethod def zeros(n: int) -> bits: \"\"\" >>>", "return bit.operation(op.xnor_, self, other) def if_(self, other): \"\"\" >>> results = [] >>>", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.nimp(ys)) ... ns = [int(z)", "other)]) def nand(self: bits, other) -> bits: \"\"\" >>> results = [] >>>", "\"\"\" >>> results = [] >>> for (x, y) in [(0, 0), (0,", "return self | (constant(other) if isinstance(other, int) else other) def nor(self, other): \"\"\"", "xor_(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_, self, other) def __mod__(self,", "1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0] \"\"\"", "failed') from None # Return the original function. return f if __name__ ==", "@staticmethod def from_bytes(bytes_, constructor=bit) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> [b.value for b", "!= 'return' } type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit = bit.circuit() except: raise RuntimeError('automated circuit synthesis failed')", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self, other) def __matmul__(self, other):", "x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.and_(y) for (x,", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) < input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "bit.circuit().evaluate([0,0])[0] True \"\"\" _circuit = None _hook_operation = None @staticmethod def circuit(circuit_=None): if", "outputs(xs < ys) ... ns = [int(z) for z in zs] ... c", "return bits([x.xor_(y) for (x, y) in zip(self, other)]) def __xor__(self: bits, other: bits)", "constructor(b1, b2=None): # The inference code below is not currently in use. \"\"\"", "[] >>> for x in [0, 1]: ... bit.circuit(circuit()) ... b = output(input(x).not_())", "return self.nif(other) def xor(self, other): \"\"\" >>> results = [] >>> for (x,", "Number of parts is `other`. def __add__(self: bits, other) -> bits: \"\"\"Concatenation of", "-> bits: \"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs =", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "= [int(z) for z in zs] ... c = bit.circuit() ... results.append(ns ==", "def __ge__(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.and_(ys)) ... ns", "... bit.circuit(circuit()) ... b = output(input(x).xor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "True \"\"\" return bit.operation(op.not_, self) def __rsub__(self, other): \"\"\" >>> results = []", "bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity]) else: # Shift return bits([constant(0)]*other) ** bits(self[0:len(self)-other]) def __lshift__(self: bits,", "\"\"\" >>> bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([255]))] [1, 1, 1, 1,", "[0, 1]: ... bit.circuit(circuit()) ... xs = inputs([x, x, x]) ... ys =", "other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\" result = list(self) result.extend(list(other)) return bits(result)", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp(input(y)))", "other) -> bits: \"\"\" >>> results = [] >>> for (x, y) in", "bits(self[other:]) ** bits([constant(0) for _ in range(other)]) def __truediv__(self: bits, other) -> Sequence[bits]:", "other): \"\"\" >>> bit.circuit(circuit()) >>> b = 0 & constant(1) >>> b.value 0", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) == input(y)) ... results.append(int(b) ==", "bit \"\"\" return bit @staticmethod def gate(operation, igs): return bit._circuit.gate(operation, igs) def __init__(self,", "True \"\"\" return bits([x.nand_(y) for (x, y) in zip(self, other)]) def __rshift__(self: bits,", ">>> all(results) True \"\"\" return bit.operation(op.nif_, self, other) def __lt__(self, other): \"\"\" >>>", ">>> for x in [0, 1]: ... bit.circuit(circuit()) ... b = output(input(x).not_()) ...", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) <= input(y)) ... results.append(int(b)", "\"\"\" return bits(self[other:]) ** bits([constant(0) for _ in range(other)]) def __truediv__(self: bits, other)", "= output(input(1).and_(input(1))) >>> b.value == bit.circuit().evaluate([1,1])[0] True >>> def make_hook(bit_): ... def hook(o,", "[b.value for b in bits.from_bytes(bytes([255]))] [1, 1, 1, 1, 1, 1, 1, 1]", "in ys] ... c = bit.circuit() ... results.append(ns == c.evaluate([x, x, x])) >>>", "= outputs(xs.nor_(ys)) ... ns = [int(z) for z in zs] ... c =", "ys] ... c = bit.circuit() ... results.append(ns == c.evaluate([x, x, x])) >>> all(results)", "for (x, y) in zip(self, other)]) def nimp(self: bits, other: bits) -> bits:", "elif isinstance(other, set) and len(other) == 1 and isinstance(list(other)[0], int): return self /", "is_input=True) class input_one(input): \"\"\"Bit that is designated as a variable input from one", "y])) ... zs = outputs(xs.nor(ys)) ... ns = [int(z) for z in zs]", "x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nand_(y) for (x,", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor_(input(y))) ... results.append(int(b) ==", "Ensure second argument is a `bit`. args = list(args) if len(args) == 2:", "bit._circuit @staticmethod def hook_operation(hook=None): bit._hook_operation = hook @staticmethod def operation(o, *args): # Ensure", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor(input(y)))", "len(args) == 2: args[1] = constant(args[1]) if isinstance(args[1], int) else args[1] # Compute", "other) -> bits: \"\"\" Overloaded operator: rotation and shift operations. >>> bit.circuit(circuit()) >>>", ">>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs << 3", "and b2 is None: return type(b1) else: return bit \"\"\" return bit @staticmethod", "def nor(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "\"\"\" return bit.operation(op.and_, self, other) def __and__(self, other): \"\"\" >>> results = []", "^ constant(0) >>> b.value 1 \"\"\" return self ^ (constant(other) if isinstance(other, int)", ">>> all(results) True \"\"\" return bit.operation(op.imp_, self, other) def __le__(self, other): \"\"\" >>>", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "int, constructor=bit) -> bits: return bits([ constructor(bit_) for bit_ in reversed([(byte_>>i)%2 for i", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) & input(y)) ... results.append(int(b)", "~(~b) # Preserve the bit by copying it to a new wire. self.value", "inputs([y, y, y])) ... zs = outputs(xs.xnor_(ys)) ... ns = [int(z) for z", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif(input(y))) ...", "def __gt__(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "+ other def constants(l): return bits(map(constant, l)) def inputs(l): return bits(map(input, l)) def", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.nif(ys)) ... ns = [int(z)", "... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs =", "def xor(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "range(other)]) def __truediv__(self: bits, other) -> Sequence[bits]: \"\"\" >>> bit.circuit(circuit()) >>> bs =", "in [0, 1]: ... bit.circuit(circuit()) ... xs = inputs([x, x, x]) ... ys", "1, 1], [0, 0, 0, 0]] \"\"\" if isinstance(other, list) and len(other) >", "... xs = inputs([x, x, x]) ... ys = outputs(xs.not_()) ... ns =", "]) @staticmethod def zeros(n: int) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> xs =", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self, other) class constant(bit):", "0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0,", "value, gate_=None): self.value = value self.gate = bit._circuit.gate() if gate_ is None else", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand_(input(y))) ... results.append(int(b)", ">>> all(results) True \"\"\" return bit.operation(op.not_, self) def __invert__(self): \"\"\" >>> results =", "\"\"\" return bits([x.xor_(y) for (x, y) in zip(self, other)]) def xor_(self: bits, other:", "[[1, 1], [1, 1], [0, 0], [0, 0]] >>> bit.circuit(circuit()) >>> bs =", "def nimp(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>>", "# Ensure second argument is a `bit`. args = list(args) if len(args) ==", "= outputs(xs.not_()) ... ns = [int(y) for y in ys] ... c =", "y, y])) >>> all(results) True \"\"\" return bits([x.nimp_(y) for (x, y) in zip(self,", "# pylint: disable=W0123 try: # Construct the circuit and add it to the", "# The inference code below is not currently in use. \"\"\" if isinstance(b1,", "outputs(xs.not_()) >>> [y.value for y in ys] [1, 1, 1] \"\"\" return bits([constant(0)]*n)", "within a circuit built up out of those operators. >>> bit.hook_operation(lambda o, v,", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) % input(y)) ... results.append(int(b) ==", "list.__new__(cls, argument) def __int__(self: bits) -> int: \"\"\" >>> bit.circuit(circuit()) >>> xs =", "bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / {2}) >>> [[b.value for", "that is designated an output. >>> bit.circuit(circuit()) >>> b0 = output(input(1).not_()) >>> b1", "= output(input(x) <= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "bit_.gate(o, [a.gate for a in args])) ... return hook >>> bit.hook_operation(make_hook(bit)) >>> bit.circuit(circuit())", "'return' } type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit = bit.circuit() except: raise RuntimeError('automated circuit synthesis failed') from", "bits object given the supplied argument. \"\"\" return bits_type(argument)\\ if isinstance(argument, int) else\\", "bits([x.or_(y) for (x, y) in zip(self, other)]) def nor(self: bits, other: bits) ->", "[1, 1]] >>> @synthesize ... def equal(x, y): ... return x & y", "Traceback (most recent call last): ... ValueError: can only subtract a bit from", "bit vectors.\"\"\" result = list(self) result.extend(list(other)) return bits(result) def __pow__(self: bits, other) ->", "\"\"\" return sum(int(b)*(2**i) for (i, b) in zip(range(len(self)), reversed(self))) def not_(self: bits) ->", "all(results) True \"\"\" return bit.operation(op.imp_, self, other) def nand(self, other): \"\"\" >>> results", "<= ys) ... ns = [int(z) for z in zs] ... c =", "None) >>> bit.circuit(circuit()) >>> b = output(input(1).and_(input(1))) >>> b.value == bit.circuit().evaluate([1,1])[0] True >>>", "= 0 & constant(1) >>> b.value 0 \"\"\" return self & (constant(other) if", "other)]) def nif(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "__ge__(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "= [] >>> for (x, y) in [(0, 0), (0, 1), (1, 0),", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).and_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "\"\"\" return bit.operation(op.if_, self, other) def imp(self, other): \"\"\" >>> results = []", "return self & (constant(other) if isinstance(other, int) else other) def nimp(self, other): \"\"\"", "True \"\"\" return bit.operation(op.nif_, self, other) def nif_(self, other): \"\"\" >>> results =", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor_(input(y)))", "0, 0, 0, 1] \"\"\" if isinstance(other, set) and isinstance(list(other)[0], int): # Rotation.", "decorated for automated synthesis. \"\"\" class bits(list): \"\"\" Class for representing a vector", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand_(input(y))) ... results.append(int(b) ==", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_, self, other) def imp_(self,", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp(input(y))) ... results.append(int(b)", "output(input(x).nimp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nimp_, self, other)", "\"\"\" >>> bit.circuit(circuit()) >>> b = 1 ^ constant(0) >>> b.value 1 \"\"\"", "Class for representing an input or output type of a function decorated for", "self]) def __invert__(self: bits) -> bits: \"\"\" >>> results = [] >>> for", "other)]) def nor(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "b = output(input(x).xor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_,", "def __rand__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 0 & constant(1) >>>", ">= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.if_, self,", "for bit_ in bits.from_byte(byte_, constructor) ]) @staticmethod def zeros(n: int) -> bits: \"\"\"", "zs = outputs(xs >= ys) ... ns = [int(z) for z in zs]", "y) in zip(self, other)]) def __le__(self: bits, other: bits) -> bits: \"\"\" >>>", ">>> b.value == bit.circuit().evaluate([1,1])[0] True >>> def make_hook(bit_): ... def hook(o, v, *args):", "y])) >>> all(results) True \"\"\" return bits([x.xnor_(y) for (x, y) in zip(self, other)])", "byte_ in bytes_ for bit_ in bits.from_byte(byte_, constructor) ]) @staticmethod def zeros(n: int)", "return bits(map(output, l)) def synthesize(f): \"\"\" Decorator for automatically synthesizing a circuit from", "of the operation on the arguments. v = o(*[a.value for a in args])", "results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operation(op.not_, self) def __invert__(self): \"\"\"", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_, self, other) def __xor__(self, other):", "b = output(input(x).not_()) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operation(op.not_,", "if isinstance(other, set) and isinstance(list(other)[0], int): # Rotation. quantity = list(other)[0] return bits(self[len(self)-quantity:])", "| (constant(other) if isinstance(other, int) else other) def nor(self, other): \"\"\" >>> results", "source.\"\"\" class input_two(input): \"\"\"Bit that is designated as a variable input from a", "y, y, y])) >>> all(results) True \"\"\" return bits([x.nimp_(y) for (x, y) in", "1, 1, 1, 0] >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [0,0,0,0,1,1,1,1])) >>> bs", "and isinstance(other[0], int): return map(bits, parts(self, length=other)) # Sequence of lengths. elif isinstance(other,", "1], [0, 0], [0, 0]] >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>>", "True \"\"\" return bit.operation(op.and_, self, other) def __rand__(self, other): \"\"\" >>> bit.circuit(circuit()) >>>", "between operators and to represent the wires within a circuit built up out", "... b = output(input(x).not_()) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return", "in (0, 1)] >>> [equal.circuit.evaluate(xy) for xy in xys] [[1], [0], [0], [1]]", "x & y Traceback (most recent call last): ... RuntimeError: automated circuit synthesis", "[1, 1, 1, 0, 0, 0, 0, 1] \"\"\" if isinstance(other, set) and", "args]) # Return output from hook if it exists and if # it", "all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def if_(self, other): \"\"\" >>> results", "bss] [[1, 1], [1, 1], [0, 0], [0, 0]] >>> bit.circuit(circuit()) >>> bs", "1)]: ... bit.circuit(circuit()) ... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))", "return self + other def constants(l): return bits(map(constant, l)) def inputs(l): return bits(map(input,", "bit.circuit(circuit()) >>> b = 1 ^ constant(0) >>> b.value 1 \"\"\" return self", "object given the supplied argument. \"\"\" return bits_type(argument)\\ if isinstance(argument, int) else\\ list.__new__(cls,", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor(input(y)))", "= outputs(xs.nimp_(ys)) ... ns = [int(z) for z in zs] ... c =", "other) def __rxor__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 1 ^ constant(0)", "= bit.circuit() ... results.append(ns == c.evaluate([x, x, x])) >>> all(results) True \"\"\" return", "if circuit_ is not None: bit._circuit = circuit_ return None else: bit._circuit.prune_and_topological_sort_stable() return", "output(input(x) > input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nimp(other)", ">>> all(results) True \"\"\" return bit.operation(op.nand_, self, other) def __matmul__(self, other): \"\"\" >>>", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_, self, other) def xnor(self,", "\"\"\" return bit.operation(op.xor_, self, other) def __xor__(self, other): \"\"\" >>> results = []", "zip(self, other)]) def nimp_(self: bits, other: bits) -> bits: \"\"\" >>> results =", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) ^ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "y) in zip(self, other)]) def nimp_(self: bits, other: bits) -> bits: \"\"\" >>>", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xor(ys)) ...", "... zs = outputs(xs.imp(ys)) ... ns = [int(z) for z in zs] ...", "and_(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "def xor(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "\"\"\"Bit that is designated as a variable input from one source.\"\"\" class input_two(input):", "those operators. >>> bit.hook_operation(lambda o, v, *args: None) >>> bit.circuit(circuit()) >>> b =", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nif(other) def xor(self, other):", "c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.if_(y) for", "= output(input(x).and_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.and_, self,", "xnor_(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "other) def or_(self, other): \"\"\" >>> results = [] >>> for (x, y)", "parts(self, length=other)) # Sequence of lengths. elif isinstance(other, set) and len(other) == 1", "... return hook >>> bit.hook_operation(make_hook(bit)) >>> bit.circuit(circuit()) >>> b = output(input(0).and_(input(0))) >>> b.value", "the function as an attribute. bit.circuit(circuit()) args_in = { k: type_in(eval_(a)) for (k,", "= outputs(xs >= ys) ... ns = [int(z) for z in zs] ...", "... zs = outputs(xs.nand_(ys)) ... ns = [int(z) for z in zs] ...", "b2 is None: return type(b1) else: return bit \"\"\" return bit @staticmethod def", "x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.xnor_(y) for (x,", "__eq__(self, other): \"\"\" >>> results = [] >>> for (x, y) in [(0,", "y])) ... zs = outputs(xs >= ys) ... ns = [int(z) for z", "return bits([x.or_(y) for (x, y) in zip(self, other)]) def nor(self: bits, other: bits)", "3 >>> [b.value for b in bs] [0, 0, 0, 1, 1, 1,", "self, other) def xor_(self, other): \"\"\" >>> results = [] >>> for (x,", "x]), inputs([y, y, y])) ... zs = outputs(xs.nif(ys)) ... ns = [int(z) for", "(xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs", "representing an input or output type of a function decorated for automated synthesis.", "[0, 0], [1, 0], [1, 1]] >>> @synthesize ... def equal(x, y): ...", "output(~input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operation(op.not_, self) def", "(x, y) in zip(self, other)]) def __and__(self: bits, other: bits) -> bits: \"\"\"", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_, self, other) def nand(self,", "x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.imp_(y) for (x,", "result = list(self) result.extend(list(other)) return bits(result) def __pow__(self: bits, other) -> bits: \"\"\"Concatenation", "for automatically synthesizing a circuit from a function that takes only `bit` and/or", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.if_, self, other) def", "for y in (0, 1)] >>> [equal.circuit.evaluate(xy) for xy in xys] [[1], [0],", "True \"\"\" return bits([x.and_(y) for (x, y) in zip(self, other)]) def nimp(self: bits,", ">>> all(results) True \"\"\" return bits([x.or_(y) for (x, y) in zip(self, other)]) def", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.or_, self, other) def __or__(self,", "(x, y) in zip(self, other)]) def nimp_(self: bits, other: bits) -> bits: \"\"\"", ">>> b = 0 & constant(1) >>> b.value 0 \"\"\" return self &", "bits: \"\"\" >>> bit.circuit(circuit()) >>> xs = bits.zeros(3) >>> ys = outputs(xs.not_()) >>>", "elif isinstance(b1, input_two) and isinstance(b2, input_two): return input_two elif isinstance(b1, (input_one, input_two)) and", "[int(y) for y in ys] ... c = bit.circuit() ... results.append(ns == c.evaluate([x,", "bs] [1, 1, 1, 0, 0, 0, 0, 1] \"\"\" if isinstance(other, set)", "bit.circuit(circuit()) >>> xs = constants([0, 0, 0]) >>> ys = outputs(xs.not_()) >>> int(ys)", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.nor_(ys)) ... ns = [int(z)", "None) -> bits: \"\"\" Return bits object given the supplied argument. \"\"\" return", "... bit.circuit(circuit()) ... b = output(input(x).not_()) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True", "bs] [0, 0, 0, 1, 1, 1, 1, 0] >>> bit.circuit(circuit()) >>> bs", "return self.nimp(other) def nif(self, other): \"\"\" >>> results = [] >>> for (x,", "(x, y) in zip(self, other)]) def nor_(self: bits, other: bits) -> bits: \"\"\"", "x, x]), inputs([y, y, y])) ... zs = outputs(xs > ys) ... ns", "input(0) Traceback (most recent call last): ... ValueError: can only subtract a bit", "b = output(input(x) > input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "output(input(x).not_()) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operation(op.not_, self) def", "[b.value for b in bits.from_bytes(bytes([11, 0]))] [0, 0, 0, 0, 1, 0, 1,", "zip(self, other)]) def xnor_(self: bits, other: bits) -> bits: \"\"\" >>> results =", "0, 0, 0]) >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss =", "value of the result of the operation on the arguments. v = o(*[a.value", "y])) >>> all(results) True \"\"\" return bits([x.imp_(y) for (x, y) in zip(self, other)])", "return bit.operation(op.nand_, self, other) def __matmul__(self, other): \"\"\" >>> results = [] >>>", "all(results) True \"\"\" return bits([x.nor_(y) for (x, y) in zip(self, other)]) def nor_(self:", "isinstance(list(other)[0], int): return self / (len(self)//list(other)[0]) # Parts of length `other`. else: return", "inputs([y, y, y])) ... zs = outputs(xs.nor(ys)) ... ns = [int(z) for z", "constants(l): return bits(map(constant, l)) def inputs(l): return bits(map(input, l)) def outputs(l): return bits(map(output,", "a) type_out = lambda a: output if a is bit else outputs #", "return bit.operation(op.imp_, self, other) def __le__(self, other): \"\"\" >>> results = [] >>>", "y])) >>> all(results) True \"\"\" return bits([x.nif_(y) for (x, y) in zip(self, other)])", "or_(self: bits, other: bits) -> bits: \"\"\" >>> results = [] >>> for", "outputs(xs % ys) ... ns = [int(z) for z in zs] ... c", "bit.circuit(circuit()) ... b = output(input(x).and_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "\"\"\" return bit.operation(op.xor_, self, other) def __rxor__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b", "1 \"\"\" if other == 1: return bit.operation(op.not_, self) raise ValueError('can only subtract", "argument) def __int__(self: bits) -> int: \"\"\" >>> bit.circuit(circuit()) >>> xs = constants([0,", "= outputs(xs.xor_(ys)) ... ns = [int(z) for z in zs] ... c =", "(constant(other) if isinstance(other, int) else other) def nimp(self, other): \"\"\" >>> results =", "for x in [0, 1]: ... bit.circuit(circuit()) ... xs = inputs([x, x, x])", "(x, y) in zip(self, other)]) def __xor__(self: bits, other: bits) -> bits: \"\"\"", "def __mod__(self, other) -> bits: \"\"\" >>> results = [] >>> for (x,", "def __rshift__(self: bits, other) -> bits: \"\"\" Overloaded operator: rotation and shift operations.", "[1, 0, 0, 0, 0, 0, 0, 0] \"\"\" return bits(self[other:]) ** bits([constant(0)", "ys = outputs(xs.not_()) >>> [y.value for y in ys] [1, 1, 1] \"\"\"", "for (x, y) in zip(self, other)]) def if_(self: bits, other: bits) -> bits:", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).if_(input(y)))", "of relationships between operators and to represent the wires within a circuit built", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nimp(other) def nif(self, other): \"\"\" >>>", "other) -> Sequence[bits]: \"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss", "other)]) def xor_(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "= output(input(x) | input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "... ValueError: can only subtract a bit from the integer 1 \"\"\" if", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp_(input(y)))", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def xnor_(self,", "the operation on the arguments. v = o(*[a.value for a in args]) #", "(x, y) in zip(self, other)]) def __eq__(self: bits, other: bits) -> bits: \"\"\"", "[0, 0]] >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs", "it is also used to keep track of relationships between operators and to", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "= outputs(xs.if_(ys)) ... ns = [int(z) for z in zs] ... c =", "y, y])) ... zs = outputs(xs >= ys) ... ns = [int(z) for", "True \"\"\" return bits([x.xnor_(y) for (x, y) in zip(self, other)]) def __eq__(self: bits,", "in bs] for bs in bss] [[1], [1, 1, 1], [0, 0, 0,", "(xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xnor_(ys))", "0, 0, 0]] \"\"\" if isinstance(other, list) and len(other) > 0 and isinstance(other[0],", "type of a function decorated for automated synthesis. \"\"\" class bits(list): \"\"\" Class", "return bit.operation(op.xnor_, self, other) def __eq__(self, other): \"\"\" >>> results = [] >>>", "other)]) def nimp(self: bits, other: bits) -> bits: \"\"\" >>> results = []", "(xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nimp_(ys))", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def __eq__(self,", "a in args])) @staticmethod def constructor(b1, b2=None): # The inference code below is", "c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.and_(y) for", "0 and isinstance(other[0], int): return map(bits, parts(self, length=other)) # Sequence of lengths. elif", "... def equal(x: bit, y: bit) -> bit: ... return (x & y)", "bs << 3 >>> [b.value for b in bs] [1, 0, 0, 0,", "for (x, y) in zip(self, other)]) def xnor_(self: bits, other: bits) -> bits:", "takes only `bit` and/or `bits` objects as its arguments and returns an output", "other) def nor(self, other): \"\"\" >>> results = [] >>> for (x, y)", "return self ^ (constant(other) if isinstance(other, int) else other) def or_(self, other): \"\"\"", "all(results) True \"\"\" return bits([x.xor_(y) for (x, y) in zip(self, other)]) def __xor__(self:", "y, y, y])) >>> all(results) True \"\"\" return bits([x.nor_(y) for (x, y) in", "... b = output(input(x).nor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "ValueError('can only subtract a bit from the integer 1') def and_(self, other): \"\"\"", "... bit.circuit(circuit()) ... b = output(input(x) @ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "in bss[1]]) ([1, 1, 1, 1], [0, 0, 0, 0]) >>> bit.circuit(circuit()) >>>", "in zs] ... c = bit.circuit() ... results.append(ns == c.evaluate([x, x, x, y,", "output(bit): \"\"\" Bit that is designated an output. >>> bit.circuit(circuit()) >>> b0 =", "all(results) True \"\"\" return bits([x.xor_(y) for (x, y) in zip(self, other)]) def or_(self:", "y])) ... zs = outputs(xs.nand(ys)) ... ns = [int(z) for z in zs]", "1, 1, 1, 1, 0] >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [0,0,0,0,1,1,1,1])) >>>", "other) def __ge__(self, other): \"\"\" >>> results = [] >>> for (x, y)", "[0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0,", "return self / (len(self)//list(other)[0]) # Parts of length `other`. else: return map(bits, parts(self,", "a: input(0) if a is bit else inputs([0] * a) type_out = lambda", "bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / 2) >>> ([b.value for", "\"\"\" return bits([x.not_() for x in self]) def and_(self: bits, other: bits) ->", ">>> ([b.value for b in bss[0]], [b.value for b in bss[1]]) ([1, 1,", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self, other) def __matmul__(self,", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nand(ys)) ...", "# the type annotation of the decorated function. type_in = lambda a: input(0)", "... bit.circuit(circuit()) ... xs = inputs([x, x, x]) ... ys = outputs(~xs) ...", "inputs([y, y, y])) ... zs = outputs(xs.nand(ys)) ... ns = [int(z) for z", "bits([x.xnor_(y) for (x, y) in zip(self, other)]) def xnor_(self: bits, other: bits) ->", "0]) >>> ys = outputs(xs.not_()) >>> int(ys) 7 \"\"\" return sum(int(b)*(2**i) for (i,", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nif(ys)) ... ns =", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "(i, b) in zip(range(len(self)), reversed(self))) def not_(self: bits) -> bits: \"\"\" >>> results", "1, 1, 0, 0, 0, 0, 0, 0, 0, 0] \"\"\" return bits([", "def __and__(self, other): \"\"\" >>> results = [] >>> for (x, y) in", "for x in self]) def and_(self: bits, other: bits) -> bits: \"\"\" >>>", "objects as its arguments and returns an output of type `bit` or `bits`.", "from None # Return the original function. return f if __name__ == \"__main__\":", "0]))] [0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0,", "is a `bit`. args = list(args) if len(args) == 2: args[1] = constant(args[1])", "1)] >>> [conjunction.circuit.evaluate(xy) for xy in xys] [[0, 0], [0, 0], [1, 0],", "0], [1, 1]] >>> @synthesize ... def equal(x, y): ... return x &" ]
[ "author = df['author'].to_list() message_counter = {} for i in author: if i in", "# for not mentioning the bot in the line graph. message_counter.pop('ninza_bot_test') authors_in_discord =", "graph. message_counter.pop('ninza_bot_test') authors_in_discord = list(message_counter.keys()) no_of_messages = list(message_counter.values()) plt.plot(authors_in_discord, no_of_messages, marker = 'o',", "def plot_user_activity(client, ctx): plt.style.use('fivethirtyeight') df = pd.read_csv('innovators.csv', encoding= 'unicode_escape') author = df['author'].to_list() message_counter", "by author in the server.') plt.xlabel('Author') plt.ylabel('Message_count') plt.savefig('output2.png') plt.tight_layout() plt.close() await ctx.send(file =", "line graph. message_counter.pop('ninza_bot_test') authors_in_discord = list(message_counter.keys()) no_of_messages = list(message_counter.values()) plt.plot(authors_in_discord, no_of_messages, marker =", "= list(message_counter.keys()) no_of_messages = list(message_counter.values()) plt.plot(authors_in_discord, no_of_messages, marker = 'o', markersize=10) plt.title('msg sent", "pandas as pd import matplotlib.pyplot as plt import csv async def plot_user_activity(client, ctx):", "import matplotlib.pyplot as plt import csv async def plot_user_activity(client, ctx): plt.style.use('fivethirtyeight') df =", "+= 1 else: message_counter[i] = 1 # for not mentioning the bot in", "author: if i in message_counter: message_counter[i] += 1 else: message_counter[i] = 1 #", "authors_in_discord = list(message_counter.keys()) no_of_messages = list(message_counter.values()) plt.plot(authors_in_discord, no_of_messages, marker = 'o', markersize=10) plt.title('msg", "not mentioning the bot in the line graph. message_counter.pop('ninza_bot_test') authors_in_discord = list(message_counter.keys()) no_of_messages", "no_of_messages, marker = 'o', markersize=10) plt.title('msg sent by author in the server.') plt.xlabel('Author')", "import csv async def plot_user_activity(client, ctx): plt.style.use('fivethirtyeight') df = pd.read_csv('innovators.csv', encoding= 'unicode_escape') author", "sent by author in the server.') plt.xlabel('Author') plt.ylabel('Message_count') plt.savefig('output2.png') plt.tight_layout() plt.close() await ctx.send(file", "{} for i in author: if i in message_counter: message_counter[i] += 1 else:", "pd import matplotlib.pyplot as plt import csv async def plot_user_activity(client, ctx): plt.style.use('fivethirtyeight') df", "plt import csv async def plot_user_activity(client, ctx): plt.style.use('fivethirtyeight') df = pd.read_csv('innovators.csv', encoding= 'unicode_escape')", "list(message_counter.values()) plt.plot(authors_in_discord, no_of_messages, marker = 'o', markersize=10) plt.title('msg sent by author in the", "as pd import matplotlib.pyplot as plt import csv async def plot_user_activity(client, ctx): plt.style.use('fivethirtyeight')", "plt.style.use('fivethirtyeight') df = pd.read_csv('innovators.csv', encoding= 'unicode_escape') author = df['author'].to_list() message_counter = {} for", "import discord import random from datetime import datetime import pandas as pd import", "df['author'].to_list() message_counter = {} for i in author: if i in message_counter: message_counter[i]", "in message_counter: message_counter[i] += 1 else: message_counter[i] = 1 # for not mentioning", "mentioning the bot in the line graph. message_counter.pop('ninza_bot_test') authors_in_discord = list(message_counter.keys()) no_of_messages =", "the line graph. message_counter.pop('ninza_bot_test') authors_in_discord = list(message_counter.keys()) no_of_messages = list(message_counter.values()) plt.plot(authors_in_discord, no_of_messages, marker", "list(message_counter.keys()) no_of_messages = list(message_counter.values()) plt.plot(authors_in_discord, no_of_messages, marker = 'o', markersize=10) plt.title('msg sent by", "discord import random from datetime import datetime import pandas as pd import matplotlib.pyplot", "i in author: if i in message_counter: message_counter[i] += 1 else: message_counter[i] =", "plt.plot(authors_in_discord, no_of_messages, marker = 'o', markersize=10) plt.title('msg sent by author in the server.')", "matplotlib.pyplot as plt import csv async def plot_user_activity(client, ctx): plt.style.use('fivethirtyeight') df = pd.read_csv('innovators.csv',", "= 'o', markersize=10) plt.title('msg sent by author in the server.') plt.xlabel('Author') plt.ylabel('Message_count') plt.savefig('output2.png')", "'o', markersize=10) plt.title('msg sent by author in the server.') plt.xlabel('Author') plt.ylabel('Message_count') plt.savefig('output2.png') plt.tight_layout()", "= pd.read_csv('innovators.csv', encoding= 'unicode_escape') author = df['author'].to_list() message_counter = {} for i in", "csv async def plot_user_activity(client, ctx): plt.style.use('fivethirtyeight') df = pd.read_csv('innovators.csv', encoding= 'unicode_escape') author =", "'unicode_escape') author = df['author'].to_list() message_counter = {} for i in author: if i", "else: message_counter[i] = 1 # for not mentioning the bot in the line", "as plt import csv async def plot_user_activity(client, ctx): plt.style.use('fivethirtyeight') df = pd.read_csv('innovators.csv', encoding=", "author in the server.') plt.xlabel('Author') plt.ylabel('Message_count') plt.savefig('output2.png') plt.tight_layout() plt.close() await ctx.send(file = discord.File('output2.png'))", "in author: if i in message_counter: message_counter[i] += 1 else: message_counter[i] = 1", "async def plot_user_activity(client, ctx): plt.style.use('fivethirtyeight') df = pd.read_csv('innovators.csv', encoding= 'unicode_escape') author = df['author'].to_list()", "= 1 # for not mentioning the bot in the line graph. message_counter.pop('ninza_bot_test')", "import pandas as pd import matplotlib.pyplot as plt import csv async def plot_user_activity(client,", "message_counter.pop('ninza_bot_test') authors_in_discord = list(message_counter.keys()) no_of_messages = list(message_counter.values()) plt.plot(authors_in_discord, no_of_messages, marker = 'o', markersize=10)", "plot_user_activity(client, ctx): plt.style.use('fivethirtyeight') df = pd.read_csv('innovators.csv', encoding= 'unicode_escape') author = df['author'].to_list() message_counter =", "bot in the line graph. message_counter.pop('ninza_bot_test') authors_in_discord = list(message_counter.keys()) no_of_messages = list(message_counter.values()) plt.plot(authors_in_discord,", "message_counter = {} for i in author: if i in message_counter: message_counter[i] +=", "from datetime import datetime import pandas as pd import matplotlib.pyplot as plt import", "plt.title('msg sent by author in the server.') plt.xlabel('Author') plt.ylabel('Message_count') plt.savefig('output2.png') plt.tight_layout() plt.close() await", "import random from datetime import datetime import pandas as pd import matplotlib.pyplot as", "= df['author'].to_list() message_counter = {} for i in author: if i in message_counter:", "message_counter: message_counter[i] += 1 else: message_counter[i] = 1 # for not mentioning the", "pd.read_csv('innovators.csv', encoding= 'unicode_escape') author = df['author'].to_list() message_counter = {} for i in author:", "if i in message_counter: message_counter[i] += 1 else: message_counter[i] = 1 # for", "random from datetime import datetime import pandas as pd import matplotlib.pyplot as plt", "for i in author: if i in message_counter: message_counter[i] += 1 else: message_counter[i]", "1 # for not mentioning the bot in the line graph. message_counter.pop('ninza_bot_test') authors_in_discord", "marker = 'o', markersize=10) plt.title('msg sent by author in the server.') plt.xlabel('Author') plt.ylabel('Message_count')", "message_counter[i] += 1 else: message_counter[i] = 1 # for not mentioning the bot", "1 else: message_counter[i] = 1 # for not mentioning the bot in the", "no_of_messages = list(message_counter.values()) plt.plot(authors_in_discord, no_of_messages, marker = 'o', markersize=10) plt.title('msg sent by author", "datetime import pandas as pd import matplotlib.pyplot as plt import csv async def", "= {} for i in author: if i in message_counter: message_counter[i] += 1", "the bot in the line graph. message_counter.pop('ninza_bot_test') authors_in_discord = list(message_counter.keys()) no_of_messages = list(message_counter.values())", "markersize=10) plt.title('msg sent by author in the server.') plt.xlabel('Author') plt.ylabel('Message_count') plt.savefig('output2.png') plt.tight_layout() plt.close()", "in the line graph. message_counter.pop('ninza_bot_test') authors_in_discord = list(message_counter.keys()) no_of_messages = list(message_counter.values()) plt.plot(authors_in_discord, no_of_messages,", "df = pd.read_csv('innovators.csv', encoding= 'unicode_escape') author = df['author'].to_list() message_counter = {} for i", "i in message_counter: message_counter[i] += 1 else: message_counter[i] = 1 # for not", "encoding= 'unicode_escape') author = df['author'].to_list() message_counter = {} for i in author: if", "ctx): plt.style.use('fivethirtyeight') df = pd.read_csv('innovators.csv', encoding= 'unicode_escape') author = df['author'].to_list() message_counter = {}", "import datetime import pandas as pd import matplotlib.pyplot as plt import csv async", "for not mentioning the bot in the line graph. message_counter.pop('ninza_bot_test') authors_in_discord = list(message_counter.keys())", "message_counter[i] = 1 # for not mentioning the bot in the line graph.", "datetime import datetime import pandas as pd import matplotlib.pyplot as plt import csv", "= list(message_counter.values()) plt.plot(authors_in_discord, no_of_messages, marker = 'o', markersize=10) plt.title('msg sent by author in" ]
[ "#!/usr/bin/env python3 import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read()", "\"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\": [\"fastnode2vec = fastnode2vec.cli:node2vec\"]}, classifiers=[\"Topic :: Scientific/Engineering :: Artificial Intelligence\"], )", "node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"], install_requires=[\"numpy\", \"numba\", \"gensim\", \"click\", \"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\": [\"fastnode2vec", "long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"], install_requires=[\"numpy\", \"numba\", \"gensim\", \"click\", \"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\": [\"fastnode2vec = fastnode2vec.cli:node2vec\"]},", "long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"], install_requires=[\"numpy\", \"numba\", \"gensim\", \"click\", \"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\": [\"fastnode2vec =", "author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast implementation of node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"], install_requires=[\"numpy\", \"numba\",", "import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\",", "\"numba\", \"gensim\", \"click\", \"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\": [\"fastnode2vec = fastnode2vec.cli:node2vec\"]}, classifiers=[\"Topic :: Scientific/Engineering ::", "version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast implementation of node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"], install_requires=[\"numpy\",", "open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast implementation of node2vec\", long_description=read(\"README.md\"),", "<reponame>skojaku/fastnode2vec<gh_stars>10-100 #!/usr/bin/env python3 import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__),", "setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast", "setup( name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast implementation of node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\",", "fname)).read() setup( name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast implementation of node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\",", "python3 import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(", "packages=[\"fastnode2vec\"], install_requires=[\"numpy\", \"numba\", \"gensim\", \"click\", \"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\": [\"fastnode2vec = fastnode2vec.cli:node2vec\"]}, classifiers=[\"Topic ::", "os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"fastnode2vec\", version=\"0.0.5\",", "description=\"Fast implementation of node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"], install_requires=[\"numpy\", \"numba\", \"gensim\", \"click\", \"tqdm\"],", "\"gensim\", \"click\", \"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\": [\"fastnode2vec = fastnode2vec.cli:node2vec\"]}, classifiers=[\"Topic :: Scientific/Engineering :: Artificial", "def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast implementation", "from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\",", "author_email=\"<EMAIL>\", description=\"Fast implementation of node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"], install_requires=[\"numpy\", \"numba\", \"gensim\", \"click\",", "install_requires=[\"numpy\", \"numba\", \"gensim\", \"click\", \"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\": [\"fastnode2vec = fastnode2vec.cli:node2vec\"]}, classifiers=[\"Topic :: Scientific/Engineering", "license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast implementation of node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"], install_requires=[\"numpy\", \"numba\", \"gensim\",", "url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"], install_requires=[\"numpy\", \"numba\", \"gensim\", \"click\", \"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\": [\"fastnode2vec = fastnode2vec.cli:node2vec\"]}, classifiers=[\"Topic", "read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast implementation of", "import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"fastnode2vec\",", "setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\",", "name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast implementation of node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"],", "implementation of node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"], install_requires=[\"numpy\", \"numba\", \"gensim\", \"click\", \"tqdm\"], python_requires=\">=3.6\",", "of node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"], install_requires=[\"numpy\", \"numba\", \"gensim\", \"click\", \"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\":", "return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast implementation of node2vec\",", "\"click\", \"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\": [\"fastnode2vec = fastnode2vec.cli:node2vec\"]}, classifiers=[\"Topic :: Scientific/Engineering :: Artificial Intelligence\"]," ]
[ "os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.getenv('SECRET_KEY', '') DEBUG = False", "True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION = False SQLALCHEMY_TRACK_MODIFICATIONS = False", "= False class ProductionConfig(Config): DEBUG = False config_by_name = dict( dev=DevelopmentConfig, test=TestingConfig, prod=ProductionConfig", "= os.getenv('SECRET_KEY', '') DEBUG = False class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI =", "PRESERVE_CONTEXT_ON_EXCEPTION = False SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(Config): DEBUG = False config_by_name =", "TESTING = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION = False SQLALCHEMY_TRACK_MODIFICATIONS", "DEBUG = False class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir,", "= 'sqlite:///' + os.path.join(basedir, 'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS = False class TestingConfig(Config): DEBUG = True", "SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION = False SQLALCHEMY_TRACK_MODIFICATIONS = False class", "TestingConfig(Config): DEBUG = True TESTING = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db')", "DEBUG = True TESTING = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION", "SQLALCHEMY_TRACK_MODIFICATIONS = False class TestingConfig(Config): DEBUG = True TESTING = True SQLALCHEMY_DATABASE_URI =", "False SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(Config): DEBUG = False config_by_name = dict( dev=DevelopmentConfig,", "+ os.path.join(basedir, 'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS = False class TestingConfig(Config): DEBUG = True TESTING =", "class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS =", "os.path.join(basedir, 'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS = False class TestingConfig(Config): DEBUG = True TESTING = True", "'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION = False SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(Config): DEBUG = False config_by_name", "= False class TestingConfig(Config): DEBUG = True TESTING = True SQLALCHEMY_DATABASE_URI = 'sqlite:///'", "'') DEBUG = False class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' +", "'sqlite:///' + os.path.join(basedir, 'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS = False class TestingConfig(Config): DEBUG = True TESTING", "= True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS = False class TestingConfig(Config):", "SECRET_KEY = os.getenv('SECRET_KEY', '') DEBUG = False class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI", "Config: SECRET_KEY = os.getenv('SECRET_KEY', '') DEBUG = False class DevelopmentConfig(Config): DEBUG = True", "= True TESTING = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION =", "= False SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(Config): DEBUG = False config_by_name = dict(", "DEBUG = False config_by_name = dict( dev=DevelopmentConfig, test=TestingConfig, prod=ProductionConfig ) key = Config.SECRET_KEY", "False class ProductionConfig(Config): DEBUG = False config_by_name = dict( dev=DevelopmentConfig, test=TestingConfig, prod=ProductionConfig )", "True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS = False class TestingConfig(Config): DEBUG", "False class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS", "= os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.getenv('SECRET_KEY', '') DEBUG = False class DevelopmentConfig(Config):", "DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS = False", "import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.getenv('SECRET_KEY', '') DEBUG =", "class TestingConfig(Config): DEBUG = True TESTING = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir,", "os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.getenv('SECRET_KEY', '') DEBUG = False class DevelopmentConfig(Config): DEBUG", "os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION = False SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(Config): DEBUG = False", "class Config: SECRET_KEY = os.getenv('SECRET_KEY', '') DEBUG = False class DevelopmentConfig(Config): DEBUG =", "DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS = False class", "= False class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db')", "= True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION = False SQLALCHEMY_TRACK_MODIFICATIONS =", "ProductionConfig(Config): DEBUG = False config_by_name = dict( dev=DevelopmentConfig, test=TestingConfig, prod=ProductionConfig ) key =", "SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(Config): DEBUG = False config_by_name = dict( dev=DevelopmentConfig, test=TestingConfig,", "SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS = False class TestingConfig(Config): DEBUG =", "os.getenv('SECRET_KEY', '') DEBUG = False class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite:///'", "False class TestingConfig(Config): DEBUG = True TESTING = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' +", "'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS = False class TestingConfig(Config): DEBUG = True TESTING = True SQLALCHEMY_DATABASE_URI", "= 'sqlite:///' + os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION = False SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(Config):", "+ os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION = False SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(Config): DEBUG =", "class ProductionConfig(Config): DEBUG = False config_by_name = dict( dev=DevelopmentConfig, test=TestingConfig, prod=ProductionConfig ) key", "basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.getenv('SECRET_KEY', '') DEBUG = False class", "'sqlite:///' + os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION = False SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(Config): DEBUG", "True TESTING = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION = False" ]
[ "exists' % self.user except KeyError: success = False ret_msg = 'User %s does", "True ret_msg = 'User %s exists' % self.user except KeyError: success = False", "chkusr.check_if_user_exists() # Error handling and JSON return if success: module.exit_json(msg=ret_msg) else: module.fail_json(msg=ret_msg) if", "= dict(required=True) ) ) user = module.params.get('user') chkusr = User(user) success, ret_msg =", "self.user except KeyError: success = False ret_msg = 'User %s does not exists'", "ret_msg = 'User %s exists' % self.user except KeyError: success = False ret_msg", "self.user return success, ret_msg def main(): # Parsing argument file module = AnsibleModule(", "ansible.module_utils.basic import AnsibleModule class User: def __init__(self, user): self.user = user # Check", "exists def check_if_user_exists(self): try: user = pwd.getpwnam(self.user) success = True ret_msg = 'User", "<reponame>djouani/Learning-Ansible-2.X-Third-Edition #!/usr/bin/env python import pwd from ansible.module_utils.basic import AnsibleModule class User: def __init__(self,", "check_if_user_exists(self): try: user = pwd.getpwnam(self.user) success = True ret_msg = 'User %s exists'", "self.user = user # Check if user exists def check_if_user_exists(self): try: user =", "python import pwd from ansible.module_utils.basic import AnsibleModule class User: def __init__(self, user): self.user", "= module.params.get('user') chkusr = User(user) success, ret_msg = chkusr.check_if_user_exists() # Error handling and", "Parsing argument file module = AnsibleModule( argument_spec = dict( user = dict(required=True) )", "class User: def __init__(self, user): self.user = user # Check if user exists", "user exists def check_if_user_exists(self): try: user = pwd.getpwnam(self.user) success = True ret_msg =", "user = dict(required=True) ) ) user = module.params.get('user') chkusr = User(user) success, ret_msg", "success = True ret_msg = 'User %s exists' % self.user except KeyError: success", "= dict( user = dict(required=True) ) ) user = module.params.get('user') chkusr = User(user)", "from ansible.module_utils.basic import AnsibleModule class User: def __init__(self, user): self.user = user #", "success, ret_msg = chkusr.check_if_user_exists() # Error handling and JSON return if success: module.exit_json(msg=ret_msg)", "User(user) success, ret_msg = chkusr.check_if_user_exists() # Error handling and JSON return if success:", "= pwd.getpwnam(self.user) success = True ret_msg = 'User %s exists' % self.user except", "chkusr = User(user) success, ret_msg = chkusr.check_if_user_exists() # Error handling and JSON return", "user = module.params.get('user') chkusr = User(user) success, ret_msg = chkusr.check_if_user_exists() # Error handling", "dict( user = dict(required=True) ) ) user = module.params.get('user') chkusr = User(user) success,", "Error handling and JSON return if success: module.exit_json(msg=ret_msg) else: module.fail_json(msg=ret_msg) if __name__ ==", "= user # Check if user exists def check_if_user_exists(self): try: user = pwd.getpwnam(self.user)", "User: def __init__(self, user): self.user = user # Check if user exists def", "pwd.getpwnam(self.user) success = True ret_msg = 'User %s exists' % self.user except KeyError:", "# Check if user exists def check_if_user_exists(self): try: user = pwd.getpwnam(self.user) success =", "argument file module = AnsibleModule( argument_spec = dict( user = dict(required=True) ) )", "def main(): # Parsing argument file module = AnsibleModule( argument_spec = dict( user", "ret_msg = 'User %s does not exists' % self.user return success, ret_msg def", "ret_msg def main(): # Parsing argument file module = AnsibleModule( argument_spec = dict(", "def __init__(self, user): self.user = user # Check if user exists def check_if_user_exists(self):", "return success, ret_msg def main(): # Parsing argument file module = AnsibleModule( argument_spec", "KeyError: success = False ret_msg = 'User %s does not exists' % self.user", "module.params.get('user') chkusr = User(user) success, ret_msg = chkusr.check_if_user_exists() # Error handling and JSON", "import pwd from ansible.module_utils.basic import AnsibleModule class User: def __init__(self, user): self.user =", "if user exists def check_if_user_exists(self): try: user = pwd.getpwnam(self.user) success = True ret_msg", "__init__(self, user): self.user = user # Check if user exists def check_if_user_exists(self): try:", "= chkusr.check_if_user_exists() # Error handling and JSON return if success: module.exit_json(msg=ret_msg) else: module.fail_json(msg=ret_msg)", "Check if user exists def check_if_user_exists(self): try: user = pwd.getpwnam(self.user) success = True", "not exists' % self.user return success, ret_msg def main(): # Parsing argument file", "% self.user return success, ret_msg def main(): # Parsing argument file module =", "argument_spec = dict( user = dict(required=True) ) ) user = module.params.get('user') chkusr =", "user): self.user = user # Check if user exists def check_if_user_exists(self): try: user", ") user = module.params.get('user') chkusr = User(user) success, ret_msg = chkusr.check_if_user_exists() # Error", "% self.user except KeyError: success = False ret_msg = 'User %s does not", "does not exists' % self.user return success, ret_msg def main(): # Parsing argument", "dict(required=True) ) ) user = module.params.get('user') chkusr = User(user) success, ret_msg = chkusr.check_if_user_exists()", "except KeyError: success = False ret_msg = 'User %s does not exists' %", "try: user = pwd.getpwnam(self.user) success = True ret_msg = 'User %s exists' %", "import AnsibleModule class User: def __init__(self, user): self.user = user # Check if", "user # Check if user exists def check_if_user_exists(self): try: user = pwd.getpwnam(self.user) success", "#!/usr/bin/env python import pwd from ansible.module_utils.basic import AnsibleModule class User: def __init__(self, user):", "user = pwd.getpwnam(self.user) success = True ret_msg = 'User %s exists' % self.user", "False ret_msg = 'User %s does not exists' % self.user return success, ret_msg", "module = AnsibleModule( argument_spec = dict( user = dict(required=True) ) ) user =", "file module = AnsibleModule( argument_spec = dict( user = dict(required=True) ) ) user", "def check_if_user_exists(self): try: user = pwd.getpwnam(self.user) success = True ret_msg = 'User %s", "# Parsing argument file module = AnsibleModule( argument_spec = dict( user = dict(required=True)", "= 'User %s exists' % self.user except KeyError: success = False ret_msg =", "= True ret_msg = 'User %s exists' % self.user except KeyError: success =", "'User %s does not exists' % self.user return success, ret_msg def main(): #", "= User(user) success, ret_msg = chkusr.check_if_user_exists() # Error handling and JSON return if", "%s exists' % self.user except KeyError: success = False ret_msg = 'User %s", "success, ret_msg def main(): # Parsing argument file module = AnsibleModule( argument_spec =", ") ) user = module.params.get('user') chkusr = User(user) success, ret_msg = chkusr.check_if_user_exists() #", "pwd from ansible.module_utils.basic import AnsibleModule class User: def __init__(self, user): self.user = user", "AnsibleModule( argument_spec = dict( user = dict(required=True) ) ) user = module.params.get('user') chkusr", "%s does not exists' % self.user return success, ret_msg def main(): # Parsing", "success = False ret_msg = 'User %s does not exists' % self.user return", "= 'User %s does not exists' % self.user return success, ret_msg def main():", "'User %s exists' % self.user except KeyError: success = False ret_msg = 'User", "main(): # Parsing argument file module = AnsibleModule( argument_spec = dict( user =", "handling and JSON return if success: module.exit_json(msg=ret_msg) else: module.fail_json(msg=ret_msg) if __name__ == \"__main__\":", "= AnsibleModule( argument_spec = dict( user = dict(required=True) ) ) user = module.params.get('user')", "# Error handling and JSON return if success: module.exit_json(msg=ret_msg) else: module.fail_json(msg=ret_msg) if __name__", "ret_msg = chkusr.check_if_user_exists() # Error handling and JSON return if success: module.exit_json(msg=ret_msg) else:", "and JSON return if success: module.exit_json(msg=ret_msg) else: module.fail_json(msg=ret_msg) if __name__ == \"__main__\": main()", "AnsibleModule class User: def __init__(self, user): self.user = user # Check if user", "exists' % self.user return success, ret_msg def main(): # Parsing argument file module", "= False ret_msg = 'User %s does not exists' % self.user return success," ]
[ "an appropriate ontology term. Args: label: the label to find ontology terms for", "a given curie like 'CL:1000413', get the label like 'endothelial cell of artery'\"\"\"", "and you want to find an appropriate ontology term. Args: label: the label", "f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class OntologyLookupError(Exception): \"\"\"Exception for some problem with looking up ontology information.\"\"\" def", "results Returns: list of (curie, label) tuples returned by OLS \"\"\" # using", "response = requests.get(url) if not response.ok: raise OntologyLookupError( f\"Label {label} lookup failed, got", "ontology term. Args: label: the label to find ontology terms for ontology: the", "else: return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def get_ontology_label(curie): \"\"\"For a given curie like 'CL:1000413', get the", "value. if not curie: return \"\" else: return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def get_ontology_label(curie): \"\"\"For a", "the id component of the curie, 0000001 from CL:0000001 for example.\"\"\" return curie.split(\":\")[1]", "OntologyLookupError( f\"Label {label} lookup failed, got status code {response.status_code}: {response.text}\" ) return [(r[\"obo_id\"],", "not url: return \"\" response = requests.get(url) if not response.ok: raise OntologyLookupError( f\"Curie", "ontology term.\"\"\" # If the curie is empty, just return an empty string.", "or efo for example method: select or search. search provides much broader results", "_iri(curie): \"\"\"Get the iri from a curie. This is a bit hopeful that", "bit hopeful that they all map to purl.obolibrary.org\"\"\" if _ontology_name(curie) == \"EFO\": return", "return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def get_ontology_label(curie): \"\"\"For a given curie like 'CL:1000413', get the label", "from CL:0000001 for example.\"\"\" return curie.split(\":\")[1] def _double_encode(url): \"\"\"Double url encode a url.", "there is an existing label in a submitted dataset, and you want to", "return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class OntologyLookupError(Exception): \"\"\"Exception for some problem with looking up ontology information.\"\"\"", "label to find ontology terms for ontology: the ontology to search in, cl", "f\"Label {label} lookup failed, got status code {response.status_code}: {response.text}\" ) return [(r[\"obo_id\"], r[\"label\"])", "CL:0000001 def _ontology_name(curie): \"\"\"Get the name of the ontology from the curie, CL", "purl.obolibrary.org\"\"\" if _ontology_name(curie) == \"EFO\": return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class OntologyLookupError(Exception): \"\"\"Exception for", "artery'\"\"\" url = _ontology_info_url(curie) if not url: return \"\" response = requests.get(url) if", "search in, cl or uberon or efo for example method: select or search.", "happens when there is no # valid ontology value. if not curie: return", "OLS REST API [https://www.ebi.ac.uk/ols/docs/api] url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response = requests.get(url) if not response.ok:", "for example method: select or search. search provides much broader results Returns: list", "REST API [https://www.ebi.ac.uk/ols/docs/api] url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response = requests.get(url) if not response.ok: raise", "existing label in a submitted dataset, and you want to find an appropriate", "(curie, label) tuples returned by OLS \"\"\" # using OLS REST API [https://www.ebi.ac.uk/ols/docs/api]", "if not response.ok: raise OntologyLookupError( f\"Label {label} lookup failed, got status code {response.status_code}:", "want to find an appropriate ontology term. Args: label: the label to find", "for ontology: the ontology to search in, cl or uberon or efo for", "This is useful when there is an existing label in a submitted dataset,", "ontology to search in, cl or uberon or efo for example method: select", "raise OntologyLookupError( f\"Label {label} lookup failed, got status code {response.status_code}: {response.text}\" ) return", "given curie like 'CL:1000413', get the label like 'endothelial cell of artery'\"\"\" url", "def _ontology_name(curie): \"\"\"Get the name of the ontology from the curie, CL or", "not response.ok: raise OntologyLookupError( f\"Curie {curie} lookup failed, got status code {response.status_code}: {response.text}\"", "response.json()[\"label\"] def lookup_candidate_term(label, ontology=\"cl\", method=\"select\"): \"\"\"Lookup candidate terms for a label. This is", "to search in, cl or uberon or efo for example method: select or", "looking up ontology information.\"\"\" def _ontology_info_url(curie): \"\"\"Get the to make a GET to", "url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response = requests.get(url) if not response.ok: raise OntologyLookupError( f\"Label {label}", "0000001 from CL:0000001 for example.\"\"\" return curie.split(\":\")[1] def _double_encode(url): \"\"\"Double url encode a", "not response.ok: raise OntologyLookupError( f\"Label {label} lookup failed, got status code {response.status_code}: {response.text}\"", "= _ontology_info_url(curie) if not url: return \"\" response = requests.get(url) if not response.ok:", "ontology information.\"\"\" def _ontology_info_url(curie): \"\"\"Get the to make a GET to to get", "an empty string. This happens when there is no # valid ontology value.", "url. This is required by the OLS API.\"\"\" return quote_plus(quote_plus(url)) def _iri(curie): \"\"\"Get", "If the curie is empty, just return an empty string. This happens when", "is an existing label in a submitted dataset, and you want to find", "just return an empty string. This happens when there is no # valid", "curie.split(\":\")[1] def _double_encode(url): \"\"\"Double url encode a url. This is required by the", "terms for ontology: the ontology to search in, cl or uberon or efo", "label in a submitted dataset, and you want to find an appropriate ontology", "raise OntologyLookupError( f\"Curie {curie} lookup failed, got status code {response.status_code}: {response.text}\" ) return", "from the curie, CL or UBERON for example.\"\"\" return curie.split(\":\")[0] def _ontology_value(curie): \"\"\"Get", "class OntologyLookupError(Exception): \"\"\"Exception for some problem with looking up ontology information.\"\"\" def _ontology_info_url(curie):", "of artery'\"\"\" url = _ontology_info_url(curie) if not url: return \"\" response = requests.get(url)", "OLS \"\"\" # using OLS REST API [https://www.ebi.ac.uk/ols/docs/api] url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response =", "# Curie means something like CL:0000001 def _ontology_name(curie): \"\"\"Get the name of the", "\"\" else: return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def get_ontology_label(curie): \"\"\"For a given curie like 'CL:1000413', get", "requests.get(url) if not response.ok: raise OntologyLookupError( f\"Label {label} lookup failed, got status code", "they all map to purl.obolibrary.org\"\"\" if _ontology_name(curie) == \"EFO\": return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\"", "if not url: return \"\" response = requests.get(url) if not response.ok: raise OntologyLookupError(", "\"\"\"Lookup candidate terms for a label. This is useful when there is an", "'CL:1000413', get the label like 'endothelial cell of artery'\"\"\" url = _ontology_info_url(curie) if", "required by the OLS API.\"\"\" return quote_plus(quote_plus(url)) def _iri(curie): \"\"\"Get the iri from", "terms for a label. This is useful when there is an existing label", "broader results Returns: list of (curie, label) tuples returned by OLS \"\"\" #", "if not curie: return \"\" else: return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def get_ontology_label(curie): \"\"\"For a given", "_ontology_info_url(curie) if not url: return \"\" response = requests.get(url) if not response.ok: raise", "This is required by the OLS API.\"\"\" return quote_plus(quote_plus(url)) def _iri(curie): \"\"\"Get the", "is a bit hopeful that they all map to purl.obolibrary.org\"\"\" if _ontology_name(curie) ==", "string. This happens when there is no # valid ontology value. if not", "label: the label to find ontology terms for ontology: the ontology to search", "dataset, and you want to find an appropriate ontology term. Args: label: the", "the ontology from the curie, CL or UBERON for example.\"\"\" return curie.split(\":\")[0] def", "uberon or efo for example method: select or search. search provides much broader", "Curie means something like CL:0000001 def _ontology_name(curie): \"\"\"Get the name of the ontology", "much broader results Returns: list of (curie, label) tuples returned by OLS \"\"\"", "_ontology_info_url(curie): \"\"\"Get the to make a GET to to get information about an", "there is no # valid ontology value. if not curie: return \"\" else:", "when there is an existing label in a submitted dataset, and you want", "for working with ontologies and the OLS.\"\"\" from urllib.parse import quote_plus import requests", "encode a url. This is required by the OLS API.\"\"\" return quote_plus(quote_plus(url)) def", "f\"Curie {curie} lookup failed, got status code {response.status_code}: {response.text}\" ) return response.json()[\"label\"] def", "by OLS \"\"\" # using OLS REST API [https://www.ebi.ac.uk/ols/docs/api] url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response", "problem with looking up ontology information.\"\"\" def _ontology_info_url(curie): \"\"\"Get the to make a", "_ontology_name(curie): \"\"\"Get the name of the ontology from the curie, CL or UBERON", "submitted dataset, and you want to find an appropriate ontology term. Args: label:", "find ontology terms for ontology: the ontology to search in, cl or uberon", "Returns: list of (curie, label) tuples returned by OLS \"\"\" # using OLS", "about an ontology term.\"\"\" # If the curie is empty, just return an", "return curie.split(\":\")[1] def _double_encode(url): \"\"\"Double url encode a url. This is required by", "def lookup_candidate_term(label, ontology=\"cl\", method=\"select\"): \"\"\"Lookup candidate terms for a label. This is useful", "# valid ontology value. if not curie: return \"\" else: return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def", "to get information about an ontology term.\"\"\" # If the curie is empty,", "OntologyLookupError( f\"Curie {curie} lookup failed, got status code {response.status_code}: {response.text}\" ) return response.json()[\"label\"]", "# If the curie is empty, just return an empty string. This happens", "the label like 'endothelial cell of artery'\"\"\" url = _ontology_info_url(curie) if not url:", "OLS_API_ROOT = \"http://www.ebi.ac.uk/ols/api\" # Curie means something like CL:0000001 def _ontology_name(curie): \"\"\"Get the", "the OLS.\"\"\" from urllib.parse import quote_plus import requests OLS_API_ROOT = \"http://www.ebi.ac.uk/ols/api\" # Curie", "{response.text}\" ) return response.json()[\"label\"] def lookup_candidate_term(label, ontology=\"cl\", method=\"select\"): \"\"\"Lookup candidate terms for a", "ontology=\"cl\", method=\"select\"): \"\"\"Lookup candidate terms for a label. This is useful when there", "example.\"\"\" return curie.split(\":\")[0] def _ontology_value(curie): \"\"\"Get the id component of the curie, 0000001", "search provides much broader results Returns: list of (curie, label) tuples returned by", "information.\"\"\" def _ontology_info_url(curie): \"\"\"Get the to make a GET to to get information", "tuples returned by OLS \"\"\" # using OLS REST API [https://www.ebi.ac.uk/ols/docs/api] url =", "a GET to to get information about an ontology term.\"\"\" # If the", "curie: return \"\" else: return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def get_ontology_label(curie): \"\"\"For a given curie like", "useful when there is an existing label in a submitted dataset, and you", "= f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response = requests.get(url) if not response.ok: raise OntologyLookupError( f\"Label {label} lookup", "\"\"\"For a given curie like 'CL:1000413', get the label like 'endothelial cell of", "in, cl or uberon or efo for example method: select or search. search", "_ontology_value(curie): \"\"\"Get the id component of the curie, 0000001 from CL:0000001 for example.\"\"\"", "to find an appropriate ontology term. Args: label: the label to find ontology", "method: select or search. search provides much broader results Returns: list of (curie,", "you want to find an appropriate ontology term. Args: label: the label to", "no # valid ontology value. if not curie: return \"\" else: return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\"", "url: return \"\" response = requests.get(url) if not response.ok: raise OntologyLookupError( f\"Curie {curie}", "of the ontology from the curie, CL or UBERON for example.\"\"\" return curie.split(\":\")[0]", "a bit hopeful that they all map to purl.obolibrary.org\"\"\" if _ontology_name(curie) == \"EFO\":", "to make a GET to to get information about an ontology term.\"\"\" #", "get information about an ontology term.\"\"\" # If the curie is empty, just", "curie.split(\":\")[0] def _ontology_value(curie): \"\"\"Get the id component of the curie, 0000001 from CL:0000001", "the curie is empty, just return an empty string. This happens when there", "= \"http://www.ebi.ac.uk/ols/api\" # Curie means something like CL:0000001 def _ontology_name(curie): \"\"\"Get the name", "lookup failed, got status code {response.status_code}: {response.text}\" ) return response.json()[\"label\"] def lookup_candidate_term(label, ontology=\"cl\",", "iri from a curie. This is a bit hopeful that they all map", "component of the curie, 0000001 from CL:0000001 for example.\"\"\" return curie.split(\":\")[1] def _double_encode(url):", "failed, got status code {response.status_code}: {response.text}\" ) return response.json()[\"label\"] def lookup_candidate_term(label, ontology=\"cl\", method=\"select\"):", "or search. search provides much broader results Returns: list of (curie, label) tuples", "like 'endothelial cell of artery'\"\"\" url = _ontology_info_url(curie) if not url: return \"\"", "means something like CL:0000001 def _ontology_name(curie): \"\"\"Get the name of the ontology from", "\"\"\"Get the to make a GET to to get information about an ontology", "= requests.get(url) if not response.ok: raise OntologyLookupError( f\"Curie {curie} lookup failed, got status", "return response.json()[\"label\"] def lookup_candidate_term(label, ontology=\"cl\", method=\"select\"): \"\"\"Lookup candidate terms for a label. This", "f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class OntologyLookupError(Exception): \"\"\"Exception for some problem with looking up ontology", "is useful when there is an existing label in a submitted dataset, and", "an existing label in a submitted dataset, and you want to find an", "empty, just return an empty string. This happens when there is no #", "with ontologies and the OLS.\"\"\" from urllib.parse import quote_plus import requests OLS_API_ROOT =", "OLS.\"\"\" from urllib.parse import quote_plus import requests OLS_API_ROOT = \"http://www.ebi.ac.uk/ols/api\" # Curie means", "working with ontologies and the OLS.\"\"\" from urllib.parse import quote_plus import requests OLS_API_ROOT", "id component of the curie, 0000001 from CL:0000001 for example.\"\"\" return curie.split(\":\")[1] def", "cell of artery'\"\"\" url = _ontology_info_url(curie) if not url: return \"\" response =", "{response.status_code}: {response.text}\" ) return response.json()[\"label\"] def lookup_candidate_term(label, ontology=\"cl\", method=\"select\"): \"\"\"Lookup candidate terms for", "UBERON for example.\"\"\" return curie.split(\":\")[0] def _ontology_value(curie): \"\"\"Get the id component of the", "example method: select or search. search provides much broader results Returns: list of", "{curie} lookup failed, got status code {response.status_code}: {response.text}\" ) return response.json()[\"label\"] def lookup_candidate_term(label,", "the OLS API.\"\"\" return quote_plus(quote_plus(url)) def _iri(curie): \"\"\"Get the iri from a curie.", "lookup_candidate_term(label, ontology=\"cl\", method=\"select\"): \"\"\"Lookup candidate terms for a label. This is useful when", "example.\"\"\" return curie.split(\":\")[1] def _double_encode(url): \"\"\"Double url encode a url. This is required", "method=\"select\"): \"\"\"Lookup candidate terms for a label. This is useful when there is", "a label. This is useful when there is an existing label in a", "valid ontology value. if not curie: return \"\" else: return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def get_ontology_label(curie):", "return an empty string. This happens when there is no # valid ontology", "hopeful that they all map to purl.obolibrary.org\"\"\" if _ontology_name(curie) == \"EFO\": return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\"", "\"\"\"Exception for some problem with looking up ontology information.\"\"\" def _ontology_info_url(curie): \"\"\"Get the", "if not response.ok: raise OntologyLookupError( f\"Curie {curie} lookup failed, got status code {response.status_code}:", "return \"\" else: return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def get_ontology_label(curie): \"\"\"For a given curie like 'CL:1000413',", "or UBERON for example.\"\"\" return curie.split(\":\")[0] def _ontology_value(curie): \"\"\"Get the id component of", "like 'CL:1000413', get the label like 'endothelial cell of artery'\"\"\" url = _ontology_info_url(curie)", "in a submitted dataset, and you want to find an appropriate ontology term.", "label) tuples returned by OLS \"\"\" # using OLS REST API [https://www.ebi.ac.uk/ols/docs/api] url", "an ontology term.\"\"\" # If the curie is empty, just return an empty", "response.ok: raise OntologyLookupError( f\"Curie {curie} lookup failed, got status code {response.status_code}: {response.text}\" )", "all map to purl.obolibrary.org\"\"\" if _ontology_name(curie) == \"EFO\": return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class", "map to purl.obolibrary.org\"\"\" if _ontology_name(curie) == \"EFO\": return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class OntologyLookupError(Exception):", "that they all map to purl.obolibrary.org\"\"\" if _ontology_name(curie) == \"EFO\": return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return", "= requests.get(url) if not response.ok: raise OntologyLookupError( f\"Label {label} lookup failed, got status", "def _iri(curie): \"\"\"Get the iri from a curie. This is a bit hopeful", "the label to find ontology terms for ontology: the ontology to search in,", "for some problem with looking up ontology information.\"\"\" def _ontology_info_url(curie): \"\"\"Get the to", "for example.\"\"\" return curie.split(\":\")[0] def _ontology_value(curie): \"\"\"Get the id component of the curie,", "the curie, 0000001 from CL:0000001 for example.\"\"\" return curie.split(\":\")[1] def _double_encode(url): \"\"\"Double url", "to purl.obolibrary.org\"\"\" if _ontology_name(curie) == \"EFO\": return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class OntologyLookupError(Exception): \"\"\"Exception", "term.\"\"\" # If the curie is empty, just return an empty string. This", "some problem with looking up ontology information.\"\"\" def _ontology_info_url(curie): \"\"\"Get the to make", "returned by OLS \"\"\" # using OLS REST API [https://www.ebi.ac.uk/ols/docs/api] url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\"", "is empty, just return an empty string. This happens when there is no", "return quote_plus(quote_plus(url)) def _iri(curie): \"\"\"Get the iri from a curie. This is a", ") return response.json()[\"label\"] def lookup_candidate_term(label, ontology=\"cl\", method=\"select\"): \"\"\"Lookup candidate terms for a label.", "find an appropriate ontology term. Args: label: the label to find ontology terms", "cl or uberon or efo for example method: select or search. search provides", "f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response = requests.get(url) if not response.ok: raise OntologyLookupError( f\"Label {label} lookup failed,", "like CL:0000001 def _ontology_name(curie): \"\"\"Get the name of the ontology from the curie,", "{label} lookup failed, got status code {response.status_code}: {response.text}\" ) return [(r[\"obo_id\"], r[\"label\"]) for", "return curie.split(\":\")[0] def _ontology_value(curie): \"\"\"Get the id component of the curie, 0000001 from", "API.\"\"\" return quote_plus(quote_plus(url)) def _iri(curie): \"\"\"Get the iri from a curie. This is", "def _ontology_value(curie): \"\"\"Get the id component of the curie, 0000001 from CL:0000001 for", "from urllib.parse import quote_plus import requests OLS_API_ROOT = \"http://www.ebi.ac.uk/ols/api\" # Curie means something", "is required by the OLS API.\"\"\" return quote_plus(quote_plus(url)) def _iri(curie): \"\"\"Get the iri", "for a label. This is useful when there is an existing label in", "status code {response.status_code}: {response.text}\" ) return response.json()[\"label\"] def lookup_candidate_term(label, ontology=\"cl\", method=\"select\"): \"\"\"Lookup candidate", "API [https://www.ebi.ac.uk/ols/docs/api] url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response = requests.get(url) if not response.ok: raise OntologyLookupError(", "failed, got status code {response.status_code}: {response.text}\" ) return [(r[\"obo_id\"], r[\"label\"]) for r in", "response.ok: raise OntologyLookupError( f\"Label {label} lookup failed, got status code {response.status_code}: {response.text}\" )", "\"\"\"Methods for working with ontologies and the OLS.\"\"\" from urllib.parse import quote_plus import", "not curie: return \"\" else: return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def get_ontology_label(curie): \"\"\"For a given curie", "select or search. search provides much broader results Returns: list of (curie, label)", "\"\"\"Get the name of the ontology from the curie, CL or UBERON for", "name of the ontology from the curie, CL or UBERON for example.\"\"\" return", "Args: label: the label to find ontology terms for ontology: the ontology to", "response = requests.get(url) if not response.ok: raise OntologyLookupError( f\"Curie {curie} lookup failed, got", "\"http://www.ebi.ac.uk/ols/api\" # Curie means something like CL:0000001 def _ontology_name(curie): \"\"\"Get the name of", "if _ontology_name(curie) == \"EFO\": return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class OntologyLookupError(Exception): \"\"\"Exception for some", "ontology value. if not curie: return \"\" else: return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def get_ontology_label(curie): \"\"\"For", "\"\"\"Get the iri from a curie. This is a bit hopeful that they", "\"\"\"Get the id component of the curie, 0000001 from CL:0000001 for example.\"\"\" return", "requests OLS_API_ROOT = \"http://www.ebi.ac.uk/ols/api\" # Curie means something like CL:0000001 def _ontology_name(curie): \"\"\"Get", "\"\"\"Double url encode a url. This is required by the OLS API.\"\"\" return", "curie, CL or UBERON for example.\"\"\" return curie.split(\":\")[0] def _ontology_value(curie): \"\"\"Get the id", "url = _ontology_info_url(curie) if not url: return \"\" response = requests.get(url) if not", "to find ontology terms for ontology: the ontology to search in, cl or", "lookup failed, got status code {response.status_code}: {response.text}\" ) return [(r[\"obo_id\"], r[\"label\"]) for r", "_double_encode(url): \"\"\"Double url encode a url. This is required by the OLS API.\"\"\"", "the to make a GET to to get information about an ontology term.\"\"\"", "term. Args: label: the label to find ontology terms for ontology: the ontology", "\"\"\" # using OLS REST API [https://www.ebi.ac.uk/ols/docs/api] url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response = requests.get(url)", "get_ontology_label(curie): \"\"\"For a given curie like 'CL:1000413', get the label like 'endothelial cell", "from a curie. This is a bit hopeful that they all map to", "a submitted dataset, and you want to find an appropriate ontology term. Args:", "url encode a url. This is required by the OLS API.\"\"\" return quote_plus(quote_plus(url))", "This is a bit hopeful that they all map to purl.obolibrary.org\"\"\" if _ontology_name(curie)", "and the OLS.\"\"\" from urllib.parse import quote_plus import requests OLS_API_ROOT = \"http://www.ebi.ac.uk/ols/api\" #", "something like CL:0000001 def _ontology_name(curie): \"\"\"Get the name of the ontology from the", "OLS API.\"\"\" return quote_plus(quote_plus(url)) def _iri(curie): \"\"\"Get the iri from a curie. This", "empty string. This happens when there is no # valid ontology value. if", "is no # valid ontology value. if not curie: return \"\" else: return", "code {response.status_code}: {response.text}\" ) return response.json()[\"label\"] def lookup_candidate_term(label, ontology=\"cl\", method=\"select\"): \"\"\"Lookup candidate terms", "a url. This is required by the OLS API.\"\"\" return quote_plus(quote_plus(url)) def _iri(curie):", "f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def get_ontology_label(curie): \"\"\"For a given curie like 'CL:1000413', get the label like", "return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class OntologyLookupError(Exception): \"\"\"Exception for some problem with looking up", "def _ontology_info_url(curie): \"\"\"Get the to make a GET to to get information about", "\"\" response = requests.get(url) if not response.ok: raise OntologyLookupError( f\"Curie {curie} lookup failed,", "requests.get(url) if not response.ok: raise OntologyLookupError( f\"Curie {curie} lookup failed, got status code", "efo for example method: select or search. search provides much broader results Returns:", "list of (curie, label) tuples returned by OLS \"\"\" # using OLS REST", "curie. This is a bit hopeful that they all map to purl.obolibrary.org\"\"\" if", "of the curie, 0000001 from CL:0000001 for example.\"\"\" return curie.split(\":\")[1] def _double_encode(url): \"\"\"Double", "import requests OLS_API_ROOT = \"http://www.ebi.ac.uk/ols/api\" # Curie means something like CL:0000001 def _ontology_name(curie):", "to to get information about an ontology term.\"\"\" # If the curie is", "This happens when there is no # valid ontology value. if not curie:", "def _double_encode(url): \"\"\"Double url encode a url. This is required by the OLS", "\"EFO\": return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class OntologyLookupError(Exception): \"\"\"Exception for some problem with looking", "candidate terms for a label. This is useful when there is an existing", "ontologies and the OLS.\"\"\" from urllib.parse import quote_plus import requests OLS_API_ROOT = \"http://www.ebi.ac.uk/ols/api\"", "up ontology information.\"\"\" def _ontology_info_url(curie): \"\"\"Get the to make a GET to to", "ontology from the curie, CL or UBERON for example.\"\"\" return curie.split(\":\")[0] def _ontology_value(curie):", "import quote_plus import requests OLS_API_ROOT = \"http://www.ebi.ac.uk/ols/api\" # Curie means something like CL:0000001", "by the OLS API.\"\"\" return quote_plus(quote_plus(url)) def _iri(curie): \"\"\"Get the iri from a", "information about an ontology term.\"\"\" # If the curie is empty, just return", "== \"EFO\": return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class OntologyLookupError(Exception): \"\"\"Exception for some problem with", "return \"\" response = requests.get(url) if not response.ok: raise OntologyLookupError( f\"Curie {curie} lookup", "ontology: the ontology to search in, cl or uberon or efo for example", "'endothelial cell of artery'\"\"\" url = _ontology_info_url(curie) if not url: return \"\" response", "search. search provides much broader results Returns: list of (curie, label) tuples returned", "make a GET to to get information about an ontology term.\"\"\" # If", "label like 'endothelial cell of artery'\"\"\" url = _ontology_info_url(curie) if not url: return", "for example.\"\"\" return curie.split(\":\")[1] def _double_encode(url): \"\"\"Double url encode a url. This is", "or uberon or efo for example method: select or search. search provides much", "the curie, CL or UBERON for example.\"\"\" return curie.split(\":\")[0] def _ontology_value(curie): \"\"\"Get the", "label. This is useful when there is an existing label in a submitted", "curie like 'CL:1000413', get the label like 'endothelial cell of artery'\"\"\" url =", "with looking up ontology information.\"\"\" def _ontology_info_url(curie): \"\"\"Get the to make a GET", "using OLS REST API [https://www.ebi.ac.uk/ols/docs/api] url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response = requests.get(url) if not", "curie, 0000001 from CL:0000001 for example.\"\"\" return curie.split(\":\")[1] def _double_encode(url): \"\"\"Double url encode", "of (curie, label) tuples returned by OLS \"\"\" # using OLS REST API", "curie is empty, just return an empty string. This happens when there is", "got status code {response.status_code}: {response.text}\" ) return response.json()[\"label\"] def lookup_candidate_term(label, ontology=\"cl\", method=\"select\"): \"\"\"Lookup", "[https://www.ebi.ac.uk/ols/docs/api] url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response = requests.get(url) if not response.ok: raise OntologyLookupError( f\"Label", "def get_ontology_label(curie): \"\"\"For a given curie like 'CL:1000413', get the label like 'endothelial", "the ontology to search in, cl or uberon or efo for example method:", "OntologyLookupError(Exception): \"\"\"Exception for some problem with looking up ontology information.\"\"\" def _ontology_info_url(curie): \"\"\"Get", "appropriate ontology term. Args: label: the label to find ontology terms for ontology:", "CL or UBERON for example.\"\"\" return curie.split(\":\")[0] def _ontology_value(curie): \"\"\"Get the id component", "_ontology_name(curie) == \"EFO\": return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class OntologyLookupError(Exception): \"\"\"Exception for some problem", "# using OLS REST API [https://www.ebi.ac.uk/ols/docs/api] url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response = requests.get(url) if", "ontology terms for ontology: the ontology to search in, cl or uberon or", "GET to to get information about an ontology term.\"\"\" # If the curie", "got status code {response.status_code}: {response.text}\" ) return [(r[\"obo_id\"], r[\"label\"]) for r in response.json()[\"response\"][\"docs\"]]", "the iri from a curie. This is a bit hopeful that they all", "a curie. This is a bit hopeful that they all map to purl.obolibrary.org\"\"\"", "get the label like 'endothelial cell of artery'\"\"\" url = _ontology_info_url(curie) if not", "the name of the ontology from the curie, CL or UBERON for example.\"\"\"", "when there is no # valid ontology value. if not curie: return \"\"", "CL:0000001 for example.\"\"\" return curie.split(\":\")[1] def _double_encode(url): \"\"\"Double url encode a url. This", "provides much broader results Returns: list of (curie, label) tuples returned by OLS", "quote_plus(quote_plus(url)) def _iri(curie): \"\"\"Get the iri from a curie. This is a bit", "quote_plus import requests OLS_API_ROOT = \"http://www.ebi.ac.uk/ols/api\" # Curie means something like CL:0000001 def", "urllib.parse import quote_plus import requests OLS_API_ROOT = \"http://www.ebi.ac.uk/ols/api\" # Curie means something like" ]
[ "\"operator\": \"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\"", "TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE", "'cut': EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)} # In some case, a metric and cohort have", "[{ \"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } .. code-block:: http", "\"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } ] } \"\"\" #pylint:disable=useless-super-delegation", "the system will magically switch between both meaning. This is an attempt at", "http GET /api/questions/languages Response: { \"slug\": \"languages\", \"title\": \"All questions related to languages\"", "return get_account_model().objects.all() def get_likely_metric(self, cohort_slug): \"\"\" Returns a URL to a ``Matrix`` derived", "self.matrix if matrix: metric = self.matrix.metric else: parts = self.kwargs.get(self.matrix_url_kwarg).split('/') metric = get_object_or_404(EditableFilter,", "accounts = get_account_model().objects.all() scores = {} if metric: assert 'metric' in metric.tags, \\", "import Http404 from django.shortcuts import get_object_or_404 from extra_views.contrib.mixins import SearchableListMixin from rest_framework import", "SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT", "this list of conditions and the following disclaimer. # 2. Redistributions in binary", "'path' question_model = get_question_serializer().Meta.model def aggregate_scores(self, metric, cohorts, cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals if accounts", ".. code-block:: http GET /api/questions/languages Response: { \"slug\": \"languages\", \"title\": \"All questions related", "\"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } \"\"\" serializer_class = MatrixSerializer", "= len(questions) if nb_questions > 0: for cohort in cohorts: if isinstance(cohort, EditableFilter):", "def get_queryset(self): return self.get_serializer_class().Meta.model.objects.all() def get(self, request, *args, **kwargs): #pylint: disable=unused-argument self.editable_filter =", "without # modification, are permitted provided that the following conditions are met: #", "**includes).exclude(**excludes) else: accounts = self.get_accounts() cohort_serializer = get_account_serializer() # Implementation Note: switch cohorts", "request, *args, **kwargs): \"\"\" Deletes a fitler **Tags**: survey **Examples** .. code-block:: http", "(get_account_model, get_account_serializer, get_question_serializer) from .serializers import EditableFilterSerializer, MatrixSerializer LOGGER = logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView):", "likely_metric = self.request.build_absolute_uri( reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist: pass return likely_metric def get(self,", "code-block:: http PUT /api/xia/matrix/filters/all/ HTTP/1.1 .. code-block:: json { \"slug\": \"all\", \"title\": \"All\",", "\"\", \"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).put( request,", "All rights reserved. # # Redistribution and use in source and binary forms,", "EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist: pass return likely_metric def get(self, request, *args, **kwargs): #pylint:disable=unused-argument,too-many-locals matrix", "= matrix.cut if not cohorts: # We don't have any cohorts, let's show", "\"operator\": \"contains\", \"operand\": \"language\", \"field\": \"text\", \"selector\":\"keepmatching\" }] } \"\"\" serializer_class = get_question_serializer()", "import MatrixMixin from ..models import Answer, Matrix, EditableFilter from ..utils import (get_account_model, get_account_serializer,", "get_question_serializer().Meta.model def aggregate_scores(self, metric, cohorts, cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals if accounts is None: accounts", "retain the above copyright notice, # this list of conditions and the following", "= view.editable_filter return super(EditableFilterPagination, self).paginate_queryset( queryset, request, view=view) def get_paginated_response(self, data): return http.Response(OrderedDict([", "if nb_accounts > 0: nb_correct_answers = Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score = nb_correct_answers", "\"title\": \"None\", \"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\": \"\", \"operand\": \"\", \"field\":", "scores for cohorts aganist a metric. **Examples**: .. code-block:: http GET /api/matrix/languages Response:", "[scores] if public_cohorts: public_scores = {} public_scores.update(val) public_scores.update( {\"cohorts\": EditableFilterSerializer( public_cohorts, many=True).data, \"values\":", "EditableFilterSerializer lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return EditableFilter.objects.all() def put(self,", "**kwargs) def delete(self, request, *args, **kwargs): \"\"\" Deletes a fitler **Tags**: survey **Examples**", "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED.", "\"\"\" List filter objects **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1", "cohort_slug): \"\"\" Returns a URL to a ``Matrix`` derived from *cohort*. Many times", "#pylint:disable=useless-super-delegation return super(EditableFilterListAPIView, self).post( request, *args, **kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\" Retrieve a fitler", ".. code-block:: http DELETE /api/xia/matrix/filters/all/ HTTP/1.1 \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).delete( request, *args,", "metric = self.matrix.metric else: parts = self.kwargs.get(self.matrix_url_kwarg).split('/') metric = get_object_or_404(EditableFilter, slug=parts[-1]) matrix =", "\"\" } ] } \"\"\" search_fields = ['tags'] serializer_class = EditableFilterSerializer def post(self,", "and the following disclaimer. # 2. Redistributions in binary form must reproduce the", "THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF", "\"cohorts\": [{ \"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } Response: 201", "..mixins import MatrixMixin from ..models import Answer, Matrix, EditableFilter from ..utils import (get_account_model,", "queryset of `Account` ... cohorts = accounts result = [] scores = {}", "name. for cohort in val['cohorts']: likely_metric = self.get_likely_metric(cohort['slug']) if likely_metric: cohort['likely_metric'] = likely_metric", "LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,", "#pylint: disable=unused-argument self.editable_filter = generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView, self).get( request, *args, **kwargs)", "LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT", "let's show individual accounts instead. if cut: includes, excludes = cut.as_kwargs() accounts =", "accounts=None): #pylint:disable=unused-argument,too-many-locals if accounts is None: accounts = get_account_model().objects.all() scores = {} if", "\"predicates\": [] }] } Response: 201 CREATED { \"slug\": \"all\", \"title\": \"All accounts", "likely_metric: cohort['likely_metric'] = likely_metric scores.update(val) scores.update({\"values\": self.aggregate_scores( metric, cohorts, cut, accounts=self.get_accounts())}) result +=", "json { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\":", "provided that the following conditions are met: # # 1. Redistributions of source", "12 } \"\"\" pagination_class = EditableFilterPagination serializer_class = None # override in subclasses", "for cohort in val['cohorts']: likely_metric = self.get_likely_metric(cohort['slug']) if likely_metric: cohort['likely_metric'] = likely_metric scores.update(val)", "from ..models import Answer, Matrix, EditableFilter from ..utils import (get_account_model, get_account_serializer, get_question_serializer) from", "100 scores.update({str(cohort): score}) return {\"scores\": scores} @property def matrix(self): if not hasattr(self, '_matrix'):", "an queryset # of `EditableFilter` to a queryset of `Account` ... cohorts =", "likely_metric = self.get_likely_metric(cohort['slug']) if likely_metric: cohort['likely_metric'] = likely_metric scores.update(val) scores.update({\"values\": self.aggregate_scores( metric, cohorts,", "some case, a metric and cohort have a connection # and could have", "queryset, request, view=view) def get_paginated_response(self, data): return http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)), ('count', self.page.paginator.count),", "\"\"\" Retrieve a fitler **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/all/ HTTP/1.1", "= self.matrix if matrix: metric = self.matrix.metric else: parts = self.kwargs.get(self.matrix_url_kwarg).split('/') metric =", "are met: # # 1. Redistributions of source code must retain the above", "\"title\": \"All accounts against all questions\", \"metric\": { \"slug\": \"all-questions\", \"title\": \"All questions\",", "OF SUCH DAMAGE. import logging, re from collections import OrderedDict from django.db.models import", "\"slug\": \"all\", \"title\": \"All accounts against all questions\", \"metric\": { \"slug\": \"all-questions\", \"title\":", "conditions and the following disclaimer in the # documentation and/or other materials provided", "/api/xia/matrix/filters/all/ HTTP/1.1 responds .. code-block:: json { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\",", "], \"likely_metric\": \"\" } \"\"\" serializer_class = EditableFilterSerializer lookup_field = 'slug' lookup_url_kwarg =", ".. code-block:: http POST /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"count\": 2,", "responds .. code-block:: json { \"created_at\": \"2020-01-01T00:00:00Z\", \"measured\": 12 } \"\"\" pagination_class =", "and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED", "* nb_accounts) LOGGER.debug(\"score for '%s' = (%d * 100) \"\\ \"/ (%d *", "\"\" } ] } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterListAPIView, self).post( request, *args, **kwargs) class", "of `EditableFilter` to a queryset of `Account` ... cohorts = accounts result =", "EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView): \"\"\" List fitlers **Tags**: survey **Examples** .. code-block::", "{\"cohorts\": EditableFilterSerializer( public_cohorts, many=True).data, \"values\": self.aggregate_scores(metric, public_cohorts)}) result += [public_scores] return http.Response(result) class", "self.editable_filter)), ('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data) ])) class EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\"", "matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts = matrix.cohorts.filter(tags__contains='aggregate') cut = matrix.cut if not cohorts: # We don't", "permitted provided that the following conditions are met: # # 1. Redistributions of", "EditableFilterSerializer( public_cohorts, many=True).data, \"values\": self.aggregate_scores(metric, public_cohorts)}) result += [public_scores] return http.Response(result) class EditableFilterQuerysetMixin(object):", "extra_views.contrib.mixins import SearchableListMixin from rest_framework import generics from rest_framework.pagination import PageNumberPagination from rest_framework", "accounts is None: accounts = get_account_model().objects.all() scores = {} if metric: assert 'metric'", "TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE", "WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF", "{ 'slug': metric.slug, 'title': metric.title, 'metric': EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)} # In", "\"predicates\": [ \"rank\": 1, \"operator\": \"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\" ],", "super(EditableFilterObjectsAPIView, self).get( request, *args, **kwargs) class AccountListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``EditableFilter``. **Examples**:", "NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A", "notice, this list of conditions and the following disclaimer in the # documentation", "= matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts = matrix.cohorts.filter(tags__contains='aggregate') cut = matrix.cut if not cohorts: # We", "# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import logging, re from collections", "+= [public_scores] return http.Response(result) class EditableFilterQuerysetMixin(object): @staticmethod def get_queryset(): return EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin,", "http from ..compat import reverse from ..mixins import MatrixMixin from ..models import Answer,", "EditableFilterSerializer().to_representation( self.editable_filter)), ('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data) ])) class EditableFilterObjectsAPIView(generics.ListAPIView):", "results: [ { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\": [ \"rank\": 1,", "DELETE /api/xia/matrix/filters/all/ HTTP/1.1 \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).delete( request, *args, **kwargs) class EditableFilterPagination(PageNumberPagination):", "view.editable_filter return super(EditableFilterPagination, self).paginate_queryset( queryset, request, view=view) def get_paginated_response(self, data): return http.Response(OrderedDict([ ('editable_filter',", "all questions\", \"metric\": { \"slug\": \"all-questions\", \"title\": \"All questions\", \"predicates\": [] }, \"cohorts\":", "lookup_url_kwarg = 'path' question_model = get_question_serializer().Meta.model def aggregate_scores(self, metric, cohorts, cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals", "code-block:: http GET /api/xia/matrix/filters/all/ HTTP/1.1 responds .. code-block:: json { \"slug\": \"all\", \"title\":", "return super(EditableFilterDetailAPIView, self).delete( request, *args, **kwargs) class EditableFilterPagination(PageNumberPagination): def paginate_queryset(self, queryset, request, view=None):", "http GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"created_at\": \"2020-01-01T00:00:00Z\", \"measured\": 12", "http GET /api/matrix/ Response: { \"slug\": \"all\", \"title\": \"All accounts against all questions\",", "nb_correct_answers * 100 / ( nb_questions * nb_accounts) LOGGER.debug(\"score for '%s' = (%d", "public_scores = {} public_scores.update(val) public_scores.update( {\"cohorts\": EditableFilterSerializer( public_cohorts, many=True).data, \"values\": self.aggregate_scores(metric, public_cohorts)}) result", "sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score = nb_correct_answers * 100 / ( nb_questions * nb_accounts) LOGGER.debug(\"score", "AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR", "class MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\" Filtered list of ``Question``. **Examples**: .. code-block:: http GET /api/matrix/", "*args, **kwargs) class AccountListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``EditableFilter``. **Examples**: .. code-block:: http", "will be a list of single account objects. qs_accounts = [cohort] nb_accounts =", "\"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } Response: 201 CREATED { \"slug\":", "with or without # modification, are permitted provided that the following conditions are", "INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, #", "assert score <= 100 scores.update({str(cohort): score}) return {\"scores\": scores} @property def matrix(self): if", "\"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" }, { \"slug\": \"none\", \"title\": \"None\",", "http GET /api/xia/matrix/filters/all/ HTTP/1.1 responds .. code-block:: json { \"slug\": \"all\", \"title\": \"All\",", "code-block:: json { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\": [ \"rank\": 1,", ".. code-block:: http GET /api/matrix/languages Response: [{ \"slug\": \"languages\", \"title\": \"All cohorts for", "EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)} # In some case, a metric and cohort", "not matrix: raise Http404() cohort_serializer = EditableFilterSerializer cohorts = matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts = matrix.cohorts.filter(tags__contains='aggregate')", "measured=F('question__correct_answer')).count() score = nb_correct_answers * 100 / ( nb_questions * nb_accounts) LOGGER.debug(\"score for", "*args, **kwargs): \"\"\" Deletes a fitler **Tags**: survey **Examples** .. code-block:: http DELETE", "in val['cohorts']: likely_metric = self.get_likely_metric(cohort['slug']) if likely_metric: cohort['likely_metric'] = likely_metric scores.update(val) scores.update({\"values\": self.aggregate_scores(", "request, *args, **kwargs) class EditableFilterPagination(PageNumberPagination): def paginate_queryset(self, queryset, request, view=None): self.editable_filter = view.editable_filter", "NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY", "OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER", "Http404 from django.shortcuts import get_object_or_404 from extra_views.contrib.mixins import SearchableListMixin from rest_framework import generics", "*cohort*. Many times people will use the same name to either mean a", "OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER", "#pylint:disable=unused-argument,too-many-locals matrix = self.matrix if matrix: metric = self.matrix.metric else: parts = self.kwargs.get(self.matrix_url_kwarg).split('/')", "excludes = metric.as_kwargs() questions = self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions = len(questions) if nb_questions >", "HTTP/1.1 responds .. code-block:: json { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\":", "following conditions are met: # # 1. Redistributions of source code must retain", "metric.tags, \\ \"filter '%s' is not tagged as a metric\" % str(metric) includes,", "# # 1. Redistributions of source code must retain the above copyright notice,", "MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT", "serializer_class = None # override in subclasses lookup_field = 'slug' lookup_url_kwarg = 'editable_filter'", "\"\"\" A table of scores for cohorts aganist a metric. **Examples**: .. code-block::", "OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR", "ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED", "= Matrix.objects.filter(slug=parts[0]).first() if not matrix: raise Http404() cohort_serializer = EditableFilterSerializer cohorts = matrix.cohorts.exclude(tags__contains='aggregate')", "( nb_questions * nb_accounts) LOGGER.debug(\"score for '%s' = (%d * 100) \"\\ \"/", "Response: { \"slug\": \"languages\", \"title\": \"All questions related to languages\" \"predicates\":[{ \"operator\": \"contains\",", "previous: null, next: null, results: [ { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\",", "Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix def get_accounts(self): #pylint:disable=unused-argument,no-self-use return get_account_model().objects.all() def get_likely_metric(self, cohort_slug): \"\"\"", "100) \"\\ \"/ (%d * %d) = %f\", str(cohort), nb_correct_answers, nb_questions, nb_accounts, score)", "in cohorts: if isinstance(cohort, EditableFilter): includes, excludes = cohort.as_kwargs() qs_accounts = accounts.filter( **includes).exclude(**excludes)", "code-block:: json { \"created_at\": \"2020-01-01T00:00:00Z\", \"measured\": 12 } \"\"\" pagination_class = EditableFilterPagination serializer_class", "Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score = nb_correct_answers * 100 / ( nb_questions *", "modification, are permitted provided that the following conditions are met: # # 1.", "= {} val = { 'slug': metric.slug, 'title': metric.title, 'metric': EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut),", "from .serializers import EditableFilterSerializer, MatrixSerializer LOGGER = logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\" Filtered list", "# of `EditableFilter` to a queryset of `Account` ... cohorts = accounts result", "= cut.as_kwargs() accounts = self.get_accounts().filter( **includes).exclude(**excludes) else: accounts = self.get_accounts() cohort_serializer = get_account_serializer()", "EditableFilterPagination serializer_class = None # override in subclasses lookup_field = 'slug' lookup_url_kwarg =", "... cohorts = accounts result = [] scores = {} val = {", "# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR #", "search_fields = ['tags'] serializer_class = EditableFilterSerializer def post(self, request, *args, **kwargs): \"\"\" Create", "CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL", "# documentation and/or other materials provided with the distribution. # # THIS SOFTWARE", "= 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return EditableFilter.objects.all() def put(self, request, *args,", "for all questions\" \"scores\":{ \"portfolio-a\": \"0.1\", \"portfolio-b\": \"0.5\", } }] \"\"\" serializer_class =", "ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED", "rights reserved. # # Redistribution and use in source and binary forms, with", "import get_object_or_404 from extra_views.contrib.mixins import SearchableListMixin from rest_framework import generics from rest_framework.pagination import", "(%d * %d) = %f\", str(cohort), nb_correct_answers, nb_questions, nb_accounts, score) assert score <=", "+= [scores] if public_cohorts: public_scores = {} public_scores.update(val) public_scores.update( {\"cohorts\": EditableFilterSerializer( public_cohorts, many=True).data,", "\"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\": \"\", \"operand\": \"\",", "could have the same name. for cohort in val['cohorts']: likely_metric = self.get_likely_metric(cohort['slug']) if", ".. code-block:: json { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\": [ \"rank\":", "**kwargs) class AccountListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``EditableFilter``. **Examples**: .. code-block:: http GET", ".. code-block:: http POST /api/matrix/ { \"slug\": \"all\", \"title\": \"All accounts against all", "a connection # and could have the same name. for cohort in val['cohorts']:", "show individual accounts instead. if cut: includes, excludes = cut.as_kwargs() accounts = self.get_accounts().filter(", "provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT", "Response: [{ \"slug\": \"languages\", \"title\": \"All cohorts for all questions\" \"scores\":{ \"portfolio-a\": \"0.1\",", "Redistributions in binary form must reproduce the above copyright # notice, this list", "score) assert score <= 100 scores.update({str(cohort): score}) return {\"scores\": scores} @property def matrix(self):", "\"text\", \"selector\":\"keepmatching\" }] } \"\"\" serializer_class = get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list", "# If `matrix.cohorts is None`, the `cohorts` argument # will be a list", "use the same name to either mean a cohort or a metric and", "Implementation Note: switch cohorts from an queryset # of `EditableFilter` to a queryset", "queryset # of `EditableFilter` to a queryset of `Account` ... cohorts = accounts", "args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist: pass return likely_metric def get(self, request, *args, **kwargs): #pylint:disable=unused-argument,too-many-locals", "get_account_serializer, get_question_serializer) from .serializers import EditableFilterSerializer, MatrixSerializer LOGGER = logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\"", "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR", "*args, **kwargs): \"\"\" Updates a fitler **Tags**: survey **Examples** .. code-block:: http PUT", "Copyright (c) 2020, DjaoDjin inc. # All rights reserved. # # Redistribution and", "get_account_model().objects.all() scores = {} if metric: assert 'metric' in metric.tags, \\ \"filter '%s'", "accounts = self.get_accounts().filter( **includes).exclude(**excludes) else: accounts = self.get_accounts() cohort_serializer = get_account_serializer() # Implementation", "\"\"\" Create a fitler **Tags**: survey **Examples** .. code-block:: http POST /api/xia/matrix/filters/ HTTP/1.1", "str(metric) includes, excludes = metric.as_kwargs() questions = self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions = len(questions) if", "}, { \"slug\": \"none\", \"title\": \"None\", \"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\":", "reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist: pass return likely_metric def get(self, request, *args, **kwargs):", "val = { 'slug': metric.slug, 'title': metric.title, 'metric': EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)}", "inc. # All rights reserved. # # Redistribution and use in source and", "aggregate_scores(self, metric, cohorts, cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals if accounts is None: accounts = get_account_model().objects.all()", "\"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\": \"\", \"operand\": \"\", \"field\": \"\", \"selector\":", "} \"\"\" serializer_class = EditableFilterSerializer lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self):", "of ``EditableFilter``. **Examples**: .. code-block:: http GET /api/questions/languages Response: { \"slug\": \"languages\", \"title\":", "None`, the `cohorts` argument # will be a list of single account objects.", "= EditableFilterSerializer def post(self, request, *args, **kwargs): \"\"\" Create a fitler **Tags**: survey", "http GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"count\": 2, previous: null,", "\"\", \"predicates\": [ \"rank\": 1, \"operator\": \"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\"", "(INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS", "SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import logging,", "'slug' lookup_url_kwarg = 'path' question_model = get_question_serializer().Meta.model def aggregate_scores(self, metric, cohorts, cut=None, accounts=None):", "MatrixSerializer lookup_field = 'slug' lookup_url_kwarg = 'path' question_model = get_question_serializer().Meta.model def aggregate_scores(self, metric,", "get_likely_metric(self, cohort_slug): \"\"\" Returns a URL to a ``Matrix`` derived from *cohort*. Many", "http POST /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"count\": 2, previous: null,", "have the same name. for cohort in val['cohorts']: likely_metric = self.get_likely_metric(cohort['slug']) if likely_metric:", "OrderedDict from django.db.models import F from django.http import Http404 from django.shortcuts import get_object_or_404", "EditableFilterQuerysetMixin, generics.ListCreateAPIView): \"\"\" List fitlers **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/", "of source code must retain the above copyright notice, # this list of", "'_matrix'): self._matrix = Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix def get_accounts(self): #pylint:disable=unused-argument,no-self-use return get_account_model().objects.all() def", "**Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json", "= get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``Question``. **Examples**: .. code-block:: http", "= {} if metric: assert 'metric' in metric.tags, \\ \"filter '%s' is not", "SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND", "<= 100 scores.update({str(cohort): score}) return {\"scores\": scores} @property def matrix(self): if not hasattr(self,", "GET /api/questions/languages Response: { \"slug\": \"languages\", \"title\": \"All questions related to languages\" \"predicates\":[{", "= cohort.as_kwargs() qs_accounts = accounts.filter( **includes).exclude(**excludes) else: # If `matrix.cohorts is None`, the", "disable=unused-argument self.editable_filter = generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView, self).get( request, *args, **kwargs) class", "accounts\", \"predicates\": [] }] } \"\"\" serializer_class = MatrixSerializer def get_queryset(self): return Matrix.objects.all()", "**Examples** .. code-block:: http POST /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"count\":", "\"title\": \"All accounts\", \"predicates\": [] }] } \"\"\" serializer_class = MatrixSerializer def get_queryset(self):", "Redistributions of source code must retain the above copyright notice, # this list", "GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"count\": 2, previous: null, next:", "] } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterListAPIView, self).post( request, *args, **kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\"", "THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,", "get(self, request, *args, **kwargs): #pylint:disable=unused-argument,too-many-locals matrix = self.matrix if matrix: metric = self.matrix.metric", "from django.db.models import F from django.http import Http404 from django.shortcuts import get_object_or_404 from", "PageNumberPagination from rest_framework import response as http from ..compat import reverse from ..mixins", "URL to a ``Matrix`` derived from *cohort*. Many times people will use the", "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; #", "DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;", "generics from rest_framework.pagination import PageNumberPagination from rest_framework import response as http from ..compat", "COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,", "{} if metric: assert 'metric' in metric.tags, \\ \"filter '%s' is not tagged", "EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\" Retrieve a fitler **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/all/", "scores} @property def matrix(self): if not hasattr(self, '_matrix'): self._matrix = Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return", "scores = {} val = { 'slug': metric.slug, 'title': metric.title, 'metric': EditableFilterSerializer().to_representation(metric), 'cut':", "or without # modification, are permitted provided that the following conditions are met:", "\"likely_metric\": \"\" } \"\"\" serializer_class = EditableFilterSerializer lookup_field = 'slug' lookup_url_kwarg = 'editable_filter'", "'editable_filter' def get_queryset(self): return self.get_serializer_class().Meta.model.objects.all() def get(self, request, *args, **kwargs): #pylint: disable=unused-argument self.editable_filter", "In some case, a metric and cohort have a connection # and could", "\"predicates\": [] }, \"cohorts\": [{ \"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }]", "= [cohort] nb_accounts = len(qs_accounts) if nb_accounts > 0: nb_correct_answers = Answer.objects.filter( question__in=questions,", "OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY", "# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR #", "= self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions = len(questions) if nb_questions > 0: for cohort in", "response as http from ..compat import reverse from ..mixins import MatrixMixin from ..models", "scores.update({str(cohort): score}) return {\"scores\": scores} @property def matrix(self): if not hasattr(self, '_matrix'): self._matrix", "def matrix(self): if not hasattr(self, '_matrix'): self._matrix = Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix def", "hasattr(self, '_matrix'): self._matrix = Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix def get_accounts(self): #pylint:disable=unused-argument,no-self-use return get_account_model().objects.all()", "'cohorts': cohort_serializer(many=True).to_representation(cohorts)} # In some case, a metric and cohort have a connection", "meaning. This is an attempt at magic. \"\"\" likely_metric = None look =", "cohorts, let's show individual accounts instead. if cut: includes, excludes = cut.as_kwargs() accounts", "matrix = self.matrix if matrix: metric = self.matrix.metric else: parts = self.kwargs.get(self.matrix_url_kwarg).split('/') metric", "expect the system will magically switch between both meaning. This is an attempt", "{ \"slug\": \"all\", \"title\": \"All accounts against all questions\", \"metric\": { \"slug\": \"all-questions\",", "('previous', self.get_previous_link()), ('results', data) ])) class EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\" List filter objects **Tags**: survey", "= %f\", str(cohort), nb_correct_answers, nb_questions, nb_accounts, score) assert score <= 100 scores.update({str(cohort): score})", "[] }] } \"\"\" serializer_class = MatrixSerializer def get_queryset(self): return Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin,", "met: # # 1. Redistributions of source code must retain the above copyright", "'metric': EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)} # In some case, a metric and", "from an queryset # of `EditableFilter` to a queryset of `Account` ... cohorts", "get_queryset(): return EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView): \"\"\" List fitlers **Tags**: survey **Examples**", "survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/all/ HTTP/1.1 responds .. code-block:: json {", "\"\" } responds .. code-block:: json { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\",", "\"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\" serializer_class =", "# notice, this list of conditions and the following disclaimer in the #", "*args, **kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\" Retrieve a fitler **Tags**: survey **Examples** .. code-block::", "= { 'slug': metric.slug, 'title': metric.title, 'metric': EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)} #", "\"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\" serializer_class = EditableFilterSerializer", "'metric' in metric.tags, \\ \"filter '%s' is not tagged as a metric\" %", "questions related to languages\" \"predicates\":[{ \"operator\": \"contains\", \"operand\": \"language\", \"field\": \"text\", \"selector\":\"keepmatching\" }]", "def get_likely_metric(self, cohort_slug): \"\"\" Returns a URL to a ``Matrix`` derived from *cohort*.", "{\"scores\": scores} @property def matrix(self): if not hasattr(self, '_matrix'): self._matrix = Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first()", "a metric. **Examples**: .. code-block:: http GET /api/matrix/languages Response: [{ \"slug\": \"languages\", \"title\":", "#pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).delete( request, *args, **kwargs) class EditableFilterPagination(PageNumberPagination): def paginate_queryset(self, queryset, request,", "of ``Question``. **Examples**: .. code-block:: http GET /api/questions/languages Response: { \"slug\": \"languages\", \"title\":", "request, *args, **kwargs): #pylint:disable=unused-argument,too-many-locals matrix = self.matrix if matrix: metric = self.matrix.metric else:", "\"\\ \"/ (%d * %d) = %f\", str(cohort), nb_correct_answers, nb_questions, nb_accounts, score) assert", "request, *args, **kwargs) def delete(self, request, *args, **kwargs): \"\"\" Deletes a fitler **Tags**:", "\"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterListAPIView, self).post( request, *args, **kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\" Retrieve a", "import generics from rest_framework.pagination import PageNumberPagination from rest_framework import response as http from", "get_paginated_response(self, data): return http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)), ('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()),", "**Tags**: survey **Examples** .. code-block:: http PUT /api/xia/matrix/filters/all/ HTTP/1.1 .. code-block:: json {", "LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND", "data) ])) class EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\" List filter objects **Tags**: survey **Examples** .. code-block::", "Filtered list of ``Question``. **Examples**: .. code-block:: http GET /api/matrix/ Response: { \"slug\":", "and could have the same name. for cohort in val['cohorts']: likely_metric = self.get_likely_metric(cohort['slug'])", "# and could have the same name. for cohort in val['cohorts']: likely_metric =", "class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\" Retrieve a fitler **Tags**: survey **Examples** .. code-block:: http GET", "1, \"operator\": \"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" },", "LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR #", "accounts\", \"predicates\": [] }] } .. code-block:: http POST /api/matrix/ { \"slug\": \"all\",", "} Response: 201 CREATED { \"slug\": \"all\", \"title\": \"All accounts against all questions\",", "THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE", "pass return likely_metric def get(self, request, *args, **kwargs): #pylint:disable=unused-argument,too-many-locals matrix = self.matrix if", "if accounts is None: accounts = get_account_model().objects.all() scores = {} if metric: assert", "class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): \"\"\" A table of scores for cohorts aganist a metric.", "metric. **Examples**: .. code-block:: http GET /api/matrix/languages Response: [{ \"slug\": \"languages\", \"title\": \"All", "cohort_serializer(many=True).to_representation(cohorts)} # In some case, a metric and cohort have a connection #", "import PageNumberPagination from rest_framework import response as http from ..compat import reverse from", "\"title\": \"All accounts\", \"predicates\": [] }] } Response: 201 CREATED { \"slug\": \"all\",", "= get_question_serializer().Meta.model def aggregate_scores(self, metric, cohorts, cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals if accounts is None:", "\"\" ], \"likely_metric\": \"\" } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).put( request, *args, **kwargs)", "languages\" \"predicates\":[{ \"operator\": \"contains\", \"operand\": \"language\", \"field\": \"text\", \"selector\":\"keepmatching\" }] } \"\"\" serializer_class", "class EditableFilterPagination(PageNumberPagination): def paginate_queryset(self, queryset, request, view=None): self.editable_filter = view.editable_filter return super(EditableFilterPagination, self).paginate_queryset(", "put(self, request, *args, **kwargs): \"\"\" Updates a fitler **Tags**: survey **Examples** .. code-block::", "\"\"\" serializer_class = MatrixSerializer def get_queryset(self): return Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): \"\"\" A", "}, \"cohorts\": [{ \"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } \"\"\"", "likely_metric scores.update(val) scores.update({\"values\": self.aggregate_scores( metric, cohorts, cut, accounts=self.get_accounts())}) result += [scores] if public_cohorts:", "get_question_serializer) from .serializers import EditableFilterSerializer, MatrixSerializer LOGGER = logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\" Filtered", "= MatrixSerializer def get_queryset(self): return Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): \"\"\" A table of", "either mean a cohort or a metric and expect the system will magically", "for cohort in cohorts: if isinstance(cohort, EditableFilter): includes, excludes = cohort.as_kwargs() qs_accounts =", "the following disclaimer. # 2. Redistributions in binary form must reproduce the above", "view=None): self.editable_filter = view.editable_filter return super(EditableFilterPagination, self).paginate_queryset( queryset, request, view=view) def get_paginated_response(self, data):", "public_scores.update( {\"cohorts\": EditableFilterSerializer( public_cohorts, many=True).data, \"values\": self.aggregate_scores(metric, public_cohorts)}) result += [public_scores] return http.Response(result)", "Filtered list of ``Question``. **Examples**: .. code-block:: http GET /api/questions/languages Response: { \"slug\":", "} \"\"\" serializer_class = get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``Question``. **Examples**:", "for '%s' = (%d * 100) \"\\ \"/ (%d * %d) = %f\",", "# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR", "OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS", "accounts = self.get_accounts() cohort_serializer = get_account_serializer() # Implementation Note: switch cohorts from an", "OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN", "Note: switch cohorts from an queryset # of `EditableFilter` to a queryset of", "AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT", "and use in source and binary forms, with or without # modification, are", "THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED", "collections import OrderedDict from django.db.models import F from django.http import Http404 from django.shortcuts", "\"scores\":{ \"portfolio-a\": \"0.1\", \"portfolio-b\": \"0.5\", } }] \"\"\" serializer_class = MatrixSerializer lookup_field =", "Create a fitler **Tags**: survey **Examples** .. code-block:: http POST /api/xia/matrix/filters/ HTTP/1.1 responds", "def paginate_queryset(self, queryset, request, view=None): self.editable_filter = view.editable_filter return super(EditableFilterPagination, self).paginate_queryset( queryset, request,", "\"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).put( request, *args,", "PUT /api/xia/matrix/filters/all/ HTTP/1.1 .. code-block:: json { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\",", "survey **Examples** .. code-block:: http PUT /api/xia/matrix/filters/all/ HTTP/1.1 .. code-block:: json { \"slug\":", "import reverse from ..mixins import MatrixMixin from ..models import Answer, Matrix, EditableFilter from", "\"none\", \"title\": \"None\", \"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\": \"\", \"operand\": \"\",", "MatrixSerializer LOGGER = logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\" Filtered list of ``Question``. **Examples**: ..", "json { \"created_at\": \"2020-01-01T00:00:00Z\", \"measured\": 12 } \"\"\" pagination_class = EditableFilterPagination serializer_class =", "fitlers **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block::", "self.get_previous_link()), ('results', data) ])) class EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\" List filter objects **Tags**: survey **Examples**", "if matrix: metric = self.matrix.metric else: parts = self.kwargs.get(self.matrix_url_kwarg).split('/') metric = get_object_or_404(EditableFilter, slug=parts[-1])", "\"\" ], \"likely_metric\": \"\" }, { \"slug\": \"none\", \"title\": \"None\", \"tags\": \"\", \"predicates\":", "conditions are met: # # 1. Redistributions of source code must retain the", "import (get_account_model, get_account_serializer, get_question_serializer) from .serializers import EditableFilterSerializer, MatrixSerializer LOGGER = logging.getLogger(__name__) class", "self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions = len(questions) if nb_questions > 0: for cohort in cohorts:", "MatrixSerializer def get_queryset(self): return Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): \"\"\" A table of scores", "\"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } ] } \"\"\" search_fields =", "accounts result = [] scores = {} val = { 'slug': metric.slug, 'title':", "\"likely_metric\": \"\" } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).put( request, *args, **kwargs) def delete(self,", "this list of conditions and the following disclaimer in the # documentation and/or", "BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF", "at magic. \"\"\" likely_metric = None look = re.match(r\"(\\S+)(-\\d+)\", cohort_slug) if look: try:", "\"contains\", \"operand\": \"language\", \"field\": \"text\", \"selector\":\"keepmatching\" }] } \"\"\" serializer_class = get_account_serializer() class", "# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED", "USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY", "attempt at magic. \"\"\" likely_metric = None look = re.match(r\"(\\S+)(-\\d+)\", cohort_slug) if look:", "\"\"\" serializer_class = EditableFilterSerializer lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return", "\"\" } \"\"\" serializer_class = EditableFilterSerializer lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def", "don't have any cohorts, let's show individual accounts instead. if cut: includes, excludes", "MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\" Filtered list of ``Question``. **Examples**: .. code-block:: http GET /api/matrix/ Response:", "fitler **Tags**: survey **Examples** .. code-block:: http DELETE /api/xia/matrix/filters/all/ HTTP/1.1 \"\"\" #pylint:disable=useless-super-delegation return", "# override in subclasses lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return", "if nb_questions > 0: for cohort in cohorts: if isinstance(cohort, EditableFilter): includes, excludes", "class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``Question``. **Examples**: .. code-block:: http GET /api/questions/languages", "return self._matrix def get_accounts(self): #pylint:disable=unused-argument,no-self-use return get_account_model().objects.all() def get_likely_metric(self, cohort_slug): \"\"\" Returns a", "\"All questions\", \"predicates\": [] }, \"cohorts\": [{ \"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\":", "http GET /api/matrix/languages Response: [{ \"slug\": \"languages\", \"title\": \"All cohorts for all questions\"", "accounts.filter( **includes).exclude(**excludes) else: # If `matrix.cohorts is None`, the `cohorts` argument # will", "Matrix, EditableFilter from ..utils import (get_account_model, get_account_serializer, get_question_serializer) from .serializers import EditableFilterSerializer, MatrixSerializer", "list of ``Question``. **Examples**: .. code-block:: http GET /api/matrix/ Response: { \"slug\": \"all\",", "except EditableFilter.DoesNotExist: pass return likely_metric def get(self, request, *args, **kwargs): #pylint:disable=unused-argument,too-many-locals matrix =", "request, *args, **kwargs): #pylint: disable=unused-argument self.editable_filter = generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView, self).get(", "disclaimer in the # documentation and/or other materials provided with the distribution. #", "get_accounts(self): #pylint:disable=unused-argument,no-self-use return get_account_model().objects.all() def get_likely_metric(self, cohort_slug): \"\"\" Returns a URL to a", "scores.update({\"values\": self.aggregate_scores( metric, cohorts, cut, accounts=self.get_accounts())}) result += [scores] if public_cohorts: public_scores =", "OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF", "mean a cohort or a metric and expect the system will magically switch", "slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView, self).get( request, *args, **kwargs) class AccountListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of", "WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND", "import OrderedDict from django.db.models import F from django.http import Http404 from django.shortcuts import", "is None`, the `cohorts` argument # will be a list of single account", "to a queryset of `Account` ... cohorts = accounts result = [] scores", "get_queryset(self): return self.get_serializer_class().Meta.model.objects.all() def get(self, request, *args, **kwargs): #pylint: disable=unused-argument self.editable_filter = generics.get_object_or_404(", "QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``Question``. **Examples**: .. code-block:: http GET /api/questions/languages Response:", "django.shortcuts import get_object_or_404 from extra_views.contrib.mixins import SearchableListMixin from rest_framework import generics from rest_framework.pagination", "[{ \"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } Response: 201 CREATED", "= self.request.build_absolute_uri( reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist: pass return likely_metric def get(self, request,", "cohort['likely_metric'] = likely_metric scores.update(val) scores.update({\"values\": self.aggregate_scores( metric, cohorts, cut, accounts=self.get_accounts())}) result += [scores]", "code-block:: http POST /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"count\": 2, previous:", "all questions\" \"scores\":{ \"portfolio-a\": \"0.1\", \"portfolio-b\": \"0.5\", } }] \"\"\" serializer_class = MatrixSerializer", "nb_accounts) LOGGER.debug(\"score for '%s' = (%d * 100) \"\\ \"/ (%d * %d)", "Many times people will use the same name to either mean a cohort", "\"All accounts\", \"predicates\": [] }] } Response: 201 CREATED { \"slug\": \"all\", \"title\":", "public_cohorts: public_scores = {} public_scores.update(val) public_scores.update( {\"cohorts\": EditableFilterSerializer( public_cohorts, many=True).data, \"values\": self.aggregate_scores(metric, public_cohorts)})", "request, *args, **kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\" Retrieve a fitler **Tags**: survey **Examples** ..", "copyright notice, # this list of conditions and the following disclaimer. # 2.", "BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR", "EditableFilterPagination(PageNumberPagination): def paginate_queryset(self, queryset, request, view=None): self.editable_filter = view.editable_filter return super(EditableFilterPagination, self).paginate_queryset( queryset,", "\"\"\" Filtered list of ``EditableFilter``. **Examples**: .. code-block:: http GET /api/questions/languages Response: {", "``Question``. **Examples**: .. code-block:: http GET /api/matrix/ Response: { \"slug\": \"all\", \"title\": \"All", "get_account_serializer() # Implementation Note: switch cohorts from an queryset # of `EditableFilter` to", "switch between both meaning. This is an attempt at magic. \"\"\" likely_metric =", "None: accounts = get_account_model().objects.all() scores = {} if metric: assert 'metric' in metric.tags,", "= get_object_or_404(EditableFilter, slug=parts[-1]) matrix = Matrix.objects.filter(slug=parts[0]).first() if not matrix: raise Http404() cohort_serializer =", "public_cohorts, many=True).data, \"values\": self.aggregate_scores(metric, public_cohorts)}) result += [public_scores] return http.Response(result) class EditableFilterQuerysetMixin(object): @staticmethod", "cut: includes, excludes = cut.as_kwargs() accounts = self.get_accounts().filter( **includes).exclude(**excludes) else: accounts = self.get_accounts()", "\"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } .. code-block:: http POST /api/matrix/", "cohort_slug) if look: try: likely_metric = self.request.build_absolute_uri( reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist: pass", "Redistribution and use in source and binary forms, with or without # modification,", "} }] \"\"\" serializer_class = MatrixSerializer lookup_field = 'slug' lookup_url_kwarg = 'path' question_model", "POSSIBILITY OF SUCH DAMAGE. import logging, re from collections import OrderedDict from django.db.models", "\"All accounts against all questions\", \"metric\": { \"slug\": \"all-questions\", \"title\": \"All questions\", \"predicates\":", "get_object_or_404 from extra_views.contrib.mixins import SearchableListMixin from rest_framework import generics from rest_framework.pagination import PageNumberPagination", "as http from ..compat import reverse from ..mixins import MatrixMixin from ..models import", "else: # If `matrix.cohorts is None`, the `cohorts` argument # will be a", "\"\"\" List fitlers **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds", "self.aggregate_scores(metric, public_cohorts)}) result += [public_scores] return http.Response(result) class EditableFilterQuerysetMixin(object): @staticmethod def get_queryset(): return", "HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, #", "source and binary forms, with or without # modification, are permitted provided that", "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE", "%d) = %f\", str(cohort), nb_correct_answers, nb_questions, nb_accounts, score) assert score <= 100 scores.update({str(cohort):", "**Examples**: .. code-block:: http GET /api/matrix/languages Response: [{ \"slug\": \"languages\", \"title\": \"All cohorts", "above copyright # notice, this list of conditions and the following disclaimer in", "get_queryset(self): return EditableFilter.objects.all() def put(self, request, *args, **kwargs): \"\"\" Updates a fitler **Tags**:", "score}) return {\"scores\": scores} @property def matrix(self): if not hasattr(self, '_matrix'): self._matrix =", "request, view=view) def get_paginated_response(self, data): return http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)), ('count', self.page.paginator.count), ('next',", "lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return self.get_serializer_class().Meta.model.objects.all() def get(self, request,", "# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,", "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\"", "binary form must reproduce the above copyright # notice, this list of conditions", "= self.get_likely_metric(cohort['slug']) if likely_metric: cohort['likely_metric'] = likely_metric scores.update(val) scores.update({\"values\": self.aggregate_scores( metric, cohorts, cut,", "accounts instead. if cut: includes, excludes = cut.as_kwargs() accounts = self.get_accounts().filter( **includes).exclude(**excludes) else:", "{} public_scores.update(val) public_scores.update( {\"cohorts\": EditableFilterSerializer( public_cohorts, many=True).data, \"values\": self.aggregate_scores(metric, public_cohorts)}) result += [public_scores]", "form must reproduce the above copyright # notice, this list of conditions and", "**kwargs): #pylint: disable=unused-argument self.editable_filter = generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView, self).get( request, *args,", "} \"\"\" pagination_class = EditableFilterPagination serializer_class = None # override in subclasses lookup_field", "nb_questions = len(questions) if nb_questions > 0: for cohort in cohorts: if isinstance(cohort,", "\"predicates\": [] }] } .. code-block:: http POST /api/matrix/ { \"slug\": \"all\", \"title\":", "cohorts aganist a metric. **Examples**: .. code-block:: http GET /api/matrix/languages Response: [{ \"slug\":", "cohort.as_kwargs() qs_accounts = accounts.filter( **includes).exclude(**excludes) else: # If `matrix.cohorts is None`, the `cohorts`", "from ..utils import (get_account_model, get_account_serializer, get_question_serializer) from .serializers import EditableFilterSerializer, MatrixSerializer LOGGER =", "get_account_model().objects.all() def get_likely_metric(self, cohort_slug): \"\"\" Returns a URL to a ``Matrix`` derived from", "of conditions and the following disclaimer. # 2. Redistributions in binary form must", "def put(self, request, *args, **kwargs): \"\"\" Updates a fitler **Tags**: survey **Examples** ..", "], \"likely_metric\": \"\" } ] } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterListAPIView, self).post( request, *args,", "\"rank\": 1, \"operator\": \"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\"", "= 'editable_filter' def get_queryset(self): return EditableFilter.objects.all() def put(self, request, *args, **kwargs): \"\"\" Updates", "return {\"scores\": scores} @property def matrix(self): if not hasattr(self, '_matrix'): self._matrix = Matrix.objects.filter(", "EditableFilterQuerysetMixin(object): @staticmethod def get_queryset(): return EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView): \"\"\" List fitlers", "is not tagged as a metric\" % str(metric) includes, excludes = metric.as_kwargs() questions", "filter objects **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds ..", "single account objects. qs_accounts = [cohort] nb_accounts = len(qs_accounts) if nb_accounts > 0:", "= self.kwargs.get(self.matrix_url_kwarg).split('/') metric = get_object_or_404(EditableFilter, slug=parts[-1]) matrix = Matrix.objects.filter(slug=parts[0]).first() if not matrix: raise", ".. code-block:: json { \"count\": 2, previous: null, next: null, results: [ {", "DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE", "= MatrixSerializer lookup_field = 'slug' lookup_url_kwarg = 'path' question_model = get_question_serializer().Meta.model def aggregate_scores(self,", "= self.get_accounts() cohort_serializer = get_account_serializer() # Implementation Note: switch cohorts from an queryset", "# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE)", "a fitler **Tags**: survey **Examples** .. code-block:: http POST /api/xia/matrix/filters/ HTTP/1.1 responds ..", "serializer_class = MatrixSerializer def get_queryset(self): return Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): \"\"\" A table", "`matrix.cohorts is None`, the `cohorts` argument # will be a list of single", "to a ``Matrix`` derived from *cohort*. Many times people will use the same", "'%s' is not tagged as a metric\" % str(metric) includes, excludes = metric.as_kwargs()", "This is an attempt at magic. \"\"\" likely_metric = None look = re.match(r\"(\\S+)(-\\d+)\",", "cohorts: # We don't have any cohorts, let's show individual accounts instead. if", "{ \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\": \"\",", "..compat import reverse from ..mixins import MatrixMixin from ..models import Answer, Matrix, EditableFilter", "following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright", "def get_accounts(self): #pylint:disable=unused-argument,no-self-use return get_account_model().objects.all() def get_likely_metric(self, cohort_slug): \"\"\" Returns a URL to", "\"All accounts\", \"predicates\": [] }] } .. code-block:: http POST /api/matrix/ { \"slug\":", "[cohort] nb_accounts = len(qs_accounts) if nb_accounts > 0: nb_correct_answers = Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter(", "a cohort or a metric and expect the system will magically switch between", "\"title\": \"All cohorts for all questions\" \"scores\":{ \"portfolio-a\": \"0.1\", \"portfolio-b\": \"0.5\", } }]", "def post(self, request, *args, **kwargs): \"\"\" Create a fitler **Tags**: survey **Examples** ..", "(INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE", "\"\" ], \"likely_metric\": \"\" } ] } \"\"\" search_fields = ['tags'] serializer_class =", "**Examples** .. code-block:: http DELETE /api/xia/matrix/filters/all/ HTTP/1.1 \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).delete( request,", "* %d) = %f\", str(cohort), nb_correct_answers, nb_questions, nb_accounts, score) assert score <= 100", "IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR", "USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH", "cohorts, cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals if accounts is None: accounts = get_account_model().objects.all() scores =", "the above copyright # notice, this list of conditions and the following disclaimer", "}] } \"\"\" serializer_class = MatrixSerializer def get_queryset(self): return Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView):", "= nb_correct_answers * 100 / ( nb_questions * nb_accounts) LOGGER.debug(\"score for '%s' =", "def delete(self, request, *args, **kwargs): \"\"\" Deletes a fitler **Tags**: survey **Examples** ..", "cohort in val['cohorts']: likely_metric = self.get_likely_metric(cohort['slug']) if likely_metric: cohort['likely_metric'] = likely_metric scores.update(val) scores.update({\"values\":", "\"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).delete( request, *args, **kwargs) class EditableFilterPagination(PageNumberPagination): def paginate_queryset(self, queryset,", "SUCH DAMAGE. import logging, re from collections import OrderedDict from django.db.models import F", "accounts against all questions\", \"metric\": { \"slug\": \"all-questions\", \"title\": \"All questions\", \"predicates\": []", "PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS", "http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)), ('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data) ]))", "DjaoDjin inc. # All rights reserved. # # Redistribution and use in source", "\\ \"filter '%s' is not tagged as a metric\" % str(metric) includes, excludes", "result = [] scores = {} val = { 'slug': metric.slug, 'title': metric.title,", "\"\", \"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\" serializer_class = EditableFilterSerializer lookup_field =", "\"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\" serializer_class = EditableFilterSerializer lookup_field = 'slug'", "question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score = nb_correct_answers * 100 / ( nb_questions * nb_accounts)", "includes, excludes = metric.as_kwargs() questions = self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions = len(questions) if nb_questions", "FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT", "EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView): \"\"\" List fitlers **Tags**: survey **Examples** .. code-block:: http GET", "rest_framework.pagination import PageNumberPagination from rest_framework import response as http from ..compat import reverse", "django.http import Http404 from django.shortcuts import get_object_or_404 from extra_views.contrib.mixins import SearchableListMixin from rest_framework", "\"selector\":\"keepmatching\" }] } \"\"\" serializer_class = get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of", "= accounts result = [] scores = {} val = { 'slug': metric.slug,", "metric.slug, 'title': metric.title, 'metric': EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)} # In some case,", "accounts=self.get_accounts())}) result += [scores] if public_cohorts: public_scores = {} public_scores.update(val) public_scores.update( {\"cohorts\": EditableFilterSerializer(", "\"operator\": \"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } responds", "documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS", "many=True).data, \"values\": self.aggregate_scores(metric, public_cohorts)}) result += [public_scores] return http.Response(result) class EditableFilterQuerysetMixin(object): @staticmethod def", "return self.get_serializer_class().Meta.model.objects.all() def get(self, request, *args, **kwargs): #pylint: disable=unused-argument self.editable_filter = generics.get_object_or_404( EditableFilter.objects.all(),", "`Account` ... cohorts = accounts result = [] scores = {} val =", "cut, accounts=self.get_accounts())}) result += [scores] if public_cohorts: public_scores = {} public_scores.update(val) public_scores.update( {\"cohorts\":", "and the following disclaimer in the # documentation and/or other materials provided with", "OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE", "from rest_framework import generics from rest_framework.pagination import PageNumberPagination from rest_framework import response as", "], \"likely_metric\": \"\" } ] } \"\"\" search_fields = ['tags'] serializer_class = EditableFilterSerializer", "\"All questions related to languages\" \"predicates\":[{ \"operator\": \"contains\", \"operand\": \"language\", \"field\": \"text\", \"selector\":\"keepmatching\"", "MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): \"\"\" A table of scores for cohorts aganist a metric. **Examples**:", ".. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"count\": 2,", "= EditableFilterSerializer lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return EditableFilter.objects.all() def", "*args, **kwargs): #pylint: disable=unused-argument self.editable_filter = generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView, self).get( request,", "*args, **kwargs) class EditableFilterPagination(PageNumberPagination): def paginate_queryset(self, queryset, request, view=None): self.editable_filter = view.editable_filter return", "self).get( request, *args, **kwargs) class AccountListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``EditableFilter``. **Examples**: ..", "A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER", "\"title\": \"All\", \"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\": \"\", \"operand\": \"\", \"field\":", "forms, with or without # modification, are permitted provided that the following conditions", "import SearchableListMixin from rest_framework import generics from rest_framework.pagination import PageNumberPagination from rest_framework import", "F from django.http import Http404 from django.shortcuts import get_object_or_404 from extra_views.contrib.mixins import SearchableListMixin", "of single account objects. qs_accounts = [cohort] nb_accounts = len(qs_accounts) if nb_accounts >", "the `cohorts` argument # will be a list of single account objects. qs_accounts", "generics.RetrieveUpdateDestroyAPIView): \"\"\" A table of scores for cohorts aganist a metric. **Examples**: ..", "= len(qs_accounts) if nb_accounts > 0: nb_correct_answers = Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score", "``Matrix`` derived from *cohort*. Many times people will use the same name to", "\"\", \"selector\": \"\" ], \"likely_metric\": \"\" } ] } \"\"\" search_fields = ['tags']", "CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY", "= likely_metric scores.update(val) scores.update({\"values\": self.aggregate_scores( metric, cohorts, cut, accounts=self.get_accounts())}) result += [scores] if", "= 'editable_filter' def get_queryset(self): return self.get_serializer_class().Meta.model.objects.all() def get(self, request, *args, **kwargs): #pylint: disable=unused-argument", "a metric\" % str(metric) includes, excludes = metric.as_kwargs() questions = self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions", "Matrix.objects.filter(slug=parts[0]).first() if not matrix: raise Http404() cohort_serializer = EditableFilterSerializer cohorts = matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts", "switch cohorts from an queryset # of `EditableFilter` to a queryset of `Account`", "}, \"cohorts\": [{ \"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } Response:", "\"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } ] }", "*args, **kwargs): #pylint:disable=unused-argument,too-many-locals matrix = self.matrix if matrix: metric = self.matrix.metric else: parts", "is an attempt at magic. \"\"\" likely_metric = None look = re.match(r\"(\\S+)(-\\d+)\", cohort_slug)", "\"selector\": \"\" ], \"likely_metric\": \"\" } ] } \"\"\" search_fields = ['tags'] serializer_class", "'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return EditableFilter.objects.all() def put(self, request, *args, **kwargs):", "conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce", "request, view=None): self.editable_filter = view.editable_filter return super(EditableFilterPagination, self).paginate_queryset( queryset, request, view=view) def get_paginated_response(self,", "EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT,", "\"title\": \"All accounts\", \"predicates\": [] }] } .. code-block:: http POST /api/matrix/ {", "\"filter '%s' is not tagged as a metric\" % str(metric) includes, excludes =", "and cohort have a connection # and could have the same name. for", "try: likely_metric = self.request.build_absolute_uri( reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist: pass return likely_metric def", "self.get_serializer_class().Meta.model.objects.all() def get(self, request, *args, **kwargs): #pylint: disable=unused-argument self.editable_filter = generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg])", "@property def matrix(self): if not hasattr(self, '_matrix'): self._matrix = Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix", "in source and binary forms, with or without # modification, are permitted provided", "HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT", "nb_accounts = len(qs_accounts) if nb_accounts > 0: nb_correct_answers = Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count()", "\"slug\": \"all-questions\", \"title\": \"All questions\", \"predicates\": [] }, \"cohorts\": [{ \"slug\": \"all-accounts\", \"title\":", "argument # will be a list of single account objects. qs_accounts = [cohort]", "Updates a fitler **Tags**: survey **Examples** .. code-block:: http PUT /api/xia/matrix/filters/all/ HTTP/1.1 ..", "notice, # this list of conditions and the following disclaimer. # 2. Redistributions", "THE POSSIBILITY OF SUCH DAMAGE. import logging, re from collections import OrderedDict from", "# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, #", "\"likely_metric\": \"\" } ] } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterListAPIView, self).post( request, *args, **kwargs)", "\"\" ], \"likely_metric\": \"\" } \"\"\" serializer_class = EditableFilterSerializer lookup_field = 'slug' lookup_url_kwarg", "], \"likely_metric\": \"\" }, { \"slug\": \"none\", \"title\": \"None\", \"tags\": \"\", \"predicates\": [", "], \"likely_metric\": \"\" } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).put( request, *args, **kwargs) def", "# # Redistribution and use in source and binary forms, with or without", "connection # and could have the same name. for cohort in val['cohorts']: likely_metric", "**Tags**: survey **Examples** .. code-block:: http POST /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json", "[] scores = {} val = { 'slug': metric.slug, 'title': metric.title, 'metric': EditableFilterSerializer().to_representation(metric),", "**Tags**: survey **Examples** .. code-block:: http DELETE /api/xia/matrix/filters/all/ HTTP/1.1 \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView,", "slug=parts[-1]) matrix = Matrix.objects.filter(slug=parts[0]).first() if not matrix: raise Http404() cohort_serializer = EditableFilterSerializer cohorts", "= logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\" Filtered list of ``Question``. **Examples**: .. code-block:: http", "\"slug\": \"languages\", \"title\": \"All questions related to languages\" \"predicates\":[{ \"operator\": \"contains\", \"operand\": \"language\",", "lookup_field = 'slug' lookup_url_kwarg = 'path' question_model = get_question_serializer().Meta.model def aggregate_scores(self, metric, cohorts,", "\"languages\", \"title\": \"All cohorts for all questions\" \"scores\":{ \"portfolio-a\": \"0.1\", \"portfolio-b\": \"0.5\", }", "re from collections import OrderedDict from django.db.models import F from django.http import Http404", "nb_questions > 0: for cohort in cohorts: if isinstance(cohort, EditableFilter): includes, excludes =", "* 100 / ( nb_questions * nb_accounts) LOGGER.debug(\"score for '%s' = (%d *", "score <= 100 scores.update({str(cohort): score}) return {\"scores\": scores} @property def matrix(self): if not", "cohort_serializer = get_account_serializer() # Implementation Note: switch cohorts from an queryset # of", "in the # documentation and/or other materials provided with the distribution. # #", "nb_correct_answers, nb_questions, nb_accounts, score) assert score <= 100 scores.update({str(cohort): score}) return {\"scores\": scores}", "metric, cohorts, cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals if accounts is None: accounts = get_account_model().objects.all() scores", "if public_cohorts: public_scores = {} public_scores.update(val) public_scores.update( {\"cohorts\": EditableFilterSerializer( public_cohorts, many=True).data, \"values\": self.aggregate_scores(metric,", "survey **Examples** .. code-block:: http POST /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json {", "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT,", "* 100) \"\\ \"/ (%d * %d) = %f\", str(cohort), nb_correct_answers, nb_questions, nb_accounts,", "any cohorts, let's show individual accounts instead. if cut: includes, excludes = cut.as_kwargs()", "request, *args, **kwargs) class AccountListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``EditableFilter``. **Examples**: .. code-block::", "OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR", "= EditableFilterSerializer cohorts = matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts = matrix.cohorts.filter(tags__contains='aggregate') cut = matrix.cut if not", "**kwargs): \"\"\" Deletes a fitler **Tags**: survey **Examples** .. code-block:: http DELETE /api/xia/matrix/filters/all/", "lookup_url_kwarg = 'editable_filter' def get_queryset(self): return EditableFilter.objects.all() def put(self, request, *args, **kwargs): \"\"\"", "# Implementation Note: switch cohorts from an queryset # of `EditableFilter` to a", "= [] scores = {} val = { 'slug': metric.slug, 'title': metric.title, 'metric':", "super(EditableFilterDetailAPIView, self).put( request, *args, **kwargs) def delete(self, request, *args, **kwargs): \"\"\" Deletes a", "code-block:: http DELETE /api/xia/matrix/filters/all/ HTTP/1.1 \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).delete( request, *args, **kwargs)", "EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES", "BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR", "NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF", "= EditableFilterPagination serializer_class = None # override in subclasses lookup_field = 'slug' lookup_url_kwarg", "DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED", "nb_accounts, score) assert score <= 100 scores.update({str(cohort): score}) return {\"scores\": scores} @property def", "\"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).put(", "\"\", \"selector\": \"\" ], \"likely_metric\": \"\" } responds .. code-block:: json { \"slug\":", "Filtered list of ``EditableFilter``. **Examples**: .. code-block:: http GET /api/questions/languages Response: { \"slug\":", "0: nb_correct_answers = Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score = nb_correct_answers * 100 /", "nb_questions * nb_accounts) LOGGER.debug(\"score for '%s' = (%d * 100) \"\\ \"/ (%d", "2020, DjaoDjin inc. # All rights reserved. # # Redistribution and use in", "questions\", \"predicates\": [] }, \"cohorts\": [{ \"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": []", "\"portfolio-a\": \"0.1\", \"portfolio-b\": \"0.5\", } }] \"\"\" serializer_class = MatrixSerializer lookup_field = 'slug'", "} \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterListAPIView, self).post( request, *args, **kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\" Retrieve", ".. code-block:: http GET /api/xia/matrix/filters/all/ HTTP/1.1 responds .. code-block:: json { \"slug\": \"all\",", "data): return http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)), ('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results',", "http DELETE /api/xia/matrix/filters/all/ HTTP/1.1 \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).delete( request, *args, **kwargs) class", "from django.shortcuts import get_object_or_404 from extra_views.contrib.mixins import SearchableListMixin from rest_framework import generics from", "{ \"slug\": \"all-questions\", \"title\": \"All questions\", \"predicates\": [] }, \"cohorts\": [{ \"slug\": \"all-accounts\",", "includes, excludes = cohort.as_kwargs() qs_accounts = accounts.filter( **includes).exclude(**excludes) else: # If `matrix.cohorts is", "IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN", "/api/questions/languages Response: { \"slug\": \"languages\", \"title\": \"All questions related to languages\" \"predicates\":[{ \"operator\":", "not cohorts: # We don't have any cohorts, let's show individual accounts instead.", "**Examples** .. code-block:: http PUT /api/xia/matrix/filters/all/ HTTP/1.1 .. code-block:: json { \"slug\": \"all\",", "matrix: raise Http404() cohort_serializer = EditableFilterSerializer cohorts = matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts = matrix.cohorts.filter(tags__contains='aggregate') cut", "Response: { \"slug\": \"all\", \"title\": \"All accounts against all questions\", \"metric\": { \"slug\":", "Answer, Matrix, EditableFilter from ..utils import (get_account_model, get_account_serializer, get_question_serializer) from .serializers import EditableFilterSerializer,", "}, \"cohorts\": [{ \"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } ..", "# 1. Redistributions of source code must retain the above copyright notice, #", "is None: accounts = get_account_model().objects.all() scores = {} if metric: assert 'metric' in", "\"All cohorts for all questions\" \"scores\":{ \"portfolio-a\": \"0.1\", \"portfolio-b\": \"0.5\", } }] \"\"\"", "rest_framework import response as http from ..compat import reverse from ..mixins import MatrixMixin", "import EditableFilterSerializer, MatrixSerializer LOGGER = logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\" Filtered list of ``Question``.", "\"\"\" pagination_class = EditableFilterPagination serializer_class = None # override in subclasses lookup_field =", "\"\"\" serializer_class = MatrixSerializer lookup_field = 'slug' lookup_url_kwarg = 'path' question_model = get_question_serializer().Meta.model", "COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,", "= Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix def get_accounts(self): #pylint:disable=unused-argument,no-self-use return get_account_model().objects.all() def get_likely_metric(self, cohort_slug):", "HTTP/1.1 responds .. code-block:: json { \"count\": 2, previous: null, next: null, results:", "will use the same name to either mean a cohort or a metric", "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN", "\"language\", \"field\": \"text\", \"selector\":\"keepmatching\" }] } \"\"\" serializer_class = get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\"", "list of conditions and the following disclaimer. # 2. Redistributions in binary form", "class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView): \"\"\" List fitlers **Tags**: survey **Examples** .. code-block:: http", "FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE", "# will be a list of single account objects. qs_accounts = [cohort] nb_accounts", "return EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView): \"\"\" List fitlers **Tags**: survey **Examples** ..", "**kwargs): \"\"\" Create a fitler **Tags**: survey **Examples** .. code-block:: http POST /api/xia/matrix/filters/", "from *cohort*. Many times people will use the same name to either mean", "= re.match(r\"(\\S+)(-\\d+)\", cohort_slug) if look: try: likely_metric = self.request.build_absolute_uri( reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except", "SearchableListMixin from rest_framework import generics from rest_framework.pagination import PageNumberPagination from rest_framework import response", "a URL to a ``Matrix`` derived from *cohort*. Many times people will use", "\"title\": \"All questions related to languages\" \"predicates\":[{ \"operator\": \"contains\", \"operand\": \"language\", \"field\": \"text\",", "def get_queryset(self): return EditableFilter.objects.all() def put(self, request, *args, **kwargs): \"\"\" Updates a fitler", "\"\" } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).put( request, *args, **kwargs) def delete(self, request,", "magically switch between both meaning. This is an attempt at magic. \"\"\" likely_metric", "HTTP/1.1 \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).delete( request, *args, **kwargs) class EditableFilterPagination(PageNumberPagination): def paginate_queryset(self,", "= accounts.filter( **includes).exclude(**excludes) else: # If `matrix.cohorts is None`, the `cohorts` argument #", "\"slug\": \"languages\", \"title\": \"All cohorts for all questions\" \"scores\":{ \"portfolio-a\": \"0.1\", \"portfolio-b\": \"0.5\",", "def aggregate_scores(self, metric, cohorts, cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals if accounts is None: accounts =", "\"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" }, { \"slug\": \"none\", \"title\":", "use in source and binary forms, with or without # modification, are permitted", "/api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"count\": 2, previous: null, next: null,", "OF THE POSSIBILITY OF SUCH DAMAGE. import logging, re from collections import OrderedDict", "EditableFilter.objects.all() def put(self, request, *args, **kwargs): \"\"\" Updates a fitler **Tags**: survey **Examples**", "in binary form must reproduce the above copyright # notice, this list of", "\"metric\": { \"slug\": \"all-questions\", \"title\": \"All questions\", \"predicates\": [] }, \"cohorts\": [{ \"slug\":", "= self.get_accounts().filter( **includes).exclude(**excludes) else: accounts = self.get_accounts() cohort_serializer = get_account_serializer() # Implementation Note:", "= 'slug' lookup_url_kwarg = 'path' question_model = get_question_serializer().Meta.model def aggregate_scores(self, metric, cohorts, cut=None,", "http.Response(result) class EditableFilterQuerysetMixin(object): @staticmethod def get_queryset(): return EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView): \"\"\"", "\"All accounts\", \"predicates\": [] }] } \"\"\" serializer_class = MatrixSerializer def get_queryset(self): return", "for cohorts aganist a metric. **Examples**: .. code-block:: http GET /api/matrix/languages Response: [{", "return super(EditableFilterObjectsAPIView, self).get( request, *args, **kwargs) class AccountListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``EditableFilter``.", "\"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } ] } \"\"\" search_fields", "lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return EditableFilter.objects.all() def put(self, request,", "CREATED { \"slug\": \"all\", \"title\": \"All accounts against all questions\", \"metric\": { \"slug\":", "name to either mean a cohort or a metric and expect the system", "\"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } responds .. code-block:: json {", "THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import", "# All rights reserved. # # Redistribution and use in source and binary", "questions\", \"metric\": { \"slug\": \"all-questions\", \"title\": \"All questions\", \"predicates\": [] }, \"cohorts\": [{", "List fitlers **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds ..", "public_scores.update(val) public_scores.update( {\"cohorts\": EditableFilterSerializer( public_cohorts, many=True).data, \"values\": self.aggregate_scores(metric, public_cohorts)}) result += [public_scores] return", "likely_metric def get(self, request, *args, **kwargs): #pylint:disable=unused-argument,too-many-locals matrix = self.matrix if matrix: metric", "/api/matrix/languages Response: [{ \"slug\": \"languages\", \"title\": \"All cohorts for all questions\" \"scores\":{ \"portfolio-a\":", "tagged as a metric\" % str(metric) includes, excludes = metric.as_kwargs() questions = self.question_model.objects.filter(", "excludes = cohort.as_kwargs() qs_accounts = accounts.filter( **includes).exclude(**excludes) else: # If `matrix.cohorts is None`,", "cohort in cohorts: if isinstance(cohort, EditableFilter): includes, excludes = cohort.as_kwargs() qs_accounts = accounts.filter(", "1. Redistributions of source code must retain the above copyright notice, # this", "metric.title, 'metric': EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)} # In some case, a metric", "PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,", "self._matrix = Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix def get_accounts(self): #pylint:disable=unused-argument,no-self-use return get_account_model().objects.all() def get_likely_metric(self,", "from django.http import Http404 from django.shortcuts import get_object_or_404 from extra_views.contrib.mixins import SearchableListMixin from", "# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS", "code-block:: http GET /api/matrix/ Response: { \"slug\": \"all\", \"title\": \"All accounts against all", "= (%d * 100) \"\\ \"/ (%d * %d) = %f\", str(cohort), nb_correct_answers,", "a queryset of `Account` ... cohorts = accounts result = [] scores =", "List filter objects **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds", "\"\"\" likely_metric = None look = re.match(r\"(\\S+)(-\\d+)\", cohort_slug) if look: try: likely_metric =", "\"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\" serializer_class", "metric = get_object_or_404(EditableFilter, slug=parts[-1]) matrix = Matrix.objects.filter(slug=parts[0]).first() if not matrix: raise Http404() cohort_serializer", "} ] } \"\"\" search_fields = ['tags'] serializer_class = EditableFilterSerializer def post(self, request,", "\"selector\": \"\" ], \"likely_metric\": \"\" } responds .. code-block:: json { \"slug\": \"all\",", "nb_correct_answers = Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score = nb_correct_answers * 100 / (", "or a metric and expect the system will magically switch between both meaning.", "POST /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"count\": 2, previous: null, next:", "def get_queryset(self): return Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): \"\"\" A table of scores for", "matrix: metric = self.matrix.metric else: parts = self.kwargs.get(self.matrix_url_kwarg).split('/') metric = get_object_or_404(EditableFilter, slug=parts[-1]) matrix", "EditableFilter): includes, excludes = cohort.as_kwargs() qs_accounts = accounts.filter( **includes).exclude(**excludes) else: # If `matrix.cohorts", "(%d * 100) \"\\ \"/ (%d * %d) = %f\", str(cohort), nb_correct_answers, nb_questions,", "def get_queryset(): return EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView): \"\"\" List fitlers **Tags**: survey", "DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY", "a metric and expect the system will magically switch between both meaning. This", "post(self, request, *args, **kwargs): \"\"\" Create a fitler **Tags**: survey **Examples** .. code-block::", "PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR", "'%s' = (%d * 100) \"\\ \"/ (%d * %d) = %f\", str(cohort),", "self.kwargs.get(self.matrix_url_kwarg).split('/') metric = get_object_or_404(EditableFilter, slug=parts[-1]) matrix = Matrix.objects.filter(slug=parts[0]).first() if not matrix: raise Http404()", "#pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).put( request, *args, **kwargs) def delete(self, request, *args, **kwargs): \"\"\"", "case, a metric and cohort have a connection # and could have the", "return http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)), ('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data)", "# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;", "import Answer, Matrix, EditableFilter from ..utils import (get_account_model, get_account_serializer, get_question_serializer) from .serializers import", "POST /api/matrix/ { \"slug\": \"all\", \"title\": \"All accounts against all questions\", \"metric\": {", "HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,", "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS", "= Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score = nb_correct_answers * 100 / ( nb_questions", "self.aggregate_scores( metric, cohorts, cut, accounts=self.get_accounts())}) result += [scores] if public_cohorts: public_scores = {}", "] } \"\"\" search_fields = ['tags'] serializer_class = EditableFilterSerializer def post(self, request, *args,", "have any cohorts, let's show individual accounts instead. if cut: includes, excludes =", "import response as http from ..compat import reverse from ..mixins import MatrixMixin from", "super(EditableFilterListAPIView, self).post( request, *args, **kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\" Retrieve a fitler **Tags**: survey", "qs_accounts = [cohort] nb_accounts = len(qs_accounts) if nb_accounts > 0: nb_correct_answers = Answer.objects.filter(", "}] } .. code-block:: http POST /api/matrix/ { \"slug\": \"all\", \"title\": \"All accounts", "} \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).put( request, *args, **kwargs) def delete(self, request, *args,", "a fitler **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/all/ HTTP/1.1 responds ..", "} \"\"\" serializer_class = MatrixSerializer def get_queryset(self): return Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): \"\"\"", "def get(self, request, *args, **kwargs): #pylint:disable=unused-argument,too-many-locals matrix = self.matrix if matrix: metric =", "= self.matrix.metric else: parts = self.kwargs.get(self.matrix_url_kwarg).split('/') metric = get_object_or_404(EditableFilter, slug=parts[-1]) matrix = Matrix.objects.filter(slug=parts[0]).first()", "/api/matrix/ Response: { \"slug\": \"all\", \"title\": \"All accounts against all questions\", \"metric\": {", "rest_framework import generics from rest_framework.pagination import PageNumberPagination from rest_framework import response as http", "override in subclasses lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return self.get_serializer_class().Meta.model.objects.all()", "pagination_class = EditableFilterPagination serializer_class = None # override in subclasses lookup_field = 'slug'", "from extra_views.contrib.mixins import SearchableListMixin from rest_framework import generics from rest_framework.pagination import PageNumberPagination from", "%f\", str(cohort), nb_correct_answers, nb_questions, nb_accounts, score) assert score <= 100 scores.update({str(cohort): score}) return", "if not matrix: raise Http404() cohort_serializer = EditableFilterSerializer cohorts = matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts =", "from ..compat import reverse from ..mixins import MatrixMixin from ..models import Answer, Matrix,", "> 0: for cohort in cohorts: if isinstance(cohort, EditableFilter): includes, excludes = cohort.as_kwargs()", "**Examples** .. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"count\":", "likely_metric = None look = re.match(r\"(\\S+)(-\\d+)\", cohort_slug) if look: try: likely_metric = self.request.build_absolute_uri(", "people will use the same name to either mean a cohort or a", "[public_scores] return http.Response(result) class EditableFilterQuerysetMixin(object): @staticmethod def get_queryset(): return EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin,", "2. Redistributions in binary form must reproduce the above copyright # notice, this", "must retain the above copyright notice, # this list of conditions and the", "/ ( nb_questions * nb_accounts) LOGGER.debug(\"score for '%s' = (%d * 100) \"\\", "result += [public_scores] return http.Response(result) class EditableFilterQuerysetMixin(object): @staticmethod def get_queryset(): return EditableFilter.objects.all() class", "= None look = re.match(r\"(\\S+)(-\\d+)\", cohort_slug) if look: try: likely_metric = self.request.build_absolute_uri( reverse('matrix_chart',", "of ``Question``. **Examples**: .. code-block:: http GET /api/matrix/ Response: { \"slug\": \"all\", \"title\":", "'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return self.get_serializer_class().Meta.model.objects.all() def get(self, request, *args, **kwargs):", "ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF", "aganist a metric. **Examples**: .. code-block:: http GET /api/matrix/languages Response: [{ \"slug\": \"languages\",", "\"title\": \"All questions\", \"predicates\": [] }, \"cohorts\": [{ \"slug\": \"all-accounts\", \"title\": \"All accounts\",", "a list of single account objects. qs_accounts = [cohort] nb_accounts = len(qs_accounts) if", "], \"likely_metric\": \"\" } responds .. code-block:: json { \"slug\": \"all\", \"title\": \"All\",", "self.editable_filter = generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView, self).get( request, *args, **kwargs) class AccountListAPIView(EditableFilterObjectsAPIView):", "fitler **Tags**: survey **Examples** .. code-block:: http POST /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block::", "cohort_serializer = EditableFilterSerializer cohorts = matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts = matrix.cohorts.filter(tags__contains='aggregate') cut = matrix.cut if", "matrix(self): if not hasattr(self, '_matrix'): self._matrix = Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix def get_accounts(self):", "\"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\" #pylint:disable=useless-super-delegation", "GET /api/xia/matrix/filters/all/ HTTP/1.1 responds .. code-block:: json { \"slug\": \"all\", \"title\": \"All\", \"tags\":", "questions = self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions = len(questions) if nb_questions > 0: for cohort", "reproduce the above copyright # notice, this list of conditions and the following", "excludes = cut.as_kwargs() accounts = self.get_accounts().filter( **includes).exclude(**excludes) else: accounts = self.get_accounts() cohort_serializer =", "OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF", "responds .. code-block:: json { \"count\": 2, previous: null, next: null, results: [", "\"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\": \"\", \"operand\":", "\"operator\": \"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" }, {", "serializer_class = EditableFilterSerializer def post(self, request, *args, **kwargs): \"\"\" Create a fitler **Tags**:", "'editable_filter' def get_queryset(self): return EditableFilter.objects.all() def put(self, request, *args, **kwargs): \"\"\" Updates a", "..models import Answer, Matrix, EditableFilter from ..utils import (get_account_model, get_account_serializer, get_question_serializer) from .serializers", "\"count\": 2, previous: null, next: null, results: [ { \"slug\": \"all\", \"title\": \"All\",", "\"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).put( request, *args, **kwargs) def delete(self, request, *args, **kwargs):", "code-block:: http POST /api/matrix/ { \"slug\": \"all\", \"title\": \"All accounts against all questions\",", "= 'path' question_model = get_question_serializer().Meta.model def aggregate_scores(self, metric, cohorts, cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals if", "self).delete( request, *args, **kwargs) class EditableFilterPagination(PageNumberPagination): def paginate_queryset(self, queryset, request, view=None): self.editable_filter =", "look: try: likely_metric = self.request.build_absolute_uri( reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist: pass return likely_metric", "the above copyright notice, # this list of conditions and the following disclaimer.", "both meaning. This is an attempt at magic. \"\"\" likely_metric = None look", "return super(EditableFilterDetailAPIView, self).put( request, *args, **kwargs) def delete(self, request, *args, **kwargs): \"\"\" Deletes", "with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS", "= generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView, self).get( request, *args, **kwargs) class AccountListAPIView(EditableFilterObjectsAPIView): \"\"\"", "/api/xia/matrix/filters/all/ HTTP/1.1 .. code-block:: json { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\":", "assert 'metric' in metric.tags, \\ \"filter '%s' is not tagged as a metric\"", "and binary forms, with or without # modification, are permitted provided that the", "if cut: includes, excludes = cut.as_kwargs() accounts = self.get_accounts().filter( **includes).exclude(**excludes) else: accounts =", "Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): \"\"\" A table of scores for cohorts aganist a", "#pylint:disable=unused-argument,no-self-use return get_account_model().objects.all() def get_likely_metric(self, cohort_slug): \"\"\" Returns a URL to a ``Matrix``", "\"operand\": \"language\", \"field\": \"text\", \"selector\":\"keepmatching\" }] } \"\"\" serializer_class = get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView):", "\"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } ] } \"\"\"", "\"0.5\", } }] \"\"\" serializer_class = MatrixSerializer lookup_field = 'slug' lookup_url_kwarg = 'path'", "cohort or a metric and expect the system will magically switch between both", "#pylint:disable=unused-argument,too-many-locals if accounts is None: accounts = get_account_model().objects.all() scores = {} if metric:", "DAMAGE. import logging, re from collections import OrderedDict from django.db.models import F from", "return http.Response(result) class EditableFilterQuerysetMixin(object): @staticmethod def get_queryset(): return EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView):", "cohorts, cut, accounts=self.get_accounts())}) result += [scores] if public_cohorts: public_scores = {} public_scores.update(val) public_scores.update(", "nb_accounts > 0: nb_correct_answers = Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score = nb_correct_answers *", "EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import logging, re", "\"predicates\": [] }] } \"\"\" serializer_class = MatrixSerializer def get_queryset(self): return Matrix.objects.all() class", "= get_account_serializer() # Implementation Note: switch cohorts from an queryset # of `EditableFilter`", "'title': metric.title, 'metric': EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)} # In some case, a", "{ \"created_at\": \"2020-01-01T00:00:00Z\", \"measured\": 12 } \"\"\" pagination_class = EditableFilterPagination serializer_class = None", "[{ \"slug\": \"languages\", \"title\": \"All cohorts for all questions\" \"scores\":{ \"portfolio-a\": \"0.1\", \"portfolio-b\":", "/api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"created_at\": \"2020-01-01T00:00:00Z\", \"measured\": 12 } \"\"\"", "[{ \"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } \"\"\" serializer_class =", "EditableFilterSerializer, MatrixSerializer LOGGER = logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\" Filtered list of ``Question``. **Examples**:", "`cohorts` argument # will be a list of single account objects. qs_accounts =", "responds .. code-block:: json { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\": [", "OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON", "following disclaimer in the # documentation and/or other materials provided with the distribution.", "If `matrix.cohorts is None`, the `cohorts` argument # will be a list of", "**kwargs): #pylint:disable=unused-argument,too-many-locals matrix = self.matrix if matrix: metric = self.matrix.metric else: parts =", "related to languages\" \"predicates\":[{ \"operator\": \"contains\", \"operand\": \"language\", \"field\": \"text\", \"selector\":\"keepmatching\" }] }", "\"measured\": 12 } \"\"\" pagination_class = EditableFilterPagination serializer_class = None # override in", "from rest_framework.pagination import PageNumberPagination from rest_framework import response as http from ..compat import", "/api/xia/matrix/filters/all/ HTTP/1.1 \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).delete( request, *args, **kwargs) class EditableFilterPagination(PageNumberPagination): def", "# this list of conditions and the following disclaimer. # 2. Redistributions in", "\"2020-01-01T00:00:00Z\", \"measured\": 12 } \"\"\" pagination_class = EditableFilterPagination serializer_class = None # override", "**Examples**: .. code-block:: http GET /api/matrix/ Response: { \"slug\": \"all\", \"title\": \"All accounts", "http POST /api/matrix/ { \"slug\": \"all\", \"title\": \"All accounts against all questions\", \"metric\":", ".. code-block:: http PUT /api/xia/matrix/filters/all/ HTTP/1.1 .. code-block:: json { \"slug\": \"all\", \"title\":", "PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS", "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE", "} \"\"\" search_fields = ['tags'] serializer_class = EditableFilterSerializer def post(self, request, *args, **kwargs):", "}] } Response: 201 CREATED { \"slug\": \"all\", \"title\": \"All accounts against all", "AccountListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``EditableFilter``. **Examples**: .. code-block:: http GET /api/questions/languages Response:", "reverse from ..mixins import MatrixMixin from ..models import Answer, Matrix, EditableFilter from ..utils", "\"slug\": \"none\", \"title\": \"None\", \"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\": \"\", \"operand\":", "\"all-questions\", \"title\": \"All questions\", \"predicates\": [] }, \"cohorts\": [{ \"slug\": \"all-accounts\", \"title\": \"All", "a ``Matrix`` derived from *cohort*. Many times people will use the same name", "\"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } \"\"\" serializer_class = MatrixSerializer def", "**kwargs): \"\"\" Updates a fitler **Tags**: survey **Examples** .. code-block:: http PUT /api/xia/matrix/filters/all/", "fitler **Tags**: survey **Examples** .. code-block:: http PUT /api/xia/matrix/filters/all/ HTTP/1.1 .. code-block:: json", "super(EditableFilterDetailAPIView, self).delete( request, *args, **kwargs) class EditableFilterPagination(PageNumberPagination): def paginate_queryset(self, queryset, request, view=None): self.editable_filter", "IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import logging, re from", "\"\", \"selector\": \"\" ], \"likely_metric\": \"\" }, { \"slug\": \"none\", \"title\": \"None\", \"tags\":", "FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT", "['tags'] serializer_class = EditableFilterSerializer def post(self, request, *args, **kwargs): \"\"\" Create a fitler", "delete(self, request, *args, **kwargs): \"\"\" Deletes a fitler **Tags**: survey **Examples** .. code-block::", "EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView, self).get( request, *args, **kwargs) class AccountListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list", "IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY", "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,", "\"\"\" Filtered list of ``Question``. **Examples**: .. code-block:: http GET /api/questions/languages Response: {", "have a connection # and could have the same name. for cohort in", "magic. \"\"\" likely_metric = None look = re.match(r\"(\\S+)(-\\d+)\", cohort_slug) if look: try: likely_metric", "materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE", "\"field\": \"text\", \"selector\":\"keepmatching\" }] } \"\"\" serializer_class = get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered", "return super(EditableFilterListAPIView, self).post( request, *args, **kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\" Retrieve a fitler **Tags**:", "system will magically switch between both meaning. This is an attempt at magic.", "201 CREATED { \"slug\": \"all\", \"title\": \"All accounts against all questions\", \"metric\": {", "question_model = get_question_serializer().Meta.model def aggregate_scores(self, metric, cohorts, cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals if accounts is", "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE", "= matrix.cohorts.filter(tags__contains='aggregate') cut = matrix.cut if not cohorts: # We don't have any", "<reponame>djaodjin/djaodjin-survey # Copyright (c) 2020, DjaoDjin inc. # All rights reserved. # #", "of conditions and the following disclaimer in the # documentation and/or other materials", "slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix def get_accounts(self): #pylint:disable=unused-argument,no-self-use return get_account_model().objects.all() def get_likely_metric(self, cohort_slug): \"\"\" Returns", "self).post( request, *args, **kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\" Retrieve a fitler **Tags**: survey **Examples**", "\"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" }, { \"slug\":", "not hasattr(self, '_matrix'): self._matrix = Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix def get_accounts(self): #pylint:disable=unused-argument,no-self-use return", "EditableFilter.DoesNotExist: pass return likely_metric def get(self, request, *args, **kwargs): #pylint:disable=unused-argument,too-many-locals matrix = self.matrix", "\"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" }, { \"slug\": \"none\",", "self.get_likely_metric(cohort['slug']) if likely_metric: cohort['likely_metric'] = likely_metric scores.update(val) scores.update({\"values\": self.aggregate_scores( metric, cohorts, cut, accounts=self.get_accounts())})", "= get_account_model().objects.all() scores = {} if metric: assert 'metric' in metric.tags, \\ \"filter", "cohort have a connection # and could have the same name. for cohort", "\"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\" #pylint:disable=useless-super-delegation return", "isinstance(cohort, EditableFilter): includes, excludes = cohort.as_kwargs() qs_accounts = accounts.filter( **includes).exclude(**excludes) else: # If", "'slug': metric.slug, 'title': metric.title, 'metric': EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)} # In some", ".serializers import EditableFilterSerializer, MatrixSerializer LOGGER = logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\" Filtered list of", "self._matrix def get_accounts(self): #pylint:disable=unused-argument,no-self-use return get_account_model().objects.all() def get_likely_metric(self, cohort_slug): \"\"\" Returns a URL", "\"\"\" search_fields = ['tags'] serializer_class = EditableFilterSerializer def post(self, request, *args, **kwargs): \"\"\"", "metric\" % str(metric) includes, excludes = metric.as_kwargs() questions = self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions =", "if not cohorts: # We don't have any cohorts, let's show individual accounts", "\"\"\" Updates a fitler **Tags**: survey **Examples** .. code-block:: http PUT /api/xia/matrix/filters/all/ HTTP/1.1", "None look = re.match(r\"(\\S+)(-\\d+)\", cohort_slug) if look: try: likely_metric = self.request.build_absolute_uri( reverse('matrix_chart', args=(", "**includes).exclude(**excludes) else: # If `matrix.cohorts is None`, the `cohorts` argument # will be", "\"values\": self.aggregate_scores(metric, public_cohorts)}) result += [public_scores] return http.Response(result) class EditableFilterQuerysetMixin(object): @staticmethod def get_queryset():", "\"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView,", "matrix = Matrix.objects.filter(slug=parts[0]).first() if not matrix: raise Http404() cohort_serializer = EditableFilterSerializer cohorts =", ".. code-block:: json { \"created_at\": \"2020-01-01T00:00:00Z\", \"measured\": 12 } \"\"\" pagination_class = EditableFilterPagination", "in subclasses lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return self.get_serializer_class().Meta.model.objects.all() def", "the same name. for cohort in val['cohorts']: likely_metric = self.get_likely_metric(cohort['slug']) if likely_metric: cohort['likely_metric']", "serializer_class = get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``Question``. **Examples**: .. code-block::", "paginate_queryset(self, queryset, request, view=None): self.editable_filter = view.editable_filter return super(EditableFilterPagination, self).paginate_queryset( queryset, request, view=view)", "100 / ( nb_questions * nb_accounts) LOGGER.debug(\"score for '%s' = (%d * 100)", "('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data) ])) class EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\" List filter objects", "metric and cohort have a connection # and could have the same name.", "} ] } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterListAPIView, self).post( request, *args, **kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView):", "qs_accounts = accounts.filter( **includes).exclude(**excludes) else: # If `matrix.cohorts is None`, the `cohorts` argument", "ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT", "between both meaning. This is an attempt at magic. \"\"\" likely_metric = None", "cut.as_kwargs() accounts = self.get_accounts().filter( **includes).exclude(**excludes) else: accounts = self.get_accounts() cohort_serializer = get_account_serializer() #", "the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND", "self.editable_filter = view.editable_filter return super(EditableFilterPagination, self).paginate_queryset( queryset, request, view=view) def get_paginated_response(self, data): return", "EditableFilterSerializer cohorts = matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts = matrix.cohorts.filter(tags__contains='aggregate') cut = matrix.cut if not cohorts:", "json { \"count\": 2, previous: null, next: null, results: [ { \"slug\": \"all\",", "matrix.cut if not cohorts: # We don't have any cohorts, let's show individual", "that the following conditions are met: # # 1. Redistributions of source code", "subclasses lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return self.get_serializer_class().Meta.model.objects.all() def get(self,", "\"operator\": \"contains\", \"operand\": \"language\", \"field\": \"text\", \"selector\":\"keepmatching\" }] } \"\"\" serializer_class = get_account_serializer()", "objects. qs_accounts = [cohort] nb_accounts = len(qs_accounts) if nb_accounts > 0: nb_correct_answers =", "a metric and cohort have a connection # and could have the same", "table of scores for cohorts aganist a metric. **Examples**: .. code-block:: http GET", "same name. for cohort in val['cohorts']: likely_metric = self.get_likely_metric(cohort['slug']) if likely_metric: cohort['likely_metric'] =", "instead. if cut: includes, excludes = cut.as_kwargs() accounts = self.get_accounts().filter( **includes).exclude(**excludes) else: accounts", "CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY,", "disclaimer. # 2. Redistributions in binary form must reproduce the above copyright #", "null, next: null, results: [ { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\":", "from collections import OrderedDict from django.db.models import F from django.http import Http404 from", "A table of scores for cohorts aganist a metric. **Examples**: .. code-block:: http", "same name to either mean a cohort or a metric and expect the", "questions\" \"scores\":{ \"portfolio-a\": \"0.1\", \"portfolio-b\": \"0.5\", } }] \"\"\" serializer_class = MatrixSerializer lookup_field", "objects **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block::", "code must retain the above copyright notice, # this list of conditions and", "``EditableFilter``. **Examples**: .. code-block:: http GET /api/questions/languages Response: { \"slug\": \"languages\", \"title\": \"All", "CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT", "BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN", "GET /api/matrix/ Response: { \"slug\": \"all\", \"title\": \"All accounts against all questions\", \"metric\":", "str(cohort), nb_correct_answers, nb_questions, nb_accounts, score) assert score <= 100 scores.update({str(cohort): score}) return {\"scores\":", "cohorts = matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts = matrix.cohorts.filter(tags__contains='aggregate') cut = matrix.cut if not cohorts: #", "the following conditions are met: # # 1. Redistributions of source code must", "/api/matrix/ { \"slug\": \"all\", \"title\": \"All accounts against all questions\", \"metric\": { \"slug\":", "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY", "scores = {} if metric: assert 'metric' in metric.tags, \\ \"filter '%s' is", "else: parts = self.kwargs.get(self.matrix_url_kwarg).split('/') metric = get_object_or_404(EditableFilter, slug=parts[-1]) matrix = Matrix.objects.filter(slug=parts[0]).first() if not", "next: null, results: [ { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\": [", "request, *args, **kwargs): \"\"\" Updates a fitler **Tags**: survey **Examples** .. code-block:: http", "*args, **kwargs) def delete(self, request, *args, **kwargs): \"\"\" Deletes a fitler **Tags**: survey", "THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE", "fitler **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/all/ HTTP/1.1 responds .. code-block::", "\"likely_metric\": \"\" } ] } \"\"\" search_fields = ['tags'] serializer_class = EditableFilterSerializer def", "be a list of single account objects. qs_accounts = [cohort] nb_accounts = len(qs_accounts)", "def get_paginated_response(self, data): return http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)), ('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous',", "{ \"count\": 2, previous: null, next: null, results: [ { \"slug\": \"all\", \"title\":", "INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS", "[ { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\":", "[ \"rank\": 1, \"operator\": \"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\":", "return Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): \"\"\" A table of scores for cohorts aganist", "EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\" List filter objects **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/", "EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)} # In some case, a metric and cohort have a", "AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL", "STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY", "IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF #", "[] }] } Response: 201 CREATED { \"slug\": \"all\", \"title\": \"All accounts against", "if look: try: likely_metric = self.request.build_absolute_uri( reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist: pass return", "ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT", "}] \"\"\" serializer_class = MatrixSerializer lookup_field = 'slug' lookup_url_kwarg = 'path' question_model =", "null, results: [ { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\": [ \"rank\":", "} responds .. code-block:: json { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\":", "\"operator\": \"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } ]", "self).put( request, *args, **kwargs) def delete(self, request, *args, **kwargs): \"\"\" Deletes a fitler", "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED #", "metric: assert 'metric' in metric.tags, \\ \"filter '%s' is not tagged as a", "\"predicates\":[{ \"operator\": \"contains\", \"operand\": \"language\", \"field\": \"text\", \"selector\":\"keepmatching\" }] } \"\"\" serializer_class =", "django.db.models import F from django.http import Http404 from django.shortcuts import get_object_or_404 from extra_views.contrib.mixins", "self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data) ])) class EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\" List filter", "list of ``EditableFilter``. **Examples**: .. code-block:: http GET /api/questions/languages Response: { \"slug\": \"languages\",", "the following disclaimer in the # documentation and/or other materials provided with the", "return super(EditableFilterPagination, self).paginate_queryset( queryset, request, view=view) def get_paginated_response(self, data): return http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation(", "must reproduce the above copyright # notice, this list of conditions and the", "import logging, re from collections import OrderedDict from django.db.models import F from django.http", "serializer_class = EditableFilterSerializer lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return EditableFilter.objects.all()", "We don't have any cohorts, let's show individual accounts instead. if cut: includes,", "SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,", "to languages\" \"predicates\":[{ \"operator\": \"contains\", \"operand\": \"language\", \"field\": \"text\", \"selector\":\"keepmatching\" }] } \"\"\"", "2, previous: null, next: null, results: [ { \"slug\": \"all\", \"title\": \"All\", \"tags\":", "\"\" ], \"likely_metric\": \"\" } responds .. code-block:: json { \"slug\": \"all\", \"title\":", "GET /api/matrix/languages Response: [{ \"slug\": \"languages\", \"title\": \"All cohorts for all questions\" \"scores\":{", "\"/ (%d * %d) = %f\", str(cohort), nb_correct_answers, nb_questions, nb_accounts, score) assert score", "OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF", "cohorts: if isinstance(cohort, EditableFilter): includes, excludes = cohort.as_kwargs() qs_accounts = accounts.filter( **includes).exclude(**excludes) else:", "if isinstance(cohort, EditableFilter): includes, excludes = cohort.as_kwargs() qs_accounts = accounts.filter( **includes).exclude(**excludes) else: #", "HTTP/1.1 .. code-block:: json { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\": [", "code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"created_at\": \"2020-01-01T00:00:00Z\", \"measured\":", "0: for cohort in cohorts: if isinstance(cohort, EditableFilter): includes, excludes = cohort.as_kwargs() qs_accounts", "**kwargs) class EditableFilterPagination(PageNumberPagination): def paginate_queryset(self, queryset, request, view=None): self.editable_filter = view.editable_filter return super(EditableFilterPagination,", "an attempt at magic. \"\"\" likely_metric = None look = re.match(r\"(\\S+)(-\\d+)\", cohort_slug) if", "code-block:: json { \"count\": 2, previous: null, next: null, results: [ { \"slug\":", "list of single account objects. qs_accounts = [cohort] nb_accounts = len(qs_accounts) if nb_accounts", "OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", "**kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\" Retrieve a fitler **Tags**: survey **Examples** .. code-block:: http", "{} val = { 'slug': metric.slug, 'title': metric.title, 'metric': EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut), 'cohorts':", "TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR", "logging, re from collections import OrderedDict from django.db.models import F from django.http import", "val['cohorts']: likely_metric = self.get_likely_metric(cohort['slug']) if likely_metric: cohort['likely_metric'] = likely_metric scores.update(val) scores.update({\"values\": self.aggregate_scores( metric,", "[] }] } .. code-block:: http POST /api/matrix/ { \"slug\": \"all\", \"title\": \"All", "of `Account` ... cohorts = accounts result = [] scores = {} val", "get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``Question``. **Examples**: .. code-block:: http GET", "**Examples**: .. code-block:: http GET /api/questions/languages Response: { \"slug\": \"languages\", \"title\": \"All questions", "1, \"operator\": \"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" }", "`EditableFilter` to a queryset of `Account` ... cohorts = accounts result = []", "IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO,", "Response: 201 CREATED { \"slug\": \"all\", \"title\": \"All accounts against all questions\", \"metric\":", "the # documentation and/or other materials provided with the distribution. # # THIS", "class EditableFilterQuerysetMixin(object): @staticmethod def get_queryset(): return EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView): \"\"\" List", "survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json {", "\"\"\" Filtered list of ``Question``. **Examples**: .. code-block:: http GET /api/matrix/ Response: {", "EditableFilterSerializer def post(self, request, *args, **kwargs): \"\"\" Create a fitler **Tags**: survey **Examples**", "len(questions) if nb_questions > 0: for cohort in cohorts: if isinstance(cohort, EditableFilter): includes,", "nb_questions, nb_accounts, score) assert score <= 100 scores.update({str(cohort): score}) return {\"scores\": scores} @property", "class EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\" List filter objects **Tags**: survey **Examples** .. code-block:: http GET", "raise Http404() cohort_serializer = EditableFilterSerializer cohorts = matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts = matrix.cohorts.filter(tags__contains='aggregate') cut =", "result += [scores] if public_cohorts: public_scores = {} public_scores.update(val) public_scores.update( {\"cohorts\": EditableFilterSerializer( public_cohorts,", "@staticmethod def get_queryset(): return EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView): \"\"\" List fitlers **Tags**:", "other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY", "LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR", "\"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } .. code-block:: http POST", "list of conditions and the following disclaimer in the # documentation and/or other", "in metric.tags, \\ \"filter '%s' is not tagged as a metric\" % str(metric)", "= {} public_scores.update(val) public_scores.update( {\"cohorts\": EditableFilterSerializer( public_cohorts, many=True).data, \"values\": self.aggregate_scores(metric, public_cohorts)}) result +=", "} .. code-block:: http POST /api/matrix/ { \"slug\": \"all\", \"title\": \"All accounts against", "\"\" ], \"likely_metric\": \"\" } ] } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterListAPIView, self).post( request,", "**Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/all/ HTTP/1.1 responds .. code-block:: json", "GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"created_at\": \"2020-01-01T00:00:00Z\", \"measured\": 12 }", "accounts\", \"predicates\": [] }] } Response: 201 CREATED { \"slug\": \"all\", \"title\": \"All", "code-block:: http GET /api/matrix/languages Response: [{ \"slug\": \"languages\", \"title\": \"All cohorts for all", "serializer_class = MatrixSerializer lookup_field = 'slug' lookup_url_kwarg = 'path' question_model = get_question_serializer().Meta.model def", "if not hasattr(self, '_matrix'): self._matrix = Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix def get_accounts(self): #pylint:disable=unused-argument,no-self-use", "get_object_or_404(EditableFilter, slug=parts[-1]) matrix = Matrix.objects.filter(slug=parts[0]).first() if not matrix: raise Http404() cohort_serializer = EditableFilterSerializer", "= 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return self.get_serializer_class().Meta.model.objects.all() def get(self, request, *args,", "# Copyright (c) 2020, DjaoDjin inc. # All rights reserved. # # Redistribution", "\"All\", \"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\": \"\", \"operand\": \"\", \"field\": \"\",", "LOGGER = logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\" Filtered list of ``Question``. **Examples**: .. code-block::", ".. code-block:: http GET /api/matrix/ Response: { \"slug\": \"all\", \"title\": \"All accounts against", "``Question``. **Examples**: .. code-block:: http GET /api/questions/languages Response: { \"slug\": \"languages\", \"title\": \"All", "SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED", "from ..mixins import MatrixMixin from ..models import Answer, Matrix, EditableFilter from ..utils import", "cohorts from an queryset # of `EditableFilter` to a queryset of `Account` ...", "[] }, \"cohorts\": [{ \"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] }", "get(self, request, *args, **kwargs): #pylint: disable=unused-argument self.editable_filter = generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView,", "if metric: assert 'metric' in metric.tags, \\ \"filter '%s' is not tagged as", "\"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } Response: 201 CREATED {", "super(EditableFilterPagination, self).paginate_queryset( queryset, request, view=view) def get_paginated_response(self, data): return http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)),", "= metric.as_kwargs() questions = self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions = len(questions) if nb_questions > 0:", "a fitler **Tags**: survey **Examples** .. code-block:: http DELETE /api/xia/matrix/filters/all/ HTTP/1.1 \"\"\" #pylint:disable=useless-super-delegation", "\"\"\" Returns a URL to a ``Matrix`` derived from *cohort*. Many times people", "the same name to either mean a cohort or a metric and expect", "re.match(r\"(\\S+)(-\\d+)\", cohort_slug) if look: try: likely_metric = self.request.build_absolute_uri( reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist:", "as a metric\" % str(metric) includes, excludes = metric.as_kwargs() questions = self.question_model.objects.filter( **includes).exclude(**excludes)", "logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\" Filtered list of ``Question``. **Examples**: .. code-block:: http GET", "not tagged as a metric\" % str(metric) includes, excludes = metric.as_kwargs() questions =", "reserved. # # Redistribution and use in source and binary forms, with or", "return likely_metric def get(self, request, *args, **kwargs): #pylint:disable=unused-argument,too-many-locals matrix = self.matrix if matrix:", "\"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } responds .. code-block:: json", "# Redistribution and use in source and binary forms, with or without #", "\"portfolio-b\": \"0.5\", } }] \"\"\" serializer_class = MatrixSerializer lookup_field = 'slug' lookup_url_kwarg =", "\"selector\": \"\" ], \"likely_metric\": \"\" } ] } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterListAPIView, self).post(", "Deletes a fitler **Tags**: survey **Examples** .. code-block:: http DELETE /api/xia/matrix/filters/all/ HTTP/1.1 \"\"\"", "get_queryset(self): return Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): \"\"\" A table of scores for cohorts", "return EditableFilter.objects.all() def put(self, request, *args, **kwargs): \"\"\" Updates a fitler **Tags**: survey", "http PUT /api/xia/matrix/filters/all/ HTTP/1.1 .. code-block:: json { \"slug\": \"all\", \"title\": \"All\", \"tags\":", "metric, cohorts, cut, accounts=self.get_accounts())}) result += [scores] if public_cohorts: public_scores = {} public_scores.update(val)", "against all questions\", \"metric\": { \"slug\": \"all-questions\", \"title\": \"All questions\", \"predicates\": [] },", "cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals if accounts is None: accounts = get_account_model().objects.all() scores = {}", "view=view) def get_paginated_response(self, data): return http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)), ('count', self.page.paginator.count), ('next', self.get_next_link()),", "Returns a URL to a ``Matrix`` derived from *cohort*. Many times people will", "code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"count\": 2, previous:", "EditableFilter from ..utils import (get_account_model, get_account_serializer, get_question_serializer) from .serializers import EditableFilterSerializer, MatrixSerializer LOGGER", "{ \"slug\": \"none\", \"title\": \"None\", \"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\": \"\",", "lookup_url_kwarg = 'editable_filter' def get_queryset(self): return self.get_serializer_class().Meta.model.objects.all() def get(self, request, *args, **kwargs): #pylint:", "public_cohorts)}) result += [public_scores] return http.Response(result) class EditableFilterQuerysetMixin(object): @staticmethod def get_queryset(): return EditableFilter.objects.all()", "# We don't have any cohorts, let's show individual accounts instead. if cut:", "\"selector\": \"\" ], \"likely_metric\": \"\" }, { \"slug\": \"none\", \"title\": \"None\", \"tags\": \"\",", "= ['tags'] serializer_class = EditableFilterSerializer def post(self, request, *args, **kwargs): \"\"\" Create a", "\"created_at\": \"2020-01-01T00:00:00Z\", \"measured\": 12 } \"\"\" pagination_class = EditableFilterPagination serializer_class = None #", "self.matrix.metric else: parts = self.kwargs.get(self.matrix_url_kwarg).split('/') metric = get_object_or_404(EditableFilter, slug=parts[-1]) matrix = Matrix.objects.filter(slug=parts[0]).first() if", "look = re.match(r\"(\\S+)(-\\d+)\", cohort_slug) if look: try: likely_metric = self.request.build_absolute_uri( reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,)))", "are permitted provided that the following conditions are met: # # 1. Redistributions", "generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView, self).get( request, *args, **kwargs) class AccountListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered", "\"\"\" serializer_class = get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``Question``. **Examples**: ..", "generics.ListCreateAPIView): \"\"\" List fitlers **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1", "will magically switch between both meaning. This is an attempt at magic. \"\"\"", "a fitler **Tags**: survey **Examples** .. code-block:: http PUT /api/xia/matrix/filters/all/ HTTP/1.1 .. code-block::", "survey **Examples** .. code-block:: http DELETE /api/xia/matrix/filters/all/ HTTP/1.1 \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).delete(", "self.request.build_absolute_uri( reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist: pass return likely_metric def get(self, request, *args,", "ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING", "NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,", "derived from *cohort*. Many times people will use the same name to either", "cohorts = accounts result = [] scores = {} val = { 'slug':", "> 0: nb_correct_answers = Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score = nb_correct_answers * 100", "GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION)", ".. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"created_at\": \"2020-01-01T00:00:00Z\",", "Http404() cohort_serializer = EditableFilterSerializer cohorts = matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts = matrix.cohorts.filter(tags__contains='aggregate') cut = matrix.cut", "scores.update(val) scores.update({\"values\": self.aggregate_scores( metric, cohorts, cut, accounts=self.get_accounts())}) result += [scores] if public_cohorts: public_scores", "\"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } responds .. code-block::", "list of ``Question``. **Examples**: .. code-block:: http GET /api/questions/languages Response: { \"slug\": \"languages\",", "ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import logging, re from collections import", "from rest_framework import response as http from ..compat import reverse from ..mixins import", "**Examples** .. code-block:: http GET /api/xia/matrix/filters/all/ HTTP/1.1 responds .. code-block:: json { \"slug\":", "account objects. qs_accounts = [cohort] nb_accounts = len(qs_accounts) if nb_accounts > 0: nb_correct_answers", "binary forms, with or without # modification, are permitted provided that the following", "\"\" }, { \"slug\": \"none\", \"title\": \"None\", \"tags\": \"\", \"predicates\": [ \"rank\": 1,", "% str(metric) includes, excludes = metric.as_kwargs() questions = self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions = len(questions)", "times people will use the same name to either mean a cohort or", "..utils import (get_account_model, get_account_serializer, get_question_serializer) from .serializers import EditableFilterSerializer, MatrixSerializer LOGGER = logging.getLogger(__name__)", "OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY,", "\"\"\" Deletes a fitler **Tags**: survey **Examples** .. code-block:: http DELETE /api/xia/matrix/filters/all/ HTTP/1.1", "self.get_next_link()), ('previous', self.get_previous_link()), ('results', data) ])) class EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\" List filter objects **Tags**:", "# 2. Redistributions in binary form must reproduce the above copyright # notice,", "('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data) ])) class EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\" List", "None # override in subclasses lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self):", "\"None\", \"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\": \"\", \"operand\": \"\", \"field\": \"\",", "distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS", "**includes).exclude(**excludes) nb_questions = len(questions) if nb_questions > 0: for cohort in cohorts: if", "import F from django.http import Http404 from django.shortcuts import get_object_or_404 from extra_views.contrib.mixins import", "\"cohorts\": [{ \"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } \"\"\" serializer_class", "Retrieve a fitler **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/all/ HTTP/1.1 responds", "\"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } responds ..", "WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING", "*args, **kwargs): \"\"\" Create a fitler **Tags**: survey **Examples** .. code-block:: http POST", "# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF", "\"all\", \"title\": \"All accounts against all questions\", \"metric\": { \"slug\": \"all-questions\", \"title\": \"All", "self.get_accounts().filter( **includes).exclude(**excludes) else: accounts = self.get_accounts() cohort_serializer = get_account_serializer() # Implementation Note: switch", "\"languages\", \"title\": \"All questions related to languages\" \"predicates\":[{ \"operator\": \"contains\", \"operand\": \"language\", \"field\":", "LOGGER.debug(\"score for '%s' = (%d * 100) \"\\ \"/ (%d * %d) =", "# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS #", "}] } \"\"\" serializer_class = get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``Question``.", "metric and expect the system will magically switch between both meaning. This is", "# In some case, a metric and cohort have a connection # and", "MatrixMixin from ..models import Answer, Matrix, EditableFilter from ..utils import (get_account_model, get_account_serializer, get_question_serializer)", "metric.as_kwargs() questions = self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions = len(questions) if nb_questions > 0: for", "\"likely_metric\": \"\" } responds .. code-block:: json { \"slug\": \"all\", \"title\": \"All\", \"tags\":", "of scores for cohorts aganist a metric. **Examples**: .. code-block:: http GET /api/matrix/languages", "('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)), ('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data) ])) class", "**Examples** .. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"created_at\":", "and expect the system will magically switch between both meaning. This is an", "code-block:: http GET /api/questions/languages Response: { \"slug\": \"languages\", \"title\": \"All questions related to", "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO", "to either mean a cohort or a metric and expect the system will", "\"likely_metric\": \"\" }, { \"slug\": \"none\", \"title\": \"None\", \"tags\": \"\", \"predicates\": [ \"rank\":", "if likely_metric: cohort['likely_metric'] = likely_metric scores.update(val) scores.update({\"values\": self.aggregate_scores( metric, cohorts, cut, accounts=self.get_accounts())}) result", "cohorts for all questions\" \"scores\":{ \"portfolio-a\": \"0.1\", \"portfolio-b\": \"0.5\", } }] \"\"\" serializer_class", "parts = self.kwargs.get(self.matrix_url_kwarg).split('/') metric = get_object_or_404(EditableFilter, slug=parts[-1]) matrix = Matrix.objects.filter(slug=parts[0]).first() if not matrix:", "HTTP/1.1 responds .. code-block:: json { \"created_at\": \"2020-01-01T00:00:00Z\", \"measured\": 12 } \"\"\" pagination_class", "includes, excludes = cut.as_kwargs() accounts = self.get_accounts().filter( **includes).exclude(**excludes) else: accounts = self.get_accounts() cohort_serializer", "(c) 2020, DjaoDjin inc. # All rights reserved. # # Redistribution and use", "queryset, request, view=None): self.editable_filter = view.editable_filter return super(EditableFilterPagination, self).paginate_queryset( queryset, request, view=view) def", "def get(self, request, *args, **kwargs): #pylint: disable=unused-argument self.editable_filter = generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return", "individual accounts instead. if cut: includes, excludes = cut.as_kwargs() accounts = self.get_accounts().filter( **includes).exclude(**excludes)", "request, *args, **kwargs): \"\"\" Create a fitler **Tags**: survey **Examples** .. code-block:: http", "public_cohorts = matrix.cohorts.filter(tags__contains='aggregate') cut = matrix.cut if not cohorts: # We don't have", "else: accounts = self.get_accounts() cohort_serializer = get_account_serializer() # Implementation Note: switch cohorts from", "OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS", "\"0.1\", \"portfolio-b\": \"0.5\", } }] \"\"\" serializer_class = MatrixSerializer lookup_field = 'slug' lookup_url_kwarg", "INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,", "= None # override in subclasses lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def", "# modification, are permitted provided that the following conditions are met: # #", "cut = matrix.cut if not cohorts: # We don't have any cohorts, let's", "\"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } ] } \"\"\" #pylint:disable=useless-super-delegation return", "score = nb_correct_answers * 100 / ( nb_questions * nb_accounts) LOGGER.debug(\"score for '%s'", "BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES", "\"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\" serializer_class = EditableFilterSerializer lookup_field", "{ \"slug\": \"languages\", \"title\": \"All questions related to languages\" \"predicates\":[{ \"operator\": \"contains\", \"operand\":", "\"\", \"selector\": \"\" ], \"likely_metric\": \"\" } ] } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterListAPIView,", "source code must retain the above copyright notice, # this list of conditions", "('results', data) ])) class EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\" List filter objects **Tags**: survey **Examples** ..", "class AccountListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``EditableFilter``. **Examples**: .. code-block:: http GET /api/questions/languages", "copyright # notice, this list of conditions and the following disclaimer in the", "self.get_accounts() cohort_serializer = get_account_serializer() # Implementation Note: switch cohorts from an queryset #", "matrix.cohorts.filter(tags__contains='aggregate') cut = matrix.cut if not cohorts: # We don't have any cohorts,", "above copyright notice, # this list of conditions and the following disclaimer. #", "len(qs_accounts) if nb_accounts > 0: nb_correct_answers = Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score =", "\"cohorts\": [{ \"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } .. code-block::", "])) class EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\" List filter objects **Tags**: survey **Examples** .. code-block:: http", "self).paginate_queryset( queryset, request, view=view) def get_paginated_response(self, data): return http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)), ('count'," ]
[ "or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials =", "'client_secret.json' APPLICATION_NAME = 'Inbox Organize' def get_credentials(): \"\"\"Gets valid user credentials from storage.", "with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path)", "flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with", "print_function import httplib2 import os import sys import pickle from apiclient import discovery", "os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json') store = Storage(credential_path) credentials = store.get() if", "If modifying these scopes, delete your previously saved credentials # at ~/.credentials/gmail-python-quickstart.json SCOPES", "('Label id: %s - Label name: %s' % (label['id'], label['name'])) \"\"\" return labels", "credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) userId =", "GetLabels(service, userId) for label in labels: if (label['type'] == 'user'): print('Deleting label:', label['name'])", "errors.HttpError as error: print ('An error occurred: %s' % error) def main(): credentials", "obtain the new credentials. Returns: Credentials, the obtained credential. \"\"\" home_dir = os.path.expanduser('~')", "Returns: Credentials, the obtained credential. \"\"\" home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials')", "occurred: %s' % error) def main(): credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service", "import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None # If modifying", "from apiclient import errors from oauth2client import client from oauth2client import tools from", "the obtained credential. \"\"\" home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not", "= credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) userId = 'me' labels = GetLabels(service,", "oauth2client import tools from oauth2client.file import Storage try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()", "(label['type'] == 'user'): print('Deleting label:', label['name']) DeleteLabel(service, userId, label['id']) if __name__ == '__main__':", "store) print('Storing credentials to ' + credential_path) return credentials def GetLabels(service, user_id): try:", "labels = GetLabels(service, userId) for label in labels: if (label['type'] == 'user'): print('Deleting", "import client from oauth2client import tools from oauth2client.file import Storage try: import argparse", "httplib2 import os import sys import pickle from apiclient import discovery from apiclient", "error occurred: %s' % error) def DeleteLabel(service, user_id, label_id): try: service.users().labels().delete(userId=user_id, id=label_id).execute() print", "error: print ('An error occurred: %s' % error) def main(): credentials = get_credentials()", "the stored credentials are invalid, the OAuth2 flow is completed to obtain the", "import httplib2 import os import sys import pickle from apiclient import discovery from", "def GetLabels(service, user_id): try: response = service.users().labels().list(userId=user_id).execute() labels = response['labels'] \"\"\" for label", "% label_id) except errors.HttpError as error: print ('An error occurred: %s' % error)", "argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None # If modifying these scopes, delete your", "for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to '", "to ' + credential_path) return credentials def GetLabels(service, user_id): try: response = service.users().labels().list(userId=user_id).execute()", "credentials to ' + credential_path) return credentials def GetLabels(service, user_id): try: response =", "from apiclient import discovery from apiclient import errors from oauth2client import client from", "occurred: %s' % error) def DeleteLabel(service, user_id, label_id): try: service.users().labels().delete(userId=user_id, id=label_id).execute() print ('Label", "%s' % error) def DeleteLabel(service, user_id, label_id): try: service.users().labels().delete(userId=user_id, id=label_id).execute() print ('Label with", "as error: print ('An error occurred: %s' % error) def main(): credentials =", "flags = None # If modifying these scopes, delete your previously saved credentials", "'me' labels = GetLabels(service, userId) for label in labels: if (label['type'] == 'user'):", "= 'me' labels = GetLabels(service, userId) for label in labels: if (label['type'] ==", "Storage try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None #", "store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME", "new credentials. Returns: Credentials, the obtained credential. \"\"\" home_dir = os.path.expanduser('~') credential_dir =", "else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store)", "nothing has been stored, or if the stored credentials are invalid, the OAuth2", "% error) def main(): credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail',", "credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials def", "discovery from apiclient import errors from oauth2client import client from oauth2client import tools", "= argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None # If modifying these scopes, delete", "scopes, delete your previously saved credentials # at ~/.credentials/gmail-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE", "credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent", "= Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE,", "with id: %s deleted successfully.' % label_id) except errors.HttpError as error: print ('An", "= os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir,", "= get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) userId = 'me'", "= tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6", "for label in labels: if (label['type'] == 'user'): print('Deleting label:', label['name']) DeleteLabel(service, userId,", "import print_function import httplib2 import os import sys import pickle from apiclient import", "successfully.' % label_id) except errors.HttpError as error: print ('An error occurred: %s' %", "def get_credentials(): \"\"\"Gets valid user credentials from storage. If nothing has been stored,", "= os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json') store =", "# at ~/.credentials/gmail-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Inbox Organize'", "Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)", "try: response = service.users().labels().list(userId=user_id).execute() labels = response['labels'] \"\"\" for label in labels: print", "client from oauth2client import tools from oauth2client.file import Storage try: import argparse flags", "if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility", "= None # If modifying these scopes, delete your previously saved credentials #", "def main(): credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http)", "name: %s' % (label['id'], label['name'])) \"\"\" return labels except errors.HttpError as error: print", "tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials def GetLabels(service, user_id):", "main(): credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) userId", "labels except errors.HttpError as error: print ('An error occurred: %s' % error) def", "modifying these scopes, delete your previously saved credentials # at ~/.credentials/gmail-python-quickstart.json SCOPES =", "APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for", "error: print ('An error occurred: %s' % error) def DeleteLabel(service, user_id, label_id): try:", "user_id): try: response = service.users().labels().list(userId=user_id).execute() labels = response['labels'] \"\"\" for label in labels:", "os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json') store = Storage(credential_path) credentials = store.get() if not", "client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else:", "from __future__ import print_function import httplib2 import os import sys import pickle from", "%s deleted successfully.' % label_id) except errors.HttpError as error: print ('An error occurred:", "userId = 'me' labels = GetLabels(service, userId) for label in labels: if (label['type']", "= os.path.join(credential_dir, 'gmail-python-quickstart.json') store = Storage(credential_path) credentials = store.get() if not credentials or", "are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns:", "2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials", "sys import pickle from apiclient import discovery from apiclient import errors from oauth2client", "print('Storing credentials to ' + credential_path) return credentials def GetLabels(service, user_id): try: response", "errors.HttpError as error: print ('An error occurred: %s' % error) def DeleteLabel(service, user_id,", "(label['id'], label['name'])) \"\"\" return labels except errors.HttpError as error: print ('An error occurred:", "has been stored, or if the stored credentials are invalid, the OAuth2 flow", "credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json') store", "credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python", "= response['labels'] \"\"\" for label in labels: print ('Label id: %s - Label", "print ('An error occurred: %s' % error) def DeleteLabel(service, user_id, label_id): try: service.users().labels().delete(userId=user_id,", "label in labels: print ('Label id: %s - Label name: %s' % (label['id'],", "os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json')", "\"\"\" home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path", "GetLabels(service, user_id): try: response = service.users().labels().list(userId=user_id).execute() labels = response['labels'] \"\"\" for label in", "home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path =", "from storage. If nothing has been stored, or if the stored credentials are", "print ('Label id: %s - Label name: %s' % (label['id'], label['name'])) \"\"\" return", "= 'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Inbox Organize' def get_credentials(): \"\"\"Gets valid", "oauth2client.file import Storage try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags =", "= 'client_secret.json' APPLICATION_NAME = 'Inbox Organize' def get_credentials(): \"\"\"Gets valid user credentials from", "return credentials def GetLabels(service, user_id): try: response = service.users().labels().list(userId=user_id).execute() labels = response['labels'] \"\"\"", "CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Inbox Organize' def get_credentials(): \"\"\"Gets valid user credentials", "credentials # at ~/.credentials/gmail-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Inbox", "http=http) userId = 'me' labels = GetLabels(service, userId) for label in labels: if", "= 'Inbox Organize' def get_credentials(): \"\"\"Gets valid user credentials from storage. If nothing", "credentials are invalid, the OAuth2 flow is completed to obtain the new credentials.", "' + credential_path) return credentials def GetLabels(service, user_id): try: response = service.users().labels().list(userId=user_id).execute() labels", "APPLICATION_NAME = 'Inbox Organize' def get_credentials(): \"\"\"Gets valid user credentials from storage. If", "tools from oauth2client.file import Storage try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError:", "%s' % (label['id'], label['name'])) \"\"\" return labels except errors.HttpError as error: print ('An", "get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) userId = 'me' labels", "if (label['type'] == 'user'): print('Deleting label:', label['name']) DeleteLabel(service, userId, label['id']) if __name__ ==", "if the stored credentials are invalid, the OAuth2 flow is completed to obtain", "None # If modifying these scopes, delete your previously saved credentials # at", "'gmail-python-quickstart.json') store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow", "these scopes, delete your previously saved credentials # at ~/.credentials/gmail-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/gmail.labels'", "'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Inbox Organize' def get_credentials(): \"\"\"Gets valid user", "if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if", "import Storage try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None", "def DeleteLabel(service, user_id, label_id): try: service.users().labels().delete(userId=user_id, id=label_id).execute() print ('Label with id: %s deleted", "or if the stored credentials are invalid, the OAuth2 flow is completed to", "tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials", "for label in labels: print ('Label id: %s - Label name: %s' %", "__future__ import print_function import httplib2 import os import sys import pickle from apiclient", "from oauth2client import tools from oauth2client.file import Storage try: import argparse flags =", "DeleteLabel(service, user_id, label_id): try: service.users().labels().delete(userId=user_id, id=label_id).execute() print ('Label with id: %s deleted successfully.'", "delete your previously saved credentials # at ~/.credentials/gmail-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE =", "labels: if (label['type'] == 'user'): print('Deleting label:', label['name']) DeleteLabel(service, userId, label['id']) if __name__", "flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential.", "been stored, or if the stored credentials are invalid, the OAuth2 flow is", "os.path.join(credential_dir, 'gmail-python-quickstart.json') store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid:", "Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return", "'v1', http=http) userId = 'me' labels = GetLabels(service, userId) for label in labels:", "previously saved credentials # at ~/.credentials/gmail-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME", "= store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent =", "apiclient import errors from oauth2client import client from oauth2client import tools from oauth2client.file", "storage. If nothing has been stored, or if the stored credentials are invalid,", "OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained", "compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' +", "print ('An error occurred: %s' % error) def main(): credentials = get_credentials() http", "discovery.build('gmail', 'v1', http=http) userId = 'me' labels = GetLabels(service, userId) for label in", "= APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only", "label_id) except errors.HttpError as error: print ('An error occurred: %s' % error) def", "only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to", "('Label with id: %s deleted successfully.' % label_id) except errors.HttpError as error: print", "Organize' def get_credentials(): \"\"\"Gets valid user credentials from storage. If nothing has been", "Credentials, the obtained credential. \"\"\" home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if", "to obtain the new credentials. Returns: Credentials, the obtained credential. \"\"\" home_dir =", "credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow,", "ImportError: flags = None # If modifying these scopes, delete your previously saved", "label['name'])) \"\"\" return labels except errors.HttpError as error: print ('An error occurred: %s'", "response = service.users().labels().list(userId=user_id).execute() labels = response['labels'] \"\"\" for label in labels: print ('Label", "= tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials def GetLabels(service,", "get_credentials(): \"\"\"Gets valid user credentials from storage. If nothing has been stored, or", "Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials", "is completed to obtain the new credentials. Returns: Credentials, the obtained credential. \"\"\"", "response['labels'] \"\"\" for label in labels: print ('Label id: %s - Label name:", "flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None # If modifying these scopes,", "labels = response['labels'] \"\"\" for label in labels: print ('Label id: %s -", "except errors.HttpError as error: print ('An error occurred: %s' % error) def DeleteLabel(service,", "If nothing has been stored, or if the stored credentials are invalid, the", "~/.credentials/gmail-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Inbox Organize' def get_credentials():", "labels: print ('Label id: %s - Label name: %s' % (label['id'], label['name'])) \"\"\"", "'Inbox Organize' def get_credentials(): \"\"\"Gets valid user credentials from storage. If nothing has", "%s - Label name: %s' % (label['id'], label['name'])) \"\"\" return labels except errors.HttpError", "= service.users().labels().list(userId=user_id).execute() labels = response['labels'] \"\"\" for label in labels: print ('Label id:", "your previously saved credentials # at ~/.credentials/gmail-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE = 'client_secret.json'", "('An error occurred: %s' % error) def main(): credentials = get_credentials() http =", "valid user credentials from storage. If nothing has been stored, or if the", "% (label['id'], label['name'])) \"\"\" return labels except errors.HttpError as error: print ('An error", "flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed", "+ credential_path) return credentials def GetLabels(service, user_id): try: response = service.users().labels().list(userId=user_id).execute() labels =", "service = discovery.build('gmail', 'v1', http=http) userId = 'me' labels = GetLabels(service, userId) for", "saved credentials # at ~/.credentials/gmail-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME =", "# Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing", "at ~/.credentials/gmail-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Inbox Organize' def", "credentials def GetLabels(service, user_id): try: response = service.users().labels().list(userId=user_id).execute() labels = response['labels'] \"\"\" for", "# If modifying these scopes, delete your previously saved credentials # at ~/.credentials/gmail-python-quickstart.json", "in labels: print ('Label id: %s - Label name: %s' % (label['id'], label['name']))", "invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials,", "the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the", "('An error occurred: %s' % error) def DeleteLabel(service, user_id, label_id): try: service.users().labels().delete(userId=user_id, id=label_id).execute()", "os import sys import pickle from apiclient import discovery from apiclient import errors", "service.users().labels().list(userId=user_id).execute() labels = response['labels'] \"\"\" for label in labels: print ('Label id: %s", "import os import sys import pickle from apiclient import discovery from apiclient import", "except errors.HttpError as error: print ('An error occurred: %s' % error) def main():", "return labels except errors.HttpError as error: print ('An error occurred: %s' % error)", "errors from oauth2client import client from oauth2client import tools from oauth2client.file import Storage", "% error) def DeleteLabel(service, user_id, label_id): try: service.users().labels().delete(userId=user_id, id=label_id).execute() print ('Label with id:", "error) def main(): credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1',", "credentials. Returns: Credentials, the obtained credential. \"\"\" home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir,", "in labels: if (label['type'] == 'user'): print('Deleting label:', label['name']) DeleteLabel(service, userId, label['id']) if", "stored credentials are invalid, the OAuth2 flow is completed to obtain the new", "credential. \"\"\" home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir)", "os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json') store = Storage(credential_path)", "\"\"\" for label in labels: print ('Label id: %s - Label name: %s'", "store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow =", "error) def DeleteLabel(service, user_id, label_id): try: service.users().labels().delete(userId=user_id, id=label_id).execute() print ('Label with id: %s", "\"\"\" return labels except errors.HttpError as error: print ('An error occurred: %s' %", "if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json') store = Storage(credential_path) credentials =", "obtained credential. \"\"\" home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir):", "= client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags)", "SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: #", "- Label name: %s' % (label['id'], label['name'])) \"\"\" return labels except errors.HttpError as", "user credentials from storage. If nothing has been stored, or if the stored", "try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None # If", "userId) for label in labels: if (label['type'] == 'user'): print('Deleting label:', label['name']) DeleteLabel(service,", "id: %s deleted successfully.' % label_id) except errors.HttpError as error: print ('An error", "import pickle from apiclient import discovery from apiclient import errors from oauth2client import", "\"\"\"Gets valid user credentials from storage. If nothing has been stored, or if", "'.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json') store = Storage(credential_path) credentials", "user_id, label_id): try: service.users().labels().delete(userId=user_id, id=label_id).execute() print ('Label with id: %s deleted successfully.' %", "apiclient import discovery from apiclient import errors from oauth2client import client from oauth2client", "= discovery.build('gmail', 'v1', http=http) userId = 'me' labels = GetLabels(service, userId) for label", "store, flags) else: # Needed only for compatibility with Python 2.6 credentials =", "except ImportError: flags = None # If modifying these scopes, delete your previously", "id=label_id).execute() print ('Label with id: %s deleted successfully.' % label_id) except errors.HttpError as", "label_id): try: service.users().labels().delete(userId=user_id, id=label_id).execute() print ('Label with id: %s deleted successfully.' % label_id)", "id: %s - Label name: %s' % (label['id'], label['name'])) \"\"\" return labels except", "oauth2client import client from oauth2client import tools from oauth2client.file import Storage try: import", "not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json') store = Storage(credential_path) credentials = store.get()", "stored, or if the stored credentials are invalid, the OAuth2 flow is completed", "service.users().labels().delete(userId=user_id, id=label_id).execute() print ('Label with id: %s deleted successfully.' % label_id) except errors.HttpError", "deleted successfully.' % label_id) except errors.HttpError as error: print ('An error occurred: %s'", "credentials from storage. If nothing has been stored, or if the stored credentials", "credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials", "import errors from oauth2client import client from oauth2client import tools from oauth2client.file import", "error occurred: %s' % error) def main(): credentials = get_credentials() http = credentials.authorize(httplib2.Http())", "= GetLabels(service, userId) for label in labels: if (label['type'] == 'user'): print('Deleting label:',", "the new credentials. Returns: Credentials, the obtained credential. \"\"\" home_dir = os.path.expanduser('~') credential_dir", "http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) userId = 'me' labels =", "pickle from apiclient import discovery from apiclient import errors from oauth2client import client", "as error: print ('An error occurred: %s' % error) def DeleteLabel(service, user_id, label_id):", "credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) userId = 'me' labels = GetLabels(service, userId)", "completed to obtain the new credentials. Returns: Credentials, the obtained credential. \"\"\" home_dir", "import sys import pickle from apiclient import discovery from apiclient import errors from", "import discovery from apiclient import errors from oauth2client import client from oauth2client import", "not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags:", "from oauth2client import client from oauth2client import tools from oauth2client.file import Storage try:", "try: service.users().labels().delete(userId=user_id, id=label_id).execute() print ('Label with id: %s deleted successfully.' % label_id) except", "Label name: %s' % (label['id'], label['name'])) \"\"\" return labels except errors.HttpError as error:", "flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow,", "== 'user'): print('Deleting label:', label['name']) DeleteLabel(service, userId, label['id']) if __name__ == '__main__': main()", "from oauth2client.file import Storage try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags", "argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None # If modifying these", "print ('Label with id: %s deleted successfully.' % label_id) except errors.HttpError as error:", "label in labels: if (label['type'] == 'user'): print('Deleting label:', label['name']) DeleteLabel(service, userId, label['id'])", "credential_path) return credentials def GetLabels(service, user_id): try: response = service.users().labels().list(userId=user_id).execute() labels = response['labels']", "SCOPES = 'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Inbox Organize' def get_credentials(): \"\"\"Gets", "%s' % error) def main(): credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service =", "credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json') store = Storage(credential_path) credentials = store.get() if not credentials", "import tools from oauth2client.file import Storage try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except", "flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store," ]
[ "halogalaxystruct1') return halogalaxystruct1 else: print('found HALO_FORMAT_REVISION=%d, if this is >1 email me!' %", "('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) ##", "('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32),", "PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1: if obj.debug: print('returning halostruct1') return halostruct1", "return halogalaxystruct1 else: print('found HALO_FORMAT_REVISION=%d, if this is >1 email me!' % obj.format_revision)", "## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) halostruct2 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32),", "('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) halostruct2", "('av_density',np.float32), ]) def getRSformat(obj): if obj.galaxies == 0: if obj.format_revision == 0: print('OUTDATED", "== 2: if obj.debug: print('returning halostruct2') return halostruct2 else: print('found HALO_FORMAT_REVISION=%d, if this", "sys.exit() elif obj.format_revision == 1: if obj.debug: print('returning halostruct1') return halostruct1 elif obj.format_revision", "halostruct2') return halostruct2 else: print('found HALO_FORMAT_REVISION=%d, if this is >2 email me!' %", "sys.exit() elif obj.galaxies == 1: if obj.format_revision == 0: print('OUTDATED ROCKSTAR-GALAXIES, PLEASE UPDATE!')", "## halostruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32),", "('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64),", "PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1: if obj.debug: print('returning halogalaxystruct1') return halogalaxystruct1", "('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32), ('type',np.int32), ('sm',np.float32),", "UPDATE!') sys.exit() elif obj.format_revision == 1: if obj.debug: print('returning halostruct1') return halostruct1 elif", "('J',np.float32,(3,)), ('energy',np.float32), ('spin',np.float32), ('alt_m',np.float32,(4,)), ('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32),", "sys.exit() elif obj.format_revision == 1: if obj.debug: print('returning halogalaxystruct1') return halogalaxystruct1 else: print('found", "('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64),", "halostruct2 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32),", "('m_pe_b',np.float32), ('m_pe_d',np.float32), ('halfmass_radius',np.float32), #('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32),", "('type',np.int32), ('sm',np.float32), ('gas',np.float32), ('bh',np.float32), ('peak_density',np.float32), ('av_density',np.float32), ]) def getRSformat(obj): if obj.galaxies == 0:", "('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64),", "('peak_density',np.float32), ('av_density',np.float32), ]) def getRSformat(obj): if obj.galaxies == 0: if obj.format_revision == 0:", "('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('dummy1',np.float32), ##", "('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('halfmass_radius',np.float32), #('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64),", "('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) ## ROCKSTAR-GALAXIES ## halogalaxystruct1 = np.dtype([('id',np.int64),", "## ROCKSTAR-GALAXIES ## halogalaxystruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32),", "('bh',np.float32), ('peak_density',np.float32), ('av_density',np.float32), ]) def getRSformat(obj): if obj.galaxies == 0: if obj.format_revision ==", "if obj.debug: print('returning halogalaxystruct1') return halogalaxystruct1 else: print('found HALO_FORMAT_REVISION=%d, if this is >1", "1: if obj.debug: print('returning halostruct1') return halostruct1 elif obj.format_revision == 2: if obj.debug:", "('halfmass_radius',np.float32), #('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT", "ROCKSTAR, PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1: if obj.debug: print('returning halostruct1') return", "## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32), ('type',np.int32), ('sm',np.float32), ('gas',np.float32), ('bh',np.float32), ('peak_density',np.float32), ('av_density',np.float32), ]) def", "np import sys ## ROCKSTAR ## halostruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32),", "halostruct1 elif obj.format_revision == 2: if obj.debug: print('returning halostruct2') return halostruct2 else: print('found", "UPDATE!') sys.exit() elif obj.format_revision == 1: if obj.debug: print('returning halogalaxystruct1') return halogalaxystruct1 else:", "('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32), ('type',np.int32),", "% obj.format_revision) sys.exit() elif obj.galaxies == 1: if obj.format_revision == 0: print('OUTDATED ROCKSTAR-GALAXIES,", "('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32), ('rs',np.float32), ('klypin_rs',np.float32), ('vrms',np.float32), ('J',np.float32,(3,)), ('energy',np.float32), ('spin',np.float32), ('alt_m',np.float32,(4,)), ('Xoff',np.float32),", "('m_pe_d',np.float32), ('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT", "if obj.debug: print('returning halostruct1') return halostruct1 elif obj.format_revision == 2: if obj.debug: print('returning", "if obj.galaxies == 0: if obj.format_revision == 0: print('OUTDATED ROCKSTAR, PLEASE UPDATE!') sys.exit()", "('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32), ('rs',np.float32), ('klypin_rs',np.float32), ('vrms',np.float32), ('J',np.float32,(3,)), ('energy',np.float32), ('spin',np.float32),", "ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32)", "ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32), ('type',np.int32), ('sm',np.float32), ('gas',np.float32), ('bh',np.float32), ('peak_density',np.float32), ('av_density',np.float32), ]) def getRSformat(obj):", "if obj.format_revision == 0: print('OUTDATED ROCKSTAR, PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1:", "print('OUTDATED ROCKSTAR, PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1: if obj.debug: print('returning halostruct1')", "elif obj.format_revision == 2: if obj.debug: print('returning halostruct2') return halostruct2 else: print('found HALO_FORMAT_REVISION=%d,", "print('returning halostruct2') return halostruct2 else: print('found HALO_FORMAT_REVISION=%d, if this is >2 email me!'", "('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32), ('type',np.int32), ('sm',np.float32), ('gas',np.float32), ('bh',np.float32), ('peak_density',np.float32), ('av_density',np.float32),", "('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32), ('type',np.int32), ('sm',np.float32), ('gas',np.float32), ('bh',np.float32), ('peak_density',np.float32), ('av_density',np.float32), ])", "== 1: if obj.debug: print('returning halostruct1') return halostruct1 elif obj.format_revision == 2: if", "ROCKSTAR-GALAXIES, PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1: if obj.debug: print('returning halogalaxystruct1') return", "]) def getRSformat(obj): if obj.galaxies == 0: if obj.format_revision == 0: print('OUTDATED ROCKSTAR,", "('sm',np.float32), ('gas',np.float32), ('bh',np.float32), ('peak_density',np.float32), ('av_density',np.float32), ]) def getRSformat(obj): if obj.galaxies == 0: if", "('vmax',np.float32), ('rvmax',np.float32), ('rs',np.float32), ('klypin_rs',np.float32), ('vrms',np.float32), ('J',np.float32,(3,)), ('energy',np.float32), ('spin',np.float32), ('alt_m',np.float32,(4,)), ('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32),", "obj.debug: print('returning halostruct1') return halostruct1 elif obj.format_revision == 2: if obj.debug: print('returning halostruct2')", "('spin',np.float32), ('alt_m',np.float32,(4,)), ('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32),", "('klypin_rs',np.float32), ('vrms',np.float32), ('J',np.float32,(3,)), ('energy',np.float32), ('spin',np.float32), ('alt_m',np.float32,(4,)), ('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32),", "('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32), ('rs',np.float32), ('klypin_rs',np.float32), ('vrms',np.float32), ('J',np.float32,(3,)),", "== 0: print('OUTDATED ROCKSTAR-GALAXIES, PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1: if obj.debug:", "('m_pe_b',np.float32), ('m_pe_d',np.float32), ('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ##", "if obj.debug: print('returning halostruct2') return halostruct2 else: print('found HALO_FORMAT_REVISION=%d, if this is >2", "== 1: if obj.debug: print('returning halogalaxystruct1') return halogalaxystruct1 else: print('found HALO_FORMAT_REVISION=%d, if this", "print('returning halogalaxystruct1') return halogalaxystruct1 else: print('found HALO_FORMAT_REVISION=%d, if this is >1 email me!'", "('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) ## ROCKSTAR-GALAXIES ## halogalaxystruct1 =", "email me!' % obj.format_revision) sys.exit() elif obj.galaxies == 1: if obj.format_revision == 0:", "ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) ## ROCKSTAR-GALAXIES ## halogalaxystruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)),", "## ROCKSTAR ## halostruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32),", "('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32), ('rs',np.float32), ('klypin_rs',np.float32), ('vrms',np.float32), ('J',np.float32,(3,)), ('energy',np.float32),", "('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('halfmass_radius',np.float32), #('dummy1',np.float32), ##", "halostruct1') return halostruct1 elif obj.format_revision == 2: if obj.debug: print('returning halostruct2') return halostruct2", "import sys ## ROCKSTAR ## halostruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32),", "import numpy as np import sys ## ROCKSTAR ## halostruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)),", "('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32), ('rs',np.float32), ('klypin_rs',np.float32), ('vrms',np.float32), ('J',np.float32,(3,)), ('energy',np.float32), ('spin',np.float32), ('alt_m',np.float32,(4,)),", "('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ])", "obj.debug: print('returning halostruct2') return halostruct2 else: print('found HALO_FORMAT_REVISION=%d, if this is >2 email", "('rvmax',np.float32), ('rs',np.float32), ('klypin_rs',np.float32), ('vrms',np.float32), ('J',np.float32,(3,)), ('energy',np.float32), ('spin',np.float32), ('alt_m',np.float32,(4,)), ('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)),", "('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) halostruct2 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)),", "('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) halostruct2 = np.dtype([('id',np.int64),", "('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) halostruct2 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)),", "2: if obj.debug: print('returning halostruct2') return halostruct2 else: print('found HALO_FORMAT_REVISION=%d, if this is", "('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('halfmass_radius',np.float32), #('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64),", "ROCKSTAR ## halostruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32),", "HALO_FORMAT_REVISION=%d, if this is >2 email me!' % obj.format_revision) sys.exit() elif obj.galaxies ==", "('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32), ('type',np.int32), ('sm',np.float32), ('gas',np.float32), ('bh',np.float32), ('peak_density',np.float32),", "('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('halfmass_radius',np.float32), #('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64),", "== 1: if obj.format_revision == 0: print('OUTDATED ROCKSTAR-GALAXIES, PLEASE UPDATE!') sys.exit() elif obj.format_revision", "('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('halfmass_radius',np.float32), #('dummy1',np.float32),", "('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) ## ROCKSTAR-GALAXIES ## halogalaxystruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)),", "('min_bulkvel_err',np.float32) ]) ## ROCKSTAR-GALAXIES ## halogalaxystruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32),", "0: print('OUTDATED ROCKSTAR-GALAXIES, PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1: if obj.debug: print('returning", "('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('halfmass_radius',np.float32), #('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64),", "('rs',np.float32), ('klypin_rs',np.float32), ('vrms',np.float32), ('J',np.float32,(3,)), ('energy',np.float32), ('spin',np.float32), ('alt_m',np.float32,(4,)), ('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32),", "('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64),", "this is >2 email me!' % obj.format_revision) sys.exit() elif obj.galaxies == 1: if", "('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64),", "## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32),", "obj.format_revision == 1: if obj.debug: print('returning halogalaxystruct1') return halogalaxystruct1 else: print('found HALO_FORMAT_REVISION=%d, if", "('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('dummy1',np.float32),", "if this is >2 email me!' % obj.format_revision) sys.exit() elif obj.galaxies == 1:", "('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32), ('type',np.int32), ('sm',np.float32), ('gas',np.float32), ('bh',np.float32), ('peak_density',np.float32), ('av_density',np.float32), ]) def getRSformat(obj): if", "('gas',np.float32), ('bh',np.float32), ('peak_density',np.float32), ('av_density',np.float32), ]) def getRSformat(obj): if obj.galaxies == 0: if obj.format_revision", "('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64),", "#('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32),", "0: if obj.format_revision == 0: print('OUTDATED ROCKSTAR, PLEASE UPDATE!') sys.exit() elif obj.format_revision ==", "as np import sys ## ROCKSTAR ## halostruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)),", "('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32), ('type',np.int32), ('sm',np.float32), ('gas',np.float32),", "('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('dummy1',np.float32), ## ALIGNMENT", "('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('halfmass_radius',np.float32),", "('min_vel_err',np.float32), ('min_bulkvel_err',np.float32), ('type',np.int32), ('sm',np.float32), ('gas',np.float32), ('bh',np.float32), ('peak_density',np.float32), ('av_density',np.float32), ]) def getRSformat(obj): if obj.galaxies", "('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32),", "return halostruct2 else: print('found HALO_FORMAT_REVISION=%d, if this is >2 email me!' % obj.format_revision)", "print('found HALO_FORMAT_REVISION=%d, if this is >2 email me!' % obj.format_revision) sys.exit() elif obj.galaxies", "numpy as np import sys ## ROCKSTAR ## halostruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)),", "('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) ## ROCKSTAR-GALAXIES ##", "## halogalaxystruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32),", "('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) halostruct2 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32),", "me!' % obj.format_revision) sys.exit() elif obj.galaxies == 1: if obj.format_revision == 0: print('OUTDATED", "('vrms',np.float32), ('J',np.float32,(3,)), ('energy',np.float32), ('spin',np.float32), ('alt_m',np.float32,(4,)), ('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)),", "('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) ## ROCKSTAR-GALAXIES", "('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32), ('rs',np.float32), ('klypin_rs',np.float32), ('vrms',np.float32), ('J',np.float32,(3,)), ('energy',np.float32), ('spin',np.float32), ('alt_m',np.float32,(4,)), ('Xoff',np.float32), ('Voff',np.float32),", "('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32), ('rs',np.float32), ('klypin_rs',np.float32), ('vrms',np.float32), ('J',np.float32,(3,)), ('energy',np.float32), ('spin',np.float32), ('alt_m',np.float32,(4,)), ('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32),", "halostruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32),", "('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) ## ROCKSTAR-GALAXIES ## halogalaxystruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32),", "return halostruct1 elif obj.format_revision == 2: if obj.debug: print('returning halostruct2') return halostruct2 else:", "ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) halostruct2 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32),", "('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('halfmass_radius',np.float32), #('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64),", "obj.format_revision == 0: print('OUTDATED ROCKSTAR, PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1: if", "== 0: print('OUTDATED ROCKSTAR, PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1: if obj.debug:", "obj.format_revision == 2: if obj.debug: print('returning halostruct2') return halostruct2 else: print('found HALO_FORMAT_REVISION=%d, if", "obj.format_revision) sys.exit() elif obj.galaxies == 1: if obj.format_revision == 0: print('OUTDATED ROCKSTAR-GALAXIES, PLEASE", "('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('halfmass_radius',np.float32), #('dummy1',np.float32), ## ALIGNMENT", "np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32), ('rs',np.float32), ('klypin_rs',np.float32),", "]) ## ROCKSTAR-GALAXIES ## halogalaxystruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32),", "elif obj.format_revision == 1: if obj.debug: print('returning halogalaxystruct1') return halogalaxystruct1 else: print('found HALO_FORMAT_REVISION=%d,", "0: print('OUTDATED ROCKSTAR, PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1: if obj.debug: print('returning", "halogalaxystruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32),", "halostruct2 else: print('found HALO_FORMAT_REVISION=%d, if this is >2 email me!' % obj.format_revision) sys.exit()", "('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) halostruct2 =", "def getRSformat(obj): if obj.galaxies == 0: if obj.format_revision == 0: print('OUTDATED ROCKSTAR, PLEASE", "('min_bulkvel_err',np.float32), ('type',np.int32), ('sm',np.float32), ('gas',np.float32), ('bh',np.float32), ('peak_density',np.float32), ('av_density',np.float32), ]) def getRSformat(obj): if obj.galaxies ==", "print('OUTDATED ROCKSTAR-GALAXIES, PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1: if obj.debug: print('returning halogalaxystruct1')", "halogalaxystruct1 else: print('found HALO_FORMAT_REVISION=%d, if this is >1 email me!' % obj.format_revision) sys.exit()", "elif obj.galaxies == 1: if obj.format_revision == 0: print('OUTDATED ROCKSTAR-GALAXIES, PLEASE UPDATE!') sys.exit()", "obj.format_revision == 0: print('OUTDATED ROCKSTAR-GALAXIES, PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1: if", "('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) halostruct2 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32),", "1: if obj.format_revision == 0: print('OUTDATED ROCKSTAR-GALAXIES, PLEASE UPDATE!') sys.exit() elif obj.format_revision ==", "('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) halostruct2 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)),", "else: print('found HALO_FORMAT_REVISION=%d, if this is >2 email me!' % obj.format_revision) sys.exit() elif", "('alt_m',np.float32,(4,)), ('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32),", "ROCKSTAR-GALAXIES ## halogalaxystruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32),", "('m_pe_d',np.float32), ('halfmass_radius',np.float32), #('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ##", "getRSformat(obj): if obj.galaxies == 0: if obj.format_revision == 0: print('OUTDATED ROCKSTAR, PLEASE UPDATE!')", "= np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32), ('rs',np.float32),", "('energy',np.float32), ('spin',np.float32), ('alt_m',np.float32,(4,)), ('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32),", "obj.galaxies == 0: if obj.format_revision == 0: print('OUTDATED ROCKSTAR, PLEASE UPDATE!') sys.exit() elif", "('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32), ('rs',np.float32), ('klypin_rs',np.float32), ('vrms',np.float32),", "if obj.format_revision == 0: print('OUTDATED ROCKSTAR-GALAXIES, PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1:", "is >2 email me!' % obj.format_revision) sys.exit() elif obj.galaxies == 1: if obj.format_revision", "obj.format_revision == 1: if obj.debug: print('returning halostruct1') return halostruct1 elif obj.format_revision == 2:", "1: if obj.debug: print('returning halogalaxystruct1') return halogalaxystruct1 else: print('found HALO_FORMAT_REVISION=%d, if this is", "('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32), ('type',np.int32), ('sm',np.float32), ('gas',np.float32), ('bh',np.float32),", "obj.galaxies == 1: if obj.format_revision == 0: print('OUTDATED ROCKSTAR-GALAXIES, PLEASE UPDATE!') sys.exit() elif", "('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('halfmass_radius',np.float32), #('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64),", "elif obj.format_revision == 1: if obj.debug: print('returning halostruct1') return halostruct1 elif obj.format_revision ==", "('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) ## ROCKSTAR-GALAXIES ## halogalaxystruct1", "('min_bulkvel_err',np.float32) ]) halostruct2 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32),", ">2 email me!' % obj.format_revision) sys.exit() elif obj.galaxies == 1: if obj.format_revision ==", "## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) ## ROCKSTAR-GALAXIES ## halogalaxystruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)),", "print('returning halostruct1') return halostruct1 elif obj.format_revision == 2: if obj.debug: print('returning halostruct2') return", "== 0: if obj.format_revision == 0: print('OUTDATED ROCKSTAR, PLEASE UPDATE!') sys.exit() elif obj.format_revision", "obj.debug: print('returning halogalaxystruct1') return halogalaxystruct1 else: print('found HALO_FORMAT_REVISION=%d, if this is >1 email", "ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32),", "]) halostruct2 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32),", "sys ## ROCKSTAR ## halostruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32)," ]
[ "def location(self): \"\"\" Retrieve the location of an event :return: location :rtype: str", "describing the event :rtype: str \"\"\" return (\"| \" + self.begin_date + self.end_date", "= self.event.location if location.lower() in locations.keys(): location = locations[location.lower()] return location @property def", "the wiki user :type wiki_pw: str :param wiki_archive: archive page :type wiki_archive: str", "args.debug if configfile: config = configparser.ConfigParser() config.read(configfile) try: ics_url = config[\"default\"][\"url\"] wiki =", "EntropiaEvent: \"\"\" Parses an ics Event and converts it to an entropia-wiki suitable", "page :type past_events: list :param wiki_user: bot user for the wiki :type wiki_user:", "! style=\"width:250px;\" | Datum !! style=\"width:50px;\" | Zeit !! Ort !! Beschreibung\\ \"\"\"", "wiki archive page :param past_events: the past events that were not added to", "be retrieved\", metavar=\"URL\", ) parser.add_argument( \"-f\", \"--file\", dest=\"local_file\", help=\"Local ics file\", metavar=\"FILE\" )", "bot automatisch generiert. Alles was hier manuell editiert, hinzugefügt wird WIRD ÜBERSCHRIEBEN -->", "| Datum !! style=\"width:50px;\" | Zeit !! Ort !! Beschreibung\\ \"\"\" ARCHIVE_TABLE_HEADER =", "ics_url = config[\"default\"][\"url\"] wiki = config[\"wiki\"] except KeyError as error: print(\"Please have a", "not in line: deradicalised += \"\\n\"+line return deradicalised def main(): \"\"\" :return: None", "event.name: description = \"N.A.\" else: description = event.name return description def __str__(self): \"\"\"", "the location of an event :return: location :rtype: str \"\"\" locations = {", "ics_url, file, wiki, debug = get_args() event_strings = [] past_events = [] if", "datetime from ics import Calendar from mwclient import Site from dateutil.tz import tzlocal", "the start of the event :rtype: datetime.timedelta \"\"\" return self.endtime - datetime.now(tz=tzlocal()) @property", "\"--wiki-user\", dest=\"wiki_user\", help=\"Wiki user\", metavar=\"WIKIUSER\" ) parser.add_argument( \"--wiki-password\", dest=\"wiki_pw\", help=\"Wiki user's password\", metavar=\"WIKIPW\"", "= \"\"\" <!-- This text is automatically generated by the ics2entropiawiki bot, everything", "'utf-8' calendar = Calendar(deradicalise_ical(ics_result.text)) for event in sorted(calendar.events, key=lambda ev: ev.begin): event =", "raise error return ics_url, file, wiki, debug def deradicalise_ical(ics): \"\"\" :param ics: input", "= \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" style=\"border-collapse:collapse;\" width=\"100%\" |width=15%|'''Datum''' |width=6%|'''Zeit''' |width=15%|'''Ort''' |width=69%|'''Beschreibung'''", "appends past events to the \"Vergangene_Termine\" Site \"\"\" import locale import configparser import", "args.wiki_user, 'pass': args.wiki_pw, 'page': args.wiki_page, 'archive': args.wiki_archive, } debug = args.debug if configfile:", "locations[location.lower()] return location @property def begin_date(self): \"\"\" :return: Entropia-Wiki formatted begin time :rtype:", "help=\"Configuration file path\", metavar=\"CONFIG\" ) parser.add_argument( \"-u\", \"--url\", dest=\"ics_url\", help=\"The URL under which", "location(self): \"\"\" Retrieve the location of an event :return: location :rtype: str \"\"\"", "dest=\"configfile\", help=\"Configuration file path\", metavar=\"CONFIG\" ) parser.add_argument( \"-u\", \"--url\", dest=\"ics_url\", help=\"The URL under", "\"\"\" import locale import configparser import re import requests from argparse import ArgumentParser", "in text: append_list = ( '\\n' + LINE_SEPARATOR + str(event) ) text =", "path='/') site.login(wiki['user'], wiki['pass']) page = site.pages[wiki['page']] if termine: page.save(termine, \"Terminbot was here\") page.purge()", "#!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\"ics2entropiawiki Read an ics file with", "+ str(event) ) text = text[:last_table_position]+[append_list, ]+text[last_table_position:] else: append_list = ( 3 *", "retrieved\", metavar=\"URL\", ) parser.add_argument( \"-f\", \"--file\", dest=\"local_file\", help=\"Local ics file\", metavar=\"FILE\" ) parser.add_argument(", ":return: Entropia-Wiki formatted end time :rtype: str \"\"\" end_date = \"\" if self.endtime", "--> \"\"\" TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" width=\"100%\" style=\"border-collapse:collapse;\" !", "wiki_archive: str :return: None :rtype: None \"\"\" site = Site('entropia.de', path='/') site.login(wiki_user, wiki_pw)", "from dateutil.tz import tzlocal BOTWARNING = \"\"\" <!-- This text is automatically generated", "\"\"\" :return: The event's description :rtype: str \"\"\" links = None wiki =", "event.name return description def __str__(self): \"\"\" :return: A wiki line describing the event", "year_header in text: append_list = ( '\\n' + LINE_SEPARATOR + str(event) ) text", "= event self.begintime = event.begin.datetime.astimezone() self.endtime = event._end_time.datetime.astimezone() @property def location(self): \"\"\" Retrieve", "pass class EntropiaEvent: \"\"\" Parses an ics Event and converts it to an", "args.wiki_pw, 'page': args.wiki_page, 'archive': args.wiki_archive, } debug = args.debug if configfile: config =", "$ ics2entropiawiki.py --config /etc/ics2entropiawiki/config.ini Inserts events not in the past to the \"Termine\"", "site.login(wiki_user, wiki_pw) page = site.pages[wiki_archive] text = page.text().split('\\n') last_table_position = 0 for event", "editiert, hinzugefügt wird WIRD ÜBERSCHRIEBEN --> \"\"\" TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\"", ") def append_past_events(past_events, wiki_user, wiki_pw, wiki_archive): \"\"\" Append the \"new\" past events to", "else: past_events.append(event) append_past_events(past_events, wiki['user'], wiki['pass'], wiki['archive']) termine = BOTWARNING + \"\\n\" + TABLE_HEADER", "+ self.end_date + \" || \" + self.start_time + \" || \" +", "Days to the start of the event :rtype: datetime.timedelta \"\"\" return self.endtime -", "list \"\"\" parser = ArgumentParser() parser.add_argument( \"-c\", \"--config\", default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\", help=\"Configuration file path\",", "[] if file: calendar = Calendar(deradicalise_ical(open(file).read())) else: ics_result = requests.get(ics_url) ics_result.encoding = 'utf-8'", "in to the entropia homepage wiki. Example: $ ics2entropiawiki.py --config /etc/ics2entropiawiki/config.ini Inserts events", "class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" style=\"border-collapse:collapse;\" width=\"100%\" |width=15%|'''Datum''' |width=6%|'''Zeit''' |width=15%|'''Ort''' |width=69%|'''Beschreibung''' \"\"\" TABLE_FOOTER =", "__init__(self, event): \"\"\" :param event: The event to be evaluated :type event: ics.event.Event", "]+text[last_table_position:] else: append_list = ( 3 * '\\n' + year_header + ARCHIVE_TABLE_HEADER +", "debug: print(termine) site = Site('entropia.de', path='/') site.login(wiki['user'], wiki['pass']) page = site.pages[wiki['page']] if termine:", "help=\"Local ics file\", metavar=\"FILE\" ) parser.add_argument( \"--wiki-user\", dest=\"wiki_user\", help=\"Wiki user\", metavar=\"WIKIUSER\" ) parser.add_argument(", "\"\" for line in ics.splitlines(): if 'X-RADICALE-NAME:' not in line: deradicalised += \"\\n\"+line", ":param wiki_archive: archive page :type wiki_archive: str :return: None :rtype: None \"\"\" site", "not event.is_past_event: event_strings.append( \"\\n\" + LINE_SEPARATOR + str(event) ) else: past_events.append(event) append_past_events(past_events, wiki['user'],", "metavar=\"URL\", ) parser.add_argument( \"-f\", \"--file\", dest=\"local_file\", help=\"Local ics file\", metavar=\"FILE\" ) parser.add_argument( \"--wiki-user\",", "'page': args.wiki_page, 'archive': args.wiki_archive, } debug = args.debug if configfile: config = configparser.ConfigParser()", "description = event.name return description def __str__(self): \"\"\" :return: A wiki line describing", "\"\"\" self.event = event self.begintime = event.begin.datetime.astimezone() self.endtime = event._end_time.datetime.astimezone() @property def location(self):", "+ LINE_SEPARATOR + str(event) ) else: past_events.append(event) append_past_events(past_events, wiki['user'], wiki['pass'], wiki['archive']) termine =", "the wiki :type wiki_user: str :param wiki_pw: password for the wiki user :type", "def get_args(): \"\"\" Retrieve arguments from the command line, the config file respectively", "None :rtype: None \"\"\" ics_url, file, wiki, debug = get_args() event_strings = []", "= BOTWARNING + \"\\n\" + TABLE_HEADER + \"\\n\" + \"\".join(event_strings) + \"\\n\" +", "append_past_events(past_events, wiki['user'], wiki['pass'], wiki['archive']) termine = BOTWARNING + \"\\n\" + TABLE_HEADER + \"\\n\"", "help=\"Wiki user's password\", metavar=\"WIKIPW\" ) parser.add_argument( \"--wiki-page\", dest=\"wiki_page\", help='Wiki page', metavar='WIKIPAGE' ) parser.add_argument(", "if not event.is_past_event: event_strings.append( \"\\n\" + LINE_SEPARATOR + str(event) ) else: past_events.append(event) append_past_events(past_events,", "get_args(): \"\"\" Retrieve arguments from the command line, the config file respectively :return:", "metavar=\"WIKIPW\" ) parser.add_argument( \"--wiki-page\", dest=\"wiki_page\", help='Wiki page', metavar='WIKIPAGE' ) parser.add_argument( \"--wiki-archive\", dest=\"wiki_archive\", help='Wiki", "The event's description :rtype: str \"\"\" links = None wiki = None event", "+ \" || \" + self.description ) def append_past_events(past_events, wiki_user, wiki_pw, wiki_archive): \"\"\"", "LINE_SEPARATOR = \"|-\\n\" try: locale.setlocale(locale.LC_ALL, 'de_DE.utf8') except locale.Error: pass class EntropiaEvent: \"\"\" Parses", "self.description ) def append_past_events(past_events, wiki_user, wiki_pw, wiki_archive): \"\"\" Append the \"new\" past events", "+ self.start_time + \" || \" + self.location + \" || \" +", "Zeit !! Ort !! Beschreibung\\ \"\"\" ARCHIVE_TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\"", "|| \" + self.location + \" || \" + self.description ) def append_past_events(past_events,", "line in ics.splitlines(): if 'X-RADICALE-NAME:' not in line: deradicalised += \"\\n\"+line return deradicalised", "\"entropia\": \"[[Anfahrt|Entropia]]\", } location = \" \" if self.event.location: location = self.event.location if", "wird WIRD ÜBERSCHRIEBEN --> \"\"\" TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\"", "links = re.findall(\"^[Ll]ink:(.*)$\", event.description) wiki = re.findall(\"^[Ww]iki:(.*)$\", event.description) if links and event.name: description", ") args = parser.parse_args() configfile = args.configfile ics_url = args.ics_url file = args.local_file", "input file :type ics: str :return: file with remove radicale_headers \"\"\" deradicalised =", "None :rtype: None \"\"\" site = Site('entropia.de', path='/') site.login(wiki_user, wiki_pw) page = site.pages[wiki_archive]", "wiki_pw: str :param wiki_archive: archive page :type wiki_archive: str :return: None :rtype: None", "locale.Error: pass class EntropiaEvent: \"\"\" Parses an ics Event and converts it to", "= self.begintime.strftime(\"%H:%M\") return start_time @property def description(self): \"\"\" :return: The event's description :rtype:", ") parser.add_argument( \"-f\", \"--file\", dest=\"local_file\", help=\"Local ics file\", metavar=\"FILE\" ) parser.add_argument( \"--wiki-user\", dest=\"wiki_user\",", "parser.add_argument( \"--wiki-user\", dest=\"wiki_user\", help=\"Wiki user\", metavar=\"WIKIUSER\" ) parser.add_argument( \"--wiki-password\", dest=\"wiki_pw\", help=\"Wiki user's password\",", ":rtype: None \"\"\" ics_url, file, wiki, debug = get_args() event_strings = [] past_events", "@property def days_to_event(self): \"\"\" :return: Days to the start of the event :rtype:", "user's password\", metavar=\"WIKIPW\" ) parser.add_argument( \"--wiki-page\", dest=\"wiki_page\", help='Wiki page', metavar='WIKIPAGE' ) parser.add_argument( \"--wiki-archive\",", "from command line, config file :rtype: list \"\"\" parser = ArgumentParser() parser.add_argument( \"-c\",", "sample config provided with the package\") raise error return ics_url, file, wiki, debug", "self.event.location if location.lower() in locations.keys(): location = locations[location.lower()] return location @property def begin_date(self):", "links = None wiki = None event = self.event if event.description: links =", "past events that were not added to the events page :type past_events: list", "debug def deradicalise_ical(ics): \"\"\" :param ics: input file :type ics: str :return: file", "event: ics.event.Event \"\"\" self.event = event self.begintime = event.begin.datetime.astimezone() self.endtime = event._end_time.datetime.astimezone() @property", "page.text().split('\\n') last_table_position = 0 for event in past_events: year_header = \"== {} ==\".format(event.endtime.strftime('%Y'))", "everything you edit WILL BE OVERWRITTEN Dieser Text ist vom ics2entropiawiki bot automatisch", "end_date = \"\" if self.endtime - self.begintime > timedelta(days=1): end_date = \" -", "|width=6%|'''Zeit''' |width=15%|'''Ort''' |width=69%|'''Beschreibung''' \"\"\" TABLE_FOOTER = ( \"|}\", \"\\n\", \"Weitere Links: [[Vorlage:Termine|Termine]] \",", "end time :rtype: str \"\"\" end_date = \"\" if self.endtime - self.begintime >", "\" [[Vorlage:Vergangene_Termine|Vergangene Termine]], [[Anfahrt]]\" ) LINE_SEPARATOR = \"|-\\n\" try: locale.setlocale(locale.LC_ALL, 'de_DE.utf8') except locale.Error:", "> timedelta(days=1): end_date = \" - \" + self.endtime.strftime(\"%a., %d.%m.%Y\") return end_date @property", "!! Beschreibung\\ \"\"\" ARCHIVE_TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" style=\"border-collapse:collapse;\" width=\"100%\"", "= re.findall(\"^[Ww]iki:(.*)$\", event.description) if links and event.name: description = \"[\"+links[0]+\" \"+event.name+\"]\" elif wiki:", "not added to the events page :type past_events: list :param wiki_user: bot user", "event.begin.datetime.astimezone() self.endtime = event._end_time.datetime.astimezone() @property def location(self): \"\"\" Retrieve the location of an", "an event :return: location :rtype: str \"\"\" locations = { \"entropia\": \"[[Anfahrt|Entropia]]\", }", "WIRD ÜBERSCHRIEBEN --> \"\"\" TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" width=\"100%\"", "None \"\"\" ics_url, file, wiki, debug = get_args() event_strings = [] past_events =", "= re.findall(\"^[Ll]ink:(.*)$\", event.description) wiki = re.findall(\"^[Ww]iki:(.*)$\", event.description) if links and event.name: description =", "Site from dateutil.tz import tzlocal BOTWARNING = \"\"\" <!-- This text is automatically", "append_list = ( 3 * '\\n' + year_header + ARCHIVE_TABLE_HEADER + '\\n' +", "ics file with the entropia events and insert them in to the entropia", "TABLE_HEADER + \"\\n\" + \"\".join(event_strings) + \"\\n\" + \"\".join(TABLE_FOOTER) if debug: print(termine) site", "the \"new\" past events to the wiki archive page :param past_events: the past", "None wiki = None event = self.event if event.description: links = re.findall(\"^[Ll]ink:(.*)$\", event.description)", "ics file\", metavar=\"FILE\" ) parser.add_argument( \"--wiki-user\", dest=\"wiki_user\", help=\"Wiki user\", metavar=\"WIKIUSER\" ) parser.add_argument( \"--wiki-password\",", "elif not event.name: description = \"N.A.\" else: description = event.name return description def", ") parser.add_argument( \"-d\", \"--debug\", dest=\"debug\", action=\"store_true\", default=False ) args = parser.parse_args() configfile =", ":rtype: str \"\"\" start_time = \" \" if not self.event.all_day: start_time = self.begintime.strftime(\"%H:%M\")", "ics_url, file, wiki, debug def deradicalise_ical(ics): \"\"\" :param ics: input file :type ics:", "border=\"1\" cellspacing=\"0\" cellpadding=\"5\" style=\"border-collapse:collapse;\" width=\"100%\" |width=15%|'''Datum''' |width=6%|'''Zeit''' |width=15%|'''Ort''' |width=69%|'''Beschreibung''' \"\"\" TABLE_FOOTER = (", ":param ics: input file :type ics: str :return: file with remove radicale_headers \"\"\"", "you edit WILL BE OVERWRITTEN Dieser Text ist vom ics2entropiawiki bot automatisch generiert.", "cellpadding=\"5\" style=\"border-collapse:collapse;\" width=\"100%\" |width=15%|'''Datum''' |width=6%|'''Zeit''' |width=15%|'''Ort''' |width=69%|'''Beschreibung''' \"\"\" TABLE_FOOTER = ( \"|}\", \"\\n\",", "to the \"Vergangene_Termine\" Site \"\"\" import locale import configparser import re import requests", "locations.keys(): location = locations[location.lower()] return location @property def begin_date(self): \"\"\" :return: Entropia-Wiki formatted", "the entropia homepage wiki. Example: $ ics2entropiawiki.py --config /etc/ics2entropiawiki/config.ini Inserts events not in", ":rtype: str \"\"\" locations = { \"entropia\": \"[[Anfahrt|Entropia]]\", } location = \" \"", ":rtype: str \"\"\" end_date = \"\" if self.endtime - self.begintime > timedelta(days=1): end_date", "index, txtline in enumerate(text): if txtline == '|}': last_table_position = index if str(event)", "if year_header in text: append_list = ( '\\n' + LINE_SEPARATOR + str(event) )", "\"-u\", \"--url\", dest=\"ics_url\", help=\"The URL under which the ICS-file can be retrieved\", metavar=\"URL\",", "BOTWARNING + \"\\n\" + TABLE_HEADER + \"\\n\" + \"\".join(event_strings) + \"\\n\" + \"\".join(TABLE_FOOTER)", "\" + self.begin_date + self.end_date + \" || \" + self.start_time + \"", "= None wiki = None event = self.event if event.description: links = re.findall(\"^[Ll]ink:(.*)$\",", "help=\"The URL under which the ICS-file can be retrieved\", metavar=\"URL\", ) parser.add_argument( \"-f\",", "def deradicalise_ical(ics): \"\"\" :param ics: input file :type ics: str :return: file with", "\"\".join(TABLE_FOOTER) if debug: print(termine) site = Site('entropia.de', path='/') site.login(wiki['user'], wiki['pass']) page = site.pages[wiki['page']]", "ics import Calendar from mwclient import Site from dateutil.tz import tzlocal BOTWARNING =", "past_events: year_header = \"== {} ==\".format(event.endtime.strftime('%Y')) for index, txtline in enumerate(text): if txtline", "args.local_file wiki = { 'user': args.wiki_user, 'pass': args.wiki_pw, 'page': args.wiki_page, 'archive': args.wiki_archive, }", "self.start_time + \" || \" + self.location + \" || \" + self.description", ") LINE_SEPARATOR = \"|-\\n\" try: locale.setlocale(locale.LC_ALL, 'de_DE.utf8') except locale.Error: pass class EntropiaEvent: \"\"\"", "line, config file :rtype: list \"\"\" parser = ArgumentParser() parser.add_argument( \"-c\", \"--config\", default=\"/etc/ics2entropiawiki/config.ini\",", "Entropia-Wiki formatted end time :rtype: str \"\"\" end_date = \"\" if self.endtime -", "under which the ICS-file can be retrieved\", metavar=\"URL\", ) parser.add_argument( \"-f\", \"--file\", dest=\"local_file\",", "config[\"default\"][\"url\"] wiki = config[\"wiki\"] except KeyError as error: print(\"Please have a look at", "%d.%m.%Y\") return end_date @property def days_to_event(self): \"\"\" :return: Days to the start of", ":return: Entropia-Wiki formatted begin time :rtype: str \"\"\" return self.begintime.strftime(\"%a., %d.%m.%Y\") @property def", "= index if str(event) in text: continue if year_header in text: append_list =", "= parser.parse_args() configfile = args.configfile ics_url = args.ics_url file = args.local_file wiki =", ":param past_events: the past events that were not added to the events page", "+ self.description ) def append_past_events(past_events, wiki_user, wiki_pw, wiki_archive): \"\"\" Append the \"new\" past", "URL under which the ICS-file can be retrieved\", metavar=\"URL\", ) parser.add_argument( \"-f\", \"--file\",", "ics2entropiawiki bot automatisch generiert. Alles was hier manuell editiert, hinzugefügt wird WIRD ÜBERSCHRIEBEN", "\"\"\"ics2entropiawiki Read an ics file with the entropia events and insert them in", "\"\\n\" + TABLE_HEADER + \"\\n\" + \"\".join(event_strings) + \"\\n\" + \"\".join(TABLE_FOOTER) if debug:", "archive page :type wiki_archive: str :return: None :rtype: None \"\"\" site = Site('entropia.de',", "append_past_events(past_events, wiki_user, wiki_pw, wiki_archive): \"\"\" Append the \"new\" past events to the wiki", "error: print(\"Please have a look at the sample config provided with the package\")", "suitable form \"\"\" def __init__(self, event): \"\"\" :param event: The event to be", "past_events: the past events that were not added to the events page :type", "= args.configfile ics_url = args.ics_url file = args.local_file wiki = { 'user': args.wiki_user,", "dest=\"local_file\", help=\"Local ics file\", metavar=\"FILE\" ) parser.add_argument( \"--wiki-user\", dest=\"wiki_user\", help=\"Wiki user\", metavar=\"WIKIUSER\" )", "= event.name return description def __str__(self): \"\"\" :return: A wiki line describing the", "def main(): \"\"\" :return: None :rtype: None \"\"\" ics_url, file, wiki, debug =", "it to an entropia-wiki suitable form \"\"\" def __init__(self, event): \"\"\" :param event:", "to the \"Termine\" Wiki page and appends past events to the \"Vergangene_Termine\" Site", "time :rtype: str \"\"\" end_date = \"\" if self.endtime - self.begintime > timedelta(days=1):", "start_time(self): \"\"\" :return: The starting time of the event :rtype: str \"\"\" start_time", "def begin_date(self): \"\"\" :return: Entropia-Wiki formatted begin time :rtype: str \"\"\" return self.begintime.strftime(\"%a.,", "'\\n' + LINE_SEPARATOR + '\\n' + str(event) + '\\n|}' ) text = text[:last_table_position+1]+[append_list,", "with remove radicale_headers \"\"\" deradicalised = \"\" for line in ics.splitlines(): if 'X-RADICALE-NAME:'", "last_table_position = 0 for event in past_events: year_header = \"== {} ==\".format(event.endtime.strftime('%Y')) for", "wiki_archive): \"\"\" Append the \"new\" past events to the wiki archive page :param", "if 'X-RADICALE-NAME:' not in line: deradicalised += \"\\n\"+line return deradicalised def main(): \"\"\"", "site.pages[wiki['page']] if termine: page.save(termine, \"Terminbot was here\") page.purge() if __name__ == '__main__': main()", "+ self.endtime.strftime(\"%a., %d.%m.%Y\") return end_date @property def days_to_event(self): \"\"\" :return: Days to the", "= event.begin.datetime.astimezone() self.endtime = event._end_time.datetime.astimezone() @property def location(self): \"\"\" Retrieve the location of", "parser.add_argument( \"-f\", \"--file\", dest=\"local_file\", help=\"Local ics file\", metavar=\"FILE\" ) parser.add_argument( \"--wiki-user\", dest=\"wiki_user\", help=\"Wiki", "ics.event.Event \"\"\" self.event = event self.begintime = event.begin.datetime.astimezone() self.endtime = event._end_time.datetime.astimezone() @property def", "wiki_pw, wiki_archive): \"\"\" Append the \"new\" past events to the wiki archive page", "parser.add_argument( \"--wiki-password\", dest=\"wiki_pw\", help=\"Wiki user's password\", metavar=\"WIKIPW\" ) parser.add_argument( \"--wiki-page\", dest=\"wiki_page\", help='Wiki page',", "import configparser import re import requests from argparse import ArgumentParser from datetime import", "and converts it to an entropia-wiki suitable form \"\"\" def __init__(self, event): \"\"\"", "datetime.now(tz=tzlocal()) @property def is_past_event(self): \"\"\" :return: Check if the event lies in the", "+ \" || \" + self.location + \" || \" + self.description )", "the past events that were not added to the events page :type past_events:", "BE OVERWRITTEN Dieser Text ist vom ics2entropiawiki bot automatisch generiert. Alles was hier", "\"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" width=\"100%\" style=\"border-collapse:collapse;\" ! style=\"width:250px;\" | Datum !!", "text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:] page.save(\"\\n\".join(text)) def get_args(): \"\"\" Retrieve arguments from the command line, the", "-*- \"\"\"ics2entropiawiki Read an ics file with the entropia events and insert them", "events to the wiki archive page :param past_events: the past events that were", "import timedelta, datetime from ics import Calendar from mwclient import Site from dateutil.tz", "from argparse import ArgumentParser from datetime import timedelta, datetime from ics import Calendar", "in the past to the \"Termine\" Wiki page and appends past events to", "event.description) wiki = re.findall(\"^[Ww]iki:(.*)$\", event.description) if links and event.name: description = \"[\"+links[0]+\" \"+event.name+\"]\"", "the event lies in the past :rtype: bool \"\"\" return self.days_to_event < timedelta(days=0)", "A wiki line describing the event :rtype: str \"\"\" return (\"| \" +", "archive', metavar='WIKIARCHIVE' ) parser.add_argument( \"-d\", \"--debug\", dest=\"debug\", action=\"store_true\", default=False ) args = parser.parse_args()", "import tzlocal BOTWARNING = \"\"\" <!-- This text is automatically generated by the", "file :type ics: str :return: file with remove radicale_headers \"\"\" deradicalised = \"\"", "end_date @property def days_to_event(self): \"\"\" :return: Days to the start of the event", "wiki_user, wiki_pw, wiki_archive): \"\"\" Append the \"new\" past events to the wiki archive", "'\\n' + LINE_SEPARATOR + str(event) ) text = text[:last_table_position]+[append_list, ]+text[last_table_position:] else: append_list =", "BOTWARNING = \"\"\" <!-- This text is automatically generated by the ics2entropiawiki bot,", "self.location + \" || \" + self.description ) def append_past_events(past_events, wiki_user, wiki_pw, wiki_archive):", "None \"\"\" site = Site('entropia.de', path='/') site.login(wiki_user, wiki_pw) page = site.pages[wiki_archive] text =", "debug = args.debug if configfile: config = configparser.ConfigParser() config.read(configfile) try: ics_url = config[\"default\"][\"url\"]", "deradicalised += \"\\n\"+line return deradicalised def main(): \"\"\" :return: None :rtype: None \"\"\"", "past_events.append(event) append_past_events(past_events, wiki['user'], wiki['pass'], wiki['archive']) termine = BOTWARNING + \"\\n\" + TABLE_HEADER +", "{ \"entropia\": \"[[Anfahrt|Entropia]]\", } location = \" \" if self.event.location: location = self.event.location", "__str__(self): \"\"\" :return: A wiki line describing the event :rtype: str \"\"\" return", "= args.ics_url file = args.local_file wiki = { 'user': args.wiki_user, 'pass': args.wiki_pw, 'page':", "utf-8 -*- \"\"\"ics2entropiawiki Read an ics file with the entropia events and insert", "for index, txtline in enumerate(text): if txtline == '|}': last_table_position = index if", "default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\", help=\"Configuration file path\", metavar=\"CONFIG\" ) parser.add_argument( \"-u\", \"--url\", dest=\"ics_url\", help=\"The URL", ") text = text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:] page.save(\"\\n\".join(text)) def get_args(): \"\"\" Retrieve arguments from the", "the past :rtype: bool \"\"\" return self.days_to_event < timedelta(days=0) @property def start_time(self): \"\"\"", "try: ics_url = config[\"default\"][\"url\"] wiki = config[\"wiki\"] except KeyError as error: print(\"Please have", "from mwclient import Site from dateutil.tz import tzlocal BOTWARNING = \"\"\" <!-- This", "location @property def begin_date(self): \"\"\" :return: Entropia-Wiki formatted begin time :rtype: str \"\"\"", "can be retrieved\", metavar=\"URL\", ) parser.add_argument( \"-f\", \"--file\", dest=\"local_file\", help=\"Local ics file\", metavar=\"FILE\"", "radicale_headers \"\"\" deradicalised = \"\" for line in ics.splitlines(): if 'X-RADICALE-NAME:' not in", "in line: deradicalised += \"\\n\"+line return deradicalised def main(): \"\"\" :return: None :rtype:", ":return: None :rtype: None \"\"\" ics_url, file, wiki, debug = get_args() event_strings =", "event_strings.append( \"\\n\" + LINE_SEPARATOR + str(event) ) else: past_events.append(event) append_past_events(past_events, wiki['user'], wiki['pass'], wiki['archive'])", "str \"\"\" locations = { \"entropia\": \"[[Anfahrt|Entropia]]\", } location = \" \" if", "except locale.Error: pass class EntropiaEvent: \"\"\" Parses an ics Event and converts it", "+ \"\\n\" + \"\".join(event_strings) + \"\\n\" + \"\".join(TABLE_FOOTER) if debug: print(termine) site =", "enumerate(text): if txtline == '|}': last_table_position = index if str(event) in text: continue", "python3 # -*- coding: utf-8 -*- \"\"\"ics2entropiawiki Read an ics file with the", "mwclient import Site from dateutil.tz import tzlocal BOTWARNING = \"\"\" <!-- This text", "= Site('entropia.de', path='/') site.login(wiki['user'], wiki['pass']) page = site.pages[wiki['page']] if termine: page.save(termine, \"Terminbot was", "start_time = self.begintime.strftime(\"%H:%M\") return start_time @property def description(self): \"\"\" :return: The event's description", "print(termine) site = Site('entropia.de', path='/') site.login(wiki['user'], wiki['pass']) page = site.pages[wiki['page']] if termine: page.save(termine,", "page = site.pages[wiki['page']] if termine: page.save(termine, \"Terminbot was here\") page.purge() if __name__ ==", "def end_date(self): \"\"\" :return: Entropia-Wiki formatted end time :rtype: str \"\"\" end_date =", "def start_time(self): \"\"\" :return: The starting time of the event :rtype: str \"\"\"", "The event to be evaluated :type event: ics.event.Event \"\"\" self.event = event self.begintime", "timedelta(days=0) @property def start_time(self): \"\"\" :return: The starting time of the event :rtype:", "event :rtype: str \"\"\" start_time = \" \" if not self.event.all_day: start_time =", "\"[\"+links[0]+\" \"+event.name+\"]\" elif wiki: description = wiki[0] elif not event.name: description = \"N.A.\"", "self.event if event.description: links = re.findall(\"^[Ll]ink:(.*)$\", event.description) wiki = re.findall(\"^[Ww]iki:(.*)$\", event.description) if links", "|width=69%|'''Beschreibung''' \"\"\" TABLE_FOOTER = ( \"|}\", \"\\n\", \"Weitere Links: [[Vorlage:Termine|Termine]] \", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\",", "respectively :return: Parsed arguments from command line, config file :rtype: list \"\"\" parser", "events to the \"Vergangene_Termine\" Site \"\"\" import locale import configparser import re import", "ICS-file can be retrieved\", metavar=\"URL\", ) parser.add_argument( \"-f\", \"--file\", dest=\"local_file\", help=\"Local ics file\",", "= configparser.ConfigParser() config.read(configfile) try: ics_url = config[\"default\"][\"url\"] wiki = config[\"wiki\"] except KeyError as", "arguments from the command line, the config file respectively :return: Parsed arguments from", "'user': args.wiki_user, 'pass': args.wiki_pw, 'page': args.wiki_page, 'archive': args.wiki_archive, } debug = args.debug if", "events that were not added to the events page :type past_events: list :param", "description def __str__(self): \"\"\" :return: A wiki line describing the event :rtype: str", "\"\".join(event_strings) + \"\\n\" + \"\".join(TABLE_FOOTER) if debug: print(termine) site = Site('entropia.de', path='/') site.login(wiki['user'],", "metavar='WIKIARCHIVE' ) parser.add_argument( \"-d\", \"--debug\", dest=\"debug\", action=\"store_true\", default=False ) args = parser.parse_args() configfile", "'\\n' + str(event) + '\\n|}' ) text = text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:] page.save(\"\\n\".join(text)) def get_args():", ":param event: The event to be evaluated :type event: ics.event.Event \"\"\" self.event =", "!! Ort !! Beschreibung\\ \"\"\" ARCHIVE_TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\"", "\"\"\" ARCHIVE_TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" style=\"border-collapse:collapse;\" width=\"100%\" |width=15%|'''Datum''' |width=6%|'''Zeit'''", "days_to_event(self): \"\"\" :return: Days to the start of the event :rtype: datetime.timedelta \"\"\"", "]+text[last_table_position+1:] page.save(\"\\n\".join(text)) def get_args(): \"\"\" Retrieve arguments from the command line, the config", "event.description) if links and event.name: description = \"[\"+links[0]+\" \"+event.name+\"]\" elif wiki: description =", "wiki: description = wiki[0] elif not event.name: description = \"N.A.\" else: description =", "Alles was hier manuell editiert, hinzugefügt wird WIRD ÜBERSCHRIEBEN --> \"\"\" TABLE_HEADER =", "vom ics2entropiawiki bot automatisch generiert. Alles was hier manuell editiert, hinzugefügt wird WIRD", "and everything you edit WILL BE OVERWRITTEN Dieser Text ist vom ics2entropiawiki bot", "help='Wiki page', metavar='WIKIPAGE' ) parser.add_argument( \"--wiki-archive\", dest=\"wiki_archive\", help='Wiki archive', metavar='WIKIARCHIVE' ) parser.add_argument( \"-d\",", "insert them in to the entropia homepage wiki. Example: $ ics2entropiawiki.py --config /etc/ics2entropiawiki/config.ini", "Append the \"new\" past events to the wiki archive page :param past_events: the", "--config /etc/ics2entropiawiki/config.ini Inserts events not in the past to the \"Termine\" Wiki page", "= \"[\"+links[0]+\" \"+event.name+\"]\" elif wiki: description = wiki[0] elif not event.name: description =", "= page.text().split('\\n') last_table_position = 0 for event in past_events: year_header = \"== {}", ":type ics: str :return: file with remove radicale_headers \"\"\" deradicalised = \"\" for", "locations = { \"entropia\": \"[[Anfahrt|Entropia]]\", } location = \" \" if self.event.location: location", "Text ist vom ics2entropiawiki bot automatisch generiert. Alles was hier manuell editiert, hinzugefügt", "site.login(wiki['user'], wiki['pass']) page = site.pages[wiki['page']] if termine: page.save(termine, \"Terminbot was here\") page.purge() if", "def __str__(self): \"\"\" :return: A wiki line describing the event :rtype: str \"\"\"", "\" || \" + self.location + \" || \" + self.description ) def", "location :rtype: str \"\"\" locations = { \"entropia\": \"[[Anfahrt|Entropia]]\", } location = \"", "str \"\"\" return self.begintime.strftime(\"%a., %d.%m.%Y\") @property def end_date(self): \"\"\" :return: Entropia-Wiki formatted end", "time :rtype: str \"\"\" return self.begintime.strftime(\"%a., %d.%m.%Y\") @property def end_date(self): \"\"\" :return: Entropia-Wiki", "\" if not self.event.all_day: start_time = self.begintime.strftime(\"%H:%M\") return start_time @property def description(self): \"\"\"", "command line, config file :rtype: list \"\"\" parser = ArgumentParser() parser.add_argument( \"-c\", \"--config\",", "\"\"\" return (\"| \" + self.begin_date + self.end_date + \" || \" +", "\"--wiki-password\", dest=\"wiki_pw\", help=\"Wiki user's password\", metavar=\"WIKIPW\" ) parser.add_argument( \"--wiki-page\", dest=\"wiki_page\", help='Wiki page', metavar='WIKIPAGE'", "of an event :return: location :rtype: str \"\"\" locations = { \"entropia\": \"[[Anfahrt|Entropia]]\",", "\"N.A.\" else: description = event.name return description def __str__(self): \"\"\" :return: A wiki", "+ year_header + ARCHIVE_TABLE_HEADER + '\\n' + LINE_SEPARATOR + '\\n' + str(event) +", "\"--url\", dest=\"ics_url\", help=\"The URL under which the ICS-file can be retrieved\", metavar=\"URL\", )", ":return: file with remove radicale_headers \"\"\" deradicalised = \"\" for line in ics.splitlines():", "self.event.location: location = self.event.location if location.lower() in locations.keys(): location = locations[location.lower()] return location", "self.begintime > timedelta(days=1): end_date = \" - \" + self.endtime.strftime(\"%a., %d.%m.%Y\") return end_date", "@property def begin_date(self): \"\"\" :return: Entropia-Wiki formatted begin time :rtype: str \"\"\" return", "{| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" style=\"border-collapse:collapse;\" width=\"100%\" |width=15%|'''Datum''' |width=6%|'''Zeit''' |width=15%|'''Ort''' |width=69%|'''Beschreibung''' \"\"\" TABLE_FOOTER", "the event :rtype: str \"\"\" return (\"| \" + self.begin_date + self.end_date +", ":type past_events: list :param wiki_user: bot user for the wiki :type wiki_user: str", "This text is automatically generated by the ics2entropiawiki bot, everything you write and", "the config file respectively :return: Parsed arguments from command line, config file :rtype:", "<!-- This text is automatically generated by the ics2entropiawiki bot, everything you write", ":return: Check if the event lies in the past :rtype: bool \"\"\" return", "\"|}\", \"\\n\", \"Weitere Links: [[Vorlage:Termine|Termine]] \", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\", \" [[Vorlage:Vergangene_Termine|Vergangene Termine]], [[Anfahrt]]\" )", "event._end_time.datetime.astimezone() @property def location(self): \"\"\" Retrieve the location of an event :return: location", "= \"\" for line in ics.splitlines(): if 'X-RADICALE-NAME:' not in line: deradicalised +=", ") else: past_events.append(event) append_past_events(past_events, wiki['user'], wiki['pass'], wiki['archive']) termine = BOTWARNING + \"\\n\" +", "else: description = event.name return description def __str__(self): \"\"\" :return: A wiki line", "past :rtype: bool \"\"\" return self.days_to_event < timedelta(days=0) @property def start_time(self): \"\"\" :return:", "config file :rtype: list \"\"\" parser = ArgumentParser() parser.add_argument( \"-c\", \"--config\", default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\",", "page :param past_events: the past events that were not added to the events", "\"\"\" def __init__(self, event): \"\"\" :param event: The event to be evaluated :type", "import re import requests from argparse import ArgumentParser from datetime import timedelta, datetime", "= { \"entropia\": \"[[Anfahrt|Entropia]]\", } location = \" \" if self.event.location: location =", "sorted(calendar.events, key=lambda ev: ev.begin): event = EntropiaEvent(event) if not event.is_past_event: event_strings.append( \"\\n\" +", "\"\\n\", \"Weitere Links: [[Vorlage:Termine|Termine]] \", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\", \" [[Vorlage:Vergangene_Termine|Vergangene Termine]], [[Anfahrt]]\" ) LINE_SEPARATOR", "bool \"\"\" return self.days_to_event < timedelta(days=0) @property def start_time(self): \"\"\" :return: The starting", "\"\\n\"+line return deradicalised def main(): \"\"\" :return: None :rtype: None \"\"\" ics_url, file,", "print(\"Please have a look at the sample config provided with the package\") raise", "ics: input file :type ics: str :return: file with remove radicale_headers \"\"\" deradicalised", "TABLE_FOOTER = ( \"|}\", \"\\n\", \"Weitere Links: [[Vorlage:Termine|Termine]] \", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\", \" [[Vorlage:Vergangene_Termine|Vergangene", "hier manuell editiert, hinzugefügt wird WIRD ÜBERSCHRIEBEN --> \"\"\" TABLE_HEADER = \"\"\" {|", "user\", metavar=\"WIKIUSER\" ) parser.add_argument( \"--wiki-password\", dest=\"wiki_pw\", help=\"Wiki user's password\", metavar=\"WIKIPW\" ) parser.add_argument( \"--wiki-page\",", "text: append_list = ( '\\n' + LINE_SEPARATOR + str(event) ) text = text[:last_table_position]+[append_list,", ":rtype: None \"\"\" site = Site('entropia.de', path='/') site.login(wiki_user, wiki_pw) page = site.pages[wiki_archive] text", "file\", metavar=\"FILE\" ) parser.add_argument( \"--wiki-user\", dest=\"wiki_user\", help=\"Wiki user\", metavar=\"WIKIUSER\" ) parser.add_argument( \"--wiki-password\", dest=\"wiki_pw\",", "the ICS-file can be retrieved\", metavar=\"URL\", ) parser.add_argument( \"-f\", \"--file\", dest=\"local_file\", help=\"Local ics", "in enumerate(text): if txtline == '|}': last_table_position = index if str(event) in text:", "- \" + self.endtime.strftime(\"%a., %d.%m.%Y\") return end_date @property def days_to_event(self): \"\"\" :return: Days", ":rtype: str \"\"\" return (\"| \" + self.begin_date + self.end_date + \" ||", "str(event) in text: continue if year_header in text: append_list = ( '\\n' +", "str(event) + '\\n|}' ) text = text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:] page.save(\"\\n\".join(text)) def get_args(): \"\"\" Retrieve", "year_header = \"== {} ==\".format(event.endtime.strftime('%Y')) for index, txtline in enumerate(text): if txtline ==", "self.endtime.strftime(\"%a., %d.%m.%Y\") return end_date @property def days_to_event(self): \"\"\" :return: Days to the start", "\"\"\" <!-- This text is automatically generated by the ics2entropiawiki bot, everything you", ":return: Parsed arguments from command line, config file :rtype: list \"\"\" parser =", "else: ics_result = requests.get(ics_url) ics_result.encoding = 'utf-8' calendar = Calendar(deradicalise_ical(ics_result.text)) for event in", "ARCHIVE_TABLE_HEADER + '\\n' + LINE_SEPARATOR + '\\n' + str(event) + '\\n|}' ) text", ") parser.add_argument( \"--wiki-password\", dest=\"wiki_pw\", help=\"Wiki user's password\", metavar=\"WIKIPW\" ) parser.add_argument( \"--wiki-page\", dest=\"wiki_page\", help='Wiki", ":rtype: str \"\"\" return self.begintime.strftime(\"%a., %d.%m.%Y\") @property def end_date(self): \"\"\" :return: Entropia-Wiki formatted", "\"\"\" :return: Check if the event lies in the past :rtype: bool \"\"\"", "EntropiaEvent(event) if not event.is_past_event: event_strings.append( \"\\n\" + LINE_SEPARATOR + str(event) ) else: past_events.append(event)", "path='/') site.login(wiki_user, wiki_pw) page = site.pages[wiki_archive] text = page.text().split('\\n') last_table_position = 0 for", "= [] past_events = [] if file: calendar = Calendar(deradicalise_ical(open(file).read())) else: ics_result =", "remove radicale_headers \"\"\" deradicalised = \"\" for line in ics.splitlines(): if 'X-RADICALE-NAME:' not", "datetime.timedelta \"\"\" return self.endtime - datetime.now(tz=tzlocal()) @property def is_past_event(self): \"\"\" :return: Check if", "def is_past_event(self): \"\"\" :return: Check if the event lies in the past :rtype:", ":param wiki_user: bot user for the wiki :type wiki_user: str :param wiki_pw: password", "if event.description: links = re.findall(\"^[Ll]ink:(.*)$\", event.description) wiki = re.findall(\"^[Ww]iki:(.*)$\", event.description) if links and", "ics2entropiawiki bot, everything you write and everything you edit WILL BE OVERWRITTEN Dieser", "str \"\"\" end_date = \"\" if self.endtime - self.begintime > timedelta(days=1): end_date =", "list :param wiki_user: bot user for the wiki :type wiki_user: str :param wiki_pw:", "wiki, debug def deradicalise_ical(ics): \"\"\" :param ics: input file :type ics: str :return:", "help=\"Wiki user\", metavar=\"WIKIUSER\" ) parser.add_argument( \"--wiki-password\", dest=\"wiki_pw\", help=\"Wiki user's password\", metavar=\"WIKIPW\" ) parser.add_argument(", "the events page :type past_events: list :param wiki_user: bot user for the wiki", "bot user for the wiki :type wiki_user: str :param wiki_pw: password for the", "txtline in enumerate(text): if txtline == '|}': last_table_position = index if str(event) in", "str \"\"\" return (\"| \" + self.begin_date + self.end_date + \" || \"", "= site.pages[wiki_archive] text = page.text().split('\\n') last_table_position = 0 for event in past_events: year_header", "the event :rtype: datetime.timedelta \"\"\" return self.endtime - datetime.now(tz=tzlocal()) @property def is_past_event(self): \"\"\"", "index if str(event) in text: continue if year_header in text: append_list = (", "if str(event) in text: continue if year_header in text: append_list = ( '\\n'", "file path\", metavar=\"CONFIG\" ) parser.add_argument( \"-u\", \"--url\", dest=\"ics_url\", help=\"The URL under which the", "requests from argparse import ArgumentParser from datetime import timedelta, datetime from ics import", "str \"\"\" start_time = \" \" if not self.event.all_day: start_time = self.begintime.strftime(\"%H:%M\") return", "text: continue if year_header in text: append_list = ( '\\n' + LINE_SEPARATOR +", "everything you write and everything you edit WILL BE OVERWRITTEN Dieser Text ist", "converts it to an entropia-wiki suitable form \"\"\" def __init__(self, event): \"\"\" :param", "\"\" if self.endtime - self.begintime > timedelta(days=1): end_date = \" - \" +", "the package\") raise error return ics_url, file, wiki, debug def deradicalise_ical(ics): \"\"\" :param", "\"\"\" :param ics: input file :type ics: str :return: file with remove radicale_headers", "wiki = { 'user': args.wiki_user, 'pass': args.wiki_pw, 'page': args.wiki_page, 'archive': args.wiki_archive, } debug", "for line in ics.splitlines(): if 'X-RADICALE-NAME:' not in line: deradicalised += \"\\n\"+line return", "Site('entropia.de', path='/') site.login(wiki['user'], wiki['pass']) page = site.pages[wiki['page']] if termine: page.save(termine, \"Terminbot was here\")", "file with remove radicale_headers \"\"\" deradicalised = \"\" for line in ics.splitlines(): if", "an entropia-wiki suitable form \"\"\" def __init__(self, event): \"\"\" :param event: The event", "- self.begintime > timedelta(days=1): end_date = \" - \" + self.endtime.strftime(\"%a., %d.%m.%Y\") return", "command line, the config file respectively :return: Parsed arguments from command line, config", "return self.days_to_event < timedelta(days=0) @property def start_time(self): \"\"\" :return: The starting time of", ") parser.add_argument( \"--wiki-user\", dest=\"wiki_user\", help=\"Wiki user\", metavar=\"WIKIUSER\" ) parser.add_argument( \"--wiki-password\", dest=\"wiki_pw\", help=\"Wiki user's", "wiki['pass']) page = site.pages[wiki['page']] if termine: page.save(termine, \"Terminbot was here\") page.purge() if __name__", ") parser.add_argument( \"--wiki-page\", dest=\"wiki_page\", help='Wiki page', metavar='WIKIPAGE' ) parser.add_argument( \"--wiki-archive\", dest=\"wiki_archive\", help='Wiki archive',", "tzlocal BOTWARNING = \"\"\" <!-- This text is automatically generated by the ics2entropiawiki", "wiki :type wiki_user: str :param wiki_pw: password for the wiki user :type wiki_pw:", "Parsed arguments from command line, config file :rtype: list \"\"\" parser = ArgumentParser()", "wiki = config[\"wiki\"] except KeyError as error: print(\"Please have a look at the", "\"[[Anfahrt|Entropia]]\", } location = \" \" if self.event.location: location = self.event.location if location.lower()", "with the entropia events and insert them in to the entropia homepage wiki.", "archive page :param past_events: the past events that were not added to the", "Dieser Text ist vom ics2entropiawiki bot automatisch generiert. Alles was hier manuell editiert,", "and appends past events to the \"Vergangene_Termine\" Site \"\"\" import locale import configparser", "\"\"\" Retrieve arguments from the command line, the config file respectively :return: Parsed", "\"--config\", default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\", help=\"Configuration file path\", metavar=\"CONFIG\" ) parser.add_argument( \"-u\", \"--url\", dest=\"ics_url\", help=\"The", "Beschreibung\\ \"\"\" ARCHIVE_TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" style=\"border-collapse:collapse;\" width=\"100%\" |width=15%|'''Datum'''", "the \"Termine\" Wiki page and appends past events to the \"Vergangene_Termine\" Site \"\"\"", "write and everything you edit WILL BE OVERWRITTEN Dieser Text ist vom ics2entropiawiki", "ÜBERSCHRIEBEN --> \"\"\" TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" width=\"100%\" style=\"border-collapse:collapse;\"", "parser.add_argument( \"--wiki-page\", dest=\"wiki_page\", help='Wiki page', metavar='WIKIPAGE' ) parser.add_argument( \"--wiki-archive\", dest=\"wiki_archive\", help='Wiki archive', metavar='WIKIARCHIVE'", "= 0 for event in past_events: year_header = \"== {} ==\".format(event.endtime.strftime('%Y')) for index,", "the event :rtype: str \"\"\" start_time = \" \" if not self.event.all_day: start_time", "entropia homepage wiki. Example: $ ics2entropiawiki.py --config /etc/ics2entropiawiki/config.ini Inserts events not in the", "args = parser.parse_args() configfile = args.configfile ics_url = args.ics_url file = args.local_file wiki", "[] past_events = [] if file: calendar = Calendar(deradicalise_ical(open(file).read())) else: ics_result = requests.get(ics_url)", "ARCHIVE_TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" style=\"border-collapse:collapse;\" width=\"100%\" |width=15%|'''Datum''' |width=6%|'''Zeit''' |width=15%|'''Ort'''", "\"\"\" start_time = \" \" if not self.event.all_day: start_time = self.begintime.strftime(\"%H:%M\") return start_time", "line: deradicalised += \"\\n\"+line return deradicalised def main(): \"\"\" :return: None :rtype: None", "( 3 * '\\n' + year_header + ARCHIVE_TABLE_HEADER + '\\n' + LINE_SEPARATOR +", "|| \" + self.description ) def append_past_events(past_events, wiki_user, wiki_pw, wiki_archive): \"\"\" Append the", "requests.get(ics_url) ics_result.encoding = 'utf-8' calendar = Calendar(deradicalise_ical(ics_result.text)) for event in sorted(calendar.events, key=lambda ev:", "which the ICS-file can be retrieved\", metavar=\"URL\", ) parser.add_argument( \"-f\", \"--file\", dest=\"local_file\", help=\"Local", "style=\"width:50px;\" | Zeit !! Ort !! Beschreibung\\ \"\"\" ARCHIVE_TABLE_HEADER = \"\"\" {| class=\"termine\"", "[[Anfahrt]]\" ) LINE_SEPARATOR = \"|-\\n\" try: locale.setlocale(locale.LC_ALL, 'de_DE.utf8') except locale.Error: pass class EntropiaEvent:", "description = \"N.A.\" else: description = event.name return description def __str__(self): \"\"\" :return:", "class EntropiaEvent: \"\"\" Parses an ics Event and converts it to an entropia-wiki", "page and appends past events to the \"Vergangene_Termine\" Site \"\"\" import locale import", "wiki_user: bot user for the wiki :type wiki_user: str :param wiki_pw: password for", "in past_events: year_header = \"== {} ==\".format(event.endtime.strftime('%Y')) for index, txtline in enumerate(text): if", "\"\"\" return self.days_to_event < timedelta(days=0) @property def start_time(self): \"\"\" :return: The starting time", "coding: utf-8 -*- \"\"\"ics2entropiawiki Read an ics file with the entropia events and", "self.event.all_day: start_time = self.begintime.strftime(\"%H:%M\") return start_time @property def description(self): \"\"\" :return: The event's", "str :return: None :rtype: None \"\"\" site = Site('entropia.de', path='/') site.login(wiki_user, wiki_pw) page", "event :return: location :rtype: str \"\"\" locations = { \"entropia\": \"[[Anfahrt|Entropia]]\", } location", "metavar=\"CONFIG\" ) parser.add_argument( \"-u\", \"--url\", dest=\"ics_url\", help=\"The URL under which the ICS-file can", "metavar='WIKIPAGE' ) parser.add_argument( \"--wiki-archive\", dest=\"wiki_archive\", help='Wiki archive', metavar='WIKIARCHIVE' ) parser.add_argument( \"-d\", \"--debug\", dest=\"debug\",", "locale import configparser import re import requests from argparse import ArgumentParser from datetime", "generated by the ics2entropiawiki bot, everything you write and everything you edit WILL", "locale.setlocale(locale.LC_ALL, 'de_DE.utf8') except locale.Error: pass class EntropiaEvent: \"\"\" Parses an ics Event and", "wiki_user: str :param wiki_pw: password for the wiki user :type wiki_pw: str :param", ") text = text[:last_table_position]+[append_list, ]+text[last_table_position:] else: append_list = ( 3 * '\\n' +", "main(): \"\"\" :return: None :rtype: None \"\"\" ics_url, file, wiki, debug = get_args()", "generiert. Alles was hier manuell editiert, hinzugefügt wird WIRD ÜBERSCHRIEBEN --> \"\"\" TABLE_HEADER", "-*- coding: utf-8 -*- \"\"\"ics2entropiawiki Read an ics file with the entropia events", "< timedelta(days=0) @property def start_time(self): \"\"\" :return: The starting time of the event", "ev.begin): event = EntropiaEvent(event) if not event.is_past_event: event_strings.append( \"\\n\" + LINE_SEPARATOR + str(event)", "= Site('entropia.de', path='/') site.login(wiki_user, wiki_pw) page = site.pages[wiki_archive] text = page.text().split('\\n') last_table_position =", "\"\"\" return self.begintime.strftime(\"%a., %d.%m.%Y\") @property def end_date(self): \"\"\" :return: Entropia-Wiki formatted end time", "location = locations[location.lower()] return location @property def begin_date(self): \"\"\" :return: Entropia-Wiki formatted begin", "+ LINE_SEPARATOR + str(event) ) text = text[:last_table_position]+[append_list, ]+text[last_table_position:] else: append_list = (", "= args.debug if configfile: config = configparser.ConfigParser() config.read(configfile) try: ics_url = config[\"default\"][\"url\"] wiki", "if the event lies in the past :rtype: bool \"\"\" return self.days_to_event <", "= args.local_file wiki = { 'user': args.wiki_user, 'pass': args.wiki_pw, 'page': args.wiki_page, 'archive': args.wiki_archive,", "config provided with the package\") raise error return ics_url, file, wiki, debug def", ":type event: ics.event.Event \"\"\" self.event = event self.begintime = event.begin.datetime.astimezone() self.endtime = event._end_time.datetime.astimezone()", "\"\\n\" + \"\".join(TABLE_FOOTER) if debug: print(termine) site = Site('entropia.de', path='/') site.login(wiki['user'], wiki['pass']) page", "Site('entropia.de', path='/') site.login(wiki_user, wiki_pw) page = site.pages[wiki_archive] text = page.text().split('\\n') last_table_position = 0", "{| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" width=\"100%\" style=\"border-collapse:collapse;\" ! style=\"width:250px;\" | Datum !! style=\"width:50px;\"", "Termine]], [[Anfahrt]]\" ) LINE_SEPARATOR = \"|-\\n\" try: locale.setlocale(locale.LC_ALL, 'de_DE.utf8') except locale.Error: pass class", "formatted end time :rtype: str \"\"\" end_date = \"\" if self.endtime - self.begintime", "\"\"\" site = Site('entropia.de', path='/') site.login(wiki_user, wiki_pw) page = site.pages[wiki_archive] text = page.text().split('\\n')", "the \"Vergangene_Termine\" Site \"\"\" import locale import configparser import re import requests from", "automatically generated by the ics2entropiawiki bot, everything you write and everything you edit", "\"Termine\" Wiki page and appends past events to the \"Vergangene_Termine\" Site \"\"\" import", "\" - \" + self.endtime.strftime(\"%a., %d.%m.%Y\") return end_date @property def days_to_event(self): \"\"\" :return:", "events and insert them in to the entropia homepage wiki. Example: $ ics2entropiawiki.py", "edit WILL BE OVERWRITTEN Dieser Text ist vom ics2entropiawiki bot automatisch generiert. Alles", "str(event) ) else: past_events.append(event) append_past_events(past_events, wiki['user'], wiki['pass'], wiki['archive']) termine = BOTWARNING + \"\\n\"", "entropia events and insert them in to the entropia homepage wiki. Example: $", "in locations.keys(): location = locations[location.lower()] return location @property def begin_date(self): \"\"\" :return: Entropia-Wiki", "site = Site('entropia.de', path='/') site.login(wiki_user, wiki_pw) page = site.pages[wiki_archive] text = page.text().split('\\n') last_table_position", "the command line, the config file respectively :return: Parsed arguments from command line,", "\" + self.start_time + \" || \" + self.location + \" || \"", "event.is_past_event: event_strings.append( \"\\n\" + LINE_SEPARATOR + str(event) ) else: past_events.append(event) append_past_events(past_events, wiki['user'], wiki['pass'],", "argparse import ArgumentParser from datetime import timedelta, datetime from ics import Calendar from", "by the ics2entropiawiki bot, everything you write and everything you edit WILL BE", "+ \"\".join(TABLE_FOOTER) if debug: print(termine) site = Site('entropia.de', path='/') site.login(wiki['user'], wiki['pass']) page =", "\"\"\" parser = ArgumentParser() parser.add_argument( \"-c\", \"--config\", default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\", help=\"Configuration file path\", metavar=\"CONFIG\"", "from ics import Calendar from mwclient import Site from dateutil.tz import tzlocal BOTWARNING", "= { 'user': args.wiki_user, 'pass': args.wiki_pw, 'page': args.wiki_page, 'archive': args.wiki_archive, } debug =", "deradicalised = \"\" for line in ics.splitlines(): if 'X-RADICALE-NAME:' not in line: deradicalised", "= config[\"wiki\"] except KeyError as error: print(\"Please have a look at the sample", "self.end_date + \" || \" + self.start_time + \" || \" + self.location", "= Calendar(deradicalise_ical(ics_result.text)) for event in sorted(calendar.events, key=lambda ev: ev.begin): event = EntropiaEvent(event) if", "past_events = [] if file: calendar = Calendar(deradicalise_ical(open(file).read())) else: ics_result = requests.get(ics_url) ics_result.encoding", "text = text[:last_table_position]+[append_list, ]+text[last_table_position:] else: append_list = ( 3 * '\\n' + year_header", "wiki user :type wiki_pw: str :param wiki_archive: archive page :type wiki_archive: str :return:", "import locale import configparser import re import requests from argparse import ArgumentParser from", "\"-c\", \"--config\", default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\", help=\"Configuration file path\", metavar=\"CONFIG\" ) parser.add_argument( \"-u\", \"--url\", dest=\"ics_url\",", "def __init__(self, event): \"\"\" :param event: The event to be evaluated :type event:", "= EntropiaEvent(event) if not event.is_past_event: event_strings.append( \"\\n\" + LINE_SEPARATOR + str(event) ) else:", ":return: A wiki line describing the event :rtype: str \"\"\" return (\"| \"", ":param wiki_pw: password for the wiki user :type wiki_pw: str :param wiki_archive: archive", "start_time = \" \" if not self.event.all_day: start_time = self.begintime.strftime(\"%H:%M\") return start_time @property", "= config[\"default\"][\"url\"] wiki = config[\"wiki\"] except KeyError as error: print(\"Please have a look", "Parses an ics Event and converts it to an entropia-wiki suitable form \"\"\"", "ics Event and converts it to an entropia-wiki suitable form \"\"\" def __init__(self,", "for event in past_events: year_header = \"== {} ==\".format(event.endtime.strftime('%Y')) for index, txtline in", "style=\"border-collapse:collapse;\" ! style=\"width:250px;\" | Datum !! style=\"width:50px;\" | Zeit !! Ort !! Beschreibung\\", "site = Site('entropia.de', path='/') site.login(wiki['user'], wiki['pass']) page = site.pages[wiki['page']] if termine: page.save(termine, \"Terminbot", "to the start of the event :rtype: datetime.timedelta \"\"\" return self.endtime - datetime.now(tz=tzlocal())", "event :rtype: str \"\"\" return (\"| \" + self.begin_date + self.end_date + \"", "= \" \" if self.event.location: location = self.event.location if location.lower() in locations.keys(): location", "Inserts events not in the past to the \"Termine\" Wiki page and appends", "str :param wiki_pw: password for the wiki user :type wiki_pw: str :param wiki_archive:", "in the past :rtype: bool \"\"\" return self.days_to_event < timedelta(days=0) @property def start_time(self):", "links and event.name: description = \"[\"+links[0]+\" \"+event.name+\"]\" elif wiki: description = wiki[0] elif", "ArgumentParser from datetime import timedelta, datetime from ics import Calendar from mwclient import", "\"\"\" :return: Entropia-Wiki formatted begin time :rtype: str \"\"\" return self.begintime.strftime(\"%a., %d.%m.%Y\") @property", "def append_past_events(past_events, wiki_user, wiki_pw, wiki_archive): \"\"\" Append the \"new\" past events to the", "3 * '\\n' + year_header + ARCHIVE_TABLE_HEADER + '\\n' + LINE_SEPARATOR + '\\n'", "event's description :rtype: str \"\"\" links = None wiki = None event =", "text = page.text().split('\\n') last_table_position = 0 for event in past_events: year_header = \"==", "return deradicalised def main(): \"\"\" :return: None :rtype: None \"\"\" ics_url, file, wiki,", "config = configparser.ConfigParser() config.read(configfile) try: ics_url = config[\"default\"][\"url\"] wiki = config[\"wiki\"] except KeyError", "width=\"100%\" style=\"border-collapse:collapse;\" ! style=\"width:250px;\" | Datum !! style=\"width:50px;\" | Zeit !! Ort !!", "manuell editiert, hinzugefügt wird WIRD ÜBERSCHRIEBEN --> \"\"\" TABLE_HEADER = \"\"\" {| class=\"termine\"", "\"\"\" ics_url, file, wiki, debug = get_args() event_strings = [] past_events = []", "wiki['archive']) termine = BOTWARNING + \"\\n\" + TABLE_HEADER + \"\\n\" + \"\".join(event_strings) +", "self.begin_date + self.end_date + \" || \" + self.start_time + \" || \"", "\"\"\" :return: None :rtype: None \"\"\" ics_url, file, wiki, debug = get_args() event_strings", "\"Vergangene_Termine\" Site \"\"\" import locale import configparser import re import requests from argparse", "width=\"100%\" |width=15%|'''Datum''' |width=6%|'''Zeit''' |width=15%|'''Ort''' |width=69%|'''Beschreibung''' \"\"\" TABLE_FOOTER = ( \"|}\", \"\\n\", \"Weitere Links:", "args.configfile ics_url = args.ics_url file = args.local_file wiki = { 'user': args.wiki_user, 'pass':", "str(event) ) text = text[:last_table_position]+[append_list, ]+text[last_table_position:] else: append_list = ( 3 * '\\n'", "if self.event.location: location = self.event.location if location.lower() in locations.keys(): location = locations[location.lower()] return", "= requests.get(ics_url) ics_result.encoding = 'utf-8' calendar = Calendar(deradicalise_ical(ics_result.text)) for event in sorted(calendar.events, key=lambda", "\"\"\" :return: Entropia-Wiki formatted end time :rtype: str \"\"\" end_date = \"\" if", "configparser import re import requests from argparse import ArgumentParser from datetime import timedelta,", "text[:last_table_position]+[append_list, ]+text[last_table_position:] else: append_list = ( 3 * '\\n' + year_header + ARCHIVE_TABLE_HEADER", "default=False ) args = parser.parse_args() configfile = args.configfile ics_url = args.ics_url file =", "event in sorted(calendar.events, key=lambda ev: ev.begin): event = EntropiaEvent(event) if not event.is_past_event: event_strings.append(", "(\"| \" + self.begin_date + self.end_date + \" || \" + self.start_time +", "Wiki page and appends past events to the \"Vergangene_Termine\" Site \"\"\" import locale", "events not in the past to the \"Termine\" Wiki page and appends past", "\"|-\\n\" try: locale.setlocale(locale.LC_ALL, 'de_DE.utf8') except locale.Error: pass class EntropiaEvent: \"\"\" Parses an ics", "cellspacing=\"0\" cellpadding=\"5\" width=\"100%\" style=\"border-collapse:collapse;\" ! style=\"width:250px;\" | Datum !! style=\"width:50px;\" | Zeit !!", "event): \"\"\" :param event: The event to be evaluated :type event: ics.event.Event \"\"\"", ") parser.add_argument( \"--wiki-archive\", dest=\"wiki_archive\", help='Wiki archive', metavar='WIKIARCHIVE' ) parser.add_argument( \"-d\", \"--debug\", dest=\"debug\", action=\"store_true\",", "OVERWRITTEN Dieser Text ist vom ics2entropiawiki bot automatisch generiert. Alles was hier manuell", "import requests from argparse import ArgumentParser from datetime import timedelta, datetime from ics", "description = wiki[0] elif not event.name: description = \"N.A.\" else: description = event.name", "= [] if file: calendar = Calendar(deradicalise_ical(open(file).read())) else: ics_result = requests.get(ics_url) ics_result.encoding =", "if file: calendar = Calendar(deradicalise_ical(open(file).read())) else: ics_result = requests.get(ics_url) ics_result.encoding = 'utf-8' calendar", "file = args.local_file wiki = { 'user': args.wiki_user, 'pass': args.wiki_pw, 'page': args.wiki_page, 'archive':", "except KeyError as error: print(\"Please have a look at the sample config provided", "= site.pages[wiki['page']] if termine: page.save(termine, \"Terminbot was here\") page.purge() if __name__ == '__main__':", "calendar = Calendar(deradicalise_ical(ics_result.text)) for event in sorted(calendar.events, key=lambda ev: ev.begin): event = EntropiaEvent(event)", "args.ics_url file = args.local_file wiki = { 'user': args.wiki_user, 'pass': args.wiki_pw, 'page': args.wiki_page,", "wiki = None event = self.event if event.description: links = re.findall(\"^[Ll]ink:(.*)$\", event.description) wiki", "dateutil.tz import tzlocal BOTWARNING = \"\"\" <!-- This text is automatically generated by", "configfile: config = configparser.ConfigParser() config.read(configfile) try: ics_url = config[\"default\"][\"url\"] wiki = config[\"wiki\"] except", "not in the past to the \"Termine\" Wiki page and appends past events", "timedelta, datetime from ics import Calendar from mwclient import Site from dateutil.tz import", "The starting time of the event :rtype: str \"\"\" start_time = \" \"", "try: locale.setlocale(locale.LC_ALL, 'de_DE.utf8') except locale.Error: pass class EntropiaEvent: \"\"\" Parses an ics Event", "and insert them in to the entropia homepage wiki. Example: $ ics2entropiawiki.py --config", "if links and event.name: description = \"[\"+links[0]+\" \"+event.name+\"]\" elif wiki: description = wiki[0]", "args.wiki_archive, } debug = args.debug if configfile: config = configparser.ConfigParser() config.read(configfile) try: ics_url", "re import requests from argparse import ArgumentParser from datetime import timedelta, datetime from", "( '\\n' + LINE_SEPARATOR + str(event) ) text = text[:last_table_position]+[append_list, ]+text[last_table_position:] else: append_list", "\"--debug\", dest=\"debug\", action=\"store_true\", default=False ) args = parser.parse_args() configfile = args.configfile ics_url =", "event = EntropiaEvent(event) if not event.is_past_event: event_strings.append( \"\\n\" + LINE_SEPARATOR + str(event) )", "self.endtime - datetime.now(tz=tzlocal()) @property def is_past_event(self): \"\"\" :return: Check if the event lies", "wiki line describing the event :rtype: str \"\"\" return (\"| \" + self.begin_date", "is automatically generated by the ics2entropiawiki bot, everything you write and everything you", "Datum !! style=\"width:50px;\" | Zeit !! Ort !! Beschreibung\\ \"\"\" ARCHIVE_TABLE_HEADER = \"\"\"", "return end_date @property def days_to_event(self): \"\"\" :return: Days to the start of the", "the entropia events and insert them in to the entropia homepage wiki. Example:", "page.save(\"\\n\".join(text)) def get_args(): \"\"\" Retrieve arguments from the command line, the config file", "* '\\n' + year_header + ARCHIVE_TABLE_HEADER + '\\n' + LINE_SEPARATOR + '\\n' +", "start_time @property def description(self): \"\"\" :return: The event's description :rtype: str \"\"\" links", "events page :type past_events: list :param wiki_user: bot user for the wiki :type", "= wiki[0] elif not event.name: description = \"N.A.\" else: description = event.name return", "str :return: file with remove radicale_headers \"\"\" deradicalised = \"\" for line in", "= ( \"|}\", \"\\n\", \"Weitere Links: [[Vorlage:Termine|Termine]] \", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\", \" [[Vorlage:Vergangene_Termine|Vergangene Termine]],", "= \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" width=\"100%\" style=\"border-collapse:collapse;\" ! style=\"width:250px;\" | Datum", "+ str(event) + '\\n|}' ) text = text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:] page.save(\"\\n\".join(text)) def get_args(): \"\"\"", "to the entropia homepage wiki. Example: $ ics2entropiawiki.py --config /etc/ics2entropiawiki/config.ini Inserts events not", "form \"\"\" def __init__(self, event): \"\"\" :param event: The event to be evaluated", "the past to the \"Termine\" Wiki page and appends past events to the", "0 for event in past_events: year_header = \"== {} ==\".format(event.endtime.strftime('%Y')) for index, txtline", "homepage wiki. Example: $ ics2entropiawiki.py --config /etc/ics2entropiawiki/config.ini Inserts events not in the past", "self.days_to_event < timedelta(days=0) @property def start_time(self): \"\"\" :return: The starting time of the", "def description(self): \"\"\" :return: The event's description :rtype: str \"\"\" links = None", "\"\"\" Retrieve the location of an event :return: location :rtype: str \"\"\" locations", "location = \" \" if self.event.location: location = self.event.location if location.lower() in locations.keys():", "from datetime import timedelta, datetime from ics import Calendar from mwclient import Site", "+ \"\\n\" + \"\".join(TABLE_FOOTER) if debug: print(termine) site = Site('entropia.de', path='/') site.login(wiki['user'], wiki['pass'])", "ics: str :return: file with remove radicale_headers \"\"\" deradicalised = \"\" for line", "\"-f\", \"--file\", dest=\"local_file\", help=\"Local ics file\", metavar=\"FILE\" ) parser.add_argument( \"--wiki-user\", dest=\"wiki_user\", help=\"Wiki user\",", "from the command line, the config file respectively :return: Parsed arguments from command", "config file respectively :return: Parsed arguments from command line, config file :rtype: list", "= \" \" if not self.event.all_day: start_time = self.begintime.strftime(\"%H:%M\") return start_time @property def", "import Site from dateutil.tz import tzlocal BOTWARNING = \"\"\" <!-- This text is", "= ( '\\n' + LINE_SEPARATOR + str(event) ) text = text[:last_table_position]+[append_list, ]+text[last_table_position:] else:", "in sorted(calendar.events, key=lambda ev: ev.begin): event = EntropiaEvent(event) if not event.is_past_event: event_strings.append( \"\\n\"", "\"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\", \" [[Vorlage:Vergangene_Termine|Vergangene Termine]], [[Anfahrt]]\" ) LINE_SEPARATOR = \"|-\\n\" try: locale.setlocale(locale.LC_ALL, 'de_DE.utf8')", "event.description: links = re.findall(\"^[Ll]ink:(.*)$\", event.description) wiki = re.findall(\"^[Ww]iki:(.*)$\", event.description) if links and event.name:", "cellspacing=\"0\" cellpadding=\"5\" style=\"border-collapse:collapse;\" width=\"100%\" |width=15%|'''Datum''' |width=6%|'''Zeit''' |width=15%|'''Ort''' |width=69%|'''Beschreibung''' \"\"\" TABLE_FOOTER = ( \"|}\",", "page = site.pages[wiki_archive] text = page.text().split('\\n') last_table_position = 0 for event in past_events:", "\"\"\" locations = { \"entropia\": \"[[Anfahrt|Entropia]]\", } location = \" \" if self.event.location:", "'\\n' + year_header + ARCHIVE_TABLE_HEADER + '\\n' + LINE_SEPARATOR + '\\n' + str(event)", "\" || \" + self.start_time + \" || \" + self.location + \"", "def days_to_event(self): \"\"\" :return: Days to the start of the event :rtype: datetime.timedelta", "= \"== {} ==\".format(event.endtime.strftime('%Y')) for index, txtline in enumerate(text): if txtline == '|}':", "+= \"\\n\"+line return deradicalised def main(): \"\"\" :return: None :rtype: None \"\"\" ics_url,", "metavar=\"FILE\" ) parser.add_argument( \"--wiki-user\", dest=\"wiki_user\", help=\"Wiki user\", metavar=\"WIKIUSER\" ) parser.add_argument( \"--wiki-password\", dest=\"wiki_pw\", help=\"Wiki", "= event._end_time.datetime.astimezone() @property def location(self): \"\"\" Retrieve the location of an event :return:", "+ '\\n' + LINE_SEPARATOR + '\\n' + str(event) + '\\n|}' ) text =", "bot, everything you write and everything you edit WILL BE OVERWRITTEN Dieser Text", "import ArgumentParser from datetime import timedelta, datetime from ics import Calendar from mwclient", "= Calendar(deradicalise_ical(open(file).read())) else: ics_result = requests.get(ics_url) ics_result.encoding = 'utf-8' calendar = Calendar(deradicalise_ical(ics_result.text)) for", ") parser.add_argument( \"-u\", \"--url\", dest=\"ics_url\", help=\"The URL under which the ICS-file can be", "+ LINE_SEPARATOR + '\\n' + str(event) + '\\n|}' ) text = text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:]", "wiki. Example: $ ics2entropiawiki.py --config /etc/ics2entropiawiki/config.ini Inserts events not in the past to", "= \"N.A.\" else: description = event.name return description def __str__(self): \"\"\" :return: A", "start of the event :rtype: datetime.timedelta \"\"\" return self.endtime - datetime.now(tz=tzlocal()) @property def", "time of the event :rtype: str \"\"\" start_time = \" \" if not", "re.findall(\"^[Ll]ink:(.*)$\", event.description) wiki = re.findall(\"^[Ww]iki:(.*)$\", event.description) if links and event.name: description = \"[\"+links[0]+\"", "str \"\"\" links = None wiki = None event = self.event if event.description:", "wiki, debug = get_args() event_strings = [] past_events = [] if file: calendar", "be evaluated :type event: ics.event.Event \"\"\" self.event = event self.begintime = event.begin.datetime.astimezone() self.endtime", "user :type wiki_pw: str :param wiki_archive: archive page :type wiki_archive: str :return: None", "Site \"\"\" import locale import configparser import re import requests from argparse import", "timedelta(days=1): end_date = \" - \" + self.endtime.strftime(\"%a., %d.%m.%Y\") return end_date @property def", "Event and converts it to an entropia-wiki suitable form \"\"\" def __init__(self, event):", "event_strings = [] past_events = [] if file: calendar = Calendar(deradicalise_ical(open(file).read())) else: ics_result", "event = self.event if event.description: links = re.findall(\"^[Ll]ink:(.*)$\", event.description) wiki = re.findall(\"^[Ww]iki:(.*)$\", event.description)", "file, wiki, debug = get_args() event_strings = [] past_events = [] if file:", "style=\"width:250px;\" | Datum !! style=\"width:50px;\" | Zeit !! Ort !! Beschreibung\\ \"\"\" ARCHIVE_TABLE_HEADER", "\"== {} ==\".format(event.endtime.strftime('%Y')) for index, txtline in enumerate(text): if txtline == '|}': last_table_position", "|| \" + self.start_time + \" || \" + self.location + \" ||", "with the package\") raise error return ics_url, file, wiki, debug def deradicalise_ical(ics): \"\"\"", "event.name: description = \"[\"+links[0]+\" \"+event.name+\"]\" elif wiki: description = wiki[0] elif not event.name:", "Retrieve arguments from the command line, the config file respectively :return: Parsed arguments", "provided with the package\") raise error return ics_url, file, wiki, debug def deradicalise_ical(ics):", ":return: location :rtype: str \"\"\" locations = { \"entropia\": \"[[Anfahrt|Entropia]]\", } location =", "@property def location(self): \"\"\" Retrieve the location of an event :return: location :rtype:", "of the event :rtype: datetime.timedelta \"\"\" return self.endtime - datetime.now(tz=tzlocal()) @property def is_past_event(self):", "is_past_event(self): \"\"\" :return: Check if the event lies in the past :rtype: bool", "event :rtype: datetime.timedelta \"\"\" return self.endtime - datetime.now(tz=tzlocal()) @property def is_past_event(self): \"\"\" :return:", "\"+event.name+\"]\" elif wiki: description = wiki[0] elif not event.name: description = \"N.A.\" else:", "'X-RADICALE-NAME:' not in line: deradicalised += \"\\n\"+line return deradicalised def main(): \"\"\" :return:", "LINE_SEPARATOR + str(event) ) else: past_events.append(event) append_past_events(past_events, wiki['user'], wiki['pass'], wiki['archive']) termine = BOTWARNING", "file: calendar = Calendar(deradicalise_ical(open(file).read())) else: ics_result = requests.get(ics_url) ics_result.encoding = 'utf-8' calendar =", "page :type wiki_archive: str :return: None :rtype: None \"\"\" site = Site('entropia.de', path='/')", "config.read(configfile) try: ics_url = config[\"default\"][\"url\"] wiki = config[\"wiki\"] except KeyError as error: print(\"Please", "location.lower() in locations.keys(): location = locations[location.lower()] return location @property def begin_date(self): \"\"\" :return:", "for event in sorted(calendar.events, key=lambda ev: ev.begin): event = EntropiaEvent(event) if not event.is_past_event:", ":return: None :rtype: None \"\"\" site = Site('entropia.de', path='/') site.login(wiki_user, wiki_pw) page =", "import Calendar from mwclient import Site from dateutil.tz import tzlocal BOTWARNING = \"\"\"", "hinzugefügt wird WIRD ÜBERSCHRIEBEN --> \"\"\" TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\"", "\"\"\" Parses an ics Event and converts it to an entropia-wiki suitable form", "location = self.event.location if location.lower() in locations.keys(): location = locations[location.lower()] return location @property", "= ( 3 * '\\n' + year_header + ARCHIVE_TABLE_HEADER + '\\n' + LINE_SEPARATOR", ":type wiki_archive: str :return: None :rtype: None \"\"\" site = Site('entropia.de', path='/') site.login(wiki_user,", "\"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" style=\"border-collapse:collapse;\" width=\"100%\" |width=15%|'''Datum''' |width=6%|'''Zeit''' |width=15%|'''Ort''' |width=69%|'''Beschreibung''' \"\"\"", "+ \"\\n\" + TABLE_HEADER + \"\\n\" + \"\".join(event_strings) + \"\\n\" + \"\".join(TABLE_FOOTER) if", "event lies in the past :rtype: bool \"\"\" return self.days_to_event < timedelta(days=0) @property", "\"\"\" Append the \"new\" past events to the wiki archive page :param past_events:", "\"new\" past events to the wiki archive page :param past_events: the past events", "begin time :rtype: str \"\"\" return self.begintime.strftime(\"%a., %d.%m.%Y\") @property def end_date(self): \"\"\" :return:", "Retrieve the location of an event :return: location :rtype: str \"\"\" locations =", "KeyError as error: print(\"Please have a look at the sample config provided with", "an ics Event and converts it to an entropia-wiki suitable form \"\"\" def", "Calendar from mwclient import Site from dateutil.tz import tzlocal BOTWARNING = \"\"\" <!--", "description :rtype: str \"\"\" links = None wiki = None event = self.event", "event self.begintime = event.begin.datetime.astimezone() self.endtime = event._end_time.datetime.astimezone() @property def location(self): \"\"\" Retrieve the", "file, wiki, debug def deradicalise_ical(ics): \"\"\" :param ics: input file :type ics: str", "password\", metavar=\"WIKIPW\" ) parser.add_argument( \"--wiki-page\", dest=\"wiki_page\", help='Wiki page', metavar='WIKIPAGE' ) parser.add_argument( \"--wiki-archive\", dest=\"wiki_archive\",", "self.begintime = event.begin.datetime.astimezone() self.endtime = event._end_time.datetime.astimezone() @property def location(self): \"\"\" Retrieve the location", "return start_time @property def description(self): \"\"\" :return: The event's description :rtype: str \"\"\"", "\"\\n\" + LINE_SEPARATOR + str(event) ) else: past_events.append(event) append_past_events(past_events, wiki['user'], wiki['pass'], wiki['archive']) termine", "an ics file with the entropia events and insert them in to the", "of the event :rtype: str \"\"\" start_time = \" \" if not self.event.all_day:", "LINE_SEPARATOR + '\\n' + str(event) + '\\n|}' ) text = text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:] page.save(\"\\n\".join(text))", "wiki_pw: password for the wiki user :type wiki_pw: str :param wiki_archive: archive page", "last_table_position = index if str(event) in text: continue if year_header in text: append_list", "file with the entropia events and insert them in to the entropia homepage", "+ str(event) ) else: past_events.append(event) append_past_events(past_events, wiki['user'], wiki['pass'], wiki['archive']) termine = BOTWARNING +", "lies in the past :rtype: bool \"\"\" return self.days_to_event < timedelta(days=0) @property def", "cellpadding=\"5\" width=\"100%\" style=\"border-collapse:collapse;\" ! style=\"width:250px;\" | Datum !! style=\"width:50px;\" | Zeit !! Ort", "past_events: list :param wiki_user: bot user for the wiki :type wiki_user: str :param", "if self.endtime - self.begintime > timedelta(days=1): end_date = \" - \" + self.endtime.strftime(\"%a.,", "\" if self.event.location: location = self.event.location if location.lower() in locations.keys(): location = locations[location.lower()]", "past events to the \"Vergangene_Termine\" Site \"\"\" import locale import configparser import re", "+ \" || \" + self.start_time + \" || \" + self.location +", "wiki[0] elif not event.name: description = \"N.A.\" else: description = event.name return description", "for the wiki :type wiki_user: str :param wiki_pw: password for the wiki user", "'\\n|}' ) text = text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:] page.save(\"\\n\".join(text)) def get_args(): \"\"\" Retrieve arguments from", "file respectively :return: Parsed arguments from command line, config file :rtype: list \"\"\"", "as error: print(\"Please have a look at the sample config provided with the", "return ics_url, file, wiki, debug def deradicalise_ical(ics): \"\"\" :param ics: input file :type", "past events to the wiki archive page :param past_events: the past events that", "not event.name: description = \"N.A.\" else: description = event.name return description def __str__(self):", "continue if year_header in text: append_list = ( '\\n' + LINE_SEPARATOR + str(event)", "} debug = args.debug if configfile: config = configparser.ConfigParser() config.read(configfile) try: ics_url =", "= locations[location.lower()] return location @property def begin_date(self): \"\"\" :return: Entropia-Wiki formatted begin time", "not self.event.all_day: start_time = self.begintime.strftime(\"%H:%M\") return start_time @property def description(self): \"\"\" :return: The", "append_list = ( '\\n' + LINE_SEPARATOR + str(event) ) text = text[:last_table_position]+[append_list, ]+text[last_table_position:]", "Calendar(deradicalise_ical(open(file).read())) else: ics_result = requests.get(ics_url) ics_result.encoding = 'utf-8' calendar = Calendar(deradicalise_ical(ics_result.text)) for event", "self.event = event self.begintime = event.begin.datetime.astimezone() self.endtime = event._end_time.datetime.astimezone() @property def location(self): \"\"\"", "parser.parse_args() configfile = args.configfile ics_url = args.ics_url file = args.local_file wiki = {", "return description def __str__(self): \"\"\" :return: A wiki line describing the event :rtype:", "Example: $ ics2entropiawiki.py --config /etc/ics2entropiawiki/config.ini Inserts events not in the past to the", "entropia-wiki suitable form \"\"\" def __init__(self, event): \"\"\" :param event: The event to", "automatisch generiert. Alles was hier manuell editiert, hinzugefügt wird WIRD ÜBERSCHRIEBEN --> \"\"\"", ":type wiki_user: str :param wiki_pw: password for the wiki user :type wiki_pw: str", "them in to the entropia homepage wiki. Example: $ ics2entropiawiki.py --config /etc/ics2entropiawiki/config.ini Inserts", "\"\"\" :return: Days to the start of the event :rtype: datetime.timedelta \"\"\" return", "( \"|}\", \"\\n\", \"Weitere Links: [[Vorlage:Termine|Termine]] \", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\", \" [[Vorlage:Vergangene_Termine|Vergangene Termine]], [[Anfahrt]]\"", "} location = \" \" if self.event.location: location = self.event.location if location.lower() in", "return self.endtime - datetime.now(tz=tzlocal()) @property def is_past_event(self): \"\"\" :return: Check if the event", "else: append_list = ( 3 * '\\n' + year_header + ARCHIVE_TABLE_HEADER + '\\n'", "\" \" if not self.event.all_day: start_time = self.begintime.strftime(\"%H:%M\") return start_time @property def description(self):", "TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" width=\"100%\" style=\"border-collapse:collapse;\" ! style=\"width:250px;\" |", "\"\"\" deradicalised = \"\" for line in ics.splitlines(): if 'X-RADICALE-NAME:' not in line:", "\"Weitere Links: [[Vorlage:Termine|Termine]] \", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\", \" [[Vorlage:Vergangene_Termine|Vergangene Termine]], [[Anfahrt]]\" ) LINE_SEPARATOR =", "was hier manuell editiert, hinzugefügt wird WIRD ÜBERSCHRIEBEN --> \"\"\" TABLE_HEADER = \"\"\"", "calendar = Calendar(deradicalise_ical(open(file).read())) else: ics_result = requests.get(ics_url) ics_result.encoding = 'utf-8' calendar = Calendar(deradicalise_ical(ics_result.text))", "/etc/ics2entropiawiki/config.ini Inserts events not in the past to the \"Termine\" Wiki page and", "Entropia-Wiki formatted begin time :rtype: str \"\"\" return self.begintime.strftime(\"%a., %d.%m.%Y\") @property def end_date(self):", "\"-d\", \"--debug\", dest=\"debug\", action=\"store_true\", default=False ) args = parser.parse_args() configfile = args.configfile ics_url", "\"\\n\" + \"\".join(event_strings) + \"\\n\" + \"\".join(TABLE_FOOTER) if debug: print(termine) site = Site('entropia.de',", "\" || \" + self.description ) def append_past_events(past_events, wiki_user, wiki_pw, wiki_archive): \"\"\" Append", "have a look at the sample config provided with the package\") raise error", "txtline == '|}': last_table_position = index if str(event) in text: continue if year_header", "line, the config file respectively :return: Parsed arguments from command line, config file", "style=\"border-collapse:collapse;\" width=\"100%\" |width=15%|'''Datum''' |width=6%|'''Zeit''' |width=15%|'''Ort''' |width=69%|'''Beschreibung''' \"\"\" TABLE_FOOTER = ( \"|}\", \"\\n\", \"Weitere", "starting time of the event :rtype: str \"\"\" start_time = \" \" if", "text = text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:] page.save(\"\\n\".join(text)) def get_args(): \"\"\" Retrieve arguments from the command", "= ArgumentParser() parser.add_argument( \"-c\", \"--config\", default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\", help=\"Configuration file path\", metavar=\"CONFIG\" ) parser.add_argument(", "wiki['user'], wiki['pass'], wiki['archive']) termine = BOTWARNING + \"\\n\" + TABLE_HEADER + \"\\n\" +", "+ TABLE_HEADER + \"\\n\" + \"\".join(event_strings) + \"\\n\" + \"\".join(TABLE_FOOTER) if debug: print(termine)", "if location.lower() in locations.keys(): location = locations[location.lower()] return location @property def begin_date(self): \"\"\"", ":return: The event's description :rtype: str \"\"\" links = None wiki = None", "\"\"\" links = None wiki = None event = self.event if event.description: links", "Links: [[Vorlage:Termine|Termine]] \", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\", \" [[Vorlage:Vergangene_Termine|Vergangene Termine]], [[Anfahrt]]\" ) LINE_SEPARATOR = \"|-\\n\"", "parser.add_argument( \"-c\", \"--config\", default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\", help=\"Configuration file path\", metavar=\"CONFIG\" ) parser.add_argument( \"-u\", \"--url\",", "+ \"\".join(event_strings) + \"\\n\" + \"\".join(TABLE_FOOTER) if debug: print(termine) site = Site('entropia.de', path='/')", "if configfile: config = configparser.ConfigParser() config.read(configfile) try: ics_url = config[\"default\"][\"url\"] wiki = config[\"wiki\"]", "deradicalised def main(): \"\"\" :return: None :rtype: None \"\"\" ics_url, file, wiki, debug", "self.endtime = event._end_time.datetime.astimezone() @property def location(self): \"\"\" Retrieve the location of an event", "@property def is_past_event(self): \"\"\" :return: Check if the event lies in the past", ":rtype: str \"\"\" links = None wiki = None event = self.event if", "dest=\"wiki_pw\", help=\"Wiki user's password\", metavar=\"WIKIPW\" ) parser.add_argument( \"--wiki-page\", dest=\"wiki_page\", help='Wiki page', metavar='WIKIPAGE' )", "year_header + ARCHIVE_TABLE_HEADER + '\\n' + LINE_SEPARATOR + '\\n' + str(event) + '\\n|}'", "deradicalise_ical(ics): \"\"\" :param ics: input file :type ics: str :return: file with remove", ":return: The starting time of the event :rtype: str \"\"\" start_time = \"", "class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" width=\"100%\" style=\"border-collapse:collapse;\" ! style=\"width:250px;\" | Datum !! style=\"width:50px;\" |", "end_date = \" - \" + self.endtime.strftime(\"%a., %d.%m.%Y\") return end_date @property def days_to_event(self):", "|width=15%|'''Datum''' |width=6%|'''Zeit''' |width=15%|'''Ort''' |width=69%|'''Beschreibung''' \"\"\" TABLE_FOOTER = ( \"|}\", \"\\n\", \"Weitere Links: [[Vorlage:Termine|Termine]]", "past to the \"Termine\" Wiki page and appends past events to the \"Vergangene_Termine\"", "return self.begintime.strftime(\"%a., %d.%m.%Y\") @property def end_date(self): \"\"\" :return: Entropia-Wiki formatted end time :rtype:", "border=\"1\" cellspacing=\"0\" cellpadding=\"5\" width=\"100%\" style=\"border-collapse:collapse;\" ! style=\"width:250px;\" | Datum !! style=\"width:50px;\" | Zeit", "ics_url = args.ics_url file = args.local_file wiki = { 'user': args.wiki_user, 'pass': args.wiki_pw,", "user for the wiki :type wiki_user: str :param wiki_pw: password for the wiki", "parser.add_argument( \"-u\", \"--url\", dest=\"ics_url\", help=\"The URL under which the ICS-file can be retrieved\",", "return location @property def begin_date(self): \"\"\" :return: Entropia-Wiki formatted begin time :rtype: str", "{} ==\".format(event.endtime.strftime('%Y')) for index, txtline in enumerate(text): if txtline == '|}': last_table_position =", "help='Wiki archive', metavar='WIKIARCHIVE' ) parser.add_argument( \"-d\", \"--debug\", dest=\"debug\", action=\"store_true\", default=False ) args =", "= \"|-\\n\" try: locale.setlocale(locale.LC_ALL, 'de_DE.utf8') except locale.Error: pass class EntropiaEvent: \"\"\" Parses an", "to be evaluated :type event: ics.event.Event \"\"\" self.event = event self.begintime = event.begin.datetime.astimezone()", "ics2entropiawiki.py --config /etc/ics2entropiawiki/config.ini Inserts events not in the past to the \"Termine\" Wiki", "\"\"\" TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" width=\"100%\" style=\"border-collapse:collapse;\" ! style=\"width:250px;\"", "= self.event if event.description: links = re.findall(\"^[Ll]ink:(.*)$\", event.description) wiki = re.findall(\"^[Ww]iki:(.*)$\", event.description) if", "to the wiki archive page :param past_events: the past events that were not", "begin_date(self): \"\"\" :return: Entropia-Wiki formatted begin time :rtype: str \"\"\" return self.begintime.strftime(\"%a., %d.%m.%Y\")", "look at the sample config provided with the package\") raise error return ics_url,", "'pass': args.wiki_pw, 'page': args.wiki_page, 'archive': args.wiki_archive, } debug = args.debug if configfile: config", ":rtype: list \"\"\" parser = ArgumentParser() parser.add_argument( \"-c\", \"--config\", default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\", help=\"Configuration file", "\"\"\" :return: The starting time of the event :rtype: str \"\"\" start_time =", "WILL BE OVERWRITTEN Dieser Text ist vom ics2entropiawiki bot automatisch generiert. Alles was", "- datetime.now(tz=tzlocal()) @property def is_past_event(self): \"\"\" :return: Check if the event lies in", "termine = BOTWARNING + \"\\n\" + TABLE_HEADER + \"\\n\" + \"\".join(event_strings) + \"\\n\"", "dest=\"wiki_page\", help='Wiki page', metavar='WIKIPAGE' ) parser.add_argument( \"--wiki-archive\", dest=\"wiki_archive\", help='Wiki archive', metavar='WIKIARCHIVE' ) parser.add_argument(", "= text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:] page.save(\"\\n\".join(text)) def get_args(): \"\"\" Retrieve arguments from the command line,", "ics_result = requests.get(ics_url) ics_result.encoding = 'utf-8' calendar = Calendar(deradicalise_ical(ics_result.text)) for event in sorted(calendar.events,", "= text[:last_table_position]+[append_list, ]+text[last_table_position:] else: append_list = ( 3 * '\\n' + year_header +", "dest=\"wiki_archive\", help='Wiki archive', metavar='WIKIARCHIVE' ) parser.add_argument( \"-d\", \"--debug\", dest=\"debug\", action=\"store_true\", default=False ) args", "+ self.begin_date + self.end_date + \" || \" + self.start_time + \" ||", "= \" - \" + self.endtime.strftime(\"%a., %d.%m.%Y\") return end_date @property def days_to_event(self): \"\"\"", "were not added to the events page :type past_events: list :param wiki_user: bot", "+ self.location + \" || \" + self.description ) def append_past_events(past_events, wiki_user, wiki_pw,", "you write and everything you edit WILL BE OVERWRITTEN Dieser Text ist vom", "= \"\" if self.endtime - self.begintime > timedelta(days=1): end_date = \" - \"", "'|}': last_table_position = index if str(event) in text: continue if year_header in text:", "\"--file\", dest=\"local_file\", help=\"Local ics file\", metavar=\"FILE\" ) parser.add_argument( \"--wiki-user\", dest=\"wiki_user\", help=\"Wiki user\", metavar=\"WIKIUSER\"", "@property def start_time(self): \"\"\" :return: The starting time of the event :rtype: str", "to an entropia-wiki suitable form \"\"\" def __init__(self, event): \"\"\" :param event: The", "args.wiki_page, 'archive': args.wiki_archive, } debug = args.debug if configfile: config = configparser.ConfigParser() config.read(configfile)", "\"--wiki-page\", dest=\"wiki_page\", help='Wiki page', metavar='WIKIPAGE' ) parser.add_argument( \"--wiki-archive\", dest=\"wiki_archive\", help='Wiki archive', metavar='WIKIARCHIVE' )", "error return ics_url, file, wiki, debug def deradicalise_ical(ics): \"\"\" :param ics: input file", "dest=\"debug\", action=\"store_true\", default=False ) args = parser.parse_args() configfile = args.configfile ics_url = args.ics_url", "re.findall(\"^[Ww]iki:(.*)$\", event.description) if links and event.name: description = \"[\"+links[0]+\" \"+event.name+\"]\" elif wiki: description", "\" \" if self.event.location: location = self.event.location if location.lower() in locations.keys(): location =", "in text: continue if year_header in text: append_list = ( '\\n' + LINE_SEPARATOR", "parser.add_argument( \"-d\", \"--debug\", dest=\"debug\", action=\"store_true\", default=False ) args = parser.parse_args() configfile = args.configfile", "datetime import timedelta, datetime from ics import Calendar from mwclient import Site from", "@property def end_date(self): \"\"\" :return: Entropia-Wiki formatted end time :rtype: str \"\"\" end_date", "Read an ics file with the entropia events and insert them in to", "file :rtype: list \"\"\" parser = ArgumentParser() parser.add_argument( \"-c\", \"--config\", default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\", help=\"Configuration", "ist vom ics2entropiawiki bot automatisch generiert. Alles was hier manuell editiert, hinzugefügt wird", "\" + self.location + \" || \" + self.description ) def append_past_events(past_events, wiki_user,", "str :param wiki_archive: archive page :type wiki_archive: str :return: None :rtype: None \"\"\"", "= None event = self.event if event.description: links = re.findall(\"^[Ll]ink:(.*)$\", event.description) wiki =", "Ort !! Beschreibung\\ \"\"\" ARCHIVE_TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" style=\"border-collapse:collapse;\"", "configfile = args.configfile ics_url = args.ics_url file = args.local_file wiki = { 'user':", "if not self.event.all_day: start_time = self.begintime.strftime(\"%H:%M\") return start_time @property def description(self): \"\"\" :return:", "formatted begin time :rtype: str \"\"\" return self.begintime.strftime(\"%a., %d.%m.%Y\") @property def end_date(self): \"\"\"", "for the wiki user :type wiki_pw: str :param wiki_archive: archive page :type wiki_archive:", "a look at the sample config provided with the package\") raise error return", "Calendar(deradicalise_ical(ics_result.text)) for event in sorted(calendar.events, key=lambda ev: ev.begin): event = EntropiaEvent(event) if not", "%d.%m.%Y\") @property def end_date(self): \"\"\" :return: Entropia-Wiki formatted end time :rtype: str \"\"\"", "= get_args() event_strings = [] past_events = [] if file: calendar = Calendar(deradicalise_ical(open(file).read()))", "ics_result.encoding = 'utf-8' calendar = Calendar(deradicalise_ical(ics_result.text)) for event in sorted(calendar.events, key=lambda ev: ev.begin):", "ev: ev.begin): event = EntropiaEvent(event) if not event.is_past_event: event_strings.append( \"\\n\" + LINE_SEPARATOR +", "path\", metavar=\"CONFIG\" ) parser.add_argument( \"-u\", \"--url\", dest=\"ics_url\", help=\"The URL under which the ICS-file", "debug = get_args() event_strings = [] past_events = [] if file: calendar =", "|width=15%|'''Ort''' |width=69%|'''Beschreibung''' \"\"\" TABLE_FOOTER = ( \"|}\", \"\\n\", \"Weitere Links: [[Vorlage:Termine|Termine]] \", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit", "+ ARCHIVE_TABLE_HEADER + '\\n' + LINE_SEPARATOR + '\\n' + str(event) + '\\n|}' )", "self.begintime.strftime(\"%a., %d.%m.%Y\") @property def end_date(self): \"\"\" :return: Entropia-Wiki formatted end time :rtype: str", "in ics.splitlines(): if 'X-RADICALE-NAME:' not in line: deradicalised += \"\\n\"+line return deradicalised def", "wiki['pass'], wiki['archive']) termine = BOTWARNING + \"\\n\" + TABLE_HEADER + \"\\n\" + \"\".join(event_strings)", ":rtype: bool \"\"\" return self.days_to_event < timedelta(days=0) @property def start_time(self): \"\"\" :return: The", "if debug: print(termine) site = Site('entropia.de', path='/') site.login(wiki['user'], wiki['pass']) page = site.pages[wiki['page']] if", "LINE_SEPARATOR + str(event) ) text = text[:last_table_position]+[append_list, ]+text[last_table_position:] else: append_list = ( 3", "action=\"store_true\", default=False ) args = parser.parse_args() configfile = args.configfile ics_url = args.ics_url file", "[[Vorlage:Termine|Termine]] \", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\", \" [[Vorlage:Vergangene_Termine|Vergangene Termine]], [[Anfahrt]]\" ) LINE_SEPARATOR = \"|-\\n\" try:", "{ 'user': args.wiki_user, 'pass': args.wiki_pw, 'page': args.wiki_page, 'archive': args.wiki_archive, } debug = args.debug", ":rtype: datetime.timedelta \"\"\" return self.endtime - datetime.now(tz=tzlocal()) @property def is_past_event(self): \"\"\" :return: Check", "added to the events page :type past_events: list :param wiki_user: bot user for", "ArgumentParser() parser.add_argument( \"-c\", \"--config\", default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\", help=\"Configuration file path\", metavar=\"CONFIG\" ) parser.add_argument( \"-u\",", "==\".format(event.endtime.strftime('%Y')) for index, txtline in enumerate(text): if txtline == '|}': last_table_position = index", "ics.splitlines(): if 'X-RADICALE-NAME:' not in line: deradicalised += \"\\n\"+line return deradicalised def main():", "\" + self.endtime.strftime(\"%a., %d.%m.%Y\") return end_date @property def days_to_event(self): \"\"\" :return: Days to", "configparser.ConfigParser() config.read(configfile) try: ics_url = config[\"default\"][\"url\"] wiki = config[\"wiki\"] except KeyError as error:", "site.pages[wiki_archive] text = page.text().split('\\n') last_table_position = 0 for event in past_events: year_header =", "= 'utf-8' calendar = Calendar(deradicalise_ical(ics_result.text)) for event in sorted(calendar.events, key=lambda ev: ev.begin): event", "the ics2entropiawiki bot, everything you write and everything you edit WILL BE OVERWRITTEN", "\" + self.description ) def append_past_events(past_events, wiki_user, wiki_pw, wiki_archive): \"\"\" Append the \"new\"", "\"\"\" end_date = \"\" if self.endtime - self.begintime > timedelta(days=1): end_date = \"", "self.begintime.strftime(\"%H:%M\") return start_time @property def description(self): \"\"\" :return: The event's description :rtype: str", "event in past_events: year_header = \"== {} ==\".format(event.endtime.strftime('%Y')) for index, txtline in enumerate(text):", "to the events page :type past_events: list :param wiki_user: bot user for the", "return (\"| \" + self.begin_date + self.end_date + \" || \" + self.start_time", ":return: Days to the start of the event :rtype: datetime.timedelta \"\"\" return self.endtime", "description(self): \"\"\" :return: The event's description :rtype: str \"\"\" links = None wiki", "\"\"\" :return: A wiki line describing the event :rtype: str \"\"\" return (\"|", "end_date(self): \"\"\" :return: Entropia-Wiki formatted end time :rtype: str \"\"\" end_date = \"\"", "wiki_pw) page = site.pages[wiki_archive] text = page.text().split('\\n') last_table_position = 0 for event in", "+ '\\n|}' ) text = text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:] page.save(\"\\n\".join(text)) def get_args(): \"\"\" Retrieve arguments", "dest=\"wiki_user\", help=\"Wiki user\", metavar=\"WIKIUSER\" ) parser.add_argument( \"--wiki-password\", dest=\"wiki_pw\", help=\"Wiki user's password\", metavar=\"WIKIPW\" )", "wiki_archive: archive page :type wiki_archive: str :return: None :rtype: None \"\"\" site =", "event to be evaluated :type event: ics.event.Event \"\"\" self.event = event self.begintime =", "the sample config provided with the package\") raise error return ics_url, file, wiki,", "None event = self.event if event.description: links = re.findall(\"^[Ll]ink:(.*)$\", event.description) wiki = re.findall(\"^[Ww]iki:(.*)$\",", "wiki = re.findall(\"^[Ww]iki:(.*)$\", event.description) if links and event.name: description = \"[\"+links[0]+\" \"+event.name+\"]\" elif", "!! style=\"width:50px;\" | Zeit !! Ort !! Beschreibung\\ \"\"\" ARCHIVE_TABLE_HEADER = \"\"\" {|", "description = \"[\"+links[0]+\" \"+event.name+\"]\" elif wiki: description = wiki[0] elif not event.name: description", "dest=\"ics_url\", help=\"The URL under which the ICS-file can be retrieved\", metavar=\"URL\", ) parser.add_argument(", "\"\"\" :param event: The event to be evaluated :type event: ics.event.Event \"\"\" self.event", "that were not added to the events page :type past_events: list :param wiki_user:", ":type wiki_pw: str :param wiki_archive: archive page :type wiki_archive: str :return: None :rtype:", "config[\"wiki\"] except KeyError as error: print(\"Please have a look at the sample config", "\"\"\" TABLE_FOOTER = ( \"|}\", \"\\n\", \"Weitere Links: [[Vorlage:Termine|Termine]] \", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\", \"", "event: The event to be evaluated :type event: ics.event.Event \"\"\" self.event = event", "self.endtime - self.begintime > timedelta(days=1): end_date = \" - \" + self.endtime.strftime(\"%a., %d.%m.%Y\")", "'archive': args.wiki_archive, } debug = args.debug if configfile: config = configparser.ConfigParser() config.read(configfile) try:", "# -*- coding: utf-8 -*- \"\"\"ics2entropiawiki Read an ics file with the entropia", "Check if the event lies in the past :rtype: bool \"\"\" return self.days_to_event", "\"--wiki-archive\", dest=\"wiki_archive\", help='Wiki archive', metavar='WIKIARCHIVE' ) parser.add_argument( \"-d\", \"--debug\", dest=\"debug\", action=\"store_true\", default=False )", "text is automatically generated by the ics2entropiawiki bot, everything you write and everything", "arguments from command line, config file :rtype: list \"\"\" parser = ArgumentParser() parser.add_argument(", "\", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\", \" [[Vorlage:Vergangene_Termine|Vergangene Termine]], [[Anfahrt]]\" ) LINE_SEPARATOR = \"|-\\n\" try: locale.setlocale(locale.LC_ALL,", "parser = ArgumentParser() parser.add_argument( \"-c\", \"--config\", default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\", help=\"Configuration file path\", metavar=\"CONFIG\" )", "== '|}': last_table_position = index if str(event) in text: continue if year_header in", "\"\"\" return self.endtime - datetime.now(tz=tzlocal()) @property def is_past_event(self): \"\"\" :return: Check if the", "parser.add_argument( \"--wiki-archive\", dest=\"wiki_archive\", help='Wiki archive', metavar='WIKIARCHIVE' ) parser.add_argument( \"-d\", \"--debug\", dest=\"debug\", action=\"store_true\", default=False", "page', metavar='WIKIPAGE' ) parser.add_argument( \"--wiki-archive\", dest=\"wiki_archive\", help='Wiki archive', metavar='WIKIARCHIVE' ) parser.add_argument( \"-d\", \"--debug\",", "evaluated :type event: ics.event.Event \"\"\" self.event = event self.begintime = event.begin.datetime.astimezone() self.endtime =", "and event.name: description = \"[\"+links[0]+\" \"+event.name+\"]\" elif wiki: description = wiki[0] elif not", "the wiki archive page :param past_events: the past events that were not added", "Bearbeiten]),\", \" [[Vorlage:Vergangene_Termine|Vergangene Termine]], [[Anfahrt]]\" ) LINE_SEPARATOR = \"|-\\n\" try: locale.setlocale(locale.LC_ALL, 'de_DE.utf8') except", "password for the wiki user :type wiki_pw: str :param wiki_archive: archive page :type", "metavar=\"WIKIUSER\" ) parser.add_argument( \"--wiki-password\", dest=\"wiki_pw\", help=\"Wiki user's password\", metavar=\"WIKIPW\" ) parser.add_argument( \"--wiki-page\", dest=\"wiki_page\",", "| Zeit !! Ort !! Beschreibung\\ \"\"\" ARCHIVE_TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\"", "key=lambda ev: ev.begin): event = EntropiaEvent(event) if not event.is_past_event: event_strings.append( \"\\n\" + LINE_SEPARATOR", "@property def description(self): \"\"\" :return: The event's description :rtype: str \"\"\" links =", "'de_DE.utf8') except locale.Error: pass class EntropiaEvent: \"\"\" Parses an ics Event and converts", "elif wiki: description = wiki[0] elif not event.name: description = \"N.A.\" else: description", "get_args() event_strings = [] past_events = [] if file: calendar = Calendar(deradicalise_ical(open(file).read())) else:", "location of an event :return: location :rtype: str \"\"\" locations = { \"entropia\":", "package\") raise error return ics_url, file, wiki, debug def deradicalise_ical(ics): \"\"\" :param ics:", "+ '\\n' + str(event) + '\\n|}' ) text = text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:] page.save(\"\\n\".join(text)) def", "line describing the event :rtype: str \"\"\" return (\"| \" + self.begin_date +", "if txtline == '|}': last_table_position = index if str(event) in text: continue if", "at the sample config provided with the package\") raise error return ics_url, file,", "[[Vorlage:Vergangene_Termine|Vergangene Termine]], [[Anfahrt]]\" ) LINE_SEPARATOR = \"|-\\n\" try: locale.setlocale(locale.LC_ALL, 'de_DE.utf8') except locale.Error: pass" ]
[ "os import random import re import sys # Complete the rotLeft function below.", "rotLeft(a, d): alist = list(a) b = alist[d:]+alist[:d] return b if __name__ ==", "= list(a) b = alist[d:]+alist[:d] return b if __name__ == '__main__': fptr =", "= int(nd[0]) d = int(nd[1]) a = list(map(int, input().rstrip().split())) result = rotLeft(a, d)", "import re import sys # Complete the rotLeft function below. def rotLeft(a, d):", "int(nd[0]) d = int(nd[1]) a = list(map(int, input().rstrip().split())) result = rotLeft(a, d) fptr.write('", "= input().split() n = int(nd[0]) d = int(nd[1]) a = list(map(int, input().rstrip().split())) result", "math import os import random import re import sys # Complete the rotLeft", "= int(nd[1]) a = list(map(int, input().rstrip().split())) result = rotLeft(a, d) fptr.write(' '.join(map(str, result)))", "import sys # Complete the rotLeft function below. def rotLeft(a, d): alist =", "alist = list(a) b = alist[d:]+alist[:d] return b if __name__ == '__main__': fptr", "d): alist = list(a) b = alist[d:]+alist[:d] return b if __name__ == '__main__':", "rotLeft function below. def rotLeft(a, d): alist = list(a) b = alist[d:]+alist[:d] return", "if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nd = input().split() n =", "import math import os import random import re import sys # Complete the", "def rotLeft(a, d): alist = list(a) b = alist[d:]+alist[:d] return b if __name__", "__name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nd = input().split() n = int(nd[0])", "list(a) b = alist[d:]+alist[:d] return b if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'],", "'__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nd = input().split() n = int(nd[0]) d =", "= open(os.environ['OUTPUT_PATH'], 'w') nd = input().split() n = int(nd[0]) d = int(nd[1]) a", "int(nd[1]) a = list(map(int, input().rstrip().split())) result = rotLeft(a, d) fptr.write(' '.join(map(str, result))) fptr.write('\\n')", "Complete the rotLeft function below. def rotLeft(a, d): alist = list(a) b =", "b if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nd = input().split() n", "alist[d:]+alist[:d] return b if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nd =", "below. def rotLeft(a, d): alist = list(a) b = alist[d:]+alist[:d] return b if", "import os import random import re import sys # Complete the rotLeft function", "#!/bin/python3 import math import os import random import re import sys # Complete", "= alist[d:]+alist[:d] return b if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nd", "re import sys # Complete the rotLeft function below. def rotLeft(a, d): alist", "sys # Complete the rotLeft function below. def rotLeft(a, d): alist = list(a)", "import random import re import sys # Complete the rotLeft function below. def", "# Complete the rotLeft function below. def rotLeft(a, d): alist = list(a) b", "nd = input().split() n = int(nd[0]) d = int(nd[1]) a = list(map(int, input().rstrip().split()))", "input().split() n = int(nd[0]) d = int(nd[1]) a = list(map(int, input().rstrip().split())) result =", "a = list(map(int, input().rstrip().split())) result = rotLeft(a, d) fptr.write(' '.join(map(str, result))) fptr.write('\\n') fptr.close()", "random import re import sys # Complete the rotLeft function below. def rotLeft(a,", "the rotLeft function below. def rotLeft(a, d): alist = list(a) b = alist[d:]+alist[:d]", "fptr = open(os.environ['OUTPUT_PATH'], 'w') nd = input().split() n = int(nd[0]) d = int(nd[1])", "open(os.environ['OUTPUT_PATH'], 'w') nd = input().split() n = int(nd[0]) d = int(nd[1]) a =", "== '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nd = input().split() n = int(nd[0]) d", "return b if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nd = input().split()", "d = int(nd[1]) a = list(map(int, input().rstrip().split())) result = rotLeft(a, d) fptr.write(' '.join(map(str,", "'w') nd = input().split() n = int(nd[0]) d = int(nd[1]) a = list(map(int,", "function below. def rotLeft(a, d): alist = list(a) b = alist[d:]+alist[:d] return b", "b = alist[d:]+alist[:d] return b if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w')", "n = int(nd[0]) d = int(nd[1]) a = list(map(int, input().rstrip().split())) result = rotLeft(a," ]
[ "import cflearn import platform import unittest from cfdata.tabular import TabularDataset num_jobs = 0", "TabularDataset.iris().xy zoo_folder = os.path.join(logging_folder, f\"__{model}__\") zoo = cflearn.Zoo(model) for key, config in zoo.benchmarks.items():", "= \"__test_zoo__\" class TestZoo(unittest.TestCase): @staticmethod def _test_zoo_core(model: str) -> None: x, y =", "num_jobs = 0 if platform.system() == \"Linux\" else 2 logging_folder = \"__test_zoo__\" class", "= 0 if platform.system() == \"Linux\" else 2 logging_folder = \"__test_zoo__\" class TestZoo(unittest.TestCase):", "cflearn import platform import unittest from cfdata.tabular import TabularDataset num_jobs = 0 if", "platform import unittest from cfdata.tabular import TabularDataset num_jobs = 0 if platform.system() ==", "config[\"logging_folder\"] = local_logging_folder m = cflearn.make(model, **config).fit(x, y) cflearn.evaluate(x, y, pipelines=m) cflearn._rmtree(logging_folder) def", "y) cflearn.evaluate(x, y, pipelines=m) cflearn._rmtree(logging_folder) def test_fcnn_zoo(self) -> None: self._test_zoo_core(\"fcnn\") def test_tree_dnn_zoo(self) ->", "logging_folder = \"__test_zoo__\" class TestZoo(unittest.TestCase): @staticmethod def _test_zoo_core(model: str) -> None: x, y", "cfdata.tabular import TabularDataset num_jobs = 0 if platform.system() == \"Linux\" else 2 logging_folder", "str) -> None: x, y = TabularDataset.iris().xy zoo_folder = os.path.join(logging_folder, f\"__{model}__\") zoo =", "y, pipelines=m) cflearn._rmtree(logging_folder) def test_fcnn_zoo(self) -> None: self._test_zoo_core(\"fcnn\") def test_tree_dnn_zoo(self) -> None: self._test_zoo_core(\"tree_dnn\")", "-> None: x, y = TabularDataset.iris().xy zoo_folder = os.path.join(logging_folder, f\"__{model}__\") zoo = cflearn.Zoo(model)", "key) config[\"logging_folder\"] = local_logging_folder m = cflearn.make(model, **config).fit(x, y) cflearn.evaluate(x, y, pipelines=m) cflearn._rmtree(logging_folder)", "local_logging_folder m = cflearn.make(model, **config).fit(x, y) cflearn.evaluate(x, y, pipelines=m) cflearn._rmtree(logging_folder) def test_fcnn_zoo(self) ->", "TestZoo(unittest.TestCase): @staticmethod def _test_zoo_core(model: str) -> None: x, y = TabularDataset.iris().xy zoo_folder =", "TabularDataset num_jobs = 0 if platform.system() == \"Linux\" else 2 logging_folder = \"__test_zoo__\"", "0 if platform.system() == \"Linux\" else 2 logging_folder = \"__test_zoo__\" class TestZoo(unittest.TestCase): @staticmethod", "== \"Linux\" else 2 logging_folder = \"__test_zoo__\" class TestZoo(unittest.TestCase): @staticmethod def _test_zoo_core(model: str)", "@staticmethod def _test_zoo_core(model: str) -> None: x, y = TabularDataset.iris().xy zoo_folder = os.path.join(logging_folder,", "import unittest from cfdata.tabular import TabularDataset num_jobs = 0 if platform.system() == \"Linux\"", "None: x, y = TabularDataset.iris().xy zoo_folder = os.path.join(logging_folder, f\"__{model}__\") zoo = cflearn.Zoo(model) for", "= os.path.join(logging_folder, f\"__{model}__\") zoo = cflearn.Zoo(model) for key, config in zoo.benchmarks.items(): local_logging_folder =", "= cflearn.make(model, **config).fit(x, y) cflearn.evaluate(x, y, pipelines=m) cflearn._rmtree(logging_folder) def test_fcnn_zoo(self) -> None: self._test_zoo_core(\"fcnn\")", "pipelines=m) cflearn._rmtree(logging_folder) def test_fcnn_zoo(self) -> None: self._test_zoo_core(\"fcnn\") def test_tree_dnn_zoo(self) -> None: self._test_zoo_core(\"tree_dnn\") if", "= os.path.join(zoo_folder, key) config[\"logging_folder\"] = local_logging_folder m = cflearn.make(model, **config).fit(x, y) cflearn.evaluate(x, y,", "cflearn.Zoo(model) for key, config in zoo.benchmarks.items(): local_logging_folder = os.path.join(zoo_folder, key) config[\"logging_folder\"] = local_logging_folder", "= TabularDataset.iris().xy zoo_folder = os.path.join(logging_folder, f\"__{model}__\") zoo = cflearn.Zoo(model) for key, config in", "zoo_folder = os.path.join(logging_folder, f\"__{model}__\") zoo = cflearn.Zoo(model) for key, config in zoo.benchmarks.items(): local_logging_folder", "x, y = TabularDataset.iris().xy zoo_folder = os.path.join(logging_folder, f\"__{model}__\") zoo = cflearn.Zoo(model) for key,", "for key, config in zoo.benchmarks.items(): local_logging_folder = os.path.join(zoo_folder, key) config[\"logging_folder\"] = local_logging_folder m", "= local_logging_folder m = cflearn.make(model, **config).fit(x, y) cflearn.evaluate(x, y, pipelines=m) cflearn._rmtree(logging_folder) def test_fcnn_zoo(self)", "class TestZoo(unittest.TestCase): @staticmethod def _test_zoo_core(model: str) -> None: x, y = TabularDataset.iris().xy zoo_folder", "os import cflearn import platform import unittest from cfdata.tabular import TabularDataset num_jobs =", "local_logging_folder = os.path.join(zoo_folder, key) config[\"logging_folder\"] = local_logging_folder m = cflearn.make(model, **config).fit(x, y) cflearn.evaluate(x,", "cflearn.make(model, **config).fit(x, y) cflearn.evaluate(x, y, pipelines=m) cflearn._rmtree(logging_folder) def test_fcnn_zoo(self) -> None: self._test_zoo_core(\"fcnn\") def", "def test_fcnn_zoo(self) -> None: self._test_zoo_core(\"fcnn\") def test_tree_dnn_zoo(self) -> None: self._test_zoo_core(\"tree_dnn\") if __name__ ==", "-> None: self._test_zoo_core(\"fcnn\") def test_tree_dnn_zoo(self) -> None: self._test_zoo_core(\"tree_dnn\") if __name__ == \"__main__\": unittest.main()", "import platform import unittest from cfdata.tabular import TabularDataset num_jobs = 0 if platform.system()", "key, config in zoo.benchmarks.items(): local_logging_folder = os.path.join(zoo_folder, key) config[\"logging_folder\"] = local_logging_folder m =", "zoo = cflearn.Zoo(model) for key, config in zoo.benchmarks.items(): local_logging_folder = os.path.join(zoo_folder, key) config[\"logging_folder\"]", "cflearn.evaluate(x, y, pipelines=m) cflearn._rmtree(logging_folder) def test_fcnn_zoo(self) -> None: self._test_zoo_core(\"fcnn\") def test_tree_dnn_zoo(self) -> None:", "else 2 logging_folder = \"__test_zoo__\" class TestZoo(unittest.TestCase): @staticmethod def _test_zoo_core(model: str) -> None:", "\"__test_zoo__\" class TestZoo(unittest.TestCase): @staticmethod def _test_zoo_core(model: str) -> None: x, y = TabularDataset.iris().xy", "def _test_zoo_core(model: str) -> None: x, y = TabularDataset.iris().xy zoo_folder = os.path.join(logging_folder, f\"__{model}__\")", "\"Linux\" else 2 logging_folder = \"__test_zoo__\" class TestZoo(unittest.TestCase): @staticmethod def _test_zoo_core(model: str) ->", "f\"__{model}__\") zoo = cflearn.Zoo(model) for key, config in zoo.benchmarks.items(): local_logging_folder = os.path.join(zoo_folder, key)", "import TabularDataset num_jobs = 0 if platform.system() == \"Linux\" else 2 logging_folder =", "y = TabularDataset.iris().xy zoo_folder = os.path.join(logging_folder, f\"__{model}__\") zoo = cflearn.Zoo(model) for key, config", "unittest from cfdata.tabular import TabularDataset num_jobs = 0 if platform.system() == \"Linux\" else", "config in zoo.benchmarks.items(): local_logging_folder = os.path.join(zoo_folder, key) config[\"logging_folder\"] = local_logging_folder m = cflearn.make(model,", "os.path.join(zoo_folder, key) config[\"logging_folder\"] = local_logging_folder m = cflearn.make(model, **config).fit(x, y) cflearn.evaluate(x, y, pipelines=m)", "_test_zoo_core(model: str) -> None: x, y = TabularDataset.iris().xy zoo_folder = os.path.join(logging_folder, f\"__{model}__\") zoo", "cflearn._rmtree(logging_folder) def test_fcnn_zoo(self) -> None: self._test_zoo_core(\"fcnn\") def test_tree_dnn_zoo(self) -> None: self._test_zoo_core(\"tree_dnn\") if __name__", "2 logging_folder = \"__test_zoo__\" class TestZoo(unittest.TestCase): @staticmethod def _test_zoo_core(model: str) -> None: x,", "in zoo.benchmarks.items(): local_logging_folder = os.path.join(zoo_folder, key) config[\"logging_folder\"] = local_logging_folder m = cflearn.make(model, **config).fit(x,", "test_fcnn_zoo(self) -> None: self._test_zoo_core(\"fcnn\") def test_tree_dnn_zoo(self) -> None: self._test_zoo_core(\"tree_dnn\") if __name__ == \"__main__\":", "zoo.benchmarks.items(): local_logging_folder = os.path.join(zoo_folder, key) config[\"logging_folder\"] = local_logging_folder m = cflearn.make(model, **config).fit(x, y)", "import os import cflearn import platform import unittest from cfdata.tabular import TabularDataset num_jobs", "= cflearn.Zoo(model) for key, config in zoo.benchmarks.items(): local_logging_folder = os.path.join(zoo_folder, key) config[\"logging_folder\"] =", "m = cflearn.make(model, **config).fit(x, y) cflearn.evaluate(x, y, pipelines=m) cflearn._rmtree(logging_folder) def test_fcnn_zoo(self) -> None:", "from cfdata.tabular import TabularDataset num_jobs = 0 if platform.system() == \"Linux\" else 2", "os.path.join(logging_folder, f\"__{model}__\") zoo = cflearn.Zoo(model) for key, config in zoo.benchmarks.items(): local_logging_folder = os.path.join(zoo_folder,", "**config).fit(x, y) cflearn.evaluate(x, y, pipelines=m) cflearn._rmtree(logging_folder) def test_fcnn_zoo(self) -> None: self._test_zoo_core(\"fcnn\") def test_tree_dnn_zoo(self)", "if platform.system() == \"Linux\" else 2 logging_folder = \"__test_zoo__\" class TestZoo(unittest.TestCase): @staticmethod def", "platform.system() == \"Linux\" else 2 logging_folder = \"__test_zoo__\" class TestZoo(unittest.TestCase): @staticmethod def _test_zoo_core(model:" ]
[ "the unsorted list at the midpoint into sublists. Takes O(k log n) quasilinear", "the linked list into sublists containing a single node - Repeatedly merge the", "right_head.next_node # Move current to next node current = current.next_node # Discard fake", "set loop condition to False right_head = right_head.next_node # If the head node", "is greater than right, set current to right node else: current.next_node = right_head", "left_head is None: current.next_node = right_head # Call next on right to set", "from right to merged linkned list if left_head is None: current.next_node = right_head", "to set loop condition to False left_head = left_head.next_node else: # Not at", "if left_data < right_data: current.next_node = left_head # Move left head to next", "All rights reserved. # ------------------------------------------------ from linked_list import Node, LinkedList def merge_sort(linked_list): '''", "linked list that contains nodes from # merging left and right merged =", "Not at either tail node # Obtain node data to perform comparison operations", "merge_sort(right_half) return merge(left, right) def split(linked_list): ''' Divide the unsorted list at the", "the sublists to produce sorted swublists until one remains Returns a sorted linked", "lists left_head = left.head right_head = right.head # Iterate over left and right", "past the tail # Add the tail node from left to merged linked", "return linked_list elif linked_list.is_empty(): return linked_list left_half, right_half = split(linked_list) left = merge_sort(left_half)", "merge_sort(linked_list): ''' Sorts a linked list in ascending order. - Recuresively divide the", "right_half = split(linked_list) left = merge_sort(left_half) right = merge_sort(right_half) return merge(left, right) def", "midpoint into sublists. Takes O(k log n) quasilinear time. ''' if linked_list ==", "head of the linked list current = merged.head # Obtain head nodes for", "# If the head node of the left is None, we're past the", "= merge_sort(right_half) return merge(left, right) def split(linked_list): ''' Divide the unsorted list at", "= linked_list right_half = None return left_half, right_half else: # non-empty linked lists", "at either tail node # Obtain node data to perform comparison operations left_data", "merged l = LinkedList() l.add(10) l.add(2) l.add(44) l.add(15) l.add(200) print(l) sorted_linked_list = merge_sort(l)", "left_head.next_node # If data on left is greater than right, set current to", "data on left is less than right, set current to left node if", "non-empty linked lists size = linked_list.size() midpoint = size // 2 mid_node =", "left.head right_head = right.head # Iterate over left and right until we reach", "O(kn log n) time. ''' if linked_list.size() == 1: return linked_list elif linked_list.is_empty():", "= mid_node.next_node mid_node.next_node = None return left_half, right_half def merge(left, right): ''' Merges", "None, we're past the tail # Add the tail node from left to", "right_head = right_head.next_node # Move current to next node current = current.next_node #", "# Python Techdegree # # Created by <NAME> on 3/24/19. # Copyright (c)", "the head node of right is None, we're past the tail # Add", "a sorted linked list. Runs in O(kn log n) time. ''' if linked_list.size()", "- Repeatedly merge the sublists to produce sorted swublists until one remains Returns", "from # merging left and right merged = LinkedList() # Add a fake", "fake head that is discarded later to simplify code merged.add(0) # Set current", "first merged node as head head = merged.head.next_node merged.head = head return merged", "a linked list in ascending order. - Recuresively divide the linked list into", "merged = LinkedList() # Add a fake head that is discarded later to", "= left_head.data right_data = right_head.data # If data on left is less than", "mid_node = linked_list.node_at_index(midpoint-1) left_half = linked_list right_half = LinkedList() right_half = mid_node.next_node mid_node.next_node", "tail # Add the node from right to merged linkned list if left_head", "to next node right_head = right_head.next_node # Move current to next node current", "None: left_half = linked_list right_half = None return left_half, right_half else: # non-empty", "= merge_sort(left_half) right = merge_sort(right_half) return merge(left, right) def split(linked_list): ''' Divide the", "in ascending order. - Recuresively divide the linked list into sublists containing a", "of either while left_head or right_head: # If the head node of the", "right_head # Move right head to next node right_head = right_head.next_node # Move", "<gh_stars>10-100 # # Data Structures: Linked List Merge Sort: The Conquer Step #", "than right, set current to left node if left_data < right_data: current.next_node =", "linked list. Runs in O(kn log n) time. ''' if linked_list.size() == 1:", "than right, set current to right node else: current.next_node = right_head # Move", "# Move right head to next node right_head = right_head.next_node # Move current", "linked_list right_half = None return left_half, right_half else: # non-empty linked lists size", "left head to next node left_head = left_head.next_node # If data on left", "lists size = linked_list.size() midpoint = size // 2 mid_node = linked_list.node_at_index(midpoint-1) left_half", "# Call next on right to set loop condition to False right_head =", "right_half = None return left_half, right_half else: # non-empty linked lists size =", "list if left_head is None: current.next_node = right_head # Call next on right", "and set first merged node as head head = merged.head.next_node merged.head = head", "linked_list left_half, right_half = split(linked_list) left = merge_sort(left_half) right = merge_sort(right_half) return merge(left,", "time. ''' # Create a new linked list that contains nodes from #", "LinkedList def merge_sort(linked_list): ''' Sorts a linked list in ascending order. - Recuresively", "to simplify code merged.add(0) # Set current to the head of the linked", "Techdegree # # Created by <NAME> on 3/24/19. # Copyright (c) 2019 ddApps.", "node # Obtain node data to perform comparison operations left_data = left_head.data right_data", "head and set first merged node as head head = merged.head.next_node merged.head =", "merge(left, right): ''' Merges two linked lists, sorting by data in nodes. Returns", "None: current.next_node = right_head # Call next on right to set loop condition", "= head return merged l = LinkedList() l.add(10) l.add(2) l.add(44) l.add(15) l.add(200) print(l)", "# merging left and right merged = LinkedList() # Add a fake head", "swublists until one remains Returns a sorted linked list. Runs in O(kn log", "node from left to merged linked list elif right_head is None: current.next_node =", "// 2 mid_node = linked_list.node_at_index(midpoint-1) left_half = linked_list right_half = LinkedList() right_half =", "discarded later to simplify code merged.add(0) # Set current to the head of", "right_head # Call next on right to set loop condition to False right_head", "linked lists size = linked_list.size() midpoint = size // 2 mid_node = linked_list.node_at_index(midpoint-1)", "linked_list import Node, LinkedList def merge_sort(linked_list): ''' Sorts a linked list in ascending", "= left_head # Call next on left to set loop condition to False", "Created by <NAME> on 3/24/19. # Copyright (c) 2019 ddApps. All rights reserved.", "mid_node.next_node mid_node.next_node = None return left_half, right_half def merge(left, right): ''' Merges two", "# Create a new linked list that contains nodes from # merging left", "< right_data: current.next_node = left_head # Move left head to next node left_head", "None return left_half, right_half def merge(left, right): ''' Merges two linked lists, sorting", "linked list elif right_head is None: current.next_node = left_head # Call next on", "the tail node # of either while left_head or right_head: # If the", "right = merge_sort(right_half) return merge(left, right) def split(linked_list): ''' Divide the unsorted list", "= right.head # Iterate over left and right until we reach the tail", "right_half = mid_node.next_node mid_node.next_node = None return left_half, right_half def merge(left, right): '''", "left_data < right_data: current.next_node = left_head # Move left head to next node", "- Recuresively divide the linked list into sublists containing a single node -", "nodes from # merging left and right merged = LinkedList() # Add a", "current to the head of the linked list current = merged.head # Obtain", "list that contains nodes from # merging left and right merged = LinkedList()", "Copyright (c) 2019 ddApps. All rights reserved. # ------------------------------------------------ from linked_list import Node,", "to next node current = current.next_node # Discard fake head and set first", "into sublists containing a single node - Repeatedly merge the sublists to produce", "is less than right, set current to left node if left_data < right_data:", "return left_half, right_half def merge(left, right): ''' Merges two linked lists, sorting by", "set current to left node if left_data < right_data: current.next_node = left_head #", "current = current.next_node # Discard fake head and set first merged node as", "that is discarded later to simplify code merged.add(0) # Set current to the", "and right linked lists left_head = left.head right_head = right.head # Iterate over", "to right node else: current.next_node = right_head # Move right head to next", "set current to right node else: current.next_node = right_head # Move right head", "''' if linked_list == None or linked_list.head == None: left_half = linked_list right_half", "else: current.next_node = right_head # Move right head to next node right_head =", "current.next_node = left_head # Move left head to next node left_head = left_head.next_node", "data to perform comparison operations left_data = left_head.data right_data = right_head.data # If", "merge(left, right) def split(linked_list): ''' Divide the unsorted list at the midpoint into", "# Call next on left to set loop condition to False left_head =", "right.head # Iterate over left and right until we reach the tail node", "left to set loop condition to False left_head = left_head.next_node else: # Not", "# If data on left is less than right, set current to left", "== None: left_half = linked_list right_half = None return left_half, right_half else: #", "= merged.head.next_node merged.head = head return merged l = LinkedList() l.add(10) l.add(2) l.add(44)", "right_half = LinkedList() right_half = mid_node.next_node mid_node.next_node = None return left_half, right_half def", "# Obtain head nodes for left and right linked lists left_head = left.head", "left_half, right_half = split(linked_list) left = merge_sort(left_half) right = merge_sort(right_half) return merge(left, right)", "2 mid_node = linked_list.node_at_index(midpoint-1) left_half = linked_list right_half = LinkedList() right_half = mid_node.next_node", "linear time. ''' # Create a new linked list that contains nodes from", "right, set current to left node if left_data < right_data: current.next_node = left_head", "size = linked_list.size() midpoint = size // 2 mid_node = linked_list.node_at_index(midpoint-1) left_half =", "unsorted list at the midpoint into sublists. Takes O(k log n) quasilinear time.", "and right merged = LinkedList() # Add a fake head that is discarded", "reach the tail node # of either while left_head or right_head: # If", "either while left_head or right_head: # If the head node of the left", "simplify code merged.add(0) # Set current to the head of the linked list", "(c) 2019 ddApps. All rights reserved. # ------------------------------------------------ from linked_list import Node, LinkedList", "merged list. Runs in O(n) linear time. ''' # Create a new linked", "is discarded later to simplify code merged.add(0) # Set current to the head", "node of right is None, we're past the tail # Add the tail", "we reach the tail node # of either while left_head or right_head: #", "# non-empty linked lists size = linked_list.size() midpoint = size // 2 mid_node", "merged linkned list if left_head is None: current.next_node = right_head # Call next", "by <NAME> on 3/24/19. # Copyright (c) 2019 ddApps. All rights reserved. #", "= left_head.next_node # If data on left is greater than right, set current", "code merged.add(0) # Set current to the head of the linked list current", "the left is None, we're past the tail # Add the node from", "O(k log n) quasilinear time. ''' if linked_list == None or linked_list.head ==", "node current = current.next_node # Discard fake head and set first merged node", "node data to perform comparison operations left_data = left_head.data right_data = right_head.data #", "right_data: current.next_node = left_head # Move left head to next node left_head =", "head that is discarded later to simplify code merged.add(0) # Set current to", "right_head = right.head # Iterate over left and right until we reach the", "until we reach the tail node # of either while left_head or right_head:", "the head node of the left is None, we're past the tail #", "or linked_list.head == None: left_half = linked_list right_half = None return left_half, right_half", "Returns a sorted linked list. Runs in O(kn log n) time. ''' if", "linked_list right_half = LinkedList() right_half = mid_node.next_node mid_node.next_node = None return left_half, right_half", "data on left is greater than right, set current to right node else:", "from linked_list import Node, LinkedList def merge_sort(linked_list): ''' Sorts a linked list in", "= right_head.next_node # Move current to next node current = current.next_node # Discard", "= LinkedList() # Add a fake head that is discarded later to simplify", "two linked lists, sorting by data in nodes. Returns a new, merged list.", "right head to next node right_head = right_head.next_node # Move current to next", "condition to False left_head = left_head.next_node else: # Not at either tail node", "to False left_head = left_head.next_node else: # Not at either tail node #", "right_data = right_head.data # If data on left is less than right, set", "either tail node # Obtain node data to perform comparison operations left_data =", "None or linked_list.head == None: left_half = linked_list right_half = None return left_half,", "head to next node left_head = left_head.next_node # If data on left is", "right is None, we're past the tail # Add the tail node from", "3/24/19. # Copyright (c) 2019 ddApps. All rights reserved. # ------------------------------------------------ from linked_list", "next node right_head = right_head.next_node # Move current to next node current =", "if linked_list == None or linked_list.head == None: left_half = linked_list right_half =", "log n) quasilinear time. ''' if linked_list == None or linked_list.head == None:", "a single node - Repeatedly merge the sublists to produce sorted swublists until", "merge the sublists to produce sorted swublists until one remains Returns a sorted", "left_half, right_half def merge(left, right): ''' Merges two linked lists, sorting by data", "def merge_sort(linked_list): ''' Sorts a linked list in ascending order. - Recuresively divide", "# Move current to next node current = current.next_node # Discard fake head", "merge_sort(left_half) right = merge_sort(right_half) return merge(left, right) def split(linked_list): ''' Divide the unsorted", "order. - Recuresively divide the linked list into sublists containing a single node", "= size // 2 mid_node = linked_list.node_at_index(midpoint-1) left_half = linked_list right_half = LinkedList()", "# Created by <NAME> on 3/24/19. # Copyright (c) 2019 ddApps. All rights", "right_head.next_node # If the head node of right is None, we're past the", "on left is less than right, set current to left node if left_data", "or right_head: # If the head node of the left is None, we're", "If the head node of right is None, we're past the tail #", "mid_node.next_node = None return left_half, right_half def merge(left, right): ''' Merges two linked", "later to simplify code merged.add(0) # Set current to the head of the", "head nodes for left and right linked lists left_head = left.head right_head =", "return merged l = LinkedList() l.add(10) l.add(2) l.add(44) l.add(15) l.add(200) print(l) sorted_linked_list =", "left and right linked lists left_head = left.head right_head = right.head # Iterate", "= current.next_node # Discard fake head and set first merged node as head", "as head head = merged.head.next_node merged.head = head return merged l = LinkedList()", "Add the node from right to merged linkned list if left_head is None:", "= left.head right_head = right.head # Iterate over left and right until we", "''' Merges two linked lists, sorting by data in nodes. Returns a new,", "# Not at either tail node # Obtain node data to perform comparison", "list elif right_head is None: current.next_node = left_head # Call next on left", "== 1: return linked_list elif linked_list.is_empty(): return linked_list left_half, right_half = split(linked_list) left", "condition to False right_head = right_head.next_node # If the head node of right", "we're past the tail # Add the node from right to merged linkned", "current.next_node = right_head # Move right head to next node right_head = right_head.next_node", "merging left and right merged = LinkedList() # Add a fake head that", "n) quasilinear time. ''' if linked_list == None or linked_list.head == None: left_half", "linked_list.size() midpoint = size // 2 mid_node = linked_list.node_at_index(midpoint-1) left_half = linked_list right_half", "right, set current to right node else: current.next_node = right_head # Move right", "''' if linked_list.size() == 1: return linked_list elif linked_list.is_empty(): return linked_list left_half, right_half", "a new linked list that contains nodes from # merging left and right", "Returns a new, merged list. Runs in O(n) linear time. ''' # Create", "# Add a fake head that is discarded later to simplify code merged.add(0)", "from left to merged linked list elif right_head is None: current.next_node = left_head", "# Move left head to next node left_head = left_head.next_node # If data", "------------------------------------------------ from linked_list import Node, LinkedList def merge_sort(linked_list): ''' Sorts a linked list", "= linked_list.node_at_index(midpoint-1) left_half = linked_list right_half = LinkedList() right_half = mid_node.next_node mid_node.next_node =", "right) def split(linked_list): ''' Divide the unsorted list at the midpoint into sublists.", "left_data = left_head.data right_data = right_head.data # If data on left is less", "# If data on left is greater than right, set current to right", "# Copyright (c) 2019 ddApps. All rights reserved. # ------------------------------------------------ from linked_list import", "Obtain head nodes for left and right linked lists left_head = left.head right_head", "Add a fake head that is discarded later to simplify code merged.add(0) #", "left_head # Move left head to next node left_head = left_head.next_node # If", "# # Data Structures: Linked List Merge Sort: The Conquer Step # Python", "Merges two linked lists, sorting by data in nodes. Returns a new, merged", "current to right node else: current.next_node = right_head # Move right head to", "the linked list current = merged.head # Obtain head nodes for left and", "list. Runs in O(kn log n) time. ''' if linked_list.size() == 1: return", "node of the left is None, we're past the tail # Add the", "= LinkedList() right_half = mid_node.next_node mid_node.next_node = None return left_half, right_half def merge(left,", "1: return linked_list elif linked_list.is_empty(): return linked_list left_half, right_half = split(linked_list) left =", "the tail node from left to merged linked list elif right_head is None:", "linked list into sublists containing a single node - Repeatedly merge the sublists", "If data on left is less than right, set current to left node", "Create a new linked list that contains nodes from # merging left and", "left and right merged = LinkedList() # Add a fake head that is", "= merged.head # Obtain head nodes for left and right linked lists left_head", "the tail # Add the node from right to merged linkned list if", "''' # Create a new linked list that contains nodes from # merging", "list at the midpoint into sublists. Takes O(k log n) quasilinear time. '''", "to False right_head = right_head.next_node # If the head node of right is", "Conquer Step # Python Techdegree # # Created by <NAME> on 3/24/19. #", "left to merged linked list elif right_head is None: current.next_node = left_head #", "current to left node if left_data < right_data: current.next_node = left_head # Move", "head return merged l = LinkedList() l.add(10) l.add(2) l.add(44) l.add(15) l.add(200) print(l) sorted_linked_list", "l = LinkedList() l.add(10) l.add(2) l.add(44) l.add(15) l.add(200) print(l) sorted_linked_list = merge_sort(l) print(sorted_linked_list)", "sorted swublists until one remains Returns a sorted linked list. Runs in O(kn", "node right_head = right_head.next_node # Move current to next node current = current.next_node", "in O(kn log n) time. ''' if linked_list.size() == 1: return linked_list elif", "Repeatedly merge the sublists to produce sorted swublists until one remains Returns a", "return linked_list left_half, right_half = split(linked_list) left = merge_sort(left_half) right = merge_sort(right_half) return", "current.next_node = left_head # Call next on left to set loop condition to", "tail node # of either while left_head or right_head: # If the head", "def merge(left, right): ''' Merges two linked lists, sorting by data in nodes.", "in O(n) linear time. ''' # Create a new linked list that contains", "to merged linkned list if left_head is None: current.next_node = right_head # Call", "new, merged list. Runs in O(n) linear time. ''' # Create a new", "linked_list == None or linked_list.head == None: left_half = linked_list right_half = None", "that contains nodes from # merging left and right merged = LinkedList() #", "time. ''' if linked_list == None or linked_list.head == None: left_half = linked_list", "of right is None, we're past the tail # Add the tail node", "<NAME> on 3/24/19. # Copyright (c) 2019 ddApps. All rights reserved. # ------------------------------------------------", "# If the head node of right is None, we're past the tail", "# # Created by <NAME> on 3/24/19. # Copyright (c) 2019 ddApps. All", "right_half else: # non-empty linked lists size = linked_list.size() midpoint = size //", "right until we reach the tail node # of either while left_head or", "the head of the linked list current = merged.head # Obtain head nodes", "merged linked list elif right_head is None: current.next_node = left_head # Call next", "left = merge_sort(left_half) right = merge_sort(right_half) return merge(left, right) def split(linked_list): ''' Divide", "over left and right until we reach the tail node # of either", "contains nodes from # merging left and right merged = LinkedList() # Add", "merged.head.next_node merged.head = head return merged l = LinkedList() l.add(10) l.add(2) l.add(44) l.add(15)", "Divide the unsorted list at the midpoint into sublists. Takes O(k log n)", "list current = merged.head # Obtain head nodes for left and right linked", "a new, merged list. Runs in O(n) linear time. ''' # Create a", "False right_head = right_head.next_node # If the head node of right is None,", "on left to set loop condition to False left_head = left_head.next_node else: #", "node as head head = merged.head.next_node merged.head = head return merged l =", "linkned list if left_head is None: current.next_node = right_head # Call next on", "linked_list.node_at_index(midpoint-1) left_half = linked_list right_half = LinkedList() right_half = mid_node.next_node mid_node.next_node = None", "# Add the node from right to merged linkned list if left_head is", "The Conquer Step # Python Techdegree # # Created by <NAME> on 3/24/19.", "O(n) linear time. ''' # Create a new linked list that contains nodes", "linked list in ascending order. - Recuresively divide the linked list into sublists", "def split(linked_list): ''' Divide the unsorted list at the midpoint into sublists. Takes", "is None: current.next_node = right_head # Call next on right to set loop", "past the tail # Add the node from right to merged linkned list", "node left_head = left_head.next_node # If data on left is greater than right,", "= left_head # Move left head to next node left_head = left_head.next_node #", "= right_head # Call next on right to set loop condition to False", "midpoint = size // 2 mid_node = linked_list.node_at_index(midpoint-1) left_half = linked_list right_half =", "left_head = left.head right_head = right.head # Iterate over left and right until", "None, we're past the tail # Add the node from right to merged", "# Set current to the head of the linked list current = merged.head", "current.next_node = right_head # Call next on right to set loop condition to", "to produce sorted swublists until one remains Returns a sorted linked list. Runs", "Linked List Merge Sort: The Conquer Step # Python Techdegree # # Created", "linked_list.head == None: left_half = linked_list right_half = None return left_half, right_half else:", "LinkedList() # Add a fake head that is discarded later to simplify code", "left_half, right_half else: # non-empty linked lists size = linked_list.size() midpoint = size", "greater than right, set current to right node else: current.next_node = right_head #", "Data Structures: Linked List Merge Sort: The Conquer Step # Python Techdegree #", "elif linked_list.is_empty(): return linked_list left_half, right_half = split(linked_list) left = merge_sort(left_half) right =", "set first merged node as head head = merged.head.next_node merged.head = head return", "Iterate over left and right until we reach the tail node # of", "Step # Python Techdegree # # Created by <NAME> on 3/24/19. # Copyright", "new linked list that contains nodes from # merging left and right merged", "left_head.next_node else: # Not at either tail node # Obtain node data to", "list in ascending order. - Recuresively divide the linked list into sublists containing", "right_head: # If the head node of the left is None, we're past", "If data on left is greater than right, set current to right node", "next on left to set loop condition to False left_head = left_head.next_node else:", "# Data Structures: Linked List Merge Sort: The Conquer Step # Python Techdegree", "''' Divide the unsorted list at the midpoint into sublists. Takes O(k log", "left_head.data right_data = right_head.data # If data on left is less than right,", "size // 2 mid_node = linked_list.node_at_index(midpoint-1) left_half = linked_list right_half = LinkedList() right_half", "linked lists left_head = left.head right_head = right.head # Iterate over left and", "right_head.data # If data on left is less than right, set current to", "rights reserved. # ------------------------------------------------ from linked_list import Node, LinkedList def merge_sort(linked_list): ''' Sorts", "merged.head # Obtain head nodes for left and right linked lists left_head =", "2019 ddApps. All rights reserved. # ------------------------------------------------ from linked_list import Node, LinkedList def", "into sublists. Takes O(k log n) quasilinear time. ''' if linked_list == None", "log n) time. ''' if linked_list.size() == 1: return linked_list elif linked_list.is_empty(): return", "# Obtain node data to perform comparison operations left_data = left_head.data right_data =", "right): ''' Merges two linked lists, sorting by data in nodes. Returns a", "loop condition to False right_head = right_head.next_node # If the head node of", "at the midpoint into sublists. Takes O(k log n) quasilinear time. ''' if", "sublists to produce sorted swublists until one remains Returns a sorted linked list.", "= linked_list.size() midpoint = size // 2 mid_node = linked_list.node_at_index(midpoint-1) left_half = linked_list", "ascending order. - Recuresively divide the linked list into sublists containing a single", "single node - Repeatedly merge the sublists to produce sorted swublists until one", "split(linked_list): ''' Divide the unsorted list at the midpoint into sublists. Takes O(k", "left_head # Call next on left to set loop condition to False left_head", "right_head = right_head.next_node # If the head node of right is None, we're", "Recuresively divide the linked list into sublists containing a single node - Repeatedly", "elif right_head is None: current.next_node = left_head # Call next on left to", "head node of right is None, we're past the tail # Add the", "head node of the left is None, we're past the tail # Add", "if linked_list.size() == 1: return linked_list elif linked_list.is_empty(): return linked_list left_half, right_half =", "Discard fake head and set first merged node as head head = merged.head.next_node", "# Iterate over left and right until we reach the tail node #", "node else: current.next_node = right_head # Move right head to next node right_head", "left_head = left_head.next_node else: # Not at either tail node # Obtain node", "None: current.next_node = left_head # Call next on left to set loop condition", "# Discard fake head and set first merged node as head head =", "= right_head.next_node # If the head node of right is None, we're past", "of the left is None, we're past the tail # Add the node", "perform comparison operations left_data = left_head.data right_data = right_head.data # If data on", "= None return left_half, right_half else: # non-empty linked lists size = linked_list.size()", "left and right until we reach the tail node # of either while", "left is less than right, set current to left node if left_data <", "= linked_list right_half = LinkedList() right_half = mid_node.next_node mid_node.next_node = None return left_half,", "if left_head is None: current.next_node = right_head # Call next on right to", "quasilinear time. ''' if linked_list == None or linked_list.head == None: left_half =", "left node if left_data < right_data: current.next_node = left_head # Move left head", "fake head and set first merged node as head head = merged.head.next_node merged.head", "# ------------------------------------------------ from linked_list import Node, LinkedList def merge_sort(linked_list): ''' Sorts a linked", "comparison operations left_data = left_head.data right_data = right_head.data # If data on left", "to next node left_head = left_head.next_node # If data on left is greater", "lists, sorting by data in nodes. Returns a new, merged list. Runs in", "ddApps. All rights reserved. # ------------------------------------------------ from linked_list import Node, LinkedList def merge_sort(linked_list):", "If the head node of the left is None, we're past the tail", "Python Techdegree # # Created by <NAME> on 3/24/19. # Copyright (c) 2019", "on right to set loop condition to False right_head = right_head.next_node # If", "for left and right linked lists left_head = left.head right_head = right.head #", "a fake head that is discarded later to simplify code merged.add(0) # Set", "merged node as head head = merged.head.next_node merged.head = head return merged l", "time. ''' if linked_list.size() == 1: return linked_list elif linked_list.is_empty(): return linked_list left_half,", "split(linked_list) left = merge_sort(left_half) right = merge_sort(right_half) return merge(left, right) def split(linked_list): '''", "tail # Add the tail node from left to merged linked list elif", "return merge(left, right) def split(linked_list): ''' Divide the unsorted list at the midpoint", "List Merge Sort: The Conquer Step # Python Techdegree # # Created by", "on left is greater than right, set current to right node else: current.next_node", "less than right, set current to left node if left_data < right_data: current.next_node", "False left_head = left_head.next_node else: # Not at either tail node # Obtain", "next on right to set loop condition to False right_head = right_head.next_node #", "right_half def merge(left, right): ''' Merges two linked lists, sorting by data in", "containing a single node - Repeatedly merge the sublists to produce sorted swublists", "left_half = linked_list right_half = LinkedList() right_half = mid_node.next_node mid_node.next_node = None return", "the midpoint into sublists. Takes O(k log n) quasilinear time. ''' if linked_list", "sublists. Takes O(k log n) quasilinear time. ''' if linked_list == None or", "Runs in O(kn log n) time. ''' if linked_list.size() == 1: return linked_list", "to merged linked list elif right_head is None: current.next_node = left_head # Call", "current to next node current = current.next_node # Discard fake head and set", "data in nodes. Returns a new, merged list. Runs in O(n) linear time.", "Call next on left to set loop condition to False left_head = left_head.next_node", "to perform comparison operations left_data = left_head.data right_data = right_head.data # If data", "right node else: current.next_node = right_head # Move right head to next node", "current.next_node # Discard fake head and set first merged node as head head", "left_head or right_head: # If the head node of the left is None,", "the tail # Add the tail node from left to merged linked list", "while left_head or right_head: # If the head node of the left is", "sorted linked list. Runs in O(kn log n) time. ''' if linked_list.size() ==", "Move right head to next node right_head = right_head.next_node # Move current to", "linked lists, sorting by data in nodes. Returns a new, merged list. Runs", "remains Returns a sorted linked list. Runs in O(kn log n) time. '''", "Move left head to next node left_head = left_head.next_node # If data on", "= right_head.data # If data on left is less than right, set current", "left is greater than right, set current to right node else: current.next_node =", "n) time. ''' if linked_list.size() == 1: return linked_list elif linked_list.is_empty(): return linked_list", "linked_list.is_empty(): return linked_list left_half, right_half = split(linked_list) left = merge_sort(left_half) right = merge_sort(right_half)", "tail node # Obtain node data to perform comparison operations left_data = left_head.data", "is None, we're past the tail # Add the node from right to", "right merged = LinkedList() # Add a fake head that is discarded later", "node - Repeatedly merge the sublists to produce sorted swublists until one remains", "divide the linked list into sublists containing a single node - Repeatedly merge", "else: # Not at either tail node # Obtain node data to perform", "Sorts a linked list in ascending order. - Recuresively divide the linked list", "by data in nodes. Returns a new, merged list. Runs in O(n) linear", "operations left_data = left_head.data right_data = right_head.data # If data on left is", "right to merged linkned list if left_head is None: current.next_node = right_head #", "head head = merged.head.next_node merged.head = head return merged l = LinkedList() l.add(10)", "import Node, LinkedList def merge_sort(linked_list): ''' Sorts a linked list in ascending order.", "head = merged.head.next_node merged.head = head return merged l = LinkedList() l.add(10) l.add(2)", "node if left_data < right_data: current.next_node = left_head # Move left head to", "== None or linked_list.head == None: left_half = linked_list right_half = None return", "linked_list.size() == 1: return linked_list elif linked_list.is_empty(): return linked_list left_half, right_half = split(linked_list)", "merged.add(0) # Set current to the head of the linked list current =", "node # of either while left_head or right_head: # If the head node", "sublists containing a single node - Repeatedly merge the sublists to produce sorted", "is None: current.next_node = left_head # Call next on left to set loop", "''' Sorts a linked list in ascending order. - Recuresively divide the linked", "Takes O(k log n) quasilinear time. ''' if linked_list == None or linked_list.head", "= left_head.next_node else: # Not at either tail node # Obtain node data", "return left_half, right_half else: # non-empty linked lists size = linked_list.size() midpoint =", "and right until we reach the tail node # of either while left_head", "Obtain node data to perform comparison operations left_data = left_head.data right_data = right_head.data", "= right_head # Move right head to next node right_head = right_head.next_node #", "is None, we're past the tail # Add the tail node from left", "tail node from left to merged linked list elif right_head is None: current.next_node", "Structures: Linked List Merge Sort: The Conquer Step # Python Techdegree # #", "Merge Sort: The Conquer Step # Python Techdegree # # Created by <NAME>", "left_half = linked_list right_half = None return left_half, right_half else: # non-empty linked", "Move current to next node current = current.next_node # Discard fake head and", "list. Runs in O(n) linear time. ''' # Create a new linked list", "right linked lists left_head = left.head right_head = right.head # Iterate over left", "the node from right to merged linkned list if left_head is None: current.next_node", "on 3/24/19. # Copyright (c) 2019 ddApps. All rights reserved. # ------------------------------------------------ from", "Set current to the head of the linked list current = merged.head #", "one remains Returns a sorted linked list. Runs in O(kn log n) time.", "next node current = current.next_node # Discard fake head and set first merged", "Sort: The Conquer Step # Python Techdegree # # Created by <NAME> on", "until one remains Returns a sorted linked list. Runs in O(kn log n)", "# of either while left_head or right_head: # If the head node of", "Node, LinkedList def merge_sort(linked_list): ''' Sorts a linked list in ascending order. -", "to left node if left_data < right_data: current.next_node = left_head # Move left", "# Add the tail node from left to merged linked list elif right_head", "right to set loop condition to False right_head = right_head.next_node # If the", "merged.head = head return merged l = LinkedList() l.add(10) l.add(2) l.add(44) l.add(15) l.add(200)", "Runs in O(n) linear time. ''' # Create a new linked list that", "sorting by data in nodes. Returns a new, merged list. Runs in O(n)", "None return left_half, right_half else: # non-empty linked lists size = linked_list.size() midpoint", "left is None, we're past the tail # Add the node from right", "linked list current = merged.head # Obtain head nodes for left and right", "current = merged.head # Obtain head nodes for left and right linked lists", "left_head = left_head.next_node # If data on left is greater than right, set", "nodes for left and right linked lists left_head = left.head right_head = right.head", "Add the tail node from left to merged linked list elif right_head is", "we're past the tail # Add the tail node from left to merged", "list into sublists containing a single node - Repeatedly merge the sublists to", "= None return left_half, right_half def merge(left, right): ''' Merges two linked lists,", "set loop condition to False left_head = left_head.next_node else: # Not at either", "LinkedList() right_half = mid_node.next_node mid_node.next_node = None return left_half, right_half def merge(left, right):", "nodes. Returns a new, merged list. Runs in O(n) linear time. ''' #", "Call next on right to set loop condition to False right_head = right_head.next_node", "head to next node right_head = right_head.next_node # Move current to next node", "= split(linked_list) left = merge_sort(left_half) right = merge_sort(right_half) return merge(left, right) def split(linked_list):", "reserved. # ------------------------------------------------ from linked_list import Node, LinkedList def merge_sort(linked_list): ''' Sorts a", "to the head of the linked list current = merged.head # Obtain head", "node from right to merged linkned list if left_head is None: current.next_node =", "right_head is None: current.next_node = left_head # Call next on left to set", "else: # non-empty linked lists size = linked_list.size() midpoint = size // 2", "in nodes. Returns a new, merged list. Runs in O(n) linear time. '''", "to set loop condition to False right_head = right_head.next_node # If the head", "produce sorted swublists until one remains Returns a sorted linked list. Runs in", "of the linked list current = merged.head # Obtain head nodes for left", "linked_list elif linked_list.is_empty(): return linked_list left_half, right_half = split(linked_list) left = merge_sort(left_half) right", "loop condition to False left_head = left_head.next_node else: # Not at either tail", "next node left_head = left_head.next_node # If data on left is greater than" ]
[ "TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "k, 10)) # Create engine engine_rbps = Engine(DIM, lshashes=hashes, distance=CosineDistance()) # First index", "EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "= numpy.random.randn(DIM) # Do random query on engine 4 print('\\nNeighbour distances with multiple", "the Software without restriction, including without limitation the rights # to use, copy,", "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN", "person obtaining a copy # of this software and associated documentation files (the", "of permutations hash permutations.add_child_hash(rbp_perm, rbp_conf) # Create engine engine_perm = Engine(DIM, lshashes=[permutations], distance=CosineDistance())", "Number of data points (dont do too much because of exact search) POINTS", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #", "range(20): hashes.append(RandomBinaryProjections('rbp_%d' % k, 10)) # Create engine engine_rbps = Engine(DIM, lshashes=hashes, distance=CosineDistance())", "THE SOFTWARE. import numpy import scipy import unittest import time from nearpy import", "to the following conditions: # The above copyright notice and this permission notice", "# Create engine engine_perm = Engine(DIM, lshashes=[permutations], distance=CosineDistance()) # First index some random", "# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies", "= time.time() print('Indexing took %f seconds' % (t1-t0)) # Get random query vector", "20000 ########################################################## print('Performing indexing with HashPermutations...') t0 = time.time() # Create permutations meta-hash", "# Create engine engine_rbps = Engine(DIM, lshashes=hashes, distance=CosineDistance()) # First index some random", "above copyright notice and this permission notice shall be included in # all", "to do so, subject to the following conditions: # The above copyright notice", "dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with HashPermutationMapper...') t0 = time.time() #", "numpy.zeros((POINTS,DIM)) for i in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_perm2.store_vector(v) t1", "hash permutations2.add_child_hash(rbp_perm2) # Create engine engine_perm2 = Engine(DIM, lshashes=[permutations2], distance=CosineDistance()) # First index", "results = engine_rbps.neighbours(query) dists = [x[2] for x in results] print(dists) # Real", "in # all copies or substantial portions of the Software. # THE SOFTWARE", "%d' % engine_perm.candidate_count(query)) results = engine_perm.neighbours(query) dists = [x[2] for x in results]", "POINTS = 20000 ########################################################## print('Performing indexing with HashPermutations...') t0 = time.time() # Create", "is hereby granted, free of charge, to any person obtaining a copy #", "HashPermutations...') t0 = time.time() # Create permutations meta-hash permutations = HashPermutations('permut') # Create", "# Create binary hash as child hash rbp_perm = RandomBinaryProjections('rbp_perm', 14) rbp_conf =", "print('\\nNeighbour distances with HashPermutations:') print(' -> Candidate count is %d' % engine_perm.candidate_count(query)) results", "persons to whom the Software is # furnished to do so, subject to", "= time.time() # Create permutations meta-hash permutations = HashPermutations('permut') # Create binary hash", "= numpy.random.randn(DIM) matrix[i] = v engine_perm.store_vector(v) # Then update permuted index permutations.build_permuted_index() t1", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A", "# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "rbp_conf) # Create engine engine_perm = Engine(DIM, lshashes=[permutations], distance=CosineDistance()) # First index some", "OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,", "for i in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_rbps.store_vector(v) t1 =", "documentation files (the \"Software\"), to deal # in the Software without restriction, including", "Create engine engine_perm2 = Engine(DIM, lshashes=[permutations2], distance=CosineDistance()) # First index some random vectors", "= dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with multiple binary hashes...')", "to permit persons to whom the Software is # furnished to do so,", "ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "points (dont do too much because of exact search) POINTS = 20000 ##########################################################", "Do random query on engine 4 print('\\nNeighbour distances with multiple binary hashes:') print('", "subject to the following conditions: # The above copyright notice and this permission", "notice and this permission notice shall be included in # all copies or", "of charge, to any person obtaining a copy # of this software and", "random query on engine 4 print('\\nNeighbour distances with multiple binary hashes:') print(' ->", "engine_rbps.candidate_count(query)) results = engine_rbps.neighbours(query) dists = [x[2] for x in results] print(dists) #", "binary hash as child hash rbp_perm2 = RandomBinaryProjections('rbp_perm2', 14) # Add rbp as", "# First index some random vectors matrix = numpy.zeros((POINTS,DIM)) for i in range(POINTS):", "as child hash rbp_perm = RandomBinaryProjections('rbp_perm', 14) rbp_conf = {'num_permutation':50,'beam_size':10,'num_neighbour':100} # Add rbp", "is %d' % engine_rbps.candidate_count(query)) results = engine_rbps.neighbours(query) dists = [x[2] for x in", "on engine 4 print('\\nNeighbour distances with multiple binary hashes:') print(' -> Candidate count", "from nearpy import Engine from nearpy.distances import CosineDistance from nearpy.hashes import RandomBinaryProjections, HashPermutations,", "4 print('\\nNeighbour distances with multiple binary hashes:') print(' -> Candidate count is %d'", "and this permission notice shall be included in # all copies or substantial", "vectors matrix = numpy.zeros((POINTS,DIM)) for i in range(POINTS): v = numpy.random.randn(DIM) matrix[i] =", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION", "of exact search) POINTS = 20000 ########################################################## print('Performing indexing with HashPermutations...') t0 =", "hashes:') print(' -> Candidate count is %d' % engine_rbps.candidate_count(query)) results = engine_rbps.neighbours(query) dists", "hash of permutations hash permutations.add_child_hash(rbp_perm, rbp_conf) # Create engine engine_perm = Engine(DIM, lshashes=[permutations],", "results = engine_perm.neighbours(query) dists = [x[2] for x in results] print(dists) # Real", "with HashPermutationMapper...') t0 = time.time() # Create permutations meta-hash permutations2 = HashPermutationMapper('permut2') #", "copy # of this software and associated documentation files (the \"Software\"), to deal", "permutations2 = HashPermutationMapper('permut2') # Create binary hash as child hash rbp_perm2 = RandomBinaryProjections('rbp_perm2',", "# Real neighbours print('\\nReal neighbour distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix, query)", "i in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_perm.store_vector(v) # Then update", "print('\\nReal neighbour distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix,query) dists = dists.reshape((-1,)) dists", "indexing with multiple binary hashes...') t0 = time.time() hashes = [] for k", "rbp as child hash of permutations hash permutations2.add_child_hash(rbp_perm2) # Create engine engine_perm2 =", "neighbours print('\\nReal neighbour distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix,query) dists = dists.reshape((-1,))", "is # furnished to do so, subject to the following conditions: # The", "and associated documentation files (the \"Software\"), to deal # in the Software without", "print(dists) # Real neighbours print('\\nReal neighbour distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix,", "# Add rbp as child hash of permutations hash permutations.add_child_hash(rbp_perm, rbp_conf) # Create", "# Real neighbours print('\\nReal neighbour distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix,query) dists", "query.reshape((DIM)) dists = CosineDistance().distance(matrix,query) dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming", "x in results] print(dists) # Real neighbours print('\\nReal neighbour distances:') query = query.reshape((DIM))", "of feature space DIM = 100 # Number of data points (dont do", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #", "child hash of permutations hash permutations2.add_child_hash(rbp_perm2) # Create engine engine_perm2 = Engine(DIM, lshashes=[permutations2],", "BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN", "= RandomBinaryProjections('rbp_perm', 14) rbp_conf = {'num_permutation':50,'beam_size':10,'num_neighbour':100} # Add rbp as child hash of", "sublicense, and/or sell # copies of the Software, and to permit persons to", "Software is # furnished to do so, subject to the following conditions: #", "% (t1-t0)) # Get random query vector query = numpy.random.randn(DIM) # Do random", "Add rbp as child hash of permutations hash permutations2.add_child_hash(rbp_perm2) # Create engine engine_perm2", "# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR", "= 100 # Number of data points (dont do too much because of", "CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT", "engine_perm2.candidate_count(query)) results = engine_perm2.neighbours(query) dists = [x[2] for x in results] print(dists) #", "OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "engine_rbps.store_vector(v) t1 = time.time() print('Indexing took %f seconds' % (t1-t0)) # Get random", "as child hash rbp_perm2 = RandomBinaryProjections('rbp_perm2', 14) # Add rbp as child hash", "for x in results] print(dists) # Real neighbours print('\\nReal neighbour distances:') query =", "# Get random query vector query = numpy.random.randn(DIM) # Do random query on", "Create binary hash as child hash rbp_perm = RandomBinaryProjections('rbp_perm', 14) rbp_conf = {'num_permutation':50,'beam_size':10,'num_neighbour':100}", "permutations.add_child_hash(rbp_perm, rbp_conf) # Create engine engine_perm = Engine(DIM, lshashes=[permutations], distance=CosineDistance()) # First index", "indexing with HashPermutationMapper...') t0 = time.time() # Create permutations meta-hash permutations2 = HashPermutationMapper('permut2')", "i in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_perm2.store_vector(v) t1 = time.time()", "matrix[i] = v engine_rbps.store_vector(v) t1 = time.time() print('Indexing took %f seconds' % (t1-t0))", "Create engine engine_rbps = Engine(DIM, lshashes=hashes, distance=CosineDistance()) # First index some random vectors", "= time.time() # Create permutations meta-hash permutations2 = HashPermutationMapper('permut2') # Create binary hash", "hash of permutations hash permutations2.add_child_hash(rbp_perm2) # Create engine engine_perm2 = Engine(DIM, lshashes=[permutations2], distance=CosineDistance())", "sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with multiple binary hashes...') t0 = time.time() hashes", "# copies of the Software, and to permit persons to whom the Software", "print('\\nNeighbour distances with multiple binary hashes:') print(' -> Candidate count is %d' %", "range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_rbps.store_vector(v) t1 = time.time() print('Indexing took", "14) rbp_conf = {'num_permutation':50,'beam_size':10,'num_neighbour':100} # Add rbp as child hash of permutations hash", "DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR", "multiple binary hashes...') t0 = time.time() hashes = [] for k in range(20):", "Engine(DIM, lshashes=[permutations2], distance=CosineDistance()) # First index some random vectors matrix = numpy.zeros((POINTS,DIM)) for", "-> Candidate count is %d' % engine_perm2.candidate_count(query)) results = engine_perm2.neighbours(query) dists = [x[2]", "-*- # Copyright (c) 2013 <NAME> # Permission is hereby granted, free of", "random vectors matrix = numpy.zeros((POINTS,DIM)) for i in range(POINTS): v = numpy.random.randn(DIM) matrix[i]", "this permission notice shall be included in # all copies or substantial portions", "count is %d' % engine_rbps.candidate_count(query)) results = engine_rbps.neighbours(query) dists = [x[2] for x", "= numpy.zeros((POINTS,DIM)) for i in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_perm.store_vector(v)", "OTHER DEALINGS IN # THE SOFTWARE. import numpy import scipy import unittest import", "CosineDistance().distance(matrix,query) dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with multiple", "NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "Real neighbours print('\\nReal neighbour distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix,query) dists =", "software and associated documentation files (the \"Software\"), to deal # in the Software", "WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT", "query = numpy.random.randn(DIM) # Do random query on engine 3 print('\\nNeighbour distances with", "permutations.build_permuted_index() t1 = time.time() print('Indexing took %f seconds' % (t1-t0)) # Get random", "OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN", "HashPermutations, HashPermutationMapper def example2(): # Dimension of feature space DIM = 100 #", "neighbour distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix,query) dists = dists.reshape((-1,)) dists =", "query) dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with HashPermutationMapper...')", "conditions: # The above copyright notice and this permission notice shall be included", "= [x[2] for x in results] print(dists) # Real neighbours print('\\nReal neighbour distances:')", "and to permit persons to whom the Software is # furnished to do", "use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the", "Do random query on engine 3 print('\\nNeighbour distances with HashPermutations:') print(' -> Candidate", "% engine_perm.candidate_count(query)) results = engine_perm.neighbours(query) dists = [x[2] for x in results] print(dists)", "query vector query = numpy.random.randn(DIM) # Do random query on engine 3 print('\\nNeighbour", "LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND", "DEALINGS IN # THE SOFTWARE. import numpy import scipy import unittest import time", "the Software, and to permit persons to whom the Software is # furnished", "rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #", "took %f seconds' % (t1-t0)) # Get random query vector query = numpy.random.randn(DIM)", "rbp_conf = {'num_permutation':50,'beam_size':10,'num_neighbour':100} # Add rbp as child hash of permutations hash permutations.add_child_hash(rbp_perm,", "= query.reshape((DIM)) dists = CosineDistance().distance(matrix, query) dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10])", "FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF", "random query vector query = numpy.random.randn(DIM) # Do random query on engine 3", "numpy.random.randn(DIM) # Do random query on engine 4 print('\\nNeighbour distances with HashPermutationMapper:') print('", "merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to", "OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING", "ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE", "THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import", "Do random query on engine 4 print('\\nNeighbour distances with HashPermutationMapper:') print(' -> Candidate", "query on engine 4 print('\\nNeighbour distances with HashPermutationMapper:') print(' -> Candidate count is", "dists = CosineDistance().distance(matrix, query) dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming", "hash as child hash rbp_perm2 = RandomBinaryProjections('rbp_perm2', 14) # Add rbp as child", "too much because of exact search) POINTS = 20000 ########################################################## print('Performing indexing with", "lshashes=[permutations2], distance=CosineDistance()) # First index some random vectors matrix = numpy.zeros((POINTS,DIM)) for i", "HashPermutationMapper:') print(' -> Candidate count is %d' % engine_perm2.candidate_count(query)) results = engine_perm2.neighbours(query) dists", "RandomBinaryProjections, HashPermutations, HashPermutationMapper def example2(): # Dimension of feature space DIM = 100", "whom the Software is # furnished to do so, subject to the following", "-> Candidate count is %d' % engine_perm.candidate_count(query)) results = engine_perm.neighbours(query) dists = [x[2]", "# Do random query on engine 4 print('\\nNeighbour distances with HashPermutationMapper:') print(' ->", "CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH", "example2(): # Dimension of feature space DIM = 100 # Number of data", "v = numpy.random.randn(DIM) matrix[i] = v engine_perm2.store_vector(v) t1 = time.time() print('Indexing took %f", "free of charge, to any person obtaining a copy # of this software", "= time.time() hashes = [] for k in range(20): hashes.append(RandomBinaryProjections('rbp_%d' % k, 10))", "Software. # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT", "copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software,", "import unittest import time from nearpy import Engine from nearpy.distances import CosineDistance from", "because of exact search) POINTS = 20000 ########################################################## print('Performing indexing with HashPermutations...') t0", "= 20000 ########################################################## print('Performing indexing with HashPermutations...') t0 = time.time() # Create permutations", "time.time() hashes = [] for k in range(20): hashes.append(RandomBinaryProjections('rbp_%d' % k, 10)) #", "print(' -> Candidate count is %d' % engine_perm2.candidate_count(query)) results = engine_perm2.neighbours(query) dists =", "without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense,", "Engine(DIM, lshashes=[permutations], distance=CosineDistance()) # First index some random vectors matrix = numpy.zeros((POINTS,DIM)) for", "rbp_perm2 = RandomBinaryProjections('rbp_perm2', 14) # Add rbp as child hash of permutations hash", "to deal # in the Software without restriction, including without limitation the rights", "to any person obtaining a copy # of this software and associated documentation", "permutations = HashPermutations('permut') # Create binary hash as child hash rbp_perm = RandomBinaryProjections('rbp_perm',", "4 print('\\nNeighbour distances with HashPermutationMapper:') print(' -> Candidate count is %d' % engine_perm2.candidate_count(query))", "is %d' % engine_perm.candidate_count(query)) results = engine_perm.neighbours(query) dists = [x[2] for x in", "= CosineDistance().distance(matrix,query) dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with", "= dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with HashPermutationMapper...') t0 =", "########################################################## print('Performing indexing with HashPermutations...') t0 = time.time() # Create permutations meta-hash permutations", "permission notice shall be included in # all copies or substantial portions of", "sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with HashPermutationMapper...') t0 = time.time() # Create permutations", "i in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_rbps.store_vector(v) t1 = time.time()", "coding: utf-8 -*- # Copyright (c) 2013 <NAME> # Permission is hereby granted,", "OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #", "Create permutations meta-hash permutations2 = HashPermutationMapper('permut2') # Create binary hash as child hash", "(c) 2013 <NAME> # Permission is hereby granted, free of charge, to any", "THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN", "engine_perm2 = Engine(DIM, lshashes=[permutations2], distance=CosineDistance()) # First index some random vectors matrix =", "HashPermutationMapper('permut2') # Create binary hash as child hash rbp_perm2 = RandomBinaryProjections('rbp_perm2', 14) #", "OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import numpy import", "index permutations.build_permuted_index() t1 = time.time() print('Indexing took %f seconds' % (t1-t0)) # Get", "binary hash as child hash rbp_perm = RandomBinaryProjections('rbp_perm', 14) rbp_conf = {'num_permutation':50,'beam_size':10,'num_neighbour':100} #", "# Create binary hash as child hash rbp_perm2 = RandomBinaryProjections('rbp_perm2', 14) # Add", "= HashPermutations('permut') # Create binary hash as child hash rbp_perm = RandomBinaryProjections('rbp_perm', 14)", "= query.reshape((DIM)) dists = CosineDistance().distance(matrix,query) dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ##########################################################", "OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE", "time.time() print('Indexing took %f seconds' % (t1-t0)) # Get random query vector query", "t0 = time.time() hashes = [] for k in range(20): hashes.append(RandomBinaryProjections('rbp_%d' % k,", "%f seconds' % (t1-t0)) # Get random query vector query = numpy.random.randn(DIM) #", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #", "SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES", "query = numpy.random.randn(DIM) # Do random query on engine 4 print('\\nNeighbour distances with", "% engine_rbps.candidate_count(query)) results = engine_rbps.neighbours(query) dists = [x[2] for x in results] print(dists)", "with HashPermutations:') print(' -> Candidate count is %d' % engine_perm.candidate_count(query)) results = engine_perm.neighbours(query)", "# Create permutations meta-hash permutations = HashPermutations('permut') # Create binary hash as child", "permutations meta-hash permutations = HashPermutations('permut') # Create binary hash as child hash rbp_perm", "import CosineDistance from nearpy.hashes import RandomBinaryProjections, HashPermutations, HashPermutationMapper def example2(): # Dimension of", "dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with multiple binary hashes...') t0", "Software, and to permit persons to whom the Software is # furnished to", "engine_rbps.neighbours(query) dists = [x[2] for x in results] print(dists) # Real neighbours print('\\nReal", "nearpy.hashes import RandomBinaryProjections, HashPermutations, HashPermutationMapper def example2(): # Dimension of feature space DIM", "# Do random query on engine 3 print('\\nNeighbour distances with HashPermutations:') print(' ->", "engine_perm2.neighbours(query) dists = [x[2] for x in results] print(dists) # Real neighbours print('\\nReal", "= v engine_perm.store_vector(v) # Then update permuted index permutations.build_permuted_index() t1 = time.time() print('Indexing", "from nearpy.distances import CosineDistance from nearpy.hashes import RandomBinaryProjections, HashPermutations, HashPermutationMapper def example2(): #", "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE.", "# Dimension of feature space DIM = 100 # Number of data points", "the Software. # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "[x[2] for x in results] print(dists) # Real neighbours print('\\nReal neighbour distances:') query", "= numpy.random.randn(DIM) matrix[i] = v engine_perm2.store_vector(v) t1 = time.time() print('Indexing took %f seconds'", "matrix[i] = v engine_perm.store_vector(v) # Then update permuted index permutations.build_permuted_index() t1 = time.time()", "unittest import time from nearpy import Engine from nearpy.distances import CosineDistance from nearpy.hashes", "this software and associated documentation files (the \"Software\"), to deal # in the", "= numpy.zeros((POINTS,DIM)) for i in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_perm2.store_vector(v)", "########################################################## print('\\nPerforming indexing with HashPermutationMapper...') t0 = time.time() # Create permutations meta-hash permutations2", "numpy.zeros((POINTS,DIM)) for i in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_rbps.store_vector(v) t1", "# THE SOFTWARE. import numpy import scipy import unittest import time from nearpy", "time from nearpy import Engine from nearpy.distances import CosineDistance from nearpy.hashes import RandomBinaryProjections,", "matrix = numpy.zeros((POINTS,DIM)) for i in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v", "update permuted index permutations.build_permuted_index() t1 = time.time() print('Indexing took %f seconds' % (t1-t0))", "shall be included in # all copies or substantial portions of the Software.", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,", "%d' % engine_perm2.candidate_count(query)) results = engine_perm2.neighbours(query) dists = [x[2] for x in results]", "distances with multiple binary hashes:') print(' -> Candidate count is %d' % engine_rbps.candidate_count(query))", "Engine(DIM, lshashes=hashes, distance=CosineDistance()) # First index some random vectors matrix = numpy.zeros((POINTS,DIM)) for", "granted, free of charge, to any person obtaining a copy # of this", "numpy.random.randn(DIM) # Do random query on engine 3 print('\\nNeighbour distances with HashPermutations:') print('", "Create permutations meta-hash permutations = HashPermutations('permut') # Create binary hash as child hash", "modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and", "ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "DIM = 100 # Number of data points (dont do too much because", "# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "# Permission is hereby granted, free of charge, to any person obtaining a", "print('Indexing took %f seconds' % (t1-t0)) # Get random query vector query =", "nearpy import Engine from nearpy.distances import CosineDistance from nearpy.hashes import RandomBinaryProjections, HashPermutations, HashPermutationMapper", "= Engine(DIM, lshashes=hashes, distance=CosineDistance()) # First index some random vectors matrix = numpy.zeros((POINTS,DIM))", "query on engine 4 print('\\nNeighbour distances with multiple binary hashes:') print(' -> Candidate", "-*- coding: utf-8 -*- # Copyright (c) 2013 <NAME> # Permission is hereby", "for i in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_perm.store_vector(v) # Then", "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF", "with multiple binary hashes...') t0 = time.time() hashes = [] for k in", "publish, distribute, sublicense, and/or sell # copies of the Software, and to permit", "%d' % engine_rbps.candidate_count(query)) results = engine_rbps.neighbours(query) dists = [x[2] for x in results]", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT", "child hash rbp_perm = RandomBinaryProjections('rbp_perm', 14) rbp_conf = {'num_permutation':50,'beam_size':10,'num_neighbour':100} # Add rbp as", "engine engine_perm = Engine(DIM, lshashes=[permutations], distance=CosineDistance()) # First index some random vectors matrix", "binary hashes:') print(' -> Candidate count is %d' % engine_rbps.candidate_count(query)) results = engine_rbps.neighbours(query)", "v engine_perm.store_vector(v) # Then update permuted index permutations.build_permuted_index() t1 = time.time() print('Indexing took", "be included in # all copies or substantial portions of the Software. #", "range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_perm2.store_vector(v) t1 = time.time() print('Indexing took", "binary hashes...') t0 = time.time() hashes = [] for k in range(20): hashes.append(RandomBinaryProjections('rbp_%d'", "OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION", "without restriction, including without limitation the rights # to use, copy, modify, merge,", "distances with HashPermutationMapper:') print(' -> Candidate count is %d' % engine_perm2.candidate_count(query)) results =", "following conditions: # The above copyright notice and this permission notice shall be", "multiple binary hashes:') print(' -> Candidate count is %d' % engine_rbps.candidate_count(query)) results =", "search) POINTS = 20000 ########################################################## print('Performing indexing with HashPermutations...') t0 = time.time() #", "% engine_perm2.candidate_count(query)) results = engine_perm2.neighbours(query) dists = [x[2] for x in results] print(dists)", "utf-8 -*- # Copyright (c) 2013 <NAME> # Permission is hereby granted, free", "in the Software without restriction, including without limitation the rights # to use,", "# Number of data points (dont do too much because of exact search)", "time.time() # Create permutations meta-hash permutations = HashPermutations('permut') # Create binary hash as", "the following conditions: # The above copyright notice and this permission notice shall", "scipy import unittest import time from nearpy import Engine from nearpy.distances import CosineDistance", "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS", "much because of exact search) POINTS = 20000 ########################################################## print('Performing indexing with HashPermutations...')", "hashes.append(RandomBinaryProjections('rbp_%d' % k, 10)) # Create engine engine_rbps = Engine(DIM, lshashes=hashes, distance=CosineDistance()) #", "copies of the Software, and to permit persons to whom the Software is", "Dimension of feature space DIM = 100 # Number of data points (dont", "HashPermutations('permut') # Create binary hash as child hash rbp_perm = RandomBinaryProjections('rbp_perm', 14) rbp_conf", "hash permutations.add_child_hash(rbp_perm, rbp_conf) # Create engine engine_perm = Engine(DIM, lshashes=[permutations], distance=CosineDistance()) # First", "Engine from nearpy.distances import CosineDistance from nearpy.hashes import RandomBinaryProjections, HashPermutations, HashPermutationMapper def example2():", "RandomBinaryProjections('rbp_perm', 14) rbp_conf = {'num_permutation':50,'beam_size':10,'num_neighbour':100} # Add rbp as child hash of permutations", "index some random vectors matrix = numpy.zeros((POINTS,DIM)) for i in range(POINTS): v =", "as child hash of permutations hash permutations2.add_child_hash(rbp_perm2) # Create engine engine_perm2 = Engine(DIM,", "hashes...') t0 = time.time() hashes = [] for k in range(20): hashes.append(RandomBinaryProjections('rbp_%d' %", "data points (dont do too much because of exact search) POINTS = 20000", "= engine_perm.neighbours(query) dists = [x[2] for x in results] print(dists) # Real neighbours", "CosineDistance().distance(matrix, query) dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with", "import scipy import unittest import time from nearpy import Engine from nearpy.distances import", "Create engine engine_perm = Engine(DIM, lshashes=[permutations], distance=CosineDistance()) # First index some random vectors", "AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR", "numpy.random.randn(DIM) matrix[i] = v engine_perm2.store_vector(v) t1 = time.time() print('Indexing took %f seconds' %", "permutations hash permutations.add_child_hash(rbp_perm, rbp_conf) # Create engine engine_perm = Engine(DIM, lshashes=[permutations], distance=CosineDistance()) #", "Create binary hash as child hash rbp_perm2 = RandomBinaryProjections('rbp_perm2', 14) # Add rbp", "Add rbp as child hash of permutations hash permutations.add_child_hash(rbp_perm, rbp_conf) # Create engine", "# Then update permuted index permutations.build_permuted_index() t1 = time.time() print('Indexing took %f seconds'", "query.reshape((DIM)) dists = CosineDistance().distance(matrix, query) dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ##########################################################", "= HashPermutationMapper('permut2') # Create binary hash as child hash rbp_perm2 = RandomBinaryProjections('rbp_perm2', 14)", "obtaining a copy # of this software and associated documentation files (the \"Software\"),", "= engine_rbps.neighbours(query) dists = [x[2] for x in results] print(dists) # Real neighbours", "NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE", "HashPermutationMapper def example2(): # Dimension of feature space DIM = 100 # Number", "print(' -> Candidate count is %d' % engine_rbps.candidate_count(query)) results = engine_rbps.neighbours(query) dists =", "MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL", "permutations meta-hash permutations2 = HashPermutationMapper('permut2') # Create binary hash as child hash rbp_perm2", "dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with multiple binary", "and/or sell # copies of the Software, and to permit persons to whom", "distances with HashPermutations:') print(' -> Candidate count is %d' % engine_perm.candidate_count(query)) results =", "on engine 3 print('\\nNeighbour distances with HashPermutations:') print(' -> Candidate count is %d'", "= engine_perm2.neighbours(query) dists = [x[2] for x in results] print(dists) # Real neighbours", "dists = CosineDistance().distance(matrix,query) dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing", "# Copyright (c) 2013 <NAME> # Permission is hereby granted, free of charge,", "engine_rbps = Engine(DIM, lshashes=hashes, distance=CosineDistance()) # First index some random vectors matrix =", "child hash of permutations hash permutations.add_child_hash(rbp_perm, rbp_conf) # Create engine engine_perm = Engine(DIM,", "3 print('\\nNeighbour distances with HashPermutations:') print(' -> Candidate count is %d' % engine_perm.candidate_count(query))", "# in the Software without restriction, including without limitation the rights # to", "copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED \"AS", "v engine_perm2.store_vector(v) t1 = time.time() print('Indexing took %f seconds' % (t1-t0)) # Get", "v engine_rbps.store_vector(v) t1 = time.time() print('Indexing took %f seconds' % (t1-t0)) # Get", "permutations2.add_child_hash(rbp_perm2) # Create engine engine_perm2 = Engine(DIM, lshashes=[permutations2], distance=CosineDistance()) # First index some", "TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE", "meta-hash permutations2 = HashPermutationMapper('permut2') # Create binary hash as child hash rbp_perm2 =", "IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #", "print('Performing indexing with HashPermutations...') t0 = time.time() # Create permutations meta-hash permutations =", "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS", "= numpy.random.randn(DIM) # Do random query on engine 3 print('\\nNeighbour distances with HashPermutations:')", "vector query = numpy.random.randn(DIM) # Do random query on engine 4 print('\\nNeighbour distances", "# all copies or substantial portions of the Software. # THE SOFTWARE IS", "hash rbp_perm = RandomBinaryProjections('rbp_perm', 14) rbp_conf = {'num_permutation':50,'beam_size':10,'num_neighbour':100} # Add rbp as child", "any person obtaining a copy # of this software and associated documentation files", "print(dists[:10]) ########################################################## print('\\nPerforming indexing with HashPermutationMapper...') t0 = time.time() # Create permutations meta-hash", "= numpy.zeros((POINTS,DIM)) for i in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_rbps.store_vector(v)", "is %d' % engine_perm2.candidate_count(query)) results = engine_perm2.neighbours(query) dists = [x[2] for x in", "in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_rbps.store_vector(v) t1 = time.time() print('Indexing", "engine_perm2.store_vector(v) t1 = time.time() print('Indexing took %f seconds' % (t1-t0)) # Get random", "numpy.random.randn(DIM) matrix[i] = v engine_rbps.store_vector(v) t1 = time.time() print('Indexing took %f seconds' %", "rbp as child hash of permutations hash permutations.add_child_hash(rbp_perm, rbp_conf) # Create engine engine_perm", "time.time() # Create permutations meta-hash permutations2 = HashPermutationMapper('permut2') # Create binary hash as", "Candidate count is %d' % engine_perm2.candidate_count(query)) results = engine_perm2.neighbours(query) dists = [x[2] for", "\"Software\"), to deal # in the Software without restriction, including without limitation the", "space DIM = 100 # Number of data points (dont do too much", "print('\\nNeighbour distances with HashPermutationMapper:') print(' -> Candidate count is %d' % engine_perm2.candidate_count(query)) results", "rbp_perm = RandomBinaryProjections('rbp_perm', 14) rbp_conf = {'num_permutation':50,'beam_size':10,'num_neighbour':100} # Add rbp as child hash", "results] print(dists) # Real neighbours print('\\nReal neighbour distances:') query = query.reshape((DIM)) dists =", "= [] for k in range(20): hashes.append(RandomBinaryProjections('rbp_%d' % k, 10)) # Create engine", "# Create permutations meta-hash permutations2 = HashPermutationMapper('permut2') # Create binary hash as child", "seconds' % (t1-t0)) # Get random query vector query = numpy.random.randn(DIM) # Do", "copyright notice and this permission notice shall be included in # all copies", "with HashPermutationMapper:') print(' -> Candidate count is %d' % engine_perm2.candidate_count(query)) results = engine_perm2.neighbours(query)", "AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,", "a copy # of this software and associated documentation files (the \"Software\"), to", "deal # in the Software without restriction, including without limitation the rights #", "with HashPermutations...') t0 = time.time() # Create permutations meta-hash permutations = HashPermutations('permut') #", "count is %d' % engine_perm.candidate_count(query)) results = engine_perm.neighbours(query) dists = [x[2] for x", "matrix[i] = v engine_perm2.store_vector(v) t1 = time.time() print('Indexing took %f seconds' % (t1-t0))", "hash rbp_perm2 = RandomBinaryProjections('rbp_perm2', 14) # Add rbp as child hash of permutations", "# -*- coding: utf-8 -*- # Copyright (c) 2013 <NAME> # Permission is", "(t1-t0)) # Get random query vector query = numpy.random.randn(DIM) # Do random query", "numpy.zeros((POINTS,DIM)) for i in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_perm.store_vector(v) #", "import Engine from nearpy.distances import CosineDistance from nearpy.hashes import RandomBinaryProjections, HashPermutations, HashPermutationMapper def", "lshashes=[permutations], distance=CosineDistance()) # First index some random vectors matrix = numpy.zeros((POINTS,DIM)) for i", "dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with HashPermutationMapper...') t0", "print('\\nReal neighbour distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix, query) dists = dists.reshape((-1,))", "RandomBinaryProjections('rbp_perm2', 14) # Add rbp as child hash of permutations hash permutations2.add_child_hash(rbp_perm2) #", "distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix,query) dists = dists.reshape((-1,)) dists = sorted(dists)", "engine 3 print('\\nNeighbour distances with HashPermutations:') print(' -> Candidate count is %d' %", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #", "(the \"Software\"), to deal # in the Software without restriction, including without limitation", "IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix, query) dists = dists.reshape((-1,)) dists =", "Copyright (c) 2013 <NAME> # Permission is hereby granted, free of charge, to", "distribute, sublicense, and/or sell # copies of the Software, and to permit persons", "v = numpy.random.randn(DIM) matrix[i] = v engine_rbps.store_vector(v) t1 = time.time() print('Indexing took %f", "in results] print(dists) # Real neighbours print('\\nReal neighbour distances:') query = query.reshape((DIM)) dists", "charge, to any person obtaining a copy # of this software and associated", "WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO", "dists = [x[2] for x in results] print(dists) # Real neighbours print('\\nReal neighbour", "# Do random query on engine 4 print('\\nNeighbour distances with multiple binary hashes:')", "feature space DIM = 100 # Number of data points (dont do too", "HashPermutations:') print(' -> Candidate count is %d' % engine_perm.candidate_count(query)) results = engine_perm.neighbours(query) dists", "= CosineDistance().distance(matrix, query) dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing", "WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO", "-> Candidate count is %d' % engine_rbps.candidate_count(query)) results = engine_rbps.neighbours(query) dists = [x[2]", "WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED", "KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "to whom the Software is # furnished to do so, subject to the", "limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or", "random query on engine 3 print('\\nNeighbour distances with HashPermutations:') print(' -> Candidate count", "from nearpy.hashes import RandomBinaryProjections, HashPermutations, HashPermutationMapper def example2(): # Dimension of feature space", "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER", "engine engine_perm2 = Engine(DIM, lshashes=[permutations2], distance=CosineDistance()) # First index some random vectors matrix", "k in range(20): hashes.append(RandomBinaryProjections('rbp_%d' % k, 10)) # Create engine engine_rbps = Engine(DIM,", "% k, 10)) # Create engine engine_rbps = Engine(DIM, lshashes=hashes, distance=CosineDistance()) # First", "import time from nearpy import Engine from nearpy.distances import CosineDistance from nearpy.hashes import", "########################################################## print('\\nPerforming indexing with multiple binary hashes...') t0 = time.time() hashes = []", "in range(20): hashes.append(RandomBinaryProjections('rbp_%d' % k, 10)) # Create engine engine_rbps = Engine(DIM, lshashes=hashes,", "= Engine(DIM, lshashes=[permutations2], distance=CosineDistance()) # First index some random vectors matrix = numpy.zeros((POINTS,DIM))", "import numpy import scipy import unittest import time from nearpy import Engine from", "engine engine_rbps = Engine(DIM, lshashes=hashes, distance=CosineDistance()) # First index some random vectors matrix", "= v engine_rbps.store_vector(v) t1 = time.time() print('Indexing took %f seconds' % (t1-t0)) #", "of the Software. # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "query = query.reshape((DIM)) dists = CosineDistance().distance(matrix, query) dists = dists.reshape((-1,)) dists = sorted(dists)", "print('\\nPerforming indexing with multiple binary hashes...') t0 = time.time() hashes = [] for", "random query vector query = numpy.random.randn(DIM) # Do random query on engine 4", "IN # THE SOFTWARE. import numpy import scipy import unittest import time from", "THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR", "v = numpy.random.randn(DIM) matrix[i] = v engine_perm.store_vector(v) # Then update permuted index permutations.build_permuted_index()", "2013 <NAME> # Permission is hereby granted, free of charge, to any person", "# furnished to do so, subject to the following conditions: # The above", "some random vectors matrix = numpy.zeros((POINTS,DIM)) for i in range(POINTS): v = numpy.random.randn(DIM)", "permit persons to whom the Software is # furnished to do so, subject", "child hash rbp_perm2 = RandomBinaryProjections('rbp_perm2', 14) # Add rbp as child hash of", "THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import numpy import scipy", "Permission is hereby granted, free of charge, to any person obtaining a copy", "neighbour distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix, query) dists = dists.reshape((-1,)) dists", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT", "dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with multiple binary hashes...') t0 =", "EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,", "Software without restriction, including without limitation the rights # to use, copy, modify,", "print(' -> Candidate count is %d' % engine_perm.candidate_count(query)) results = engine_perm.neighbours(query) dists =", "print(dists) # Real neighbours print('\\nReal neighbour distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix,query)", "furnished to do so, subject to the following conditions: # The above copyright", "with multiple binary hashes:') print(' -> Candidate count is %d' % engine_rbps.candidate_count(query)) results", "substantial portions of the Software. # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "count is %d' % engine_perm2.candidate_count(query)) results = engine_perm2.neighbours(query) dists = [x[2] for x", "Candidate count is %d' % engine_rbps.candidate_count(query)) results = engine_rbps.neighbours(query) dists = [x[2] for", "portions of the Software. # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", "neighbours print('\\nReal neighbour distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix, query) dists =", "= numpy.random.randn(DIM) # Do random query on engine 4 print('\\nNeighbour distances with HashPermutationMapper:')", "SOFTWARE. import numpy import scipy import unittest import time from nearpy import Engine", "query on engine 3 print('\\nNeighbour distances with HashPermutations:') print(' -> Candidate count is", "Then update permuted index permutations.build_permuted_index() t1 = time.time() print('Indexing took %f seconds' %", "# The above copyright notice and this permission notice shall be included in", "# of this software and associated documentation files (the \"Software\"), to deal #", "OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR", "or substantial portions of the Software. # THE SOFTWARE IS PROVIDED \"AS IS\",", "query = query.reshape((DIM)) dists = CosineDistance().distance(matrix,query) dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10])", "= sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with multiple binary hashes...') t0 = time.time()", "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE", "meta-hash permutations = HashPermutations('permut') # Create binary hash as child hash rbp_perm =", "sell # copies of the Software, and to permit persons to whom the", "results = engine_perm2.neighbours(query) dists = [x[2] for x in results] print(dists) # Real", "lshashes=hashes, distance=CosineDistance()) # First index some random vectors matrix = numpy.zeros((POINTS,DIM)) for i", "hash as child hash rbp_perm = RandomBinaryProjections('rbp_perm', 14) rbp_conf = {'num_permutation':50,'beam_size':10,'num_neighbour':100} # Add", "engine_perm.store_vector(v) # Then update permuted index permutations.build_permuted_index() t1 = time.time() print('Indexing took %f", "print('\\nPerforming indexing with HashPermutationMapper...') t0 = time.time() # Create permutations meta-hash permutations2 =", "hashes = [] for k in range(20): hashes.append(RandomBinaryProjections('rbp_%d' % k, 10)) # Create", "Candidate count is %d' % engine_perm.candidate_count(query)) results = engine_perm.neighbours(query) dists = [x[2] for", "SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import numpy", "100 # Number of data points (dont do too much because of exact", "= sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with HashPermutationMapper...') t0 = time.time() # Create", "as child hash of permutations hash permutations.add_child_hash(rbp_perm, rbp_conf) # Create engine engine_perm =", "restriction, including without limitation the rights # to use, copy, modify, merge, publish,", "permuted index permutations.build_permuted_index() t1 = time.time() print('Indexing took %f seconds' % (t1-t0)) #", "= v engine_perm2.store_vector(v) t1 = time.time() print('Indexing took %f seconds' % (t1-t0)) #", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS", "t0 = time.time() # Create permutations meta-hash permutations2 = HashPermutationMapper('permut2') # Create binary", "t0 = time.time() # Create permutations meta-hash permutations = HashPermutations('permut') # Create binary", "of data points (dont do too much because of exact search) POINTS =", "BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR", "<NAME> # Permission is hereby granted, free of charge, to any person obtaining", "def example2(): # Dimension of feature space DIM = 100 # Number of", "numpy import scipy import unittest import time from nearpy import Engine from nearpy.distances", "in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_perm.store_vector(v) # Then update permuted", "FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE", "OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING", "HashPermutationMapper...') t0 = time.time() # Create permutations meta-hash permutations2 = HashPermutationMapper('permut2') # Create", "= RandomBinaryProjections('rbp_perm2', 14) # Add rbp as child hash of permutations hash permutations2.add_child_hash(rbp_perm2)", "Real neighbours print('\\nReal neighbour distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix, query) dists", "files (the \"Software\"), to deal # in the Software without restriction, including without", "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS", "do too much because of exact search) POINTS = 20000 ########################################################## print('Performing indexing", "engine_perm.candidate_count(query)) results = engine_perm.neighbours(query) dists = [x[2] for x in results] print(dists) #", "for i in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_perm2.store_vector(v) t1 =", "engine 4 print('\\nNeighbour distances with multiple binary hashes:') print(' -> Candidate count is", "the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "CosineDistance from nearpy.hashes import RandomBinaryProjections, HashPermutations, HashPermutationMapper def example2(): # Dimension of feature", "engine 4 print('\\nNeighbour distances with HashPermutationMapper:') print(' -> Candidate count is %d' %", "of the Software, and to permit persons to whom the Software is #", "numpy.random.randn(DIM) matrix[i] = v engine_perm.store_vector(v) # Then update permuted index permutations.build_permuted_index() t1 =", "# Create engine engine_perm2 = Engine(DIM, lshashes=[permutations2], distance=CosineDistance()) # First index some random", "First index some random vectors matrix = numpy.zeros((POINTS,DIM)) for i in range(POINTS): v", "so, subject to the following conditions: # The above copyright notice and this", "The above copyright notice and this permission notice shall be included in #", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR", "OR OTHER DEALINGS IN # THE SOFTWARE. import numpy import scipy import unittest", "10)) # Create engine engine_rbps = Engine(DIM, lshashes=hashes, distance=CosineDistance()) # First index some", "= numpy.random.randn(DIM) matrix[i] = v engine_rbps.store_vector(v) t1 = time.time() print('Indexing took %f seconds'", "print(dists[:10]) ########################################################## print('\\nPerforming indexing with multiple binary hashes...') t0 = time.time() hashes =", "on engine 4 print('\\nNeighbour distances with HashPermutationMapper:') print(' -> Candidate count is %d'", "import RandomBinaryProjections, HashPermutations, HashPermutationMapper def example2(): # Dimension of feature space DIM =", "# Add rbp as child hash of permutations hash permutations2.add_child_hash(rbp_perm2) # Create engine", "= {'num_permutation':50,'beam_size':10,'num_neighbour':100} # Add rbp as child hash of permutations hash permutations.add_child_hash(rbp_perm, rbp_conf)", "indexing with HashPermutations...') t0 = time.time() # Create permutations meta-hash permutations = HashPermutations('permut')", "numpy.random.randn(DIM) # Do random query on engine 4 print('\\nNeighbour distances with multiple binary", "[] for k in range(20): hashes.append(RandomBinaryProjections('rbp_%d' % k, 10)) # Create engine engine_rbps", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER", "HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN", "including without limitation the rights # to use, copy, modify, merge, publish, distribute,", "distance=CosineDistance()) # First index some random vectors matrix = numpy.zeros((POINTS,DIM)) for i in", "query vector query = numpy.random.randn(DIM) # Do random query on engine 4 print('\\nNeighbour", "permutations hash permutations2.add_child_hash(rbp_perm2) # Create engine engine_perm2 = Engine(DIM, lshashes=[permutations2], distance=CosineDistance()) # First", "in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_perm2.store_vector(v) t1 = time.time() print('Indexing", "included in # all copies or substantial portions of the Software. # THE", "# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_perm.store_vector(v) # Then update permuted index", "nearpy.distances import CosineDistance from nearpy.hashes import RandomBinaryProjections, HashPermutations, HashPermutationMapper def example2(): # Dimension", "= Engine(DIM, lshashes=[permutations], distance=CosineDistance()) # First index some random vectors matrix = numpy.zeros((POINTS,DIM))", "engine_perm.neighbours(query) dists = [x[2] for x in results] print(dists) # Real neighbours print('\\nReal", "associated documentation files (the \"Software\"), to deal # in the Software without restriction,", "USE OR OTHER DEALINGS IN # THE SOFTWARE. import numpy import scipy import", "for k in range(20): hashes.append(RandomBinaryProjections('rbp_%d' % k, 10)) # Create engine engine_rbps =", "hereby granted, free of charge, to any person obtaining a copy # of", "of this software and associated documentation files (the \"Software\"), to deal # in", "OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS", "{'num_permutation':50,'beam_size':10,'num_neighbour':100} # Add rbp as child hash of permutations hash permutations.add_child_hash(rbp_perm, rbp_conf) #", "notice shall be included in # all copies or substantial portions of the", "(dont do too much because of exact search) POINTS = 20000 ########################################################## print('Performing", "engine_perm = Engine(DIM, lshashes=[permutations], distance=CosineDistance()) # First index some random vectors matrix =", "t1 = time.time() print('Indexing took %f seconds' % (t1-t0)) # Get random query", "vector query = numpy.random.randn(DIM) # Do random query on engine 3 print('\\nNeighbour distances", "of permutations hash permutations2.add_child_hash(rbp_perm2) # Create engine engine_perm2 = Engine(DIM, lshashes=[permutations2], distance=CosineDistance()) #", "NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with HashPermutationMapper...') t0 = time.time()", "all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of", "exact search) POINTS = 20000 ########################################################## print('Performing indexing with HashPermutations...') t0 = time.time()", "14) # Add rbp as child hash of permutations hash permutations2.add_child_hash(rbp_perm2) # Create", "the Software is # furnished to do so, subject to the following conditions:", "Get random query vector query = numpy.random.randn(DIM) # Do random query on engine", "do so, subject to the following conditions: # The above copyright notice and", "random query on engine 4 print('\\nNeighbour distances with HashPermutationMapper:') print(' -> Candidate count" ]
[ "print(discord.__version__) # discord.pyのバージョン print('----------------') print('Hello World !!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms')) conn=r.connect() ky=conn.keys()", "discord.pyのバージョン print('----------------') print('Hello World !!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms')) conn=r.connect() ky=conn.keys() global_ch=\"gloch\" count=0", "1000:.0f}ms')) conn=r.connect() ky=conn.keys() global_ch=\"gloch\" count=0 for i in ky: i=str(i) if i ==", "p=conn.sadd(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") class JapaneseHelpCommand(commands.DefaultHelpCommand): def __init__(self): super().__init__() self.commands_heading =", "else: print(ky) else: p=conn.sadd(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") class JapaneseHelpCommand(commands.DefaultHelpCommand): def __init__(self):", "# Bot Commands Frameworkをインポート import traceback # エラー表示のためにインポート import os import discord import", "traceback.print_exc() # Botの準備完了時に呼び出されるイベント async def on_ready(self): print(self.user.name) # ボットの名前 print(self.user.id) # ボットのID print(discord.__version__)", "print(\"異常発生\") else: print(ky) else: p=conn.sadd(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") class JapaneseHelpCommand(commands.DefaultHelpCommand): def", "# 読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS = [ 'cogs.eval', 'cogs.glchat', 'cogs.gladd', 'cogs.gldel' ] # クラスの定義。ClientのサブクラスであるBotクラスを継承。 class", "Botの準備完了時に呼び出されるイベント async def on_ready(self): print(self.user.name) # ボットの名前 print(self.user.id) # ボットのID print(discord.__version__) # discord.pyのバージョン", "Commands Frameworkをインポート import traceback # エラー表示のためにインポート import os import discord import r TOKEN", "# discord.pyのバージョン print('----------------') print('Hello World !!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms')) conn=r.connect() ky=conn.keys() global_ch=\"gloch\"", "ky: i=str(i) if i == global_ch: count+=1 if count>0: smsd=conn.smembers(global_ch) count=0 for q", "# クラスの定義。ClientのサブクラスであるBotクラスを継承。 class MyBot(commands.Bot): # MyBotのコンストラクタ。 def __init__(self, command_prefix, help_command): # スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command)", "super().__init__(command_prefix,help_command) # INITIAL_COGSに格納されている名前から、コグを読み込む。 # エラーが発生した場合は、エラー内容を表示。 for cog in INITIAL_EXTENSIONS: try: self.load_extension(cog) except Exception:", "print(self.user.id) # ボットのID print(discord.__version__) # discord.pyのバージョン print('----------------') print('Hello World !!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency *", "os.environ['DISCORD_BOT_PREFIX'] #プレフィックス # 読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS = [ 'cogs.eval', 'cogs.glchat', 'cogs.gladd', 'cogs.gldel' ] #", "INITIAL_EXTENSIONS = [ 'cogs.eval', 'cogs.glchat', 'cogs.gladd', 'cogs.gldel' ] # クラスの定義。ClientのサブクラスであるBotクラスを継承。 class MyBot(commands.Bot): #", "__init__(self, command_prefix, help_command): # スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command) # INITIAL_COGSに格納されている名前から、コグを読み込む。 # エラーが発生した場合は、エラー内容を表示。 for cog in", "cog in INITIAL_EXTENSIONS: try: self.load_extension(cog) except Exception: traceback.print_exc() # Botの準備完了時に呼び出されるイベント async def on_ready(self):", "<カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。 if __name__ == '__main__': bot = MyBot(command_prefix=prefix,help_command=JapaneseHelpCommand()) # command_prefixはコマンドの最初の文字として使うもの。 e.g. !ping", "import traceback # エラー表示のためにインポート import os import discord import r TOKEN = os.environ['DISCORD_BOT_TOKEN']", "p=conn.srem(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") else: print(ky) else: p=conn.sadd(global_ch,\"0\") if p==True: print(\"正常起動\")", "__name__ == '__main__': bot = MyBot(command_prefix=prefix,help_command=JapaneseHelpCommand()) # command_prefixはコマンドの最初の文字として使うもの。 e.g. !ping bot.run(TOKEN) # Botのトークン", "ボットの名前 print(self.user.id) # ボットのID print(discord.__version__) # discord.pyのバージョン print('----------------') print('Hello World !!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency", "if count>0: smsd=conn.smembers(global_ch) count=0 for q in smsd: q=str(q) if q==\"0\": count+=1 if", "def __init__(self): super().__init__() self.commands_heading = \"コマンド:\" self.no_category = \"その他\" self.command_attrs[\"help\"] = \"コマンド一覧と簡単な説明を表示\" def", "<コマンド名>\\n\" f\"各カテゴリの説明: {prefix}help <カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。 if __name__ == '__main__': bot = MyBot(command_prefix=prefix,help_command=JapaneseHelpCommand()) #", "{prefix}help <コマンド名>\\n\" f\"各カテゴリの説明: {prefix}help <カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。 if __name__ == '__main__': bot = MyBot(command_prefix=prefix,help_command=JapaneseHelpCommand())", "p==True: print(\"正常起動\") else: print(\"異常発生\") else: print(ky) else: p=conn.sadd(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\")", "on_ready(self): print(self.user.name) # ボットの名前 print(self.user.id) # ボットのID print(discord.__version__) # discord.pyのバージョン print('----------------') print('Hello World", "else: print(\"異常発生\") else: print(ky) else: p=conn.sadd(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") class JapaneseHelpCommand(commands.DefaultHelpCommand):", "__init__(self): super().__init__() self.commands_heading = \"コマンド:\" self.no_category = \"その他\" self.command_attrs[\"help\"] = \"コマンド一覧と簡単な説明を表示\" def get_ending_note(self):", "import r TOKEN = os.environ['DISCORD_BOT_TOKEN'] prefix = os.environ['DISCORD_BOT_PREFIX'] #プレフィックス # 読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS =", "= \"コマンド一覧と簡単な説明を表示\" def get_ending_note(self): return (f\"各コマンドの説明: {prefix}help <コマンド名>\\n\" f\"各カテゴリの説明: {prefix}help <カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。 if", "get_ending_note(self): return (f\"各コマンドの説明: {prefix}help <コマンド名>\\n\" f\"各カテゴリの説明: {prefix}help <カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。 if __name__ == '__main__':", "INITIAL_COGSに格納されている名前から、コグを読み込む。 # エラーが発生した場合は、エラー内容を表示。 for cog in INITIAL_EXTENSIONS: try: self.load_extension(cog) except Exception: traceback.print_exc() #", "return (f\"各コマンドの説明: {prefix}help <コマンド名>\\n\" f\"各カテゴリの説明: {prefix}help <カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。 if __name__ == '__main__': bot", "] # クラスの定義。ClientのサブクラスであるBotクラスを継承。 class MyBot(commands.Bot): # MyBotのコンストラクタ。 def __init__(self, command_prefix, help_command): # スーパークラスのコンストラクタに値を渡して実行。", "i=str(i) if i == global_ch: count+=1 if count>0: smsd=conn.smembers(global_ch) count=0 for q in", "Exception: traceback.print_exc() # Botの準備完了時に呼び出されるイベント async def on_ready(self): print(self.user.name) # ボットの名前 print(self.user.id) # ボットのID", "in ky: i=str(i) if i == global_ch: count+=1 if count>0: smsd=conn.smembers(global_ch) count=0 for", "for q in smsd: q=str(q) if q==\"0\": count+=1 if count>0: p=conn.srem(global_ch,\"0\") if p==True:", "= \"その他\" self.command_attrs[\"help\"] = \"コマンド一覧と簡単な説明を表示\" def get_ending_note(self): return (f\"各コマンドの説明: {prefix}help <コマンド名>\\n\" f\"各カテゴリの説明: {prefix}help", "def __init__(self, command_prefix, help_command): # スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command) # INITIAL_COGSに格納されている名前から、コグを読み込む。 # エラーが発生した場合は、エラー内容を表示。 for cog", "count=0 for i in ky: i=str(i) if i == global_ch: count+=1 if count>0:", "# エラー表示のためにインポート import os import discord import r TOKEN = os.environ['DISCORD_BOT_TOKEN'] prefix =", "commands, tasks # Bot Commands Frameworkをインポート import traceback # エラー表示のためにインポート import os import", "async def on_ready(self): print(self.user.name) # ボットの名前 print(self.user.id) # ボットのID print(discord.__version__) # discord.pyのバージョン print('----------------')", "await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms')) conn=r.connect() ky=conn.keys() global_ch=\"gloch\" count=0 for i in ky: i=str(i)", "\"コマンド:\" self.no_category = \"その他\" self.command_attrs[\"help\"] = \"コマンド一覧と簡単な説明を表示\" def get_ending_note(self): return (f\"各コマンドの説明: {prefix}help <コマンド名>\\n\"", "in smsd: q=str(q) if q==\"0\": count+=1 if count>0: p=conn.srem(global_ch,\"0\") if p==True: print(\"正常起動\") else:", "discord.ext import commands, tasks # Bot Commands Frameworkをインポート import traceback # エラー表示のためにインポート import", "import commands, tasks # Bot Commands Frameworkをインポート import traceback # エラー表示のためにインポート import os", "smsd=conn.smembers(global_ch) count=0 for q in smsd: q=str(q) if q==\"0\": count+=1 if count>0: p=conn.srem(global_ch,\"0\")", "global_ch=\"gloch\" count=0 for i in ky: i=str(i) if i == global_ch: count+=1 if", "INITIAL_EXTENSIONS: try: self.load_extension(cog) except Exception: traceback.print_exc() # Botの準備完了時に呼び出されるイベント async def on_ready(self): print(self.user.name) #", "Frameworkをインポート import traceback # エラー表示のためにインポート import os import discord import r TOKEN =", "{prefix}help <カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。 if __name__ == '__main__': bot = MyBot(command_prefix=prefix,help_command=JapaneseHelpCommand()) # command_prefixはコマンドの最初の文字として使うもの。 e.g.", "count>0: smsd=conn.smembers(global_ch) count=0 for q in smsd: q=str(q) if q==\"0\": count+=1 if count>0:", "count+=1 if count>0: p=conn.srem(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") else: print(ky) else: p=conn.sadd(global_ch,\"0\")", "print(ky) else: p=conn.sadd(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") class JapaneseHelpCommand(commands.DefaultHelpCommand): def __init__(self): super().__init__()", "self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms')) conn=r.connect() ky=conn.keys() global_ch=\"gloch\" count=0 for i in ky: i=str(i) if", "\"その他\" self.command_attrs[\"help\"] = \"コマンド一覧と簡単な説明を表示\" def get_ending_note(self): return (f\"各コマンドの説明: {prefix}help <コマンド名>\\n\" f\"各カテゴリの説明: {prefix}help <カテゴリ名>\\n\")", "def get_ending_note(self): return (f\"各コマンドの説明: {prefix}help <コマンド名>\\n\" f\"各カテゴリの説明: {prefix}help <カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。 if __name__ ==", "ボットのID print(discord.__version__) # discord.pyのバージョン print('----------------') print('Hello World !!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms')) conn=r.connect()", "os.environ['DISCORD_BOT_TOKEN'] prefix = os.environ['DISCORD_BOT_PREFIX'] #プレフィックス # 読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS = [ 'cogs.eval', 'cogs.glchat', 'cogs.gladd',", "if count>0: p=conn.srem(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") else: print(ky) else: p=conn.sadd(global_ch,\"0\") if", "= \"コマンド:\" self.no_category = \"その他\" self.command_attrs[\"help\"] = \"コマンド一覧と簡単な説明を表示\" def get_ending_note(self): return (f\"各コマンドの説明: {prefix}help", "for i in ky: i=str(i) if i == global_ch: count+=1 if count>0: smsd=conn.smembers(global_ch)", "\"コマンド一覧と簡単な説明を表示\" def get_ending_note(self): return (f\"各コマンドの説明: {prefix}help <コマンド名>\\n\" f\"各カテゴリの説明: {prefix}help <カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。 if __name__", "else: print(\"異常発生\") class JapaneseHelpCommand(commands.DefaultHelpCommand): def __init__(self): super().__init__() self.commands_heading = \"コマンド:\" self.no_category = \"その他\"", "self.commands_heading = \"コマンド:\" self.no_category = \"その他\" self.command_attrs[\"help\"] = \"コマンド一覧と簡単な説明を表示\" def get_ending_note(self): return (f\"各コマンドの説明:", "i == global_ch: count+=1 if count>0: smsd=conn.smembers(global_ch) count=0 for q in smsd: q=str(q)", "# MyBotのコンストラクタ。 def __init__(self, command_prefix, help_command): # スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command) # INITIAL_COGSに格納されている名前から、コグを読み込む。 # エラーが発生した場合は、エラー内容を表示。", "import os import discord import r TOKEN = os.environ['DISCORD_BOT_TOKEN'] prefix = os.environ['DISCORD_BOT_PREFIX'] #プレフィックス", "print('----------------') print('Hello World !!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms')) conn=r.connect() ky=conn.keys() global_ch=\"gloch\" count=0 for", "try: self.load_extension(cog) except Exception: traceback.print_exc() # Botの準備完了時に呼び出されるイベント async def on_ready(self): print(self.user.name) # ボットの名前", "= [ 'cogs.eval', 'cogs.glchat', 'cogs.gladd', 'cogs.gldel' ] # クラスの定義。ClientのサブクラスであるBotクラスを継承。 class MyBot(commands.Bot): # MyBotのコンストラクタ。", "print(\"異常発生\") class JapaneseHelpCommand(commands.DefaultHelpCommand): def __init__(self): super().__init__() self.commands_heading = \"コマンド:\" self.no_category = \"その他\" self.command_attrs[\"help\"]", "# ボットのID print(discord.__version__) # discord.pyのバージョン print('----------------') print('Hello World !!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms'))", "smsd: q=str(q) if q==\"0\": count+=1 if count>0: p=conn.srem(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\")", "== global_ch: count+=1 if count>0: smsd=conn.smembers(global_ch) count=0 for q in smsd: q=str(q) if", "= os.environ['DISCORD_BOT_PREFIX'] #プレフィックス # 読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS = [ 'cogs.eval', 'cogs.glchat', 'cogs.gladd', 'cogs.gldel' ]", "* 1000:.0f}ms')) conn=r.connect() ky=conn.keys() global_ch=\"gloch\" count=0 for i in ky: i=str(i) if i", "MyBotのコンストラクタ。 def __init__(self, command_prefix, help_command): # スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command) # INITIAL_COGSに格納されている名前から、コグを読み込む。 # エラーが発生した場合は、エラー内容を表示。 for", "def on_ready(self): print(self.user.name) # ボットの名前 print(self.user.id) # ボットのID print(discord.__version__) # discord.pyのバージョン print('----------------') print('Hello", "self.command_attrs[\"help\"] = \"コマンド一覧と簡単な説明を表示\" def get_ending_note(self): return (f\"各コマンドの説明: {prefix}help <コマンド名>\\n\" f\"各カテゴリの説明: {prefix}help <カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。", "#MyBotのインスタンス化及び起動処理。 if __name__ == '__main__': bot = MyBot(command_prefix=prefix,help_command=JapaneseHelpCommand()) # command_prefixはコマンドの最初の文字として使うもの。 e.g. !ping bot.run(TOKEN)", "(f\"各コマンドの説明: {prefix}help <コマンド名>\\n\" f\"各カテゴリの説明: {prefix}help <カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。 if __name__ == '__main__': bot =", "help_command): # スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command) # INITIAL_COGSに格納されている名前から、コグを読み込む。 # エラーが発生した場合は、エラー内容を表示。 for cog in INITIAL_EXTENSIONS: try:", "q in smsd: q=str(q) if q==\"0\": count+=1 if count>0: p=conn.srem(global_ch,\"0\") if p==True: print(\"正常起動\")", "# エラーが発生した場合は、エラー内容を表示。 for cog in INITIAL_EXTENSIONS: try: self.load_extension(cog) except Exception: traceback.print_exc() # Botの準備完了時に呼び出されるイベント", "except Exception: traceback.print_exc() # Botの準備完了時に呼び出されるイベント async def on_ready(self): print(self.user.name) # ボットの名前 print(self.user.id) #", "if p==True: print(\"正常起動\") else: print(\"異常発生\") class JapaneseHelpCommand(commands.DefaultHelpCommand): def __init__(self): super().__init__() self.commands_heading = \"コマンド:\"", "= os.environ['DISCORD_BOT_TOKEN'] prefix = os.environ['DISCORD_BOT_PREFIX'] #プレフィックス # 読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS = [ 'cogs.eval', 'cogs.glchat',", "q==\"0\": count+=1 if count>0: p=conn.srem(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") else: print(ky) else:", "p==True: print(\"正常起動\") else: print(\"異常発生\") class JapaneseHelpCommand(commands.DefaultHelpCommand): def __init__(self): super().__init__() self.commands_heading = \"コマンド:\" self.no_category", "i in ky: i=str(i) if i == global_ch: count+=1 if count>0: smsd=conn.smembers(global_ch) count=0", "# Botの準備完了時に呼び出されるイベント async def on_ready(self): print(self.user.name) # ボットの名前 print(self.user.id) # ボットのID print(discord.__version__) #", "print('Hello World !!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms')) conn=r.connect() ky=conn.keys() global_ch=\"gloch\" count=0 for i", "エラーが発生した場合は、エラー内容を表示。 for cog in INITIAL_EXTENSIONS: try: self.load_extension(cog) except Exception: traceback.print_exc() # Botの準備完了時に呼び出されるイベント async", "count+=1 if count>0: smsd=conn.smembers(global_ch) count=0 for q in smsd: q=str(q) if q==\"0\": count+=1", "else: p=conn.sadd(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") class JapaneseHelpCommand(commands.DefaultHelpCommand): def __init__(self): super().__init__() self.commands_heading", "!!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms')) conn=r.connect() ky=conn.keys() global_ch=\"gloch\" count=0 for i in ky:", "# スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command) # INITIAL_COGSに格納されている名前から、コグを読み込む。 # エラーが発生した場合は、エラー内容を表示。 for cog in INITIAL_EXTENSIONS: try: self.load_extension(cog)", "'cogs.gldel' ] # クラスの定義。ClientのサブクラスであるBotクラスを継承。 class MyBot(commands.Bot): # MyBotのコンストラクタ。 def __init__(self, command_prefix, help_command): #", "print(\"正常起動\") else: print(\"異常発生\") class JapaneseHelpCommand(commands.DefaultHelpCommand): def __init__(self): super().__init__() self.commands_heading = \"コマンド:\" self.no_category =", "count>0: p=conn.srem(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") else: print(ky) else: p=conn.sadd(global_ch,\"0\") if p==True:", "スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command) # INITIAL_COGSに格納されている名前から、コグを読み込む。 # エラーが発生した場合は、エラー内容を表示。 for cog in INITIAL_EXTENSIONS: try: self.load_extension(cog) except", "q=str(q) if q==\"0\": count+=1 if count>0: p=conn.srem(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") else:", "print(\"正常起動\") else: print(\"異常発生\") else: print(ky) else: p=conn.sadd(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") class", "if p==True: print(\"正常起動\") else: print(\"異常発生\") else: print(ky) else: p=conn.sadd(global_ch,\"0\") if p==True: print(\"正常起動\") else:", "r TOKEN = os.environ['DISCORD_BOT_TOKEN'] prefix = os.environ['DISCORD_BOT_PREFIX'] #プレフィックス # 読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS = [", "[ 'cogs.eval', 'cogs.glchat', 'cogs.gladd', 'cogs.gldel' ] # クラスの定義。ClientのサブクラスであるBotクラスを継承。 class MyBot(commands.Bot): # MyBotのコンストラクタ。 def", "TOKEN = os.environ['DISCORD_BOT_TOKEN'] prefix = os.environ['DISCORD_BOT_PREFIX'] #プレフィックス # 読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS = [ 'cogs.eval',", "print(self.user.name) # ボットの名前 print(self.user.id) # ボットのID print(discord.__version__) # discord.pyのバージョン print('----------------') print('Hello World !!')", "traceback # エラー表示のためにインポート import os import discord import r TOKEN = os.environ['DISCORD_BOT_TOKEN'] prefix", "class JapaneseHelpCommand(commands.DefaultHelpCommand): def __init__(self): super().__init__() self.commands_heading = \"コマンド:\" self.no_category = \"その他\" self.command_attrs[\"help\"] =", "import discord import r TOKEN = os.environ['DISCORD_BOT_TOKEN'] prefix = os.environ['DISCORD_BOT_PREFIX'] #プレフィックス # 読み込むコグの名前を格納しておく。", "tasks # Bot Commands Frameworkをインポート import traceback # エラー表示のためにインポート import os import discord", "discord import r TOKEN = os.environ['DISCORD_BOT_TOKEN'] prefix = os.environ['DISCORD_BOT_PREFIX'] #プレフィックス # 読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS", "読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS = [ 'cogs.eval', 'cogs.glchat', 'cogs.gladd', 'cogs.gldel' ] # クラスの定義。ClientのサブクラスであるBotクラスを継承。 class MyBot(commands.Bot):", "from discord.ext import commands, tasks # Bot Commands Frameworkをインポート import traceback # エラー表示のためにインポート", "for cog in INITIAL_EXTENSIONS: try: self.load_extension(cog) except Exception: traceback.print_exc() # Botの準備完了時に呼び出されるイベント async def", "class MyBot(commands.Bot): # MyBotのコンストラクタ。 def __init__(self, command_prefix, help_command): # スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command) # INITIAL_COGSに格納されている名前から、コグを読み込む。", "self.load_extension(cog) except Exception: traceback.print_exc() # Botの準備完了時に呼び出されるイベント async def on_ready(self): print(self.user.name) # ボットの名前 print(self.user.id)", "#プレフィックス # 読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS = [ 'cogs.eval', 'cogs.glchat', 'cogs.gladd', 'cogs.gldel' ] # クラスの定義。ClientのサブクラスであるBotクラスを継承。", "World !!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms')) conn=r.connect() ky=conn.keys() global_ch=\"gloch\" count=0 for i in", "エラー表示のためにインポート import os import discord import r TOKEN = os.environ['DISCORD_BOT_TOKEN'] prefix = os.environ['DISCORD_BOT_PREFIX']", "f\"各カテゴリの説明: {prefix}help <カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。 if __name__ == '__main__': bot = MyBot(command_prefix=prefix,help_command=JapaneseHelpCommand()) # command_prefixはコマンドの最初の文字として使うもの。", "MyBot(commands.Bot): # MyBotのコンストラクタ。 def __init__(self, command_prefix, help_command): # スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command) # INITIAL_COGSに格納されている名前から、コグを読み込む。 #", "in INITIAL_EXTENSIONS: try: self.load_extension(cog) except Exception: traceback.print_exc() # Botの準備完了時に呼び出されるイベント async def on_ready(self): print(self.user.name)", "JapaneseHelpCommand(commands.DefaultHelpCommand): def __init__(self): super().__init__() self.commands_heading = \"コマンド:\" self.no_category = \"その他\" self.command_attrs[\"help\"] = \"コマンド一覧と簡単な説明を表示\"", "super().__init__() self.commands_heading = \"コマンド:\" self.no_category = \"その他\" self.command_attrs[\"help\"] = \"コマンド一覧と簡単な説明を表示\" def get_ending_note(self): return", "if i == global_ch: count+=1 if count>0: smsd=conn.smembers(global_ch) count=0 for q in smsd:", "self.no_category = \"その他\" self.command_attrs[\"help\"] = \"コマンド一覧と簡単な説明を表示\" def get_ending_note(self): return (f\"各コマンドの説明: {prefix}help <コマンド名>\\n\" f\"各カテゴリの説明:", "Bot Commands Frameworkをインポート import traceback # エラー表示のためにインポート import os import discord import r", "ky=conn.keys() global_ch=\"gloch\" count=0 for i in ky: i=str(i) if i == global_ch: count+=1", "global_ch: count+=1 if count>0: smsd=conn.smembers(global_ch) count=0 for q in smsd: q=str(q) if q==\"0\":", "'cogs.glchat', 'cogs.gladd', 'cogs.gldel' ] # クラスの定義。ClientのサブクラスであるBotクラスを継承。 class MyBot(commands.Bot): # MyBotのコンストラクタ。 def __init__(self, command_prefix,", "クラスの定義。ClientのサブクラスであるBotクラスを継承。 class MyBot(commands.Bot): # MyBotのコンストラクタ。 def __init__(self, command_prefix, help_command): # スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command) #", "if q==\"0\": count+=1 if count>0: p=conn.srem(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") else: print(ky)", "conn=r.connect() ky=conn.keys() global_ch=\"gloch\" count=0 for i in ky: i=str(i) if i == global_ch:", "prefix = os.environ['DISCORD_BOT_PREFIX'] #プレフィックス # 読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS = [ 'cogs.eval', 'cogs.glchat', 'cogs.gladd', 'cogs.gldel'", "command_prefix, help_command): # スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command) # INITIAL_COGSに格納されている名前から、コグを読み込む。 # エラーが発生した場合は、エラー内容を表示。 for cog in INITIAL_EXTENSIONS:", "'cogs.eval', 'cogs.glchat', 'cogs.gladd', 'cogs.gldel' ] # クラスの定義。ClientのサブクラスであるBotクラスを継承。 class MyBot(commands.Bot): # MyBotのコンストラクタ。 def __init__(self,", "'cogs.gladd', 'cogs.gldel' ] # クラスの定義。ClientのサブクラスであるBotクラスを継承。 class MyBot(commands.Bot): # MyBotのコンストラクタ。 def __init__(self, command_prefix, help_command):", "os import discord import r TOKEN = os.environ['DISCORD_BOT_TOKEN'] prefix = os.environ['DISCORD_BOT_PREFIX'] #プレフィックス #", "# ボットの名前 print(self.user.id) # ボットのID print(discord.__version__) # discord.pyのバージョン print('----------------') print('Hello World !!') await", "# INITIAL_COGSに格納されている名前から、コグを読み込む。 # エラーが発生した場合は、エラー内容を表示。 for cog in INITIAL_EXTENSIONS: try: self.load_extension(cog) except Exception: traceback.print_exc()", "count=0 for q in smsd: q=str(q) if q==\"0\": count+=1 if count>0: p=conn.srem(global_ch,\"0\") if", "if __name__ == '__main__': bot = MyBot(command_prefix=prefix,help_command=JapaneseHelpCommand()) # command_prefixはコマンドの最初の文字として使うもの。 e.g. !ping bot.run(TOKEN) #" ]
[ "# The package used for creating and manipulating HDF5 files: import h5py #", "# Import packages # Ensure that this code works on both python 2", "files: # finally import pycroscopy: try: import pycroscopy as px except ImportError: print('pycroscopy", "method to determine the types of spectral responses present in the # data.", "px.plot_utils.plot_scree(h5_s, title='Note the exponential drop of variance with number of components') # Visualize", "factors (matrices) W and H, given a matrix V, as shown below #", "px except ImportError: print('pycroscopy not found. Will install with pip.') import pip install('pycroscopy')", "Excitation Piezoresponse Force Microscopy (BE-PFM)** imaging dataset # acquired from advanced atomic force", "of the page) and use your own data instead. # When using your", "# 1. Singular Value Decomposition (SVD) # ===================================== # # SVD is an", "Notice that we are working with a complex valued dataset. Passing the complex", "# (ie., assignment of each spectra as belonging to the k<sup>th</sup> set) such", "the non-negative portion of the dataset data_mat = np.abs(h5_main) model = NMF(n_components=num_comps, init='random',", "a quick and easy method to determine the types of spectral responses present", "Data # ======== # # In this example, we will work on a", "the concatenation of the real and imaginary # components. So, the eigenvectors would", "source h5 file including all relevant links to the source dataset and other", "clusters below num_clusters = 4 estimator = px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters)) h5_kmeans_grp = estimator.compute(h5_main) h5_kmeans_labels", "# finally import pycroscopy: try: import pycroscopy as px except ImportError: print('pycroscopy not", "unmixing of spectral # data. It only works on data with positive real", "(x, y) have been collapsed to one, we need to reshape the abundance", "been collapsed to one, we need to reshape the abundance maps: abun_maps =", "with pip.') import pip install('pycroscopy') import pycroscopy as px from pycroscopy.viz import cluster_utils", "source dataset and other ancillary datasets decomposer = px.processing.svd_utils.SVD(h5_main, num_components=100) h5_svd_group = decomposer.compute()", "Component #') axis.set_xlabel(x_label, fontsize=12) axis.set_ylabel(y_label, fontsize=12) axis.set_title('NMF Components', fontsize=14) axis.legend(bbox_to_anchor=[1.0, 1.0], fontsize=12) #####################################################################################", "# .. image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png # # Unlike SVD and k-Means that can be", "= np.abs(h5_main) model = NMF(n_components=num_comps, init='random', random_state=0) model.fit(data_mat) fig, axis = plt.subplots(figsize=(5.5, 5))", "np # The package used for creating and manipulating HDF5 files: import h5py", "In this notebook we load some spectral data, and perform basic data analysis,", "Passing the complex values as is to SVD would result in # complex", "decomposer.compute() h5_u = h5_svd_group['U'] h5_v = h5_svd_group['V'] h5_s = h5_svd_group['S'] # Since the", "data. It is not a decomposition method, but a basic clustering method. The", "from sklearn.decomposition import NMF import subprocess import sys def install(package): subprocess.call([sys.executable, \"-m\", \"pip\",", "(SVD) # ===================================== # # SVD is an eigenvector decomposition that is defined", "Furthermore, while it is not discussed in this example, pycroscopy also writes back", "KMeans Clustering * Non-negative Matrix Factorization * Principal Component Analysis Software Prerequisites: =======================", "eigenvectors / endmembers as well as abundance maps. Complex valued abundance maps are", "result in # complex valued eigenvectors / endmembers as well as abundance maps.", "# After SVD, the real-valued eigenvectors would need to be treated as the", "other things \"\"\" # Import packages # Ensure that this code works on", "results back into the same dataset among other things \"\"\" # Import packages", "* Center for Nanophase Materials Sciences Oak Ridge National Laboratory, Oak Ridge TN", "# =========================================== # # NMF, or non-negative matrix factorization, is a method that", "\"-m\", \"pip\", \"install\", package]) # Package for downloading online files: # finally import", "would need to restructure the data such that it is real-valued only. #", "h5_svd_group['S'] # Since the two spatial dimensions (x, y) have been collapsed to", "Since the two spatial dimensions (x, y) have been collapsed to one, we", "# For illustrative purposes, we will only take the amplitude component of the", "package]) # Package for downloading online files: # finally import pycroscopy: try: import", "non-negative datasets. # For illustrative purposes, we will only take the amplitude component", "Non-negative Matrix Factorization (NMF) # =========================================== # # NMF, or non-negative matrix factorization,", "and therefore typically produces # non-physical eigenvectors. Consequently, the interpretation of eigenvectors and", "V, as shown below # # .. image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png # # Unlike SVD", "the data into. The algorithm proceeds to find the optimal labeling # (ie.,", "matplotlib.pyplot as plt # for downloading files: import wget import os # multivariate", "importance of each component: px.plot_utils.plot_scree(h5_s, title='Note the exponential drop of variance with number", "(matrices) W and H, given a matrix V, as shown below # #", "two dimensional matrix. # # We will be using an data file available", "amplitude component of the spectral data num_comps = 4 # get the non-negative", "k<sup>th</sup> set) such that the within-cluster # sum of squares is minimized. #", "dataset using only the first N (most significant) components. # # SVD results", "is # formatted in the same manner of [position x spectra] in a", "for quickly # visualizing the major trends in the dataset since the resultant", "the spectral data num_comps = 4 # get the non-negative portion of the", "Standard distribution of **Anaconda** (includes numpy, scipy, matplotlib and sci-kit learn) * **pycroscopy**", "= 4 # get the non-negative portion of the dataset data_mat = np.abs(h5_main)", "= wget.download(url, data_file_path, bar=None) h5_file = h5py.File(data_file_path, mode='r+') print('Contents of data file:') print('----------------------')", "dataset, a spectra was collected for each position in a two # dimensional", "within-cluster # sum of squares is minimized. # # Set the number of", "a **Band Excitation Piezoresponse Force Microscopy (BE-PFM)** imaging dataset # acquired from advanced", "care and caution in interpretation. Nonetheless, it is a good method for quickly", "analysis, including: ======================================================================================== * KMeans Clustering * Non-negative Matrix Factorization * Principal Component", "(a.u.)' ##################################################################################### # 1. Singular Value Decomposition (SVD) # ===================================== # # SVD", "labeling # (ie., assignment of each spectra as belonging to the k<sup>th</sup> set)", "to complex-valued datasets, NMF only works on non-negative datasets. # For illustrative purposes,", "subprocess import sys def install(package): subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", package]) # Package for", "of spectral # data. It only works on data with positive real values.", "title_yoffset=0.95) # Visualize the variance / statistical importance of each component: px.plot_utils.plot_scree(h5_s, title='Note", "the optimal labeling # (ie., assignment of each spectra as belonging to the", "Extracting the X axis - vector of frequencies h5_spec_vals = px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1] freq_vec", "example, pycroscopy also writes back the results from SVD back to # the", "be restructured to get back the complex valued eigenvectors. # # **Pycroscopy handles", "handles all these data transformations (both for the source dataset and the eigenvectors)", "and python 3 from __future__ import division, print_function, absolute_import, unicode_literals # basic numeric", "import pycroscopy: try: import pycroscopy as px except ImportError: print('pycroscopy not found. Will", "valued abundance maps are not physical. # Thus, one would need to restructure", "belonging to the k<sup>th</sup> set) such that the within-cluster # sum of squares", "# Notice that we are working with a complex valued dataset. Passing the", "Visualize the variance / statistical importance of each component: px.plot_utils.plot_scree(h5_s, title='Note the exponential", "# The Data # ======== # # In this example, we will work", "Components', fontsize=14) axis.legend(bbox_to_anchor=[1.0, 1.0], fontsize=12) ##################################################################################### # Close and delete the h5_file h5_file.close()", "axis.set_title('NMF Components', fontsize=14) axis.legend(bbox_to_anchor=[1.0, 1.0], fontsize=12) ##################################################################################### # Close and delete the h5_file", "are realized through the ability to seamlessly perform these analyses on any imaging", "and visualization: import matplotlib.pyplot as plt # for downloading files: import wget import", "importance. Furthermore, SVD is also very well suited for data cleaning through #", "and easy method to determine the types of spectral responses present in the", "x_label = 'Frequency (kHz)' y_label = 'Amplitude (a.u.)' ##################################################################################### # 1. Singular Value", "Nonetheless, it is a good method for quickly # visualizing the major trends", "try: import pycroscopy as px except ImportError: print('pycroscopy not found. Will install with", "dataset and the eigenvectors) # automatically.** In general, pycroscopy handles compound / complex", "of variance or importance. Furthermore, SVD is also very well suited for data", "compound / complex valued datasets everywhere possible # # Furthermore, while it is", "import os # multivariate analysis: from sklearn.cluster import KMeans from sklearn.decomposition import NMF", "your own data, you can skip this cell and provide the path to", "the dataset using only the first N (most significant) components. # # SVD", "matplotlib and sci-kit learn) * **pycroscopy** : Though pycroscopy is mainly used here", "# Ensure that this code works on both python 2 and python 3", "etc. only accept data that is # formatted in the same manner of", "* V - Eigenvectors sorted by variance in descending order # * U", "get the non-negative portion of the dataset data_mat = np.abs(h5_main) model = NMF(n_components=num_comps,", "python 3 from __future__ import division, print_function, absolute_import, unicode_literals # basic numeric computation:", "# Plotting and visualization: import matplotlib.pyplot as plt # for downloading files: import", "you can skip this cell and provide the path to your data using", "provide the path to your data using the variable - data_file_path data_file_path =", "to be treated as the concatenation of the real and imaginary # components.", "Will install with pip.') import pip install('pycroscopy') import pycroscopy as px from pycroscopy.viz", "true capabilities are realized through the ability to seamlessly perform these analyses on", "we will only take the amplitude component of the spectral data num_comps =", "it is not discussed in this example, pycroscopy also writes back the results", "# factors (matrices) W and H, given a matrix V, as shown below", "dataset among other things \"\"\" # Import packages # Ensure that this code", "in the dataset since the resultant eigenvectors are sorted in descending # order", "python 2 and python 3 from __future__ import division, print_function, absolute_import, unicode_literals #", "We will be using an data file available on our GitHub project page", "the two spatial dimensions (x, y) have been collapsed to one, we need", "but a basic clustering method. The user inputs the number of # clusters", "px.plot_utils.plot_map_stack(abun_maps, num_comps=9, title='SVD Abundance Maps', reverse_dims=True, color_bar_mode='single', cmap='inferno', title_yoffset=0.95) # Visualize the variance", "that has been flattened to a two # dimensional matrix in accordance with", "in three matrices: # # * V - Eigenvectors sorted by variance in", "##################################################################################### # 2. KMeans Clustering # ==================== # # KMeans clustering is a", "both python 2 and python 3 from __future__ import division, print_function, absolute_import, unicode_literals", "unmixing algorithms, etc. only accept data that is # formatted in the same", "# SVD requires care and caution in interpretation. Nonetheless, it is a good", "imaging dataset # acquired from advanced atomic force microscopes. In this dataset, a", "2 and python 3 from __future__ import division, print_function, absolute_import, unicode_literals # basic", "h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### # 3. Non-negative Matrix Factorization (NMF) # ===========================================", "import sys def install(package): subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", package]) # Package for downloading", "dataset # acquired from advanced atomic force microscopes. In this dataset, a spectra", "by variance in descending order # * U - corresponding abundance maps #", "perform these analyses on any imaging dataset (regardless of origin, size, complexity) and", "random_state=0) model.fit(data_mat) fig, axis = plt.subplots(figsize=(5.5, 5)) px.plot_utils.plot_line_family(axis, freq_vec, model.components_, label_prefix='NMF Component #')", "perform basic data analysis, including: ======================================================================================== * KMeans Clustering * Non-negative Matrix Factorization", "KMeans from sklearn.decomposition import NMF import subprocess import sys def install(package): subprocess.call([sys.executable, \"-m\",", "\"pip\", \"install\", package]) # Package for downloading online files: # finally import pycroscopy:", "= px.processing.svd_utils.SVD(h5_main, num_components=100) h5_svd_group = decomposer.compute() h5_u = h5_svd_group['U'] h5_v = h5_svd_group['V'] h5_s", "the major trends in the dataset since the resultant eigenvectors are sorted in", "good method for quickly # visualizing the major trends in the dataset since", "for each position in a two # dimensional grid of spatial locations. Thus,", "dimensional dataset that has been flattened to a two # dimensional matrix in", "# # In this example, we will work on a **Band Excitation Piezoresponse", "pycroscopy handles compound / complex valued datasets everywhere possible # # Furthermore, while", "reshape the abundance maps: abun_maps = np.reshape(h5_u[:, :25], (num_rows, num_cols, -1)) px.plot_utils.plot_map_stack(abun_maps, num_comps=9,", "h5_kmeans_labels = h5_kmeans_grp['Labels'] h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### # 3. Non-negative Matrix Factorization", "notebook we load some spectral data, and perform basic data analysis, including: ========================================================================================", "of the dataset data_mat = np.abs(h5_main) model = NMF(n_components=num_comps, init='random', random_state=0) model.fit(data_mat) fig,", "3 from __future__ import division, print_function, absolute_import, unicode_literals # basic numeric computation: import", "* S - Variance or importance of each of these components # #", "also writes back the results from SVD back to # the same source", "can skip this cell and provide the path to your data using the", "= h5_file['Measurement_000'] # Extracting some basic parameters: num_rows = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows') num_cols =", "= px.plot_utils.plot_complex_spectra(h5_v[:9, :], x_label=x_label, y_label=y_label, title='SVD Eigenvectors', evenly_spaced=False) ##################################################################################### # 2. KMeans Clustering", "It operates by approximate determination of # factors (matrices) W and H, given", "SVD and k-Means that can be applied to complex-valued datasets, NMF only works", "Institute for Functional Imaging of Materials * Center for Nanophase Materials Sciences Oak", "also very well suited for data cleaning through # the reconstruction of the", "the number of # clusters (sets) to partition the data into. The algorithm", "Materials * Center for Nanophase Materials Sciences Oak Ridge National Laboratory, Oak Ridge", "for plotting purposes only, it's true capabilities are realized through the ability to", "as well as abundance maps. Complex valued abundance maps are not physical. #", "be treated as the concatenation of the real and imaginary # components. So,", "h5 file including all relevant links to the source dataset and other ancillary", "endmembers as well as abundance maps. Complex valued abundance maps are not physical.", "absolute_import, unicode_literals # basic numeric computation: import numpy as np # The package", "some basic parameters: num_rows = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows') num_cols = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') # Getting", "a matrix V, as shown below # # .. image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png # #", "Maps', reverse_dims=True, color_bar_mode='single', cmap='inferno', title_yoffset=0.95) # Visualize the variance / statistical importance of", "**pycroscopy** : Though pycroscopy is mainly used here for plotting purposes only, it's", "the amplitude component of the spectral data num_comps = 4 # get the", "as plt # for downloading files: import wget import os # multivariate analysis:", "# # **Pycroscopy handles all these data transformations (both for the source dataset", "= 'temp_um.h5' # download the data file from Github: url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path", "# the reconstruction of the dataset using only the first N (most significant)", "as np # The package used for creating and manipulating HDF5 files: import", "same source h5 file including all relevant links to the source dataset and", "Nanophase Materials Sciences Oak Ridge National Laboratory, Oak Ridge TN 37831, USA In", "working with a complex valued dataset. Passing the complex values as is to", "of clusters below num_clusters = 4 estimator = px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters)) h5_kmeans_grp = estimator.compute(h5_main)", "valued eigenvectors / endmembers as well as abundance maps. Complex valued abundance maps", "================================================================= Spectral Unmixing ================================================================= <NAME>, <NAME>, <NAME> * Institute for Functional Imaging of", "import KMeans from sklearn.decomposition import NMF import subprocess import sys def install(package): subprocess.call([sys.executable,", "take the amplitude component of the spectral data num_comps = 4 # get", "dataset and other ancillary datasets decomposer = px.processing.svd_utils.SVD(h5_main, num_components=100) h5_svd_group = decomposer.compute() h5_u", "the eigenvectors: _ = px.plot_utils.plot_complex_spectra(h5_v[:9, :], x_label=x_label, y_label=y_label, title='SVD Eigenvectors', evenly_spaced=False) ##################################################################################### #", "these data transformations (both for the source dataset and the eigenvectors) # automatically.**", "import subprocess import sys def install(package): subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", package]) # Package", "a good method for quickly # visualizing the major trends in the dataset", "h5_kmeans_grp = estimator.compute(h5_main) h5_kmeans_labels = h5_kmeans_grp['Labels'] h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### # 3.", "dataset data_mat = np.abs(h5_main) model = NMF(n_components=num_comps, init='random', random_state=0) model.fit(data_mat) fig, axis =", "data transformations (both for the source dataset and the eigenvectors) # automatically.** In", "= 'Frequency (kHz)' y_label = 'Amplitude (a.u.)' ##################################################################################### # 1. Singular Value Decomposition", "as the concatenation of the real and imaginary # components. So, the eigenvectors", "interpretation of eigenvectors and abundance maps from # SVD requires care and caution", "Unmixing ================================================================= <NAME>, <NAME>, <NAME> * Institute for Functional Imaging of Materials *", "SVD. # After SVD, the real-valued eigenvectors would need to be treated as", "illustrative purposes, we will only take the amplitude component of the spectral data", "(most significant) components. # # SVD results in three matrices: # # *", "h5py # Plotting and visualization: import matplotlib.pyplot as plt # for downloading files:", "example, we will work on a **Band Excitation Piezoresponse Force Microscopy (BE-PFM)** imaging", "need to reshape the abundance maps: abun_maps = np.reshape(h5_u[:, :25], (num_rows, num_cols, -1))", "x_label=x_label, y_label=y_label, title='SVD Eigenvectors', evenly_spaced=False) ##################################################################################### # 2. KMeans Clustering # ==================== #", "to stack the real value followed by the magnitude of the imaginary component", "and H, given a matrix V, as shown below # # .. image::", "drop of variance with number of components') # Visualize the eigenvectors: _ =", "data such that it is real-valued only. # # One solution is to", "towards unmixing of spectral # data. It only works on data with positive", "a basic clustering method. The user inputs the number of # clusters (sets)", "(ie., assignment of each spectra as belonging to the k<sup>th</sup> set) such that", "the same source h5 file including all relevant links to the source dataset", "import numpy as np # The package used for creating and manipulating HDF5", "plt # for downloading files: import wget import os # multivariate analysis: from", "that this code works on both python 2 and python 3 from __future__", "passing to SVD. # After SVD, the real-valued eigenvectors would need to be", "through the ability to seamlessly perform these analyses on any imaging dataset (regardless", "writes back the results from SVD back to # the same source h5", "px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main, {'quantity': 'Deflection', 'units': 'V'}) # Extracting the X axis - vector", "method. The user inputs the number of # clusters (sets) to partition the", "order # * U - corresponding abundance maps # * S - Variance", "'grid_num_rows') num_cols = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') # Getting a reference to the main dataset:", "Eigenvectors sorted by variance in descending order # * U - corresponding abundance", "maps # * S - Variance or importance of each of these components", ".. image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png # # Unlike SVD and k-Means that can be applied", "datasets. # For illustrative purposes, we will only take the amplitude component of", "= h5_kmeans_grp['Labels'] h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### # 3. Non-negative Matrix Factorization (NMF)", "analysis: from sklearn.cluster import KMeans from sklearn.decomposition import NMF import subprocess import sys", "it is a good method for quickly # visualizing the major trends in", "# multivariate analysis: from sklearn.cluster import KMeans from sklearn.decomposition import NMF import subprocess", "available on our GitHub project page by default. You are encouraged # to", "only works on non-negative datasets. # For illustrative purposes, we will only take", "the real value followed by the magnitude of the imaginary component before passing", "# NMF, or non-negative matrix factorization, is a method that is useful towards", "\"install\", package]) # Package for downloading online files: # finally import pycroscopy: try:", "maps: abun_maps = np.reshape(h5_u[:, :25], (num_rows, num_cols, -1)) px.plot_utils.plot_map_stack(abun_maps, num_comps=9, title='SVD Abundance Maps',", "(both for the source dataset and the eigenvectors) # automatically.** In general, pycroscopy", "to find the optimal labeling # (ie., assignment of each spectra as belonging", "Factorization * Principal Component Analysis Software Prerequisites: ======================= * Standard distribution of **Anaconda**", "our GitHub project page by default. You are encouraged # to download this", "the eigenvectors would need to be restructured to get back the complex valued", "shown below # # .. image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png # # Unlike SVD and k-Means", "NMF(n_components=num_comps, init='random', random_state=0) model.fit(data_mat) fig, axis = plt.subplots(figsize=(5.5, 5)) px.plot_utils.plot_line_family(axis, freq_vec, model.components_, label_prefix='NMF", "4 # get the non-negative portion of the dataset data_mat = np.abs(h5_main) model", "of Materials * Center for Nanophase Materials Sciences Oak Ridge National Laboratory, Oak", "it's true capabilities are realized through the ability to seamlessly perform these analyses", "# # Unlike SVD and k-Means that can be applied to complex-valued datasets,", "estimator.compute(h5_main) h5_kmeans_labels = h5_kmeans_grp['Labels'] h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### # 3. Non-negative Matrix", "manner of [position x spectra] in a two dimensional matrix. # # We", "install with pip.') import pip install('pycroscopy') import pycroscopy as px from pycroscopy.viz import", "num_cols = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') # Getting a reference to the main dataset: h5_main", "instead. # When using your own data, you can skip this cell and", "- vector of frequencies h5_spec_vals = px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1] freq_vec = np.squeeze(h5_spec_vals.value) * 1E-3", "complex values as is to SVD would result in # complex valued eigenvectors", "we will work on a **Band Excitation Piezoresponse Force Microscopy (BE-PFM)** imaging dataset", "(num_rows, num_cols, -1)) px.plot_utils.plot_map_stack(abun_maps, num_comps=9, title='SVD Abundance Maps', reverse_dims=True, color_bar_mode='single', cmap='inferno', title_yoffset=0.95) #", "# **Pycroscopy handles all these data transformations (both for the source dataset and", "import matplotlib.pyplot as plt # for downloading files: import wget import os #", "using the variable - data_file_path data_file_path = 'temp_um.h5' # download the data file", "would result in # complex valued eigenvectors / endmembers as well as abundance", "init='random', random_state=0) model.fit(data_mat) fig, axis = plt.subplots(figsize=(5.5, 5)) px.plot_utils.plot_line_family(axis, freq_vec, model.components_, label_prefix='NMF Component", "**Band Excitation Piezoresponse Force Microscopy (BE-PFM)** imaging dataset # acquired from advanced atomic", "the page) and use your own data instead. # When using your own", "found. Will install with pip.') import pip install('pycroscopy') import pycroscopy as px from", "# to download this document as a Jupyter Notebook (button at the bottom", "below # # .. image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png # # Unlike SVD and k-Means that", "magnitude of the imaginary component before passing to SVD. # After SVD, the", "into. The algorithm proceeds to find the optimal labeling # (ie., assignment of", "including: ======================================================================================== * KMeans Clustering * Non-negative Matrix Factorization * Principal Component Analysis", "learning, spectral unmixing algorithms, etc. only accept data that is # formatted in", "data num_comps = 4 # get the non-negative portion of the dataset data_mat", "the within-cluster # sum of squares is minimized. # # Set the number", "for downloading online files: # finally import pycroscopy: try: import pycroscopy as px", "variance or importance. Furthermore, SVD is also very well suited for data cleaning", "to be restructured to get back the complex valued eigenvectors. # # **Pycroscopy", "works on non-negative datasets. # For illustrative purposes, we will only take the", "the main dataset: h5_main = px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main, {'quantity': 'Deflection', 'units': 'V'}) # Extracting", "===================================== # # SVD is an eigenvector decomposition that is defined statistically, and", "is to SVD would result in # complex valued eigenvectors / endmembers as", "import pycroscopy as px from pycroscopy.viz import cluster_utils ##################################################################################### # The Data #", "matrices: # # * V - Eigenvectors sorted by variance in descending order", "the resultant eigenvectors are sorted in descending # order of variance or importance.", "SVD is also very well suited for data cleaning through # the reconstruction", "is mainly used here for plotting purposes only, it's true capabilities are realized", "1E-3 print('Data currently of shape:', h5_main.shape) x_label = 'Frequency (kHz)' y_label = 'Amplitude", "title='SVD Eigenvectors', evenly_spaced=False) ##################################################################################### # 2. KMeans Clustering # ==================== # # KMeans", "eigenvectors would need to be restructured to get back the complex valued eigenvectors.", "a decomposition method, but a basic clustering method. The user inputs the number", "import pip install('pycroscopy') import pycroscopy as px from pycroscopy.viz import cluster_utils ##################################################################################### #", ":], x_label=x_label, y_label=y_label, title='SVD Eigenvectors', evenly_spaced=False) ##################################################################################### # 2. KMeans Clustering # ====================", "label_prefix='NMF Component #') axis.set_xlabel(x_label, fontsize=12) axis.set_ylabel(y_label, fontsize=12) axis.set_title('NMF Components', fontsize=14) axis.legend(bbox_to_anchor=[1.0, 1.0], fontsize=12)", "model = NMF(n_components=num_comps, init='random', random_state=0) model.fit(data_mat) fig, axis = plt.subplots(figsize=(5.5, 5)) px.plot_utils.plot_line_family(axis, freq_vec,", "* Principal Component Analysis Software Prerequisites: ======================= * Standard distribution of **Anaconda** (includes", "unicode_literals # basic numeric computation: import numpy as np # The package used", "eigenvectors are sorted in descending # order of variance or importance. Furthermore, SVD", "Package for downloading online files: # finally import pycroscopy: try: import pycroscopy as", "in # complex valued eigenvectors / endmembers as well as abundance maps. Complex", "imaging dataset (regardless of origin, size, complexity) and storing the results back into", "Clustering * Non-negative Matrix Factorization * Principal Component Analysis Software Prerequisites: ======================= *", "major trends in the dataset since the resultant eigenvectors are sorted in descending", "while it is not discussed in this example, pycroscopy also writes back the", "number of components') # Visualize the eigenvectors: _ = px.plot_utils.plot_complex_spectra(h5_v[:9, :], x_label=x_label, y_label=y_label,", "general, pycroscopy handles compound / complex valued datasets everywhere possible # # Furthermore,", "value followed by the magnitude of the imaginary component before passing to SVD.", "= 4 estimator = px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters)) h5_kmeans_grp = estimator.compute(h5_main) h5_kmeans_labels = h5_kmeans_grp['Labels'] h5_kmeans_mean_resp", "and perform basic data analysis, including: ======================================================================================== * KMeans Clustering * Non-negative Matrix", "accordance with the pycroscopy data format. # # Fortunately, all statistical analysis, machine", "file from Github: url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path = wget.download(url, data_file_path, bar=None) h5_file =", "maps. Complex valued abundance maps are not physical. # Thus, one would need", "Matrix Factorization * Principal Component Analysis Software Prerequisites: ======================= * Standard distribution of", "all these data transformations (both for the source dataset and the eigenvectors) #", "Clustering # ==================== # # KMeans clustering is a quick and easy method", "only take the amplitude component of the spectral data num_comps = 4 #", "spectral # data. It only works on data with positive real values. It", "* Standard distribution of **Anaconda** (includes numpy, scipy, matplotlib and sci-kit learn) *", "The algorithm proceeds to find the optimal labeling # (ie., assignment of each", "import wget import os # multivariate analysis: from sklearn.cluster import KMeans from sklearn.decomposition", "basic data analysis, including: ======================================================================================== * KMeans Clustering * Non-negative Matrix Factorization *", "Thus, one would need to restructure the data such that it is real-valued", "of # clusters (sets) to partition the data into. The algorithm proceeds to", "method, but a basic clustering method. The user inputs the number of #", "h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### # 3. Non-negative Matrix Factorization (NMF) # =========================================== # #", "is not discussed in this example, pycroscopy also writes back the results from", "two # dimensional matrix in accordance with the pycroscopy data format. # #", "mainly used here for plotting purposes only, it's true capabilities are realized through", "load some spectral data, and perform basic data analysis, including: ======================================================================================== * KMeans", "h5_main = px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main, {'quantity': 'Deflection', 'units': 'V'}) # Extracting the X axis", "works on data with positive real values. It operates by approximate determination of", "2. KMeans Clustering # ==================== # # KMeans clustering is a quick and", "for downloading files: import wget import os # multivariate analysis: from sklearn.cluster import", "imaginary component before passing to SVD. # After SVD, the real-valued eigenvectors would", "Sciences Oak Ridge National Laboratory, Oak Ridge TN 37831, USA In this notebook", "squares is minimized. # # Set the number of clusters below num_clusters =", "multivariate analysis: from sklearn.cluster import KMeans from sklearn.decomposition import NMF import subprocess import", "flattened to a two # dimensional matrix in accordance with the pycroscopy data", "the pycroscopy data format. # # Fortunately, all statistical analysis, machine learning, spectral", "are sorted in descending # order of variance or importance. Furthermore, SVD is", "plotting purposes only, it's true capabilities are realized through the ability to seamlessly", "for Functional Imaging of Materials * Center for Nanophase Materials Sciences Oak Ridge", "the data such that it is real-valued only. # # One solution is", "packages # Ensure that this code works on both python 2 and python", "descending # order of variance or importance. Furthermore, SVD is also very well", "\"\"\" # Import packages # Ensure that this code works on both python", "Non-negative Matrix Factorization * Principal Component Analysis Software Prerequisites: ======================= * Standard distribution", "# When using your own data, you can skip this cell and provide", "valued eigenvectors. # # **Pycroscopy handles all these data transformations (both for the", "In this dataset, a spectra was collected for each position in a two", "visualization: import matplotlib.pyplot as plt # for downloading files: import wget import os", "# # Fortunately, all statistical analysis, machine learning, spectral unmixing algorithms, etc. only", "three matrices: # # * V - Eigenvectors sorted by variance in descending", "complex valued eigenvectors. # # **Pycroscopy handles all these data transformations (both for", "automatically.** In general, pycroscopy handles compound / complex valued datasets everywhere possible #", "(sets) to partition the data into. The algorithm proceeds to find the optimal", "px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters)) h5_kmeans_grp = estimator.compute(h5_main) h5_kmeans_labels = h5_kmeans_grp['Labels'] h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) #####################################################################################", "is a method that is useful towards unmixing of spectral # data. It", "Unlike SVD and k-Means that can be applied to complex-valued datasets, NMF only", "'grid_num_cols') # Getting a reference to the main dataset: h5_main = px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main,", "is an eigenvector decomposition that is defined statistically, and therefore typically produces #", "y) have been collapsed to one, we need to reshape the abundance maps:", "code works on both python 2 and python 3 from __future__ import division,", "freq_vec = np.squeeze(h5_spec_vals.value) * 1E-3 print('Data currently of shape:', h5_main.shape) x_label = 'Frequency", "main dataset: h5_main = px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main, {'quantity': 'Deflection', 'units': 'V'}) # Extracting the", "method for quickly # visualizing the major trends in the dataset since the", "the eigenvectors) # automatically.** In general, pycroscopy handles compound / complex valued datasets", "cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### # 3. Non-negative Matrix Factorization (NMF) # =========================================== # # NMF,", "corresponding abundance maps # * S - Variance or importance of each of", "realized through the ability to seamlessly perform these analyses on any imaging dataset", "solution is to stack the real value followed by the magnitude of the", "that the within-cluster # sum of squares is minimized. # # Set the", "of data file:') print('----------------------') px.hdf_utils.print_tree(h5_file) print('----------------------') h5_meas_grp = h5_file['Measurement_000'] # Extracting some basic", "portion of the dataset data_mat = np.abs(h5_main) model = NMF(n_components=num_comps, init='random', random_state=0) model.fit(data_mat)", "data cleaning through # the reconstruction of the dataset using only the first", "h5_s = h5_svd_group['S'] # Since the two spatial dimensions (x, y) have been", "axis.set_xlabel(x_label, fontsize=12) axis.set_ylabel(y_label, fontsize=12) axis.set_title('NMF Components', fontsize=14) axis.legend(bbox_to_anchor=[1.0, 1.0], fontsize=12) ##################################################################################### # Close", "##################################################################################### # 3. Non-negative Matrix Factorization (NMF) # =========================================== # # NMF, or", "all statistical analysis, machine learning, spectral unmixing algorithms, etc. only accept data that", "each of these components # # Advantage of pycroscopy: # ------------------------ # Notice", "sys def install(package): subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", package]) # Package for downloading online", "dataset that has been flattened to a two # dimensional matrix in accordance", "assignment of each spectra as belonging to the k<sup>th</sup> set) such that the", "given a matrix V, as shown below # # .. image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png #", "datasets everywhere possible # # Furthermore, while it is not discussed in this", "For illustrative purposes, we will only take the amplitude component of the spectral", "is also very well suited for data cleaning through # the reconstruction of", "subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", package]) # Package for downloading online files: # finally", "from Github: url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path = wget.download(url, data_file_path, bar=None) h5_file = h5py.File(data_file_path,", "the variable - data_file_path data_file_path = 'temp_um.h5' # download the data file from", "purposes, we will only take the amplitude component of the spectral data num_comps", "a Jupyter Notebook (button at the bottom of the page) and use your", "basic clustering method. The user inputs the number of # clusters (sets) to", "quick and easy method to determine the types of spectral responses present in", "this is a three dimensional dataset that has been flattened to a two", "that is defined statistically, and therefore typically produces # non-physical eigenvectors. Consequently, the", "present in the # data. It is not a decomposition method, but a", "# Fortunately, all statistical analysis, machine learning, spectral unmixing algorithms, etc. only accept", "= h5_svd_group['U'] h5_v = h5_svd_group['V'] h5_s = h5_svd_group['S'] # Since the two spatial", "data format. # # Fortunately, all statistical analysis, machine learning, spectral unmixing algorithms,", "= px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1] freq_vec = np.squeeze(h5_spec_vals.value) * 1E-3 print('Data currently of shape:', h5_main.shape)", "num_cols, -1)) px.plot_utils.plot_map_stack(abun_maps, num_comps=9, title='SVD Abundance Maps', reverse_dims=True, color_bar_mode='single', cmap='inferno', title_yoffset=0.95) # Visualize", "# ==================== # # KMeans clustering is a quick and easy method to", "37831, USA In this notebook we load some spectral data, and perform basic", "data analysis, including: ======================================================================================== * KMeans Clustering * Non-negative Matrix Factorization * Principal", "Analysis Software Prerequisites: ======================= * Standard distribution of **Anaconda** (includes numpy, scipy, matplotlib", "= estimator.compute(h5_main) h5_kmeans_labels = h5_kmeans_grp['Labels'] h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### # 3. Non-negative", "produces # non-physical eigenvectors. Consequently, the interpretation of eigenvectors and abundance maps from", "dataset since the resultant eigenvectors are sorted in descending # order of variance", "your data using the variable - data_file_path data_file_path = 'temp_um.h5' # download the", "and caution in interpretation. Nonetheless, it is a good method for quickly #", "ability to seamlessly perform these analyses on any imaging dataset (regardless of origin,", "SVD results in three matrices: # # * V - Eigenvectors sorted by", "# automatically.** In general, pycroscopy handles compound / complex valued datasets everywhere possible", "print_function, absolute_import, unicode_literals # basic numeric computation: import numpy as np # The", "/ complex valued datasets everywhere possible # # Furthermore, while it is not", "importance of each of these components # # Advantage of pycroscopy: # ------------------------", "matrix V, as shown below # # .. image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png # # Unlike", "only works on data with positive real values. It operates by approximate determination", "by the magnitude of the imaginary component before passing to SVD. # After", "results in three matrices: # # * V - Eigenvectors sorted by variance", "links to the source dataset and other ancillary datasets decomposer = px.processing.svd_utils.SVD(h5_main, num_components=100)", "variance / statistical importance of each component: px.plot_utils.plot_scree(h5_s, title='Note the exponential drop of", "is a quick and easy method to determine the types of spectral responses", "cmap='inferno', title_yoffset=0.95) # Visualize the variance / statistical importance of each component: px.plot_utils.plot_scree(h5_s,", "the dataset data_mat = np.abs(h5_main) model = NMF(n_components=num_comps, init='random', random_state=0) model.fit(data_mat) fig, axis", "each position in a two # dimensional grid of spatial locations. Thus, this", "statistical analysis, machine learning, spectral unmixing algorithms, etc. only accept data that is", "data, and perform basic data analysis, including: ======================================================================================== * KMeans Clustering * Non-negative", "**Anaconda** (includes numpy, scipy, matplotlib and sci-kit learn) * **pycroscopy** : Though pycroscopy", "# non-physical eigenvectors. Consequently, the interpretation of eigenvectors and abundance maps from #", "finally import pycroscopy: try: import pycroscopy as px except ImportError: print('pycroscopy not found.", "# * S - Variance or importance of each of these components #", "mode='r+') print('Contents of data file:') print('----------------------') px.hdf_utils.print_tree(h5_file) print('----------------------') h5_meas_grp = h5_file['Measurement_000'] # Extracting", "(NMF) # =========================================== # # NMF, or non-negative matrix factorization, is a method", "such that it is real-valued only. # # One solution is to stack", "through # the reconstruction of the dataset using only the first N (most", "# for downloading files: import wget import os # multivariate analysis: from sklearn.cluster", "downloading files: import wget import os # multivariate analysis: from sklearn.cluster import KMeans", "first N (most significant) components. # # SVD results in three matrices: #", "of each component: px.plot_utils.plot_scree(h5_s, title='Note the exponential drop of variance with number of", "of variance with number of components') # Visualize the eigenvectors: _ = px.plot_utils.plot_complex_spectra(h5_v[:9,", "to determine the types of spectral responses present in the # data. It", "easy method to determine the types of spectral responses present in the #", "cell and provide the path to your data using the variable - data_file_path", "this dataset, a spectra was collected for each position in a two #", "components') # Visualize the eigenvectors: _ = px.plot_utils.plot_complex_spectra(h5_v[:9, :], x_label=x_label, y_label=y_label, title='SVD Eigenvectors',", "sorted by variance in descending order # * U - corresponding abundance maps", "determine the types of spectral responses present in the # data. It is", "of frequencies h5_spec_vals = px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1] freq_vec = np.squeeze(h5_spec_vals.value) * 1E-3 print('Data currently", "decomposition that is defined statistically, and therefore typically produces # non-physical eigenvectors. Consequently,", "of pycroscopy: # ------------------------ # Notice that we are working with a complex", "Materials Sciences Oak Ridge National Laboratory, Oak Ridge TN 37831, USA In this", "clustering method. The user inputs the number of # clusters (sets) to partition", "any imaging dataset (regardless of origin, size, complexity) and storing the results back", "basic parameters: num_rows = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows') num_cols = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') # Getting a", "# Package for downloading online files: # finally import pycroscopy: try: import pycroscopy", "Force Microscopy (BE-PFM)** imaging dataset # acquired from advanced atomic force microscopes. In", "origin, size, complexity) and storing the results back into the same dataset among", "It is not a decomposition method, but a basic clustering method. The user", "# SVD is an eigenvector decomposition that is defined statistically, and therefore typically", "model.fit(data_mat) fig, axis = plt.subplots(figsize=(5.5, 5)) px.plot_utils.plot_line_family(axis, freq_vec, model.components_, label_prefix='NMF Component #') axis.set_xlabel(x_label,", "spectral unmixing algorithms, etc. only accept data that is # formatted in the", "own data, you can skip this cell and provide the path to your", "an eigenvector decomposition that is defined statistically, and therefore typically produces # non-physical", "= h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### # 3. Non-negative Matrix Factorization (NMF) # =========================================== #", "all relevant links to the source dataset and other ancillary datasets decomposer =", "among other things \"\"\" # Import packages # Ensure that this code works", "{'quantity': 'Deflection', 'units': 'V'}) # Extracting the X axis - vector of frequencies", "not discussed in this example, pycroscopy also writes back the results from SVD", "image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png # # Unlike SVD and k-Means that can be applied to", "data, you can skip this cell and provide the path to your data", "useful towards unmixing of spectral # data. It only works on data with", "the # data. It is not a decomposition method, but a basic clustering", "Variance or importance of each of these components # # Advantage of pycroscopy:", "we are working with a complex valued dataset. Passing the complex values as", "values. It operates by approximate determination of # factors (matrices) W and H,", "= px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') # Getting a reference to the main dataset: h5_main =", "statistically, and therefore typically produces # non-physical eigenvectors. Consequently, the interpretation of eigenvectors", "Visualize the eigenvectors: _ = px.plot_utils.plot_complex_spectra(h5_v[:9, :], x_label=x_label, y_label=y_label, title='SVD Eigenvectors', evenly_spaced=False) #####################################################################################", "(includes numpy, scipy, matplotlib and sci-kit learn) * **pycroscopy** : Though pycroscopy is", "= px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows') num_cols = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') # Getting a reference to the", "to partition the data into. The algorithm proceeds to find the optimal labeling", "as shown below # # .. image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png # # Unlike SVD and", "of spatial locations. Thus, this is a three dimensional dataset that has been", "of the dataset using only the first N (most significant) components. # #", "Spectral Unmixing ================================================================= <NAME>, <NAME>, <NAME> * Institute for Functional Imaging of Materials", "same manner of [position x spectra] in a two dimensional matrix. # #", "learn) * **pycroscopy** : Though pycroscopy is mainly used here for plotting purposes", "h5_meas_grp = h5_file['Measurement_000'] # Extracting some basic parameters: num_rows = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows') num_cols", "cleaning through # the reconstruction of the dataset using only the first N", "is real-valued only. # # One solution is to stack the real value", "of spectral responses present in the # data. It is not a decomposition", "real values. It operates by approximate determination of # factors (matrices) W and", "Furthermore, SVD is also very well suited for data cleaning through # the", "pycroscopy also writes back the results from SVD back to # the same", "National Laboratory, Oak Ridge TN 37831, USA In this notebook we load some", "as px from pycroscopy.viz import cluster_utils ##################################################################################### # The Data # ======== #", "including all relevant links to the source dataset and other ancillary datasets decomposer", "method that is useful towards unmixing of spectral # data. It only works", "the ability to seamlessly perform these analyses on any imaging dataset (regardless of", "num_rows = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows') num_cols = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') # Getting a reference to", "requires care and caution in interpretation. Nonetheless, it is a good method for", "title='Note the exponential drop of variance with number of components') # Visualize the", "pip.') import pip install('pycroscopy') import pycroscopy as px from pycroscopy.viz import cluster_utils #####################################################################################", "are encouraged # to download this document as a Jupyter Notebook (button at", "model.components_, label_prefix='NMF Component #') axis.set_xlabel(x_label, fontsize=12) axis.set_ylabel(y_label, fontsize=12) axis.set_title('NMF Components', fontsize=14) axis.legend(bbox_to_anchor=[1.0, 1.0],", "datasets decomposer = px.processing.svd_utils.SVD(h5_main, num_components=100) h5_svd_group = decomposer.compute() h5_u = h5_svd_group['U'] h5_v =", "not physical. # Thus, one would need to restructure the data such that", "atomic force microscopes. In this dataset, a spectra was collected for each position", "to restructure the data such that it is real-valued only. # # One", "a two # dimensional grid of spatial locations. Thus, this is a three", "online files: # finally import pycroscopy: try: import pycroscopy as px except ImportError:", "for data cleaning through # the reconstruction of the dataset using only the", "px.processing.svd_utils.SVD(h5_main, num_components=100) h5_svd_group = decomposer.compute() h5_u = h5_svd_group['U'] h5_v = h5_svd_group['V'] h5_s =", "data file available on our GitHub project page by default. You are encouraged", "the same manner of [position x spectra] in a two dimensional matrix. #", "minimized. # # Set the number of clusters below num_clusters = 4 estimator", "the path to your data using the variable - data_file_path data_file_path = 'temp_um.h5'", "'Frequency (kHz)' y_label = 'Amplitude (a.u.)' ##################################################################################### # 1. Singular Value Decomposition (SVD)", "on both python 2 and python 3 from __future__ import division, print_function, absolute_import,", "complex valued dataset. Passing the complex values as is to SVD would result", "document as a Jupyter Notebook (button at the bottom of the page) and", "cluster_utils ##################################################################################### # The Data # ======== # # In this example, we", "[position x spectra] in a two dimensional matrix. # # We will be", "* U - corresponding abundance maps # * S - Variance or importance", "dimensional matrix in accordance with the pycroscopy data format. # # Fortunately, all", "= 'Amplitude (a.u.)' ##################################################################################### # 1. Singular Value Decomposition (SVD) # ===================================== #", "only accept data that is # formatted in the same manner of [position", "# Visualize the variance / statistical importance of each component: px.plot_utils.plot_scree(h5_s, title='Note the", "KMeans clustering is a quick and easy method to determine the types of", "from sklearn.cluster import KMeans from sklearn.decomposition import NMF import subprocess import sys def", "TN 37831, USA In this notebook we load some spectral data, and perform", "real-valued only. # # One solution is to stack the real value followed", "The Data # ======== # # In this example, we will work on", "other ancillary datasets decomposer = px.processing.svd_utils.SVD(h5_main, num_components=100) h5_svd_group = decomposer.compute() h5_u = h5_svd_group['U']", "two # dimensional grid of spatial locations. Thus, this is a three dimensional", "# Visualize the eigenvectors: _ = px.plot_utils.plot_complex_spectra(h5_v[:9, :], x_label=x_label, y_label=y_label, title='SVD Eigenvectors', evenly_spaced=False)", "y_label=y_label, title='SVD Eigenvectors', evenly_spaced=False) ##################################################################################### # 2. KMeans Clustering # ==================== # #", "<gh_stars>0 \"\"\" ================================================================= Spectral Unmixing ================================================================= <NAME>, <NAME>, <NAME> * Institute for Functional", "download the data file from Github: url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path = wget.download(url, data_file_path,", "of origin, size, complexity) and storing the results back into the same dataset", "two spatial dimensions (x, y) have been collapsed to one, we need to", "# # We will be using an data file available on our GitHub", "the X axis - vector of frequencies h5_spec_vals = px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1] freq_vec =", "data file from Github: url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path = wget.download(url, data_file_path, bar=None) h5_file", "print('----------------------') px.hdf_utils.print_tree(h5_file) print('----------------------') h5_meas_grp = h5_file['Measurement_000'] # Extracting some basic parameters: num_rows =", "h5_spec_vals = px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1] freq_vec = np.squeeze(h5_spec_vals.value) * 1E-3 print('Data currently of shape:',", "NMF import subprocess import sys def install(package): subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", package]) #", "in accordance with the pycroscopy data format. # # Fortunately, all statistical analysis,", "downloading online files: # finally import pycroscopy: try: import pycroscopy as px except", "would need to be restructured to get back the complex valued eigenvectors. #", "same dataset among other things \"\"\" # Import packages # Ensure that this", "= NMF(n_components=num_comps, init='random', random_state=0) model.fit(data_mat) fig, axis = plt.subplots(figsize=(5.5, 5)) px.plot_utils.plot_line_family(axis, freq_vec, model.components_,", "used here for plotting purposes only, it's true capabilities are realized through the", "is a good method for quickly # visualizing the major trends in the", "in a two # dimensional grid of spatial locations. Thus, this is a", "collected for each position in a two # dimensional grid of spatial locations.", "np.squeeze(h5_spec_vals.value) * 1E-3 print('Data currently of shape:', h5_main.shape) x_label = 'Frequency (kHz)' y_label", "one would need to restructure the data such that it is real-valued only.", "the real-valued eigenvectors would need to be treated as the concatenation of the", "numpy as np # The package used for creating and manipulating HDF5 files:", "os # multivariate analysis: from sklearn.cluster import KMeans from sklearn.decomposition import NMF import", "pycroscopy data format. # # Fortunately, all statistical analysis, machine learning, spectral unmixing", "factorization, is a method that is useful towards unmixing of spectral # data.", "h5_svd_group['V'] h5_s = h5_svd_group['S'] # Since the two spatial dimensions (x, y) have", "data. It only works on data with positive real values. It operates by", "Getting a reference to the main dataset: h5_main = px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main, {'quantity': 'Deflection',", "encouraged # to download this document as a Jupyter Notebook (button at the", "skip this cell and provide the path to your data using the variable", "Extracting some basic parameters: num_rows = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows') num_cols = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') #", "'Spectroscopic_Values')[-1] freq_vec = np.squeeze(h5_spec_vals.value) * 1E-3 print('Data currently of shape:', h5_main.shape) x_label =", "spectral responses present in the # data. It is not a decomposition method,", "format. # # Fortunately, all statistical analysis, machine learning, spectral unmixing algorithms, etc.", "from SVD back to # the same source h5 file including all relevant", "determination of # factors (matrices) W and H, given a matrix V, as", "pycroscopy is mainly used here for plotting purposes only, it's true capabilities are", "files: import wget import os # multivariate analysis: from sklearn.cluster import KMeans from", "U - corresponding abundance maps # * S - Variance or importance of", "= decomposer.compute() h5_u = h5_svd_group['U'] h5_v = h5_svd_group['V'] h5_s = h5_svd_group['S'] # Since", "# KMeans clustering is a quick and easy method to determine the types", "a method that is useful towards unmixing of spectral # data. It only", "distribution of **Anaconda** (includes numpy, scipy, matplotlib and sci-kit learn) * **pycroscopy** :", "back the complex valued eigenvectors. # # **Pycroscopy handles all these data transformations", "# Advantage of pycroscopy: # ------------------------ # Notice that we are working with", "this example, we will work on a **Band Excitation Piezoresponse Force Microscopy (BE-PFM)**", "Ridge National Laboratory, Oak Ridge TN 37831, USA In this notebook we load", "the interpretation of eigenvectors and abundance maps from # SVD requires care and", "of each of these components # # Advantage of pycroscopy: # ------------------------ #", "- data_file_path data_file_path = 'temp_um.h5' # download the data file from Github: url", "to reshape the abundance maps: abun_maps = np.reshape(h5_u[:, :25], (num_rows, num_cols, -1)) px.plot_utils.plot_map_stack(abun_maps,", "y_label = 'Amplitude (a.u.)' ##################################################################################### # 1. Singular Value Decomposition (SVD) # =====================================", "KMeans(n_clusters=num_clusters)) h5_kmeans_grp = estimator.compute(h5_main) h5_kmeans_labels = h5_kmeans_grp['Labels'] h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### #", "source dataset and the eigenvectors) # automatically.** In general, pycroscopy handles compound /", "visualizing the major trends in the dataset since the resultant eigenvectors are sorted", "in a two dimensional matrix. # # We will be using an data", "dataset: h5_main = px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main, {'quantity': 'Deflection', 'units': 'V'}) # Extracting the X", "package used for creating and manipulating HDF5 files: import h5py # Plotting and", ": Though pycroscopy is mainly used here for plotting purposes only, it's true", "# basic numeric computation: import numpy as np # The package used for", "pycroscopy: try: import pycroscopy as px except ImportError: print('pycroscopy not found. Will install", "analysis, machine learning, spectral unmixing algorithms, etc. only accept data that is #", "path to your data using the variable - data_file_path data_file_path = 'temp_um.h5' #", "the complex values as is to SVD would result in # complex valued", "relevant links to the source dataset and other ancillary datasets decomposer = px.processing.svd_utils.SVD(h5_main,", "sum of squares is minimized. # # Set the number of clusters below", "since the resultant eigenvectors are sorted in descending # order of variance or", "np.abs(h5_main) model = NMF(n_components=num_comps, init='random', random_state=0) model.fit(data_mat) fig, axis = plt.subplots(figsize=(5.5, 5)) px.plot_utils.plot_line_family(axis,", "data_file_path = wget.download(url, data_file_path, bar=None) h5_file = h5py.File(data_file_path, mode='r+') print('Contents of data file:')", "(regardless of origin, size, complexity) and storing the results back into the same", "pycroscopy as px except ImportError: print('pycroscopy not found. Will install with pip.') import", "dimensional matrix. # # We will be using an data file available on", "======================================================================================== * KMeans Clustering * Non-negative Matrix Factorization * Principal Component Analysis Software", "url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path = wget.download(url, data_file_path, bar=None) h5_file = h5py.File(data_file_path, mode='r+') print('Contents", "trends in the dataset since the resultant eigenvectors are sorted in descending #", "followed by the magnitude of the imaginary component before passing to SVD. #", "decomposer = px.processing.svd_utils.SVD(h5_main, num_components=100) h5_svd_group = decomposer.compute() h5_u = h5_svd_group['U'] h5_v = h5_svd_group['V']", "using only the first N (most significant) components. # # SVD results in", "# # SVD results in three matrices: # # * V - Eigenvectors", "Imaging of Materials * Center for Nanophase Materials Sciences Oak Ridge National Laboratory,", "# dimensional grid of spatial locations. Thus, this is a three dimensional dataset", "4 estimator = px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters)) h5_kmeans_grp = estimator.compute(h5_main) h5_kmeans_labels = h5_kmeans_grp['Labels'] h5_kmeans_mean_resp =", "https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png # # Unlike SVD and k-Means that can be applied to complex-valued", "a three dimensional dataset that has been flattened to a two # dimensional", "Matrix Factorization (NMF) # =========================================== # # NMF, or non-negative matrix factorization, is", "# Thus, one would need to restructure the data such that it is", "own data instead. # When using your own data, you can skip this", "download this document as a Jupyter Notebook (button at the bottom of the", "# Unlike SVD and k-Means that can be applied to complex-valued datasets, NMF", "'units': 'V'}) # Extracting the X axis - vector of frequencies h5_spec_vals =", "data instead. # When using your own data, you can skip this cell", "statistical importance of each component: px.plot_utils.plot_scree(h5_s, title='Note the exponential drop of variance with", "N (most significant) components. # # SVD results in three matrices: # #", "is to stack the real value followed by the magnitude of the imaginary", "pycroscopy: # ------------------------ # Notice that we are working with a complex valued", "and abundance maps from # SVD requires care and caution in interpretation. Nonetheless,", "pycroscopy as px from pycroscopy.viz import cluster_utils ##################################################################################### # The Data # ========", "Decomposition (SVD) # ===================================== # # SVD is an eigenvector decomposition that is", "get back the complex valued eigenvectors. # # **Pycroscopy handles all these data", "H, given a matrix V, as shown below # # .. image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png", "on any imaging dataset (regardless of origin, size, complexity) and storing the results", "for the source dataset and the eigenvectors) # automatically.** In general, pycroscopy handles", "Singular Value Decomposition (SVD) # ===================================== # # SVD is an eigenvector decomposition", "the types of spectral responses present in the # data. It is not", "that it is real-valued only. # # One solution is to stack the", "stack the real value followed by the magnitude of the imaginary component before", "some spectral data, and perform basic data analysis, including: ======================================================================================== * KMeans Clustering", "basic numeric computation: import numpy as np # The package used for creating", "h5_svd_group = decomposer.compute() h5_u = h5_svd_group['U'] h5_v = h5_svd_group['V'] h5_s = h5_svd_group['S'] #", "axis.set_ylabel(y_label, fontsize=12) axis.set_title('NMF Components', fontsize=14) axis.legend(bbox_to_anchor=[1.0, 1.0], fontsize=12) ##################################################################################### # Close and delete", "this cell and provide the path to your data using the variable -", "* Institute for Functional Imaging of Materials * Center for Nanophase Materials Sciences", "operates by approximate determination of # factors (matrices) W and H, given a", "# order of variance or importance. Furthermore, SVD is also very well suited", "<NAME>, <NAME> * Institute for Functional Imaging of Materials * Center for Nanophase", "install('pycroscopy') import pycroscopy as px from pycroscopy.viz import cluster_utils ##################################################################################### # The Data", "and manipulating HDF5 files: import h5py # Plotting and visualization: import matplotlib.pyplot as", "##################################################################################### # 1. Singular Value Decomposition (SVD) # ===================================== # # SVD is", "reconstruction of the dataset using only the first N (most significant) components. #", "shape:', h5_main.shape) x_label = 'Frequency (kHz)' y_label = 'Amplitude (a.u.)' ##################################################################################### # 1.", "only the first N (most significant) components. # # SVD results in three", "significant) components. # # SVD results in three matrices: # # * V", "file including all relevant links to the source dataset and other ancillary datasets", "-1)) px.plot_utils.plot_map_stack(abun_maps, num_comps=9, title='SVD Abundance Maps', reverse_dims=True, color_bar_mode='single', cmap='inferno', title_yoffset=0.95) # Visualize the", "It only works on data with positive real values. It operates by approximate", "fig, axis = plt.subplots(figsize=(5.5, 5)) px.plot_utils.plot_line_family(axis, freq_vec, model.components_, label_prefix='NMF Component #') axis.set_xlabel(x_label, fontsize=12)", "as belonging to the k<sup>th</sup> set) such that the within-cluster # sum of", "therefore typically produces # non-physical eigenvectors. Consequently, the interpretation of eigenvectors and abundance", "purposes only, it's true capabilities are realized through the ability to seamlessly perform", "need to be restructured to get back the complex valued eigenvectors. # #", "eigenvectors) # automatically.** In general, pycroscopy handles compound / complex valued datasets everywhere", "data_file_path = 'temp_um.h5' # download the data file from Github: url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5'", "on our GitHub project page by default. You are encouraged # to download", "seamlessly perform these analyses on any imaging dataset (regardless of origin, size, complexity)", "The package used for creating and manipulating HDF5 files: import h5py # Plotting", "= plt.subplots(figsize=(5.5, 5)) px.plot_utils.plot_line_family(axis, freq_vec, model.components_, label_prefix='NMF Component #') axis.set_xlabel(x_label, fontsize=12) axis.set_ylabel(y_label, fontsize=12)", "sklearn.decomposition import NMF import subprocess import sys def install(package): subprocess.call([sys.executable, \"-m\", \"pip\", \"install\",", "manipulating HDF5 files: import h5py # Plotting and visualization: import matplotlib.pyplot as plt", "When using your own data, you can skip this cell and provide the", "component of the spectral data num_comps = 4 # get the non-negative portion", "the magnitude of the imaginary component before passing to SVD. # After SVD,", "component before passing to SVD. # After SVD, the real-valued eigenvectors would need", "= np.squeeze(h5_spec_vals.value) * 1E-3 print('Data currently of shape:', h5_main.shape) x_label = 'Frequency (kHz)'", "ancillary datasets decomposer = px.processing.svd_utils.SVD(h5_main, num_components=100) h5_svd_group = decomposer.compute() h5_u = h5_svd_group['U'] h5_v", "as is to SVD would result in # complex valued eigenvectors / endmembers", "and other ancillary datasets decomposer = px.processing.svd_utils.SVD(h5_main, num_components=100) h5_svd_group = decomposer.compute() h5_u =", "work on a **Band Excitation Piezoresponse Force Microscopy (BE-PFM)** imaging dataset # acquired", "frequencies h5_spec_vals = px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1] freq_vec = np.squeeze(h5_spec_vals.value) * 1E-3 print('Data currently of", "# 2. KMeans Clustering # ==================== # # KMeans clustering is a quick", "optimal labeling # (ie., assignment of each spectra as belonging to the k<sup>th</sup>", "variance in descending order # * U - corresponding abundance maps # *", "# clusters (sets) to partition the data into. The algorithm proceeds to find", "to get back the complex valued eigenvectors. # # **Pycroscopy handles all these", "abundance maps: abun_maps = np.reshape(h5_u[:, :25], (num_rows, num_cols, -1)) px.plot_utils.plot_map_stack(abun_maps, num_comps=9, title='SVD Abundance", "\"\"\" ================================================================= Spectral Unmixing ================================================================= <NAME>, <NAME>, <NAME> * Institute for Functional Imaging", "px.plot_utils.plot_complex_spectra(h5_v[:9, :], x_label=x_label, y_label=y_label, title='SVD Eigenvectors', evenly_spaced=False) ##################################################################################### # 2. KMeans Clustering #", "of the real and imaginary # components. So, the eigenvectors would need to", "real-valued eigenvectors would need to be treated as the concatenation of the real", "# get the non-negative portion of the dataset data_mat = np.abs(h5_main) model =", "px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1] freq_vec = np.squeeze(h5_spec_vals.value) * 1E-3 print('Data currently of shape:', h5_main.shape) x_label", "V - Eigenvectors sorted by variance in descending order # * U -", "Complex valued abundance maps are not physical. # Thus, one would need to", "position in a two # dimensional grid of spatial locations. Thus, this is", "* **pycroscopy** : Though pycroscopy is mainly used here for plotting purposes only,", "transformations (both for the source dataset and the eigenvectors) # automatically.** In general,", "install(package): subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", package]) # Package for downloading online files: #", "h5_u = h5_svd_group['U'] h5_v = h5_svd_group['V'] h5_s = h5_svd_group['S'] # Since the two", "a two # dimensional matrix in accordance with the pycroscopy data format. #", "matrix factorization, is a method that is useful towards unmixing of spectral #", "from __future__ import division, print_function, absolute_import, unicode_literals # basic numeric computation: import numpy", "and use your own data instead. # When using your own data, you", "using your own data, you can skip this cell and provide the path", "we load some spectral data, and perform basic data analysis, including: ======================================================================================== *", "is a three dimensional dataset that has been flattened to a two #", "Prerequisites: ======================= * Standard distribution of **Anaconda** (includes numpy, scipy, matplotlib and sci-kit", "from advanced atomic force microscopes. In this dataset, a spectra was collected for", "it is real-valued only. # # One solution is to stack the real", "NMF only works on non-negative datasets. # For illustrative purposes, we will only", "the results back into the same dataset among other things \"\"\" # Import", "USA In this notebook we load some spectral data, and perform basic data", "estimator = px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters)) h5_kmeans_grp = estimator.compute(h5_main) h5_kmeans_labels = h5_kmeans_grp['Labels'] h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response']", "x spectra] in a two dimensional matrix. # # We will be using", "<NAME> * Institute for Functional Imaging of Materials * Center for Nanophase Materials", "SVD requires care and caution in interpretation. Nonetheless, it is a good method", "spectra was collected for each position in a two # dimensional grid of", "abundance maps # * S - Variance or importance of each of these", "valued dataset. Passing the complex values as is to SVD would result in", "these analyses on any imaging dataset (regardless of origin, size, complexity) and storing", "num_comps=9, title='SVD Abundance Maps', reverse_dims=True, color_bar_mode='single', cmap='inferno', title_yoffset=0.95) # Visualize the variance /", "# Getting a reference to the main dataset: h5_main = px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main, {'quantity':", "In general, pycroscopy handles compound / complex valued datasets everywhere possible # #", "formatted in the same manner of [position x spectra] in a two dimensional", "the reconstruction of the dataset using only the first N (most significant) components.", "# dimensional matrix in accordance with the pycroscopy data format. # # Fortunately,", "evenly_spaced=False) ##################################################################################### # 2. KMeans Clustering # ==================== # # KMeans clustering is", "dataset (regardless of origin, size, complexity) and storing the results back into the", "px.hdf_utils.write_simple_attrs(h5_main, {'quantity': 'Deflection', 'units': 'V'}) # Extracting the X axis - vector of", "So, the eigenvectors would need to be restructured to get back the complex", "Ridge TN 37831, USA In this notebook we load some spectral data, and", "the first N (most significant) components. # # SVD results in three matrices:", "=========================================== # # NMF, or non-negative matrix factorization, is a method that is", "exponential drop of variance with number of components') # Visualize the eigenvectors: _", "everywhere possible # # Furthermore, while it is not discussed in this example,", "# 3. Non-negative Matrix Factorization (NMF) # =========================================== # # NMF, or non-negative", "of components') # Visualize the eigenvectors: _ = px.plot_utils.plot_complex_spectra(h5_v[:9, :], x_label=x_label, y_label=y_label, title='SVD", "# SVD results in three matrices: # # * V - Eigenvectors sorted", "# the same source h5 file including all relevant links to the source", "suited for data cleaning through # the reconstruction of the dataset using only", "One solution is to stack the real value followed by the magnitude of", "import h5py # Plotting and visualization: import matplotlib.pyplot as plt # for downloading", "Import packages # Ensure that this code works on both python 2 and", "Oak Ridge National Laboratory, Oak Ridge TN 37831, USA In this notebook we", "user inputs the number of # clusters (sets) to partition the data into.", "this code works on both python 2 and python 3 from __future__ import", "back to # the same source h5 file including all relevant links to", "# sum of squares is minimized. # # Set the number of clusters", "abundance maps from # SVD requires care and caution in interpretation. Nonetheless, it", "Principal Component Analysis Software Prerequisites: ======================= * Standard distribution of **Anaconda** (includes numpy,", "a complex valued dataset. Passing the complex values as is to SVD would", "# Set the number of clusters below num_clusters = 4 estimator = px.processing.Cluster(h5_main,", "from # SVD requires care and caution in interpretation. Nonetheless, it is a", "datasets, NMF only works on non-negative datasets. # For illustrative purposes, we will", "px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') # Getting a reference to the main dataset: h5_main = px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data'])", "is defined statistically, and therefore typically produces # non-physical eigenvectors. Consequently, the interpretation", "Jupyter Notebook (button at the bottom of the page) and use your own", "well as abundance maps. Complex valued abundance maps are not physical. # Thus,", "as abundance maps. Complex valued abundance maps are not physical. # Thus, one", "num_components=100) h5_svd_group = decomposer.compute() h5_u = h5_svd_group['U'] h5_v = h5_svd_group['V'] h5_s = h5_svd_group['S']", "GitHub project page by default. You are encouraged # to download this document", "in descending # order of variance or importance. Furthermore, SVD is also very", "# Furthermore, while it is not discussed in this example, pycroscopy also writes", "plt.subplots(figsize=(5.5, 5)) px.plot_utils.plot_line_family(axis, freq_vec, model.components_, label_prefix='NMF Component #') axis.set_xlabel(x_label, fontsize=12) axis.set_ylabel(y_label, fontsize=12) axis.set_title('NMF", "interpretation. Nonetheless, it is a good method for quickly # visualizing the major", "bar=None) h5_file = h5py.File(data_file_path, mode='r+') print('Contents of data file:') print('----------------------') px.hdf_utils.print_tree(h5_file) print('----------------------') h5_meas_grp", "to seamlessly perform these analyses on any imaging dataset (regardless of origin, size,", "resultant eigenvectors are sorted in descending # order of variance or importance. Furthermore,", "imaginary # components. So, the eigenvectors would need to be restructured to get", "the data file from Github: url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path = wget.download(url, data_file_path, bar=None)", "non-physical eigenvectors. Consequently, the interpretation of eigenvectors and abundance maps from # SVD", "Functional Imaging of Materials * Center for Nanophase Materials Sciences Oak Ridge National", "from pycroscopy.viz import cluster_utils ##################################################################################### # The Data # ======== # # In", "spectral data num_comps = 4 # get the non-negative portion of the dataset", "the same dataset among other things \"\"\" # Import packages # Ensure that", "Plotting and visualization: import matplotlib.pyplot as plt # for downloading files: import wget", "has been flattened to a two # dimensional matrix in accordance with the", "are not physical. # Thus, one would need to restructure the data such", "_ = px.plot_utils.plot_complex_spectra(h5_v[:9, :], x_label=x_label, y_label=y_label, title='SVD Eigenvectors', evenly_spaced=False) ##################################################################################### # 2. KMeans", "or importance of each of these components # # Advantage of pycroscopy: #", "# components. So, the eigenvectors would need to be restructured to get back", "components. So, the eigenvectors would need to be restructured to get back the", "title='SVD Abundance Maps', reverse_dims=True, color_bar_mode='single', cmap='inferno', title_yoffset=0.95) # Visualize the variance / statistical", "back into the same dataset among other things \"\"\" # Import packages #", "have been collapsed to one, we need to reshape the abundance maps: abun_maps", "below num_clusters = 4 estimator = px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters)) h5_kmeans_grp = estimator.compute(h5_main) h5_kmeans_labels =", "#') axis.set_xlabel(x_label, fontsize=12) axis.set_ylabel(y_label, fontsize=12) axis.set_title('NMF Components', fontsize=14) axis.legend(bbox_to_anchor=[1.0, 1.0], fontsize=12) ##################################################################################### #", "Github: url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path = wget.download(url, data_file_path, bar=None) h5_file = h5py.File(data_file_path, mode='r+')", "machine learning, spectral unmixing algorithms, etc. only accept data that is # formatted", "algorithms, etc. only accept data that is # formatted in the same manner", "SVD is an eigenvector decomposition that is defined statistically, and therefore typically produces", "default. You are encouraged # to download this document as a Jupyter Notebook", "defined statistically, and therefore typically produces # non-physical eigenvectors. Consequently, the interpretation of", "values as is to SVD would result in # complex valued eigenvectors /", "= np.reshape(h5_u[:, :25], (num_rows, num_cols, -1)) px.plot_utils.plot_map_stack(abun_maps, num_comps=9, title='SVD Abundance Maps', reverse_dims=True, color_bar_mode='single',", "/ statistical importance of each component: px.plot_utils.plot_scree(h5_s, title='Note the exponential drop of variance", "or non-negative matrix factorization, is a method that is useful towards unmixing of", "px.plot_utils.plot_line_family(axis, freq_vec, model.components_, label_prefix='NMF Component #') axis.set_xlabel(x_label, fontsize=12) axis.set_ylabel(y_label, fontsize=12) axis.set_title('NMF Components', fontsize=14)", "page) and use your own data instead. # When using your own data,", "5)) px.plot_utils.plot_line_family(axis, freq_vec, model.components_, label_prefix='NMF Component #') axis.set_xlabel(x_label, fontsize=12) axis.set_ylabel(y_label, fontsize=12) axis.set_title('NMF Components',", "pip install('pycroscopy') import pycroscopy as px from pycroscopy.viz import cluster_utils ##################################################################################### # The", "bottom of the page) and use your own data instead. # When using", "You are encouraged # to download this document as a Jupyter Notebook (button", "px.hdf_utils.print_tree(h5_file) print('----------------------') h5_meas_grp = h5_file['Measurement_000'] # Extracting some basic parameters: num_rows = px.hdf_utils.get_attr(h5_meas_grp,", "to one, we need to reshape the abundance maps: abun_maps = np.reshape(h5_u[:, :25],", "not a decomposition method, but a basic clustering method. The user inputs the", "approximate determination of # factors (matrices) W and H, given a matrix V,", "# # .. image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png # # Unlike SVD and k-Means that can", "discussed in this example, pycroscopy also writes back the results from SVD back", "Thus, this is a three dimensional dataset that has been flattened to a", "that is useful towards unmixing of spectral # data. It only works on", "eigenvectors would need to be treated as the concatenation of the real and", "works on both python 2 and python 3 from __future__ import division, print_function,", "fontsize=12) axis.set_title('NMF Components', fontsize=14) axis.legend(bbox_to_anchor=[1.0, 1.0], fontsize=12) ##################################################################################### # Close and delete the", "eigenvectors. # # **Pycroscopy handles all these data transformations (both for the source", "creating and manipulating HDF5 files: import h5py # Plotting and visualization: import matplotlib.pyplot", "of **Anaconda** (includes numpy, scipy, matplotlib and sci-kit learn) * **pycroscopy** : Though", "print('Data currently of shape:', h5_main.shape) x_label = 'Frequency (kHz)' y_label = 'Amplitude (a.u.)'", "complex valued datasets everywhere possible # # Furthermore, while it is not discussed", "= h5_svd_group['V'] h5_s = h5_svd_group['S'] # Since the two spatial dimensions (x, y)", "# # KMeans clustering is a quick and easy method to determine the", "the bottom of the page) and use your own data instead. # When", "KMeans Clustering # ==================== # # KMeans clustering is a quick and easy", "order of variance or importance. Furthermore, SVD is also very well suited for", "data_file_path data_file_path = 'temp_um.h5' # download the data file from Github: url =", "* KMeans Clustering * Non-negative Matrix Factorization * Principal Component Analysis Software Prerequisites:", "After SVD, the real-valued eigenvectors would need to be treated as the concatenation", "to your data using the variable - data_file_path data_file_path = 'temp_um.h5' # download", "**Pycroscopy handles all these data transformations (both for the source dataset and the", "parameters: num_rows = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows') num_cols = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') # Getting a reference", "np.reshape(h5_u[:, :25], (num_rows, num_cols, -1)) px.plot_utils.plot_map_stack(abun_maps, num_comps=9, title='SVD Abundance Maps', reverse_dims=True, color_bar_mode='single', cmap='inferno',", "Center for Nanophase Materials Sciences Oak Ridge National Laboratory, Oak Ridge TN 37831,", "not found. Will install with pip.') import pip install('pycroscopy') import pycroscopy as px", "##################################################################################### # The Data # ======== # # In this example, we will", "======== # # In this example, we will work on a **Band Excitation", "The user inputs the number of # clusters (sets) to partition the data", "find the optimal labeling # (ie., assignment of each spectra as belonging to", "types of spectral responses present in the # data. It is not a", "these components # # Advantage of pycroscopy: # ------------------------ # Notice that we", "can be applied to complex-valued datasets, NMF only works on non-negative datasets. #", "Piezoresponse Force Microscopy (BE-PFM)** imaging dataset # acquired from advanced atomic force microscopes.", "Ensure that this code works on both python 2 and python 3 from", "In this example, we will work on a **Band Excitation Piezoresponse Force Microscopy", "* Non-negative Matrix Factorization * Principal Component Analysis Software Prerequisites: ======================= * Standard", "concatenation of the real and imaginary # components. So, the eigenvectors would need", "print('Contents of data file:') print('----------------------') px.hdf_utils.print_tree(h5_file) print('----------------------') h5_meas_grp = h5_file['Measurement_000'] # Extracting some", "in interpretation. Nonetheless, it is a good method for quickly # visualizing the", "# data. It is not a decomposition method, but a basic clustering method.", "except ImportError: print('pycroscopy not found. Will install with pip.') import pip install('pycroscopy') import", "that we are working with a complex valued dataset. Passing the complex values", "dimensional grid of spatial locations. Thus, this is a three dimensional dataset that", "set) such that the within-cluster # sum of squares is minimized. # #", "will work on a **Band Excitation Piezoresponse Force Microscopy (BE-PFM)** imaging dataset #", "a reference to the main dataset: h5_main = px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main, {'quantity': 'Deflection', 'units':", "each spectra as belonging to the k<sup>th</sup> set) such that the within-cluster #", "h5_file['Measurement_000'] # Extracting some basic parameters: num_rows = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows') num_cols = px.hdf_utils.get_attr(h5_meas_grp,", "freq_vec, model.components_, label_prefix='NMF Component #') axis.set_xlabel(x_label, fontsize=12) axis.set_ylabel(y_label, fontsize=12) axis.set_title('NMF Components', fontsize=14) axis.legend(bbox_to_anchor=[1.0,", "computation: import numpy as np # The package used for creating and manipulating", "wget import os # multivariate analysis: from sklearn.cluster import KMeans from sklearn.decomposition import", "as a Jupyter Notebook (button at the bottom of the page) and use", "Value Decomposition (SVD) # ===================================== # # SVD is an eigenvector decomposition that", "Microscopy (BE-PFM)** imaging dataset # acquired from advanced atomic force microscopes. In this", "import pycroscopy as px except ImportError: print('pycroscopy not found. Will install with pip.')", "spatial locations. Thus, this is a three dimensional dataset that has been flattened", "physical. # Thus, one would need to restructure the data such that it", "partition the data into. The algorithm proceeds to find the optimal labeling #", "decomposition method, but a basic clustering method. The user inputs the number of", "Eigenvectors', evenly_spaced=False) ##################################################################################### # 2. KMeans Clustering # ==================== # # KMeans clustering", "we need to reshape the abundance maps: abun_maps = np.reshape(h5_u[:, :25], (num_rows, num_cols,", "component: px.plot_utils.plot_scree(h5_s, title='Note the exponential drop of variance with number of components') #", "by approximate determination of # factors (matrices) W and H, given a matrix", "variance with number of components') # Visualize the eigenvectors: _ = px.plot_utils.plot_complex_spectra(h5_v[:9, :],", "of shape:', h5_main.shape) x_label = 'Frequency (kHz)' y_label = 'Amplitude (a.u.)' ##################################################################################### #", "maps from # SVD requires care and caution in interpretation. Nonetheless, it is", "capabilities are realized through the ability to seamlessly perform these analyses on any", "abundance maps are not physical. # Thus, one would need to restructure the", "reference to the main dataset: h5_main = px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main, {'quantity': 'Deflection', 'units': 'V'})", "import NMF import subprocess import sys def install(package): subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", package])", "Fortunately, all statistical analysis, machine learning, spectral unmixing algorithms, etc. only accept data", "vector of frequencies h5_spec_vals = px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1] freq_vec = np.squeeze(h5_spec_vals.value) * 1E-3 print('Data", "spectra] in a two dimensional matrix. # # We will be using an", "and k-Means that can be applied to complex-valued datasets, NMF only works on", "size, complexity) and storing the results back into the same dataset among other", "================================================================= <NAME>, <NAME>, <NAME> * Institute for Functional Imaging of Materials * Center", "advanced atomic force microscopes. In this dataset, a spectra was collected for each", "wget.download(url, data_file_path, bar=None) h5_file = h5py.File(data_file_path, mode='r+') print('Contents of data file:') print('----------------------') px.hdf_utils.print_tree(h5_file)", "h5py.File(data_file_path, mode='r+') print('Contents of data file:') print('----------------------') px.hdf_utils.print_tree(h5_file) print('----------------------') h5_meas_grp = h5_file['Measurement_000'] #", "'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path = wget.download(url, data_file_path, bar=None) h5_file = h5py.File(data_file_path, mode='r+') print('Contents of data", "components # # Advantage of pycroscopy: # ------------------------ # Notice that we are", "locations. Thus, this is a three dimensional dataset that has been flattened to", "algorithm proceeds to find the optimal labeling # (ie., assignment of each spectra", "and provide the path to your data using the variable - data_file_path data_file_path", "3. Non-negative Matrix Factorization (NMF) # =========================================== # # NMF, or non-negative matrix", "the complex valued eigenvectors. # # **Pycroscopy handles all these data transformations (both", "the source dataset and the eigenvectors) # automatically.** In general, pycroscopy handles compound", "numeric computation: import numpy as np # The package used for creating and", "project page by default. You are encouraged # to download this document as", "px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows') num_cols = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') # Getting a reference to the main", "data with positive real values. It operates by approximate determination of # factors", "eigenvectors and abundance maps from # SVD requires care and caution in interpretation.", "'temp_um.h5' # download the data file from Github: url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path =", "of each spectra as belonging to the k<sup>th</sup> set) such that the within-cluster", "very well suited for data cleaning through # the reconstruction of the dataset", "possible # # Furthermore, while it is not discussed in this example, pycroscopy", "that is # formatted in the same manner of [position x spectra] in", "eigenvectors. Consequently, the interpretation of eigenvectors and abundance maps from # SVD requires", "valued datasets everywhere possible # # Furthermore, while it is not discussed in", "only, it's true capabilities are realized through the ability to seamlessly perform these", "= h5_svd_group['S'] # Since the two spatial dimensions (x, y) have been collapsed", "import cluster_utils ##################################################################################### # The Data # ======== # # In this example,", "data using the variable - data_file_path data_file_path = 'temp_um.h5' # download the data", "HDF5 files: import h5py # Plotting and visualization: import matplotlib.pyplot as plt #", "was collected for each position in a two # dimensional grid of spatial", "dataset. Passing the complex values as is to SVD would result in #", "well suited for data cleaning through # the reconstruction of the dataset using", "Oak Ridge TN 37831, USA In this notebook we load some spectral data,", "# Extracting the X axis - vector of frequencies h5_spec_vals = px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1]", "# complex valued eigenvectors / endmembers as well as abundance maps. Complex valued", "this example, pycroscopy also writes back the results from SVD back to #", "in descending order # * U - corresponding abundance maps # * S", "grid of spatial locations. Thus, this is a three dimensional dataset that has", "for creating and manipulating HDF5 files: import h5py # Plotting and visualization: import", "dimensions (x, y) have been collapsed to one, we need to reshape the", "storing the results back into the same dataset among other things \"\"\" #", "# ======== # # In this example, we will work on a **Band", "sci-kit learn) * **pycroscopy** : Though pycroscopy is mainly used here for plotting", "to SVD. # After SVD, the real-valued eigenvectors would need to be treated", "Component Analysis Software Prerequisites: ======================= * Standard distribution of **Anaconda** (includes numpy, scipy,", "# We will be using an data file available on our GitHub project", "# * U - corresponding abundance maps # * S - Variance or", "file available on our GitHub project page by default. You are encouraged #", "<NAME>, <NAME>, <NAME> * Institute for Functional Imaging of Materials * Center for", "def install(package): subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", package]) # Package for downloading online files:", "- Variance or importance of each of these components # # Advantage of", "eigenvectors: _ = px.plot_utils.plot_complex_spectra(h5_v[:9, :], x_label=x_label, y_label=y_label, title='SVD Eigenvectors', evenly_spaced=False) ##################################################################################### # 2.", "the k<sup>th</sup> set) such that the within-cluster # sum of squares is minimized.", "division, print_function, absolute_import, unicode_literals # basic numeric computation: import numpy as np #", "this document as a Jupyter Notebook (button at the bottom of the page)", "complexity) and storing the results back into the same dataset among other things", "descending order # * U - corresponding abundance maps # * S -", "page by default. You are encouraged # to download this document as a", "pycroscopy.viz import cluster_utils ##################################################################################### # The Data # ======== # # In this", "h5_file = h5py.File(data_file_path, mode='r+') print('Contents of data file:') print('----------------------') px.hdf_utils.print_tree(h5_file) print('----------------------') h5_meas_grp =", "only. # # One solution is to stack the real value followed by", "# formatted in the same manner of [position x spectra] in a two", "num_clusters = 4 estimator = px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters)) h5_kmeans_grp = estimator.compute(h5_main) h5_kmeans_labels = h5_kmeans_grp['Labels']", "caution in interpretation. Nonetheless, it is a good method for quickly # visualizing", "on data with positive real values. It operates by approximate determination of #", "# One solution is to stack the real value followed by the magnitude", "matrix. # # We will be using an data file available on our", "Advantage of pycroscopy: # ------------------------ # Notice that we are working with a", "print('----------------------') h5_meas_grp = h5_file['Measurement_000'] # Extracting some basic parameters: num_rows = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows')", "complex-valued datasets, NMF only works on non-negative datasets. # For illustrative purposes, we", "ImportError: print('pycroscopy not found. Will install with pip.') import pip install('pycroscopy') import pycroscopy", "# In this example, we will work on a **Band Excitation Piezoresponse Force", "the imaginary component before passing to SVD. # After SVD, the real-valued eigenvectors", "h5_kmeans_grp['Labels'] h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### # 3. Non-negative Matrix Factorization (NMF) #", "with the pycroscopy data format. # # Fortunately, all statistical analysis, machine learning,", "# Extracting some basic parameters: num_rows = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows') num_cols = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols')", "be applied to complex-valued datasets, NMF only works on non-negative datasets. # For", "# visualizing the major trends in the dataset since the resultant eigenvectors are", "h5_main.shape) x_label = 'Frequency (kHz)' y_label = 'Amplitude (a.u.)' ##################################################################################### # 1. Singular", "of eigenvectors and abundance maps from # SVD requires care and caution in", "would need to be treated as the concatenation of the real and imaginary", "microscopes. In this dataset, a spectra was collected for each position in a", "'V'}) # Extracting the X axis - vector of frequencies h5_spec_vals = px.hdf_utils.get_auxiliary_datasets(h5_main,", "complex valued eigenvectors / endmembers as well as abundance maps. Complex valued abundance", "to the source dataset and other ancillary datasets decomposer = px.processing.svd_utils.SVD(h5_main, num_components=100) h5_svd_group", "with number of components') # Visualize the eigenvectors: _ = px.plot_utils.plot_complex_spectra(h5_v[:9, :], x_label=x_label,", "number of clusters below num_clusters = 4 estimator = px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters)) h5_kmeans_grp =", "is minimized. # # Set the number of clusters below num_clusters = 4", "analyses on any imaging dataset (regardless of origin, size, complexity) and storing the", "spatial dimensions (x, y) have been collapsed to one, we need to reshape", "non-negative matrix factorization, is a method that is useful towards unmixing of spectral", "# data. It only works on data with positive real values. It operates", "axis = plt.subplots(figsize=(5.5, 5)) px.plot_utils.plot_line_family(axis, freq_vec, model.components_, label_prefix='NMF Component #') axis.set_xlabel(x_label, fontsize=12) axis.set_ylabel(y_label,", "acquired from advanced atomic force microscopes. In this dataset, a spectra was collected", "Software Prerequisites: ======================= * Standard distribution of **Anaconda** (includes numpy, scipy, matplotlib and", "the real and imaginary # components. So, the eigenvectors would need to be", "data that is # formatted in the same manner of [position x spectra]", "# * V - Eigenvectors sorted by variance in descending order # *", "treated as the concatenation of the real and imaginary # components. So, the", "applied to complex-valued datasets, NMF only works on non-negative datasets. # For illustrative", "axis - vector of frequencies h5_spec_vals = px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1] freq_vec = np.squeeze(h5_spec_vals.value) *", "or importance. Furthermore, SVD is also very well suited for data cleaning through", "to # the same source h5 file including all relevant links to the", "color_bar_mode='single', cmap='inferno', title_yoffset=0.95) # Visualize the variance / statistical importance of each component:", "non-negative portion of the dataset data_mat = np.abs(h5_main) model = NMF(n_components=num_comps, init='random', random_state=0)", "variable - data_file_path data_file_path = 'temp_um.h5' # download the data file from Github:", "a spectra was collected for each position in a two # dimensional grid", "to download this document as a Jupyter Notebook (button at the bottom of", "Abundance Maps', reverse_dims=True, color_bar_mode='single', cmap='inferno', title_yoffset=0.95) # Visualize the variance / statistical importance", "spectra as belonging to the k<sup>th</sup> set) such that the within-cluster # sum", "NMF, or non-negative matrix factorization, is a method that is useful towards unmixing", "* 1E-3 print('Data currently of shape:', h5_main.shape) x_label = 'Frequency (kHz)' y_label =", "in the # data. It is not a decomposition method, but a basic", "SVD back to # the same source h5 file including all relevant links", "and sci-kit learn) * **pycroscopy** : Though pycroscopy is mainly used here for", "back the results from SVD back to # the same source h5 file", "restructure the data such that it is real-valued only. # # One solution", "= px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main, {'quantity': 'Deflection', 'units': 'V'}) # Extracting the X axis -", "and storing the results back into the same dataset among other things \"\"\"", "typically produces # non-physical eigenvectors. Consequently, the interpretation of eigenvectors and abundance maps", "quickly # visualizing the major trends in the dataset since the resultant eigenvectors", "an data file available on our GitHub project page by default. You are", "of the spectral data num_comps = 4 # get the non-negative portion of", "your own data instead. # When using your own data, you can skip", "and imaginary # components. So, the eigenvectors would need to be restructured to", "with positive real values. It operates by approximate determination of # factors (matrices)", ":25], (num_rows, num_cols, -1)) px.plot_utils.plot_map_stack(abun_maps, num_comps=9, title='SVD Abundance Maps', reverse_dims=True, color_bar_mode='single', cmap='inferno', title_yoffset=0.95)", "- Eigenvectors sorted by variance in descending order # * U - corresponding", "------------------------ # Notice that we are working with a complex valued dataset. Passing", "(button at the bottom of the page) and use your own data instead.", "import division, print_function, absolute_import, unicode_literals # basic numeric computation: import numpy as np", "h5_v = h5_svd_group['V'] h5_s = h5_svd_group['S'] # Since the two spatial dimensions (x,", "need to restructure the data such that it is real-valued only. # #", "on a **Band Excitation Piezoresponse Force Microscopy (BE-PFM)** imaging dataset # acquired from", "clustering is a quick and easy method to determine the types of spectral", "to a two # dimensional matrix in accordance with the pycroscopy data format.", "data file:') print('----------------------') px.hdf_utils.print_tree(h5_file) print('----------------------') h5_meas_grp = h5_file['Measurement_000'] # Extracting some basic parameters:", "the exponential drop of variance with number of components') # Visualize the eigenvectors:", "data_mat = np.abs(h5_main) model = NMF(n_components=num_comps, init='random', random_state=0) model.fit(data_mat) fig, axis = plt.subplots(figsize=(5.5,", "numpy, scipy, matplotlib and sci-kit learn) * **pycroscopy** : Though pycroscopy is mainly", "as px except ImportError: print('pycroscopy not found. Will install with pip.') import pip", "using an data file available on our GitHub project page by default. You", "to SVD would result in # complex valued eigenvectors / endmembers as well", "fontsize=12) axis.set_ylabel(y_label, fontsize=12) axis.set_title('NMF Components', fontsize=14) axis.legend(bbox_to_anchor=[1.0, 1.0], fontsize=12) ##################################################################################### # Close and", "used for creating and manipulating HDF5 files: import h5py # Plotting and visualization:", "fontsize=14) axis.legend(bbox_to_anchor=[1.0, 1.0], fontsize=12) ##################################################################################### # Close and delete the h5_file h5_file.close() os.remove(data_file_path)", "responses present in the # data. It is not a decomposition method, but", "for Nanophase Materials Sciences Oak Ridge National Laboratory, Oak Ridge TN 37831, USA", "======================= * Standard distribution of **Anaconda** (includes numpy, scipy, matplotlib and sci-kit learn)", "= 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path = wget.download(url, data_file_path, bar=None) h5_file = h5py.File(data_file_path, mode='r+') print('Contents of", "abun_maps = np.reshape(h5_u[:, :25], (num_rows, num_cols, -1)) px.plot_utils.plot_map_stack(abun_maps, num_comps=9, title='SVD Abundance Maps', reverse_dims=True,", "sklearn.cluster import KMeans from sklearn.decomposition import NMF import subprocess import sys def install(package):", "in this example, pycroscopy also writes back the results from SVD back to", "file:') print('----------------------') px.hdf_utils.print_tree(h5_file) print('----------------------') h5_meas_grp = h5_file['Measurement_000'] # Extracting some basic parameters: num_rows", "restructured to get back the complex valued eigenvectors. # # **Pycroscopy handles all", "of squares is minimized. # # Set the number of clusters below num_clusters", "num_comps = 4 # get the non-negative portion of the dataset data_mat =", "1. Singular Value Decomposition (SVD) # ===================================== # # SVD is an eigenvector", "into the same dataset among other things \"\"\" # Import packages # Ensure", "# ------------------------ # Notice that we are working with a complex valued dataset.", "real and imaginary # components. So, the eigenvectors would need to be restructured", "will only take the amplitude component of the spectral data num_comps = 4", "of the imaginary component before passing to SVD. # After SVD, the real-valued", "the variance / statistical importance of each component: px.plot_utils.plot_scree(h5_s, title='Note the exponential drop", "this notebook we load some spectral data, and perform basic data analysis, including:", "sorted in descending # order of variance or importance. Furthermore, SVD is also", "with a complex valued dataset. Passing the complex values as is to SVD", "handles compound / complex valued datasets everywhere possible # # Furthermore, while it", "__future__ import division, print_function, absolute_import, unicode_literals # basic numeric computation: import numpy as", "are working with a complex valued dataset. Passing the complex values as is", "S - Variance or importance of each of these components # # Advantage", "# # Set the number of clusters below num_clusters = 4 estimator =", "of [position x spectra] in a two dimensional matrix. # # We will", "the source dataset and other ancillary datasets decomposer = px.processing.svd_utils.SVD(h5_main, num_components=100) h5_svd_group =", "# acquired from advanced atomic force microscopes. In this dataset, a spectra was", "need to be treated as the concatenation of the real and imaginary #", "by default. You are encouraged # to download this document as a Jupyter", "X axis - vector of frequencies h5_spec_vals = px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1] freq_vec = np.squeeze(h5_spec_vals.value)", "files: import h5py # Plotting and visualization: import matplotlib.pyplot as plt # for", "px from pycroscopy.viz import cluster_utils ##################################################################################### # The Data # ======== # #", "/ endmembers as well as abundance maps. Complex valued abundance maps are not", "data into. The algorithm proceeds to find the optimal labeling # (ie., assignment", "reverse_dims=True, color_bar_mode='single', cmap='inferno', title_yoffset=0.95) # Visualize the variance / statistical importance of each", "# # Furthermore, while it is not discussed in this example, pycroscopy also", "clusters (sets) to partition the data into. The algorithm proceeds to find the", "eigenvector decomposition that is defined statistically, and therefore typically produces # non-physical eigenvectors.", "a two dimensional matrix. # # We will be using an data file", "the abundance maps: abun_maps = np.reshape(h5_u[:, :25], (num_rows, num_cols, -1)) px.plot_utils.plot_map_stack(abun_maps, num_comps=9, title='SVD", "is not a decomposition method, but a basic clustering method. The user inputs", "# ===================================== # # SVD is an eigenvector decomposition that is defined statistically,", "force microscopes. In this dataset, a spectra was collected for each position in", "# # Advantage of pycroscopy: # ------------------------ # Notice that we are working", "Laboratory, Oak Ridge TN 37831, USA In this notebook we load some spectral", "on non-negative datasets. # For illustrative purposes, we will only take the amplitude", "that can be applied to complex-valued datasets, NMF only works on non-negative datasets.", "= h5py.File(data_file_path, mode='r+') print('Contents of data file:') print('----------------------') px.hdf_utils.print_tree(h5_file) print('----------------------') h5_meas_grp = h5_file['Measurement_000']", "SVD would result in # complex valued eigenvectors / endmembers as well as", "==================== # # KMeans clustering is a quick and easy method to determine", "# Since the two spatial dimensions (x, y) have been collapsed to one,", "accept data that is # formatted in the same manner of [position x", "results from SVD back to # the same source h5 file including all", "will be using an data file available on our GitHub project page by", "to the main dataset: h5_main = px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main, {'quantity': 'Deflection', 'units': 'V'}) #", "number of # clusters (sets) to partition the data into. The algorithm proceeds", "# # SVD is an eigenvector decomposition that is defined statistically, and therefore", "h5_svd_group['U'] h5_v = h5_svd_group['V'] h5_s = h5_svd_group['S'] # Since the two spatial dimensions", "is useful towards unmixing of spectral # data. It only works on data", "the results from SVD back to # the same source h5 file including", "currently of shape:', h5_main.shape) x_label = 'Frequency (kHz)' y_label = 'Amplitude (a.u.)' #####################################################################################", "here for plotting purposes only, it's true capabilities are realized through the ability", "been flattened to a two # dimensional matrix in accordance with the pycroscopy", "Notebook (button at the bottom of the page) and use your own data", "# # * V - Eigenvectors sorted by variance in descending order #", "'Amplitude (a.u.)' ##################################################################################### # 1. Singular Value Decomposition (SVD) # ===================================== # #", "things \"\"\" # Import packages # Ensure that this code works on both", "matrix in accordance with the pycroscopy data format. # # Fortunately, all statistical", "W and H, given a matrix V, as shown below # # ..", "(BE-PFM)** imaging dataset # acquired from advanced atomic force microscopes. In this dataset,", "Consequently, the interpretation of eigenvectors and abundance maps from # SVD requires care", "before passing to SVD. # After SVD, the real-valued eigenvectors would need to", "at the bottom of the page) and use your own data instead. #", "proceeds to find the optimal labeling # (ie., assignment of each spectra as", "SVD, the real-valued eigenvectors would need to be treated as the concatenation of", "scipy, matplotlib and sci-kit learn) * **pycroscopy** : Though pycroscopy is mainly used", "Set the number of clusters below num_clusters = 4 estimator = px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters))", "abundance maps. Complex valued abundance maps are not physical. # Thus, one would", "of these components # # Advantage of pycroscopy: # ------------------------ # Notice that", "the dataset since the resultant eigenvectors are sorted in descending # order of", "each component: px.plot_utils.plot_scree(h5_s, title='Note the exponential drop of variance with number of components')", "use your own data instead. # When using your own data, you can", "= px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters)) h5_kmeans_grp = estimator.compute(h5_main) h5_kmeans_labels = h5_kmeans_grp['Labels'] h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp)", "# # NMF, or non-negative matrix factorization, is a method that is useful", "# # One solution is to stack the real value followed by the", "maps are not physical. # Thus, one would need to restructure the data", "three dimensional dataset that has been flattened to a two # dimensional matrix", "one, we need to reshape the abundance maps: abun_maps = np.reshape(h5_u[:, :25], (num_rows,", "spectral data, and perform basic data analysis, including: ======================================================================================== * KMeans Clustering *", "such that the within-cluster # sum of squares is minimized. # # Set", "and the eigenvectors) # automatically.** In general, pycroscopy handles compound / complex valued", "be using an data file available on our GitHub project page by default.", "real value followed by the magnitude of the imaginary component before passing to", "collapsed to one, we need to reshape the abundance maps: abun_maps = np.reshape(h5_u[:,", "print('pycroscopy not found. Will install with pip.') import pip install('pycroscopy') import pycroscopy as", "'Deflection', 'units': 'V'}) # Extracting the X axis - vector of frequencies h5_spec_vals", "in the same manner of [position x spectra] in a two dimensional matrix.", "the number of clusters below num_clusters = 4 estimator = px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters)) h5_kmeans_grp", "inputs the number of # clusters (sets) to partition the data into. The", "(kHz)' y_label = 'Amplitude (a.u.)' ##################################################################################### # 1. Singular Value Decomposition (SVD) #", "# download the data file from Github: url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path = wget.download(url,", "k-Means that can be applied to complex-valued datasets, NMF only works on non-negative", "data_file_path, bar=None) h5_file = h5py.File(data_file_path, mode='r+') print('Contents of data file:') print('----------------------') px.hdf_utils.print_tree(h5_file) print('----------------------')", "to the k<sup>th</sup> set) such that the within-cluster # sum of squares is", "Though pycroscopy is mainly used here for plotting purposes only, it's true capabilities", "Factorization (NMF) # =========================================== # # NMF, or non-negative matrix factorization, is a", "positive real values. It operates by approximate determination of # factors (matrices) W", "components. # # SVD results in three matrices: # # * V -", "- corresponding abundance maps # * S - Variance or importance of each", "of # factors (matrices) W and H, given a matrix V, as shown" ]
[ "TestCase from unittest.mock import Mock from unittest.mock import patch from foliant.config.downloadfile import download_file", "= get_file_ext_from_url(url) self.assertEqual(ext, '.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' ext = get_file_ext_from_url(url) self.assertEqual(ext,", "unittest import TestCase from unittest.mock import Mock from unittest.mock import patch from foliant.config.downloadfile", "def test_no_ext(self): url = 'http://example.com/sub/myfile' ext = get_file_ext_from_url(url) self.assertEqual(ext, '') def test_with_clutter(self): url", "self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen',", "foliant.config.downloadfile import get_file_name_from_url class TestDownloadFile(TestCase): def setUp(self): self.project_dir = (Path(__file__).parent / 'project_dir').resolve() self.project_dir.mkdir(exist_ok=True)", "content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file(root_dir=self.project_dir, url=url) request = urlopen.call_args.args[0] context", "content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_save_to(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content'", "urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertIn('Authorization', request.headers) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f:", "= urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertIn('Authorization', request.headers) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as", "url = 'http://example.com/sub/myfile.txt' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile'", "{}) self.assertIsNone(context) with open(self.project_dir / save_to) as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True)", "= 'http://example.com/sub/myfile.txt' ext = get_file_ext_from_url(url) self.assertEqual(ext, '.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' ext", "save_to=save_to) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir /", "ext = get_file_ext_from_url(url) self.assertEqual(ext, '.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' ext = get_file_ext_from_url(url)", "from unittest.mock import patch from foliant.config.downloadfile import download_file from foliant.config.downloadfile import get_file_ext_from_url from", "def test_only_url(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content' urlopen.return_value = mock_response", "content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_with_auth(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content'", "'http://example.com/sub/myfile' ext = get_file_ext_from_url(url) self.assertEqual(ext, '') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' ext =", "url=url, save_to=save_to) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir", "request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt')", "url=url, login='john', password='<PASSWORD>' ) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertIn('Authorization', request.headers) self.assertIsNone(context)", "from unittest import TestCase from unittest.mock import Mock from unittest.mock import patch from", "password='<PASSWORD>' ) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertIn('Authorization', request.headers) self.assertIsNone(context) with open(self.project_dir", "from pathlib import Path from unittest import TestCase from unittest.mock import Mock from", "b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file( root_dir=self.project_dir, url=url, login='john', password='<PASSWORD>'", "open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File content') class TestGetFileNameFromURL(TestCase): def test_with_ext(self): url", "import patch from foliant.config.downloadfile import download_file from foliant.config.downloadfile import get_file_ext_from_url from foliant.config.downloadfile import", "content') class TestGetFileNameFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt')", "= get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') class TestGetFileExtFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' ext =", "request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertIn('Authorization', request.headers) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt')", "= (Path(__file__).parent / 'project_dir').resolve() self.project_dir.mkdir(exist_ok=True) def tearDown(self): shutil.rmtree(self.project_dir, ignore_errors=True) @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_only_url(self,", "'File content') class TestGetFileNameFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' name = get_file_name_from_url(url) self.assertEqual(name,", "'myfile.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile') def test_with_clutter(self):", "test_no_ext(self): url = 'http://example.com/sub/myfile' ext = get_file_ext_from_url(url) self.assertEqual(ext, '') def test_with_clutter(self): url =", "def test_save_to(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content' urlopen.return_value = mock_response", "mock_response.read.return_value = b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file(root_dir=self.project_dir, url=url) request", "self.assertIsNone(context) with open(self.project_dir / save_to) as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def", "class TestGetFileExtFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' ext = get_file_ext_from_url(url) self.assertEqual(ext, '.txt') def", "get_file_name_from_url class TestDownloadFile(TestCase): def setUp(self): self.project_dir = (Path(__file__).parent / 'project_dir').resolve() self.project_dir.mkdir(exist_ok=True) def tearDown(self):", "url = 'http://example.com/sub/myfile' ext = get_file_ext_from_url(url) self.assertEqual(ext, '') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar'", "get_file_ext_from_url(url) self.assertEqual(ext, '') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' ext = get_file_ext_from_url(url) self.assertEqual(ext, '.txt')", "request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / save_to)", "= mock_response url = 'http://example.com/myfile.txt' download_file( root_dir=self.project_dir, url=url, login='john', password='<PASSWORD>' ) request =", "self.assertEqual(name, 'myfile.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile') def", "url = 'http://example.com/myfile.txt' save_to = 'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir, url=url, save_to=save_to) request = urlopen.call_args.args[0] context", "'myfile') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') class TestGetFileExtFromURL(TestCase):", "= 'http://example.com/sub/myfile.txt' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' name", "self.assertEqual(name, 'myfile.txt') class TestGetFileExtFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' ext = get_file_ext_from_url(url) self.assertEqual(ext,", "mock_response url = 'http://example.com/myfile.txt' save_to = 'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir, url=url, save_to=save_to) request = urlopen.call_args.args[0]", "as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_save_to(self, urlopen): mock_response = Mock()", "def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') class TestGetFileExtFromURL(TestCase): def", "'http://example.com/myfile.txt' download_file( root_dir=self.project_dir, url=url, login='john', password='<PASSWORD>' ) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context']", "self.assertEqual(name, 'myfile') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') class", "from foliant.config.downloadfile import get_file_ext_from_url from foliant.config.downloadfile import get_file_name_from_url class TestDownloadFile(TestCase): def setUp(self): self.project_dir", "= 'http://example.com/myfile.txt' download_file( root_dir=self.project_dir, url=url, login='john', password='<PASSWORD>' ) request = urlopen.call_args.args[0] context =", "download_file(root_dir=self.project_dir, url=url, save_to=save_to) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with", "= urlopen.call_args.kwargs['context'] self.assertIn('Authorization', request.headers) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File", "{}) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True)", "/ 'myfile.txt') as f: self.assertEqual(f.read(), 'File content') class TestGetFileNameFromURL(TestCase): def test_with_ext(self): url =", "class TestGetFileNameFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') def", "from unittest.mock import Mock from unittest.mock import patch from foliant.config.downloadfile import download_file from", "f: self.assertEqual(f.read(), 'File content') class TestGetFileNameFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' name =", "url = 'http://example.com/sub/myfile' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar'", "urlopen): mock_response = Mock() mock_response.read.return_value = b'File content' urlopen.return_value = mock_response url =", "name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' name = get_file_name_from_url(url)", "name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') class TestGetFileExtFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' ext", "'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_with_auth(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File", "get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile')", "urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / save_to) as f:", "def test_with_auth(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content' urlopen.return_value = mock_response", "root_dir=self.project_dir, url=url, login='john', password='<PASSWORD>' ) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertIn('Authorization', request.headers)", "test_with_ext(self): url = 'http://example.com/sub/myfile.txt' ext = get_file_ext_from_url(url) self.assertEqual(ext, '.txt') def test_no_ext(self): url =", "self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_save_to(self, urlopen): mock_response = Mock() mock_response.read.return_value =", "context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(),", "foliant.config.downloadfile import download_file from foliant.config.downloadfile import get_file_ext_from_url from foliant.config.downloadfile import get_file_name_from_url class TestDownloadFile(TestCase):", "b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file(root_dir=self.project_dir, url=url) request = urlopen.call_args.args[0]", "mock_response.read.return_value = b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' save_to = 'subdir1/subdir2/downloaded.txt'", "urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' save_to = 'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir, url=url, save_to=save_to) request", "def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' ext = get_file_ext_from_url(url) self.assertEqual(ext, '.txt') def test_no_ext(self): url", "login='john', password='<PASSWORD>' ) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertIn('Authorization', request.headers) self.assertIsNone(context) with", "b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' save_to = 'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir, url=url,", "/ 'project_dir').resolve() self.project_dir.mkdir(exist_ok=True) def tearDown(self): shutil.rmtree(self.project_dir, ignore_errors=True) @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_only_url(self, urlopen): mock_response", "self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / save_to) as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen',", "self.assertEqual(f.read(), 'File content') class TestGetFileNameFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' name = get_file_name_from_url(url)", "= get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' name = get_file_name_from_url(url) self.assertEqual(name,", "test_no_ext(self): url = 'http://example.com/sub/myfile' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile') def test_with_clutter(self): url =", "import TestCase from unittest.mock import Mock from unittest.mock import patch from foliant.config.downloadfile import", "from foliant.config.downloadfile import get_file_name_from_url class TestDownloadFile(TestCase): def setUp(self): self.project_dir = (Path(__file__).parent / 'project_dir').resolve()", "def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') def test_no_ext(self): url", "class TestDownloadFile(TestCase): def setUp(self): self.project_dir = (Path(__file__).parent / 'project_dir').resolve() self.project_dir.mkdir(exist_ok=True) def tearDown(self): shutil.rmtree(self.project_dir,", "'myfile.txt') class TestGetFileExtFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' ext = get_file_ext_from_url(url) self.assertEqual(ext, '.txt')", "with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_save_to(self,", "/ save_to) as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_with_auth(self, urlopen): mock_response", "mock_response = Mock() mock_response.read.return_value = b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt'", "= b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file(root_dir=self.project_dir, url=url) request =", "= Mock() mock_response.read.return_value = b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' save_to", "@patch('foliant.config.downloadfile.urlopen', autospec=True) def test_with_auth(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content' urlopen.return_value", "url = 'http://example.com/myfile.txt' download_file( root_dir=self.project_dir, url=url, login='john', password='<PASSWORD>' ) request = urlopen.call_args.args[0] context", "import Path from unittest import TestCase from unittest.mock import Mock from unittest.mock import", "patch from foliant.config.downloadfile import download_file from foliant.config.downloadfile import get_file_ext_from_url from foliant.config.downloadfile import get_file_name_from_url", "Mock() mock_response.read.return_value = b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file( root_dir=self.project_dir,", "pathlib import Path from unittest import TestCase from unittest.mock import Mock from unittest.mock", "test_save_to(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content' urlopen.return_value = mock_response url", "context = urlopen.call_args.kwargs['context'] self.assertIn('Authorization', request.headers) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(),", "with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File content') class TestGetFileNameFromURL(TestCase): def test_with_ext(self):", "= b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file( root_dir=self.project_dir, url=url, login='john',", "open(self.project_dir / save_to) as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_with_auth(self, urlopen):", "def setUp(self): self.project_dir = (Path(__file__).parent / 'project_dir').resolve() self.project_dir.mkdir(exist_ok=True) def tearDown(self): shutil.rmtree(self.project_dir, ignore_errors=True) @patch('foliant.config.downloadfile.urlopen',", "test_with_auth(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content' urlopen.return_value = mock_response url", "ignore_errors=True) @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_only_url(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content'", "TestDownloadFile(TestCase): def setUp(self): self.project_dir = (Path(__file__).parent / 'project_dir').resolve() self.project_dir.mkdir(exist_ok=True) def tearDown(self): shutil.rmtree(self.project_dir, ignore_errors=True)", "autospec=True) def test_with_auth(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content' urlopen.return_value =", "unittest.mock import Mock from unittest.mock import patch from foliant.config.downloadfile import download_file from foliant.config.downloadfile", "self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File content') class TestGetFileNameFromURL(TestCase): def", "url=url) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir /", "'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_save_to(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File", "url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') class TestGetFileExtFromURL(TestCase): def test_with_ext(self): url", "mock_response url = 'http://example.com/myfile.txt' download_file( root_dir=self.project_dir, url=url, login='john', password='<PASSWORD>' ) request = urlopen.call_args.args[0]", "= Mock() mock_response.read.return_value = b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file(", "= mock_response url = 'http://example.com/myfile.txt' download_file(root_dir=self.project_dir, url=url) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context']", "@patch('foliant.config.downloadfile.urlopen', autospec=True) def test_save_to(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content' urlopen.return_value", "= b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' save_to = 'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir,", "shutil.rmtree(self.project_dir, ignore_errors=True) @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_only_url(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File", "save_to) as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_with_auth(self, urlopen): mock_response =", "from foliant.config.downloadfile import download_file from foliant.config.downloadfile import get_file_ext_from_url from foliant.config.downloadfile import get_file_name_from_url class", "= get_file_ext_from_url(url) self.assertEqual(ext, '') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' ext = get_file_ext_from_url(url) self.assertEqual(ext,", "'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir, url=url, save_to=save_to) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context)", "= urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / save_to) as", "'project_dir').resolve() self.project_dir.mkdir(exist_ok=True) def tearDown(self): shutil.rmtree(self.project_dir, ignore_errors=True) @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_only_url(self, urlopen): mock_response =", "def tearDown(self): shutil.rmtree(self.project_dir, ignore_errors=True) @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_only_url(self, urlopen): mock_response = Mock() mock_response.read.return_value", "mock_response.read.return_value = b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file( root_dir=self.project_dir, url=url,", "self.project_dir.mkdir(exist_ok=True) def tearDown(self): shutil.rmtree(self.project_dir, ignore_errors=True) @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_only_url(self, urlopen): mock_response = Mock()", "setUp(self): self.project_dir = (Path(__file__).parent / 'project_dir').resolve() self.project_dir.mkdir(exist_ok=True) def tearDown(self): shutil.rmtree(self.project_dir, ignore_errors=True) @patch('foliant.config.downloadfile.urlopen', autospec=True)", "as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_with_auth(self, urlopen): mock_response = Mock()", "f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_with_auth(self, urlopen): mock_response = Mock() mock_response.read.return_value", "= 'http://example.com/sub/myfile.txt?param=val&foo=bar' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') class TestGetFileExtFromURL(TestCase): def test_with_ext(self): url =", "'http://example.com/sub/myfile.txt?param=val&foo=bar' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') class TestGetFileExtFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt'", "= 'http://example.com/sub/myfile' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' name", "'myfile.txt') as f: self.assertEqual(f.read(), 'File content') class TestGetFileNameFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt'", ") request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertIn('Authorization', request.headers) self.assertIsNone(context) with open(self.project_dir /", "TestGetFileExtFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' ext = get_file_ext_from_url(url) self.assertEqual(ext, '.txt') def test_no_ext(self):", "self.assertIn('Authorization', request.headers) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File content') class", "urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File content')", "with open(self.project_dir / save_to) as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_with_auth(self,", "self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def", "test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') class TestGetFileExtFromURL(TestCase): def test_with_ext(self):", "= get_file_name_from_url(url) self.assertEqual(name, 'myfile') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' name = get_file_name_from_url(url) self.assertEqual(name,", "'http://example.com/sub/myfile.txt' ext = get_file_ext_from_url(url) self.assertEqual(ext, '.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' ext =", "'http://example.com/myfile.txt' save_to = 'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir, url=url, save_to=save_to) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context']", "content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file( root_dir=self.project_dir, url=url, login='john', password='<PASSWORD>' )", "= urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / save_to) as f: self.assertEqual(f.read(), 'File", "Mock() mock_response.read.return_value = b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file(root_dir=self.project_dir, url=url)", "self.assertEqual(ext, '.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' ext = get_file_ext_from_url(url) self.assertEqual(ext, '') def", "import download_file from foliant.config.downloadfile import get_file_ext_from_url from foliant.config.downloadfile import get_file_name_from_url class TestDownloadFile(TestCase): def", "download_file( root_dir=self.project_dir, url=url, login='john', password='<PASSWORD>' ) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertIn('Authorization',", "download_file(root_dir=self.project_dir, url=url) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir", "= 'http://example.com/myfile.txt' download_file(root_dir=self.project_dir, url=url) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context)", "foliant.config.downloadfile import get_file_ext_from_url from foliant.config.downloadfile import get_file_name_from_url class TestDownloadFile(TestCase): def setUp(self): self.project_dir =", "shutil from pathlib import Path from unittest import TestCase from unittest.mock import Mock", "urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / save_to) as f: self.assertEqual(f.read(), 'File content')", "ext = get_file_ext_from_url(url) self.assertEqual(ext, '') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' ext = get_file_ext_from_url(url)", "/ 'myfile.txt') as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_save_to(self, urlopen): mock_response", "url = 'http://example.com/myfile.txt' download_file(root_dir=self.project_dir, url=url) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {})", "def test_no_ext(self): url = 'http://example.com/sub/myfile' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile') def test_with_clutter(self): url", "request.headers) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File content') class TestGetFileNameFromURL(TestCase):", "tearDown(self): shutil.rmtree(self.project_dir, ignore_errors=True) @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_only_url(self, urlopen): mock_response = Mock() mock_response.read.return_value =", "= mock_response url = 'http://example.com/myfile.txt' save_to = 'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir, url=url, save_to=save_to) request =", "import Mock from unittest.mock import patch from foliant.config.downloadfile import download_file from foliant.config.downloadfile import", "test_only_url(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content' urlopen.return_value = mock_response url", "= urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as", "@patch('foliant.config.downloadfile.urlopen', autospec=True) def test_only_url(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content' urlopen.return_value", "autospec=True) def test_save_to(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content' urlopen.return_value =", "autospec=True) def test_only_url(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content' urlopen.return_value =", "open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_save_to(self, urlopen):", "content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' save_to = 'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir, url=url, save_to=save_to)", "get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') class TestGetFileExtFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' ext = get_file_ext_from_url(url)", "self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_with_auth(self, urlopen): mock_response = Mock() mock_response.read.return_value =", "= Mock() mock_response.read.return_value = b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file(root_dir=self.project_dir,", "url = 'http://example.com/sub/myfile.txt' ext = get_file_ext_from_url(url) self.assertEqual(ext, '.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile'", "save_to = 'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir, url=url, save_to=save_to) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers,", "urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file( root_dir=self.project_dir, url=url, login='john', password='<PASSWORD>' ) request", "get_file_ext_from_url from foliant.config.downloadfile import get_file_name_from_url class TestDownloadFile(TestCase): def setUp(self): self.project_dir = (Path(__file__).parent /", "get_file_ext_from_url(url) self.assertEqual(ext, '.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' ext = get_file_ext_from_url(url) self.assertEqual(ext, '')", "= urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File", "'http://example.com/sub/myfile.txt' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' name =", "self.project_dir = (Path(__file__).parent / 'project_dir').resolve() self.project_dir.mkdir(exist_ok=True) def tearDown(self): shutil.rmtree(self.project_dir, ignore_errors=True) @patch('foliant.config.downloadfile.urlopen', autospec=True) def", "= 'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir, url=url, save_to=save_to) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {})", "TestGetFileNameFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') def test_no_ext(self):", "as f: self.assertEqual(f.read(), 'File content') class TestGetFileNameFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' name", "test_with_ext(self): url = 'http://example.com/sub/myfile.txt' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') def test_no_ext(self): url =", "import get_file_ext_from_url from foliant.config.downloadfile import get_file_name_from_url class TestDownloadFile(TestCase): def setUp(self): self.project_dir = (Path(__file__).parent", "urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f:", "get_file_name_from_url(url) self.assertEqual(name, 'myfile') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt')", "= 'http://example.com/myfile.txt' save_to = 'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir, url=url, save_to=save_to) request = urlopen.call_args.args[0] context =", "= 'http://example.com/sub/myfile' ext = get_file_ext_from_url(url) self.assertEqual(ext, '') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' ext", "'.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' ext = get_file_ext_from_url(url) self.assertEqual(ext, '') def test_with_clutter(self):", "import shutil from pathlib import Path from unittest import TestCase from unittest.mock import", "download_file from foliant.config.downloadfile import get_file_ext_from_url from foliant.config.downloadfile import get_file_name_from_url class TestDownloadFile(TestCase): def setUp(self):", "f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_save_to(self, urlopen): mock_response = Mock() mock_response.read.return_value", "name = get_file_name_from_url(url) self.assertEqual(name, 'myfile') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' name = get_file_name_from_url(url)", "'myfile.txt') as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_save_to(self, urlopen): mock_response =", "urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file(root_dir=self.project_dir, url=url) request = urlopen.call_args.args[0] context =", "import get_file_name_from_url class TestDownloadFile(TestCase): def setUp(self): self.project_dir = (Path(__file__).parent / 'project_dir').resolve() self.project_dir.mkdir(exist_ok=True) def", "mock_response url = 'http://example.com/myfile.txt' download_file(root_dir=self.project_dir, url=url) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers,", "'http://example.com/sub/myfile' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' name =", "urlopen.call_args.kwargs['context'] self.assertIn('Authorization', request.headers) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File content')", "Path from unittest import TestCase from unittest.mock import Mock from unittest.mock import patch", "(Path(__file__).parent / 'project_dir').resolve() self.project_dir.mkdir(exist_ok=True) def tearDown(self): shutil.rmtree(self.project_dir, ignore_errors=True) @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_only_url(self, urlopen):", "Mock() mock_response.read.return_value = b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' save_to =", "unittest.mock import patch from foliant.config.downloadfile import download_file from foliant.config.downloadfile import get_file_ext_from_url from foliant.config.downloadfile", "context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / save_to) as f: self.assertEqual(f.read(),", "'http://example.com/myfile.txt' download_file(root_dir=self.project_dir, url=url) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with", "Mock from unittest.mock import patch from foliant.config.downloadfile import download_file from foliant.config.downloadfile import get_file_ext_from_url" ]
[ "idが0以外なら匿名質問する if target_channel_id == 0: dm = await message.author.create_dm() # 質問者へDM作成 await dm.send(", "チャンネルに質問メッセージ送信 await target_channel.send(question) # 匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId() -> int:", "discord.Client() # 接続に使用するオブジェクト # 起動時 @client.event async def on_ready(): print('ログイン成功') # メッセージを監視 @client.event", "「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'): # 文字から「/box」を抜く question = message.content[len('/box'):].strip() # 質問させたいチャンネルのid target_channel_id = getTargetChannelId()", "匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId() -> int: # 質問させたいチャンネル(対象チャンネル) target_channel =", "else: # 匿名質問させたいチャンネル target_channel = client.get_channel(target_channel_id) # チャンネルに質問メッセージ送信 await target_channel.send(question) # 匿名質問させたいチャンネルのidを取得 #", "初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 # 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if target_channel['position'] > int(channel.position): target_channel['id'] = int(channel.id) target_channel['position'] = int(channel.position)", "channel in all_channels: # 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category) == target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定", "711238137598181396 # カテゴリidを指定 target_category_name = client.get_channel(category_id).name # *********************************************************** # 指定したサーバにある全てのTextチャンネル一覧 all_channels = client.get_guild(602423784946925568).text_channels", "指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category) == target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 # 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if target_channel['position']", "= client.get_channel(category_id).name # *********************************************************** # 指定したサーバにある全てのTextチャンネル一覧 all_channels = client.get_guild(602423784946925568).text_channels # 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for channel", "= discord.Client() # 接続に使用するオブジェクト # 起動時 @client.event async def on_ready(): print('ログイン成功') # メッセージを監視", "# 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id = 711238137598181396 # カテゴリidを指定 target_category_name = client.get_channel(category_id).name # *********************************************************** #", "target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 # 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if target_channel['position'] > int(channel.position): target_channel['id'] =", "positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 # 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if target_channel['position'] > int(channel.position): target_channel['id'] = int(channel.id) target_channel['position']", "接続に使用するオブジェクト # 起動時 @client.event async def on_ready(): print('ログイン成功') # メッセージを監視 @client.event async def", "= message.content[len('/box'):].strip() # 質問させたいチャンネルのid target_channel_id = getTargetChannelId() # id=0なら質問者にエラー報告DM # idが0以外なら匿名質問する if target_channel_id", "target_channel['position'] > int(channel.position): target_channel['id'] = int(channel.id) target_channel['position'] = int(channel.position) # 最終的に代入されたidを返す return target_channel['id']", "@client.event async def on_message(message): # 「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'): # 文字から「/box」を抜く question = message.content[len('/box'):].strip()", "getTargetChannelId() -> int: # 質問させたいチャンネル(対象チャンネル) target_channel = {'id': 0, 'position': 99999999} # ***********************************************************", "str(channel.category) == target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 # 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if target_channel['position'] > int(channel.position):", "on_ready(): print('ログイン成功') # メッセージを監視 @client.event async def on_message(message): # 「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'): #", "指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id = 711238137598181396 # カテゴリidを指定 target_category_name = client.get_channel(category_id).name # *********************************************************** # 指定したサーバにある全てのTextチャンネル一覧", "message.content.startswith('/box'): # 文字から「/box」を抜く question = message.content[len('/box'):].strip() # 質問させたいチャンネルのid target_channel_id = getTargetChannelId() # id=0なら質問者にエラー報告DM", "target_channel_id == 0: dm = await message.author.create_dm() # 質問者へDM作成 await dm.send( 'Sorry, メッセージを送信できませんでした.'", "# ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId() -> int: # 質問させたいチャンネル(対象チャンネル) target_channel = {'id': 0, 'position':", "*********************************************************** # 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id = 711238137598181396 # カテゴリidを指定 target_category_name = client.get_channel(category_id).name # ***********************************************************", "ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId() -> int: # 質問させたいチャンネル(対象チャンネル) target_channel = {'id': 0, 'position': 99999999}", "question) else: # 匿名質問させたいチャンネル target_channel = client.get_channel(target_channel_id) # チャンネルに質問メッセージ送信 await target_channel.send(question) # 匿名質問させたいチャンネルのidを取得", "質問者へDM作成 await dm.send( 'Sorry, メッセージを送信できませんでした.' 'もう1度試してみてください.\\n' '【質問文】' + question) else: # 匿名質問させたいチャンネル target_channel", "# 質問させたいチャンネル(対象チャンネル) target_channel = {'id': 0, 'position': 99999999} # *********************************************************** # 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id", "int: # 質問させたいチャンネル(対象チャンネル) target_channel = {'id': 0, 'position': 99999999} # *********************************************************** # 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前", "client.get_channel(category_id).name # *********************************************************** # 指定したサーバにある全てのTextチャンネル一覧 all_channels = client.get_guild(602423784946925568).text_channels # 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for channel in", "@client.event async def on_ready(): print('ログイン成功') # メッセージを監視 @client.event async def on_message(message): # 「/box」が頭についたメッセージならオウム返しする", "# *********************************************************** # 指定したサーバにある全てのTextチャンネル一覧 all_channels = client.get_guild(602423784946925568).text_channels # 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for channel in all_channels:", "import discord client = discord.Client() # 接続に使用するオブジェクト # 起動時 @client.event async def on_ready():", "0: dm = await message.author.create_dm() # 質問者へDM作成 await dm.send( 'Sorry, メッセージを送信できませんでした.' 'もう1度試してみてください.\\n' '【質問文】'", "message.content[len('/box'):].strip() # 質問させたいチャンネルのid target_channel_id = getTargetChannelId() # id=0なら質問者にエラー報告DM # idが0以外なら匿名質問する if target_channel_id ==", "全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for channel in all_channels: # 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category) == target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換", "# チャンネルに質問メッセージ送信 await target_channel.send(question) # 匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId() ->", "# 接続に使用するオブジェクト # 起動時 @client.event async def on_ready(): print('ログイン成功') # メッセージを監視 @client.event async", "await message.author.create_dm() # 質問者へDM作成 await dm.send( 'Sorry, メッセージを送信できませんでした.' 'もう1度試してみてください.\\n' '【質問文】' + question) else:", "# 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category) == target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 # 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if", "dm.send( 'Sorry, メッセージを送信できませんでした.' 'もう1度試してみてください.\\n' '【質問文】' + question) else: # 匿名質問させたいチャンネル target_channel = client.get_channel(target_channel_id)", "# 質問者へDM作成 await dm.send( 'Sorry, メッセージを送信できませんでした.' 'もう1度試してみてください.\\n' '【質問文】' + question) else: # 匿名質問させたいチャンネル", "if message.content.startswith('/box'): # 文字から「/box」を抜く question = message.content[len('/box'):].strip() # 質問させたいチャンネルのid target_channel_id = getTargetChannelId() #", "for channel in all_channels: # 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category) == target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換 #", "# 文字から「/box」を抜く question = message.content[len('/box'):].strip() # 質問させたいチャンネルのid target_channel_id = getTargetChannelId() # id=0なら質問者にエラー報告DM #", "question = message.content[len('/box'):].strip() # 質問させたいチャンネルのid target_channel_id = getTargetChannelId() # id=0なら質問者にエラー報告DM # idが0以外なら匿名質問する if", "== target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 # 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if target_channel['position'] > int(channel.position): target_channel['id']", "質問させたいチャンネル(対象チャンネル) target_channel = {'id': 0, 'position': 99999999} # *********************************************************** # 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id =", "target_channel['id'] = int(channel.id) target_channel['position'] = int(channel.position) # 最終的に代入されたidを返す return target_channel['id'] # botとしてDiscordに接続(botのトークンを指定) client.run('605042341715378176')", "'position': 99999999} # *********************************************************** # 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id = 711238137598181396 # カテゴリidを指定 target_category_name =", "message.author.create_dm() # 質問者へDM作成 await dm.send( 'Sorry, メッセージを送信できませんでした.' 'もう1度試してみてください.\\n' '【質問文】' + question) else: #", "起動時 @client.event async def on_ready(): print('ログイン成功') # メッセージを監視 @client.event async def on_message(message): #", "{'id': 0, 'position': 99999999} # *********************************************************** # 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id = 711238137598181396 # カテゴリidを指定", "= 711238137598181396 # カテゴリidを指定 target_category_name = client.get_channel(category_id).name # *********************************************************** # 指定したサーバにある全てのTextチャンネル一覧 all_channels =", "文字から「/box」を抜く question = message.content[len('/box'):].strip() # 質問させたいチャンネルのid target_channel_id = getTargetChannelId() # id=0なら質問者にエラー報告DM # idが0以外なら匿名質問する", "99999999} # *********************************************************** # 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id = 711238137598181396 # カテゴリidを指定 target_category_name = client.get_channel(category_id).name", "-> int: # 質問させたいチャンネル(対象チャンネル) target_channel = {'id': 0, 'position': 99999999} # *********************************************************** #", "= {'id': 0, 'position': 99999999} # *********************************************************** # 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id = 711238137598181396 #", "id=0なら質問者にエラー報告DM # idが0以外なら匿名質問する if target_channel_id == 0: dm = await message.author.create_dm() # 質問者へDM作成", "'Sorry, メッセージを送信できませんでした.' 'もう1度試してみてください.\\n' '【質問文】' + question) else: # 匿名質問させたいチャンネル target_channel = client.get_channel(target_channel_id) #", "on_message(message): # 「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'): # 文字から「/box」を抜く question = message.content[len('/box'):].strip() # 質問させたいチャンネルのid target_channel_id", "if str(channel.category) == target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 # 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if target_channel['position'] >", "async def on_ready(): print('ログイン成功') # メッセージを監視 @client.event async def on_message(message): # 「/box」が頭についたメッセージならオウム返しする if", "メッセージを送信できませんでした.' 'もう1度試してみてください.\\n' '【質問文】' + question) else: # 匿名質問させたいチャンネル target_channel = client.get_channel(target_channel_id) # チャンネルに質問メッセージ送信", "category_id = 711238137598181396 # カテゴリidを指定 target_category_name = client.get_channel(category_id).name # *********************************************************** # 指定したサーバにある全てのTextチャンネル一覧 all_channels", "if target_channel['position'] > int(channel.position): target_channel['id'] = int(channel.id) target_channel['position'] = int(channel.position) # 最終的に代入されたidを返す return", "# メッセージを監視 @client.event async def on_message(message): # 「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'): # 文字から「/box」を抜く question", "if target_channel_id == 0: dm = await message.author.create_dm() # 質問者へDM作成 await dm.send( 'Sorry,", "# positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 # 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if target_channel['position'] > int(channel.position): target_channel['id'] = int(channel.id)", "client.get_channel(target_channel_id) # チャンネルに質問メッセージ送信 await target_channel.send(question) # 匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId()", "await dm.send( 'Sorry, メッセージを送信できませんでした.' 'もう1度試してみてください.\\n' '【質問文】' + question) else: # 匿名質問させたいチャンネル target_channel =", "カテゴリidを指定 target_category_name = client.get_channel(category_id).name # *********************************************************** # 指定したサーバにある全てのTextチャンネル一覧 all_channels = client.get_guild(602423784946925568).text_channels # 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す", "# idが0以外なら匿名質問する if target_channel_id == 0: dm = await message.author.create_dm() # 質問者へDM作成 await", "all_channels = client.get_guild(602423784946925568).text_channels # 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for channel in all_channels: # 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category)", "target_channel.send(question) # 匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId() -> int: # 質問させたいチャンネル(対象チャンネル)", "= client.get_guild(602423784946925568).text_channels # 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for channel in all_channels: # 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category) ==", "<gh_stars>0 import discord client = discord.Client() # 接続に使用するオブジェクト # 起動時 @client.event async def", "getTargetChannelId() # id=0なら質問者にエラー報告DM # idが0以外なら匿名質問する if target_channel_id == 0: dm = await message.author.create_dm()", "メッセージを監視 @client.event async def on_message(message): # 「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'): # 文字から「/box」を抜く question =", "await target_channel.send(question) # 匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId() -> int: #", "== 0: dm = await message.author.create_dm() # 質問者へDM作成 await dm.send( 'Sorry, メッセージを送信できませんでした.' 'もう1度試してみてください.\\n'", "指定したサーバにある全てのTextチャンネル一覧 all_channels = client.get_guild(602423784946925568).text_channels # 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for channel in all_channels: # 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if", "# 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 # 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if target_channel['position'] > int(channel.position): target_channel['id'] = int(channel.id) target_channel['position'] =", "# *********************************************************** # 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id = 711238137598181396 # カテゴリidを指定 target_category_name = client.get_channel(category_id).name #", "匿名質問させたいチャンネル target_channel = client.get_channel(target_channel_id) # チャンネルに質問メッセージ送信 await target_channel.send(question) # 匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす #", "+ question) else: # 匿名質問させたいチャンネル target_channel = client.get_channel(target_channel_id) # チャンネルに質問メッセージ送信 await target_channel.send(question) #", "# 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if target_channel['position'] > int(channel.position): target_channel['id'] = int(channel.id) target_channel['position'] = int(channel.position) #", "client.get_guild(602423784946925568).text_channels # 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for channel in all_channels: # 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category) == target_category_name:", "'もう1度試してみてください.\\n' '【質問文】' + question) else: # 匿名質問させたいチャンネル target_channel = client.get_channel(target_channel_id) # チャンネルに質問メッセージ送信 await", "= await message.author.create_dm() # 質問者へDM作成 await dm.send( 'Sorry, メッセージを送信できませんでした.' 'もう1度試してみてください.\\n' '【質問文】' + question)", "= client.get_channel(target_channel_id) # チャンネルに質問メッセージ送信 await target_channel.send(question) # 匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す def", "# 指定したサーバにある全てのTextチャンネル一覧 all_channels = client.get_guild(602423784946925568).text_channels # 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for channel in all_channels: # 指定カテゴリに属する場合だけ対象チャンネル候補とみなす", "target_channel_id = getTargetChannelId() # id=0なら質問者にエラー報告DM # idが0以外なら匿名質問する if target_channel_id == 0: dm =", "print('ログイン成功') # メッセージを監視 @client.event async def on_message(message): # 「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'): # 文字から「/box」を抜く", "0, 'position': 99999999} # *********************************************************** # 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id = 711238137598181396 # カテゴリidを指定 target_category_name", "*********************************************************** # 指定したサーバにある全てのTextチャンネル一覧 all_channels = client.get_guild(602423784946925568).text_channels # 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for channel in all_channels: #", "int(channel.position): target_channel['id'] = int(channel.id) target_channel['position'] = int(channel.position) # 最終的に代入されたidを返す return target_channel['id'] # botとしてDiscordに接続(botのトークンを指定)", "質問させたいチャンネルのid target_channel_id = getTargetChannelId() # id=0なら質問者にエラー報告DM # idが0以外なら匿名質問する if target_channel_id == 0: dm", "target_channel = client.get_channel(target_channel_id) # チャンネルに質問メッセージ送信 await target_channel.send(question) # 匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す", "# 質問させたいチャンネルのid target_channel_id = getTargetChannelId() # id=0なら質問者にエラー報告DM # idが0以外なら匿名質問する if target_channel_id == 0:", "# 「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'): # 文字から「/box」を抜く question = message.content[len('/box'):].strip() # 質問させたいチャンネルのid target_channel_id =", "target_category_name = client.get_channel(category_id).name # *********************************************************** # 指定したサーバにある全てのTextチャンネル一覧 all_channels = client.get_guild(602423784946925568).text_channels # 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for", "def on_message(message): # 「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'): # 文字から「/box」を抜く question = message.content[len('/box'):].strip() # 質問させたいチャンネルのid", "= getTargetChannelId() # id=0なら質問者にエラー報告DM # idが0以外なら匿名質問する if target_channel_id == 0: dm = await", "# カテゴリidを指定 target_category_name = client.get_channel(category_id).name # *********************************************************** # 指定したサーバにある全てのTextチャンネル一覧 all_channels = client.get_guild(602423784946925568).text_channels #", "# 匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId() -> int: # 質問させたいチャンネル(対象チャンネル) target_channel", "# 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for channel in all_channels: # 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category) == target_category_name: #", "dm = await message.author.create_dm() # 質問者へDM作成 await dm.send( 'Sorry, メッセージを送信できませんでした.' 'もう1度試してみてください.\\n' '【質問文】' +", "client = discord.Client() # 接続に使用するオブジェクト # 起動時 @client.event async def on_ready(): print('ログイン成功') #", "# 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId() -> int: # 質問させたいチャンネル(対象チャンネル) target_channel = {'id':", "# 匿名質問させたいチャンネル target_channel = client.get_channel(target_channel_id) # チャンネルに質問メッセージ送信 await target_channel.send(question) # 匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす", "# 起動時 @client.event async def on_ready(): print('ログイン成功') # メッセージを監視 @client.event async def on_message(message):", "discord client = discord.Client() # 接続に使用するオブジェクト # 起動時 @client.event async def on_ready(): print('ログイン成功')", "'【質問文】' + question) else: # 匿名質問させたいチャンネル target_channel = client.get_channel(target_channel_id) # チャンネルに質問メッセージ送信 await target_channel.send(question)", "async def on_message(message): # 「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'): # 文字から「/box」を抜く question = message.content[len('/box'):].strip() #", "> int(channel.position): target_channel['id'] = int(channel.id) target_channel['position'] = int(channel.position) # 最終的に代入されたidを返す return target_channel['id'] #", "target_channel = {'id': 0, 'position': 99999999} # *********************************************************** # 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id = 711238137598181396", "指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId() -> int: # 質問させたいチャンネル(対象チャンネル) target_channel = {'id': 0,", "# id=0なら質問者にエラー報告DM # idが0以外なら匿名質問する if target_channel_id == 0: dm = await message.author.create_dm() #", "all_channels: # 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category) == target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 # 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる", "def on_ready(): print('ログイン成功') # メッセージを監視 @client.event async def on_message(message): # 「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'):", "繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if target_channel['position'] > int(channel.position): target_channel['id'] = int(channel.id) target_channel['position'] = int(channel.position) # 最終的に代入されたidを返す", "in all_channels: # 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category) == target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 #", "def getTargetChannelId() -> int: # 質問させたいチャンネル(対象チャンネル) target_channel = {'id': 0, 'position': 99999999} #" ]
[ "max cell count if any(data_t >= 1): survive_count += 1 if counts_total is", "at least 10% of the max cell count if any(data_t >= 1): survive_count", "exp_info.populations[0] ax = ax.reshape((len(k_abs),)) axnum = 0 tc_axes=[] drug_axes=[] for exp in exp_folders:", "== k_abs_t) num = num[0,0] # generate timecourse axes tcax = ax[axnum] #", "import numpy as np from fears.utils import results_manager, plotter, dir_manager import os suffix", "plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop = exp_info.populations[0] ax = ax.reshape((len(k_abs),)) axnum = 0 tc_axes=[] drug_axes=[] for", "cell count if any(data_t >= 1): survive_count += 1 if counts_total is None:", "counts_total = data else: counts_total += data # data = data/np.max(data) # exp_info.populations[num].counts_log_scale", "= ax.reshape((len(k_abs),)) axnum = 0 tc_axes=[] drug_axes=[] for exp in exp_folders: k_abs_t =", "= results_manager.get_data(sim) dc = data[:,-1] data = data[:,0:-1] # data = data/np.max(data) data_t", "data else: counts_total += data # data = data/np.max(data) # exp_info.populations[num].counts_log_scale = True", "= True data = data/max_cells if k==0: drug_kwargs = {'alpha':0.7, 'color':'black', 'linewidth':2, 'label':'Drug", "np.flip(k_abs) fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop = exp_info.populations[0] ax = ax.reshape((len(k_abs),)) axnum = 0", "counts_avg = counts_total/survive_count # counts_avg = counts_avg/np.max(counts_avg) # counts_avg = counts_total counts_avg =", "color='gray', linewidth=1, labelsize=12, alpha=0.7 ) drug_ax.set_ylabel('') drug_axes.append( drug_ax ) else: tcax,da = plotter.plot_timecourse_to_axes(exp_info.populations[num],", "counts_avg/np.max(counts_avg) tcax,temp = plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg, tcax, labelsize=12) # t = np.arange(len(dc)) # t", "data, tcax, grayscale=True, color='gray', legend_labels=False, linewidth=2, labelsize=12, alpha=0.2 ) # drug_ax.set_ylim(0,10**4) k+=1 if", "# for sim in sim_files: sim = sim_files[k] sim = exp + os.sep", "= exp_info.populations[0] ax = ax.reshape((len(k_abs),)) axnum = 0 tc_axes=[] drug_axes=[] for exp in", "for sim in sim_files: sim = sim_files[k] sim = exp + os.sep +", "numpy as np from fears.utils import results_manager, plotter, dir_manager import os suffix =", "= exp + os.sep + sim data = results_manager.get_data(sim) dc = data[:,-1] data", "counts_avg/np.max(counts_avg) # counts_avg = counts_total counts_avg = counts_avg/np.max(counts_avg) tcax,temp = plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg, tcax,", "max_cells = exp_info.populations[0].max_cells n_sims = exp_info.n_sims k_abs = exp_info.slopes exp_folders.reverse() k_abs = np.flip(k_abs)", "1 if counts_total is None: counts_total = data else: counts_total += data #", "sim_files: sim = sim_files[k] sim = exp + os.sep + sim data =", "legend_labels=False, linewidth=2, labelsize=12, alpha=0.2 ) # drug_ax.set_ylim(0,10**4) k+=1 if survive_count > 0: counts_avg", "tcax, drug_curve=dc, drug_ax_sci_notation=True, drug_kwargs=drug_kwargs, legend_labels=False, grayscale=True, color='gray', linewidth=1, labelsize=12, alpha=0.7 ) drug_ax.set_ylabel('') drug_axes.append(", "= os.listdir(path=exp) sim_files = sorted(sim_files) survive_count = 0 counts_total = None k=0 while", "while k < len(sim_files): # for sim in sim_files: sim = sim_files[k] sim", "exp_folders: k_abs_t = exp[exp.find('=')+1:] k_abs_t = float(k_abs_t) num = np.argwhere(k_abs == k_abs_t) num", "sorted(sim_files) survive_count = 0 counts_total = None k=0 while k < len(sim_files): #", "0 counts_total = None k=0 while k < len(sim_files): # for sim in", "= sorted(sim_files) survive_count = 0 counts_total = None k=0 while k < len(sim_files):", "linewidth=1, labelsize=12, alpha=0.7 ) drug_ax.set_ylabel('') drug_axes.append( drug_ax ) else: tcax,da = plotter.plot_timecourse_to_axes(exp_info.populations[num], data,", "data, tcax, drug_curve=dc, drug_ax_sci_notation=True, drug_kwargs=drug_kwargs, legend_labels=False, grayscale=True, color='gray', linewidth=1, labelsize=12, alpha=0.7 ) drug_ax.set_ylabel('')", "= exp[exp.find('=')+1:] k_abs_t = float(k_abs_t) num = np.argwhere(k_abs == k_abs_t) num = num[0,0]", "# data = data/np.max(data) # exp_info.populations[num].counts_log_scale = True data = data/max_cells if k==0:", "tcax,temp = plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg, tcax, labelsize=12) # t = np.arange(len(dc)) # t =", "= data[:,0:-1] # data = data/np.max(data) data_t = data[-1,:] # check to see", "'color':'black', 'linewidth':2, 'label':'Drug Concentration ($\\u03BC$M)' } tcax,drug_ax = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, drug_curve=dc, drug_ax_sci_notation=True,", "k_abs_t) num = num[0,0] # generate timecourse axes tcax = ax[axnum] # da", "is None: counts_total = data else: counts_total += data # data = data/np.max(data)", "counts_avg = counts_total counts_avg = counts_avg/np.max(counts_avg) tcax,temp = plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg, tcax, labelsize=12) #", "= np.flip(k_abs) fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop = exp_info.populations[0] ax = ax.reshape((len(k_abs),)) axnum =", "plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg, tcax, labelsize=12) # t = np.arange(len(dc)) # t = t*exp_info.populations[0].timestep_scale/24 #", "the max cell count if any(data_t >= 1): survive_count += 1 if counts_total", "> 0: counts_avg = counts_total/survive_count # counts_avg = counts_avg/np.max(counts_avg) # counts_avg = counts_total", "sim_files = sorted(sim_files) survive_count = 0 counts_total = None k=0 while k <", "suffix + '.p' exp_folders,exp_info = results_manager.get_experiment_results(data_folder, exp_info_file) max_cells = exp_info.populations[0].max_cells n_sims = exp_info.n_sims", "data = data/max_cells if k==0: drug_kwargs = {'alpha':0.7, 'color':'black', 'linewidth':2, 'label':'Drug Concentration ($\\u03BC$M)'", "exp_info.n_sims k_abs = exp_info.slopes exp_folders.reverse() k_abs = np.flip(k_abs) fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop =", "= plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop = exp_info.populations[0] ax = ax.reshape((len(k_abs),)) axnum = 0 tc_axes=[] drug_axes=[]", "matplotlib.pyplot as plt import numpy as np from fears.utils import results_manager, plotter, dir_manager", "if any(data_t >= 1): survive_count += 1 if counts_total is None: counts_total =", "any(data_t >= 1): survive_count += 1 if counts_total is None: counts_total = data", "tcax = ax[axnum] # da = tcax.twinx() sim_files = os.listdir(path=exp) sim_files = sorted(sim_files)", ") drug_ax.set_ylabel('') drug_axes.append( drug_ax ) else: tcax,da = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, grayscale=True, color='gray',", "# counts_avg = counts_total counts_avg = counts_avg/np.max(counts_avg) tcax,temp = plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg, tcax, labelsize=12)", "import os suffix = '07212021_0001' data_folder = 'results_' + suffix exp_info_file = 'experiment_info_'", "linewidth=2, labelsize=12, alpha=0.2 ) # drug_ax.set_ylim(0,10**4) k+=1 if survive_count > 0: counts_avg =", "num[0,0] # generate timecourse axes tcax = ax[axnum] # da = tcax.twinx() sim_files", "'label':'Drug Concentration ($\\u03BC$M)' } tcax,drug_ax = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, drug_curve=dc, drug_ax_sci_notation=True, drug_kwargs=drug_kwargs, legend_labels=False,", "color='gray', legend_labels=False, linewidth=2, labelsize=12, alpha=0.2 ) # drug_ax.set_ylim(0,10**4) k+=1 if survive_count > 0:", "tcax.twinx() sim_files = os.listdir(path=exp) sim_files = sorted(sim_files) survive_count = 0 counts_total = None", "as np from fears.utils import results_manager, plotter, dir_manager import os suffix = '07212021_0001'", "= 0 tc_axes=[] drug_axes=[] for exp in exp_folders: k_abs_t = exp[exp.find('=')+1:] k_abs_t =", "1): survive_count += 1 if counts_total is None: counts_total = data else: counts_total", "generate timecourse axes tcax = ax[axnum] # da = tcax.twinx() sim_files = os.listdir(path=exp)", "exp in exp_folders: k_abs_t = exp[exp.find('=')+1:] k_abs_t = float(k_abs_t) num = np.argwhere(k_abs ==", "plotter, dir_manager import os suffix = '07212021_0001' data_folder = 'results_' + suffix exp_info_file", "ax = ax.reshape((len(k_abs),)) axnum = 0 tc_axes=[] drug_axes=[] for exp in exp_folders: k_abs_t", "grayscale=True, color='gray', linewidth=1, labelsize=12, alpha=0.7 ) drug_ax.set_ylabel('') drug_axes.append( drug_ax ) else: tcax,da =", "grayscale=True, color='gray', legend_labels=False, linewidth=2, labelsize=12, alpha=0.2 ) # drug_ax.set_ylim(0,10**4) k+=1 if survive_count >", "tcax, grayscale=True, color='gray', legend_labels=False, linewidth=2, labelsize=12, alpha=0.2 ) # drug_ax.set_ylim(0,10**4) k+=1 if survive_count", "for exp in exp_folders: k_abs_t = exp[exp.find('=')+1:] k_abs_t = float(k_abs_t) num = np.argwhere(k_abs", "from fears.utils import results_manager, plotter, dir_manager import os suffix = '07212021_0001' data_folder =", "data = data/np.max(data) # exp_info.populations[num].counts_log_scale = True data = data/max_cells if k==0: drug_kwargs", "= results_manager.get_experiment_results(data_folder, exp_info_file) max_cells = exp_info.populations[0].max_cells n_sims = exp_info.n_sims k_abs = exp_info.slopes exp_folders.reverse()", "axnum = 0 tc_axes=[] drug_axes=[] for exp in exp_folders: k_abs_t = exp[exp.find('=')+1:] k_abs_t", "k < len(sim_files): # for sim in sim_files: sim = sim_files[k] sim =", "data = data/np.max(data) data_t = data[-1,:] # check to see if any genotypes", "+ '.p' exp_folders,exp_info = results_manager.get_experiment_results(data_folder, exp_info_file) max_cells = exp_info.populations[0].max_cells n_sims = exp_info.n_sims k_abs", "< len(sim_files): # for sim in sim_files: sim = sim_files[k] sim = exp", "suffix = '07212021_0001' data_folder = 'results_' + suffix exp_info_file = 'experiment_info_' + suffix", "exp_info.populations[0].max_cells n_sims = exp_info.n_sims k_abs = exp_info.slopes exp_folders.reverse() k_abs = np.flip(k_abs) fig,ax =", "= data/np.max(data) # exp_info.populations[num].counts_log_scale = True data = data/max_cells if k==0: drug_kwargs =", "+= 1 if counts_total is None: counts_total = data else: counts_total += data", "= plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, drug_curve=dc, drug_ax_sci_notation=True, drug_kwargs=drug_kwargs, legend_labels=False, grayscale=True, color='gray', linewidth=1, labelsize=12, alpha=0.7", "if k==0: drug_kwargs = {'alpha':0.7, 'color':'black', 'linewidth':2, 'label':'Drug Concentration ($\\u03BC$M)' } tcax,drug_ax =", "# check to see if any genotypes are at least 10% of the", "k_abs = np.flip(k_abs) fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop = exp_info.populations[0] ax = ax.reshape((len(k_abs),)) axnum", "= data[-1,:] # check to see if any genotypes are at least 10%", "'07212021_0001' data_folder = 'results_' + suffix exp_info_file = 'experiment_info_' + suffix + '.p'", "len(sim_files): # for sim in sim_files: sim = sim_files[k] sim = exp +", "= data[:,-1] data = data[:,0:-1] # data = data/np.max(data) data_t = data[-1,:] #", "0: counts_avg = counts_total/survive_count # counts_avg = counts_avg/np.max(counts_avg) # counts_avg = counts_total counts_avg", "timecourse axes tcax = ax[axnum] # da = tcax.twinx() sim_files = os.listdir(path=exp) sim_files", "ax[axnum] # da = tcax.twinx() sim_files = os.listdir(path=exp) sim_files = sorted(sim_files) survive_count =", "exp_folders.reverse() k_abs = np.flip(k_abs) fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop = exp_info.populations[0] ax = ax.reshape((len(k_abs),))", "# da = tcax.twinx() sim_files = os.listdir(path=exp) sim_files = sorted(sim_files) survive_count = 0", "data_t = data[-1,:] # check to see if any genotypes are at least", "counts_total counts_avg = counts_avg/np.max(counts_avg) tcax,temp = plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg, tcax, labelsize=12) # t =", "+ suffix + '.p' exp_folders,exp_info = results_manager.get_experiment_results(data_folder, exp_info_file) max_cells = exp_info.populations[0].max_cells n_sims =", "if counts_total is None: counts_total = data else: counts_total += data # data", "labelsize=12, alpha=0.2 ) # drug_ax.set_ylim(0,10**4) k+=1 if survive_count > 0: counts_avg = counts_total/survive_count", "# counts_avg = counts_avg/np.max(counts_avg) # counts_avg = counts_total counts_avg = counts_avg/np.max(counts_avg) tcax,temp =", "counts_avg = counts_avg/np.max(counts_avg) tcax,temp = plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg, tcax, labelsize=12) # t = np.arange(len(dc))", "sim_files[k] sim = exp + os.sep + sim data = results_manager.get_data(sim) dc =", "= data/np.max(data) data_t = data[-1,:] # check to see if any genotypes are", "least 10% of the max cell count if any(data_t >= 1): survive_count +=", "sim_files = os.listdir(path=exp) sim_files = sorted(sim_files) survive_count = 0 counts_total = None k=0", "else: counts_total += data # data = data/np.max(data) # exp_info.populations[num].counts_log_scale = True data", "num = np.argwhere(k_abs == k_abs_t) num = num[0,0] # generate timecourse axes tcax", "drug_curve=dc, drug_ax_sci_notation=True, drug_kwargs=drug_kwargs, legend_labels=False, grayscale=True, color='gray', linewidth=1, labelsize=12, alpha=0.7 ) drug_ax.set_ylabel('') drug_axes.append( drug_ax", "= {'alpha':0.7, 'color':'black', 'linewidth':2, 'label':'Drug Concentration ($\\u03BC$M)' } tcax,drug_ax = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax,", "} tcax,drug_ax = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, drug_curve=dc, drug_ax_sci_notation=True, drug_kwargs=drug_kwargs, legend_labels=False, grayscale=True, color='gray', linewidth=1,", "drug_ax_sci_notation=True, drug_kwargs=drug_kwargs, legend_labels=False, grayscale=True, color='gray', linewidth=1, labelsize=12, alpha=0.7 ) drug_ax.set_ylabel('') drug_axes.append( drug_ax )", "drug_ax.set_ylabel('') drug_axes.append( drug_ax ) else: tcax,da = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, grayscale=True, color='gray', legend_labels=False,", "= exp_info.populations[0].max_cells n_sims = exp_info.n_sims k_abs = exp_info.slopes exp_folders.reverse() k_abs = np.flip(k_abs) fig,ax", "= counts_avg/np.max(counts_avg) # counts_avg = counts_total counts_avg = counts_avg/np.max(counts_avg) tcax,temp = plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg,", "alpha=0.2 ) # drug_ax.set_ylim(0,10**4) k+=1 if survive_count > 0: counts_avg = counts_total/survive_count #", "drug_ax ) else: tcax,da = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, grayscale=True, color='gray', legend_labels=False, linewidth=2, labelsize=12,", "= counts_avg/np.max(counts_avg) tcax,temp = plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg, tcax, labelsize=12) # t = np.arange(len(dc)) #", "sim in sim_files: sim = sim_files[k] sim = exp + os.sep + sim", "counts_total += data # data = data/np.max(data) # exp_info.populations[num].counts_log_scale = True data =", "pop = exp_info.populations[0] ax = ax.reshape((len(k_abs),)) axnum = 0 tc_axes=[] drug_axes=[] for exp", "dir_manager import os suffix = '07212021_0001' data_folder = 'results_' + suffix exp_info_file =", "+ sim data = results_manager.get_data(sim) dc = data[:,-1] data = data[:,0:-1] # data", "tcax,drug_ax = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, drug_curve=dc, drug_ax_sci_notation=True, drug_kwargs=drug_kwargs, legend_labels=False, grayscale=True, color='gray', linewidth=1, labelsize=12,", "# t = np.arange(len(dc)) # t = t*exp_info.populations[0].timestep_scale/24 # da.plot(t,dc) tc_axes.append( tcax )", "Concentration ($\\u03BC$M)' } tcax,drug_ax = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, drug_curve=dc, drug_ax_sci_notation=True, drug_kwargs=drug_kwargs, legend_labels=False, grayscale=True,", "# drug_ax.set_ylim(0,10**4) k+=1 if survive_count > 0: counts_avg = counts_total/survive_count # counts_avg =", "exp_info_file = 'experiment_info_' + suffix + '.p' exp_folders,exp_info = results_manager.get_experiment_results(data_folder, exp_info_file) max_cells =", "= sim_files[k] sim = exp + os.sep + sim data = results_manager.get_data(sim) dc", "k_abs_t = exp[exp.find('=')+1:] k_abs_t = float(k_abs_t) num = np.argwhere(k_abs == k_abs_t) num =", "survive_count = 0 counts_total = None k=0 while k < len(sim_files): # for", "genotypes are at least 10% of the max cell count if any(data_t >=", "= data else: counts_total += data # data = data/np.max(data) # exp_info.populations[num].counts_log_scale =", "see if any genotypes are at least 10% of the max cell count", "survive_count += 1 if counts_total is None: counts_total = data else: counts_total +=", "if any genotypes are at least 10% of the max cell count if", "= exp_info.slopes exp_folders.reverse() k_abs = np.flip(k_abs) fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop = exp_info.populations[0] ax", "None: counts_total = data else: counts_total += data # data = data/np.max(data) #", "exp_info.populations[num].counts_log_scale = True data = data/max_cells if k==0: drug_kwargs = {'alpha':0.7, 'color':'black', 'linewidth':2,", "exp + os.sep + sim data = results_manager.get_data(sim) dc = data[:,-1] data =", "= '07212021_0001' data_folder = 'results_' + suffix exp_info_file = 'experiment_info_' + suffix +", "labelsize=12) # t = np.arange(len(dc)) # t = t*exp_info.populations[0].timestep_scale/24 # da.plot(t,dc) tc_axes.append( tcax", "k+=1 if survive_count > 0: counts_avg = counts_total/survive_count # counts_avg = counts_avg/np.max(counts_avg) #", ") # drug_ax.set_ylim(0,10**4) k+=1 if survive_count > 0: counts_avg = counts_total/survive_count # counts_avg", "# exp_info.populations[num].counts_log_scale = True data = data/max_cells if k==0: drug_kwargs = {'alpha':0.7, 'color':'black',", ">= 1): survive_count += 1 if counts_total is None: counts_total = data else:", "{'alpha':0.7, 'color':'black', 'linewidth':2, 'label':'Drug Concentration ($\\u03BC$M)' } tcax,drug_ax = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, drug_curve=dc,", "results_manager.get_data(sim) dc = data[:,-1] data = data[:,0:-1] # data = data/np.max(data) data_t =", "np from fears.utils import results_manager, plotter, dir_manager import os suffix = '07212021_0001' data_folder", "exp[exp.find('=')+1:] k_abs_t = float(k_abs_t) num = np.argwhere(k_abs == k_abs_t) num = num[0,0] #", "data/np.max(data) data_t = data[-1,:] # check to see if any genotypes are at", "if survive_count > 0: counts_avg = counts_total/survive_count # counts_avg = counts_avg/np.max(counts_avg) # counts_avg", "= counts_total counts_avg = counts_avg/np.max(counts_avg) tcax,temp = plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg, tcax, labelsize=12) # t", "drug_axes=[] for exp in exp_folders: k_abs_t = exp[exp.find('=')+1:] k_abs_t = float(k_abs_t) num =", "t = np.arange(len(dc)) # t = t*exp_info.populations[0].timestep_scale/24 # da.plot(t,dc) tc_axes.append( tcax ) axnum+=1", "sim data = results_manager.get_data(sim) dc = data[:,-1] data = data[:,0:-1] # data =", "any genotypes are at least 10% of the max cell count if any(data_t", ") else: tcax,da = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, grayscale=True, color='gray', legend_labels=False, linewidth=2, labelsize=12, alpha=0.2", "fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop = exp_info.populations[0] ax = ax.reshape((len(k_abs),)) axnum = 0 tc_axes=[]", "data # data = data/np.max(data) # exp_info.populations[num].counts_log_scale = True data = data/max_cells if", "n_sims = exp_info.n_sims k_abs = exp_info.slopes exp_folders.reverse() k_abs = np.flip(k_abs) fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4))", "in sim_files: sim = sim_files[k] sim = exp + os.sep + sim data", "k_abs_t = float(k_abs_t) num = np.argwhere(k_abs == k_abs_t) num = num[0,0] # generate", "labelsize=12, alpha=0.7 ) drug_ax.set_ylabel('') drug_axes.append( drug_ax ) else: tcax,da = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax,", "= plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, grayscale=True, color='gray', legend_labels=False, linewidth=2, labelsize=12, alpha=0.2 ) # drug_ax.set_ylim(0,10**4)", "ax.reshape((len(k_abs),)) axnum = 0 tc_axes=[] drug_axes=[] for exp in exp_folders: k_abs_t = exp[exp.find('=')+1:]", "data/max_cells if k==0: drug_kwargs = {'alpha':0.7, 'color':'black', 'linewidth':2, 'label':'Drug Concentration ($\\u03BC$M)' } tcax,drug_ax", "results_manager, plotter, dir_manager import os suffix = '07212021_0001' data_folder = 'results_' + suffix", "0 tc_axes=[] drug_axes=[] for exp in exp_folders: k_abs_t = exp[exp.find('=')+1:] k_abs_t = float(k_abs_t)", "= data/max_cells if k==0: drug_kwargs = {'alpha':0.7, 'color':'black', 'linewidth':2, 'label':'Drug Concentration ($\\u03BC$M)' }", "tc_axes=[] drug_axes=[] for exp in exp_folders: k_abs_t = exp[exp.find('=')+1:] k_abs_t = float(k_abs_t) num", "survive_count > 0: counts_avg = counts_total/survive_count # counts_avg = counts_avg/np.max(counts_avg) # counts_avg =", "+ os.sep + sim data = results_manager.get_data(sim) dc = data[:,-1] data = data[:,0:-1]", "check to see if any genotypes are at least 10% of the max", "sim = sim_files[k] sim = exp + os.sep + sim data = results_manager.get_data(sim)", "= 0 counts_total = None k=0 while k < len(sim_files): # for sim", "= 'experiment_info_' + suffix + '.p' exp_folders,exp_info = results_manager.get_experiment_results(data_folder, exp_info_file) max_cells = exp_info.populations[0].max_cells", "import results_manager, plotter, dir_manager import os suffix = '07212021_0001' data_folder = 'results_' +", "= exp_info.n_sims k_abs = exp_info.slopes exp_folders.reverse() k_abs = np.flip(k_abs) fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop", "counts_total is None: counts_total = data else: counts_total += data # data =", "of the max cell count if any(data_t >= 1): survive_count += 1 if", "suffix exp_info_file = 'experiment_info_' + suffix + '.p' exp_folders,exp_info = results_manager.get_experiment_results(data_folder, exp_info_file) max_cells", "# data = data/np.max(data) data_t = data[-1,:] # check to see if any", "tcax,da = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, grayscale=True, color='gray', legend_labels=False, linewidth=2, labelsize=12, alpha=0.2 ) #", "tcax, labelsize=12) # t = np.arange(len(dc)) # t = t*exp_info.populations[0].timestep_scale/24 # da.plot(t,dc) tc_axes.append(", "= float(k_abs_t) num = np.argwhere(k_abs == k_abs_t) num = num[0,0] # generate timecourse", "data[-1,:] # check to see if any genotypes are at least 10% of", "= np.argwhere(k_abs == k_abs_t) num = num[0,0] # generate timecourse axes tcax =", "exp_info_file) max_cells = exp_info.populations[0].max_cells n_sims = exp_info.n_sims k_abs = exp_info.slopes exp_folders.reverse() k_abs =", "fears.utils import results_manager, plotter, dir_manager import os suffix = '07212021_0001' data_folder = 'results_'", "= plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg, tcax, labelsize=12) # t = np.arange(len(dc)) # t = t*exp_info.populations[0].timestep_scale/24", "+ suffix exp_info_file = 'experiment_info_' + suffix + '.p' exp_folders,exp_info = results_manager.get_experiment_results(data_folder, exp_info_file)", "'experiment_info_' + suffix + '.p' exp_folders,exp_info = results_manager.get_experiment_results(data_folder, exp_info_file) max_cells = exp_info.populations[0].max_cells n_sims", "da = tcax.twinx() sim_files = os.listdir(path=exp) sim_files = sorted(sim_files) survive_count = 0 counts_total", "= 'results_' + suffix exp_info_file = 'experiment_info_' + suffix + '.p' exp_folders,exp_info =", "results_manager.get_experiment_results(data_folder, exp_info_file) max_cells = exp_info.populations[0].max_cells n_sims = exp_info.n_sims k_abs = exp_info.slopes exp_folders.reverse() k_abs", "k=0 while k < len(sim_files): # for sim in sim_files: sim = sim_files[k]", "counts_avg, tcax, labelsize=12) # t = np.arange(len(dc)) # t = t*exp_info.populations[0].timestep_scale/24 # da.plot(t,dc)", "exp_folders,exp_info = results_manager.get_experiment_results(data_folder, exp_info_file) max_cells = exp_info.populations[0].max_cells n_sims = exp_info.n_sims k_abs = exp_info.slopes", "data[:,0:-1] # data = data/np.max(data) data_t = data[-1,:] # check to see if", "# generate timecourse axes tcax = ax[axnum] # da = tcax.twinx() sim_files =", "None k=0 while k < len(sim_files): # for sim in sim_files: sim =", "k_abs = exp_info.slopes exp_folders.reverse() k_abs = np.flip(k_abs) fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop = exp_info.populations[0]", "drug_axes.append( drug_ax ) else: tcax,da = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, grayscale=True, color='gray', legend_labels=False, linewidth=2,", "counts_total/survive_count # counts_avg = counts_avg/np.max(counts_avg) # counts_avg = counts_total counts_avg = counts_avg/np.max(counts_avg) tcax,temp", "to see if any genotypes are at least 10% of the max cell", "data_folder = 'results_' + suffix exp_info_file = 'experiment_info_' + suffix + '.p' exp_folders,exp_info", "= None k=0 while k < len(sim_files): # for sim in sim_files: sim", "data = data[:,0:-1] # data = data/np.max(data) data_t = data[-1,:] # check to", "'linewidth':2, 'label':'Drug Concentration ($\\u03BC$M)' } tcax,drug_ax = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, drug_curve=dc, drug_ax_sci_notation=True, drug_kwargs=drug_kwargs,", "os suffix = '07212021_0001' data_folder = 'results_' + suffix exp_info_file = 'experiment_info_' +", "os.listdir(path=exp) sim_files = sorted(sim_files) survive_count = 0 counts_total = None k=0 while k", "data/np.max(data) # exp_info.populations[num].counts_log_scale = True data = data/max_cells if k==0: drug_kwargs = {'alpha':0.7,", "'.p' exp_folders,exp_info = results_manager.get_experiment_results(data_folder, exp_info_file) max_cells = exp_info.populations[0].max_cells n_sims = exp_info.n_sims k_abs =", "in exp_folders: k_abs_t = exp[exp.find('=')+1:] k_abs_t = float(k_abs_t) num = np.argwhere(k_abs == k_abs_t)", "alpha=0.7 ) drug_ax.set_ylabel('') drug_axes.append( drug_ax ) else: tcax,da = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, grayscale=True,", "else: tcax,da = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, grayscale=True, color='gray', legend_labels=False, linewidth=2, labelsize=12, alpha=0.2 )", "drug_kwargs = {'alpha':0.7, 'color':'black', 'linewidth':2, 'label':'Drug Concentration ($\\u03BC$M)' } tcax,drug_ax = plotter.plot_timecourse_to_axes(exp_info.populations[num], data,", "sim = exp + os.sep + sim data = results_manager.get_data(sim) dc = data[:,-1]", "np.argwhere(k_abs == k_abs_t) num = num[0,0] # generate timecourse axes tcax = ax[axnum]", "= num[0,0] # generate timecourse axes tcax = ax[axnum] # da = tcax.twinx()", "10% of the max cell count if any(data_t >= 1): survive_count += 1", "legend_labels=False, grayscale=True, color='gray', linewidth=1, labelsize=12, alpha=0.7 ) drug_ax.set_ylabel('') drug_axes.append( drug_ax ) else: tcax,da", "plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, grayscale=True, color='gray', legend_labels=False, linewidth=2, labelsize=12, alpha=0.2 ) # drug_ax.set_ylim(0,10**4) k+=1", "= ax[axnum] # da = tcax.twinx() sim_files = os.listdir(path=exp) sim_files = sorted(sim_files) survive_count", "= tcax.twinx() sim_files = os.listdir(path=exp) sim_files = sorted(sim_files) survive_count = 0 counts_total =", "num = num[0,0] # generate timecourse axes tcax = ax[axnum] # da =", "axes tcax = ax[axnum] # da = tcax.twinx() sim_files = os.listdir(path=exp) sim_files =", "data = results_manager.get_data(sim) dc = data[:,-1] data = data[:,0:-1] # data = data/np.max(data)", "exp_info.slopes exp_folders.reverse() k_abs = np.flip(k_abs) fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop = exp_info.populations[0] ax =", "drug_kwargs=drug_kwargs, legend_labels=False, grayscale=True, color='gray', linewidth=1, labelsize=12, alpha=0.7 ) drug_ax.set_ylabel('') drug_axes.append( drug_ax ) else:", "os.sep + sim data = results_manager.get_data(sim) dc = data[:,-1] data = data[:,0:-1] #", "plt import numpy as np from fears.utils import results_manager, plotter, dir_manager import os", "data[:,-1] data = data[:,0:-1] # data = data/np.max(data) data_t = data[-1,:] # check", "+= data # data = data/np.max(data) # exp_info.populations[num].counts_log_scale = True data = data/max_cells", "as plt import numpy as np from fears.utils import results_manager, plotter, dir_manager import", "plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, drug_curve=dc, drug_ax_sci_notation=True, drug_kwargs=drug_kwargs, legend_labels=False, grayscale=True, color='gray', linewidth=1, labelsize=12, alpha=0.7 )", "import matplotlib.pyplot as plt import numpy as np from fears.utils import results_manager, plotter,", "k==0: drug_kwargs = {'alpha':0.7, 'color':'black', 'linewidth':2, 'label':'Drug Concentration ($\\u03BC$M)' } tcax,drug_ax = plotter.plot_timecourse_to_axes(exp_info.populations[num],", "counts_avg = counts_avg/np.max(counts_avg) # counts_avg = counts_total counts_avg = counts_avg/np.max(counts_avg) tcax,temp = plotter.plot_timecourse_to_axes(exp_info.populations[num],", "dc = data[:,-1] data = data[:,0:-1] # data = data/np.max(data) data_t = data[-1,:]", "($\\u03BC$M)' } tcax,drug_ax = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, drug_curve=dc, drug_ax_sci_notation=True, drug_kwargs=drug_kwargs, legend_labels=False, grayscale=True, color='gray',", "= counts_total/survive_count # counts_avg = counts_avg/np.max(counts_avg) # counts_avg = counts_total counts_avg = counts_avg/np.max(counts_avg)", "counts_total = None k=0 while k < len(sim_files): # for sim in sim_files:", "float(k_abs_t) num = np.argwhere(k_abs == k_abs_t) num = num[0,0] # generate timecourse axes", "count if any(data_t >= 1): survive_count += 1 if counts_total is None: counts_total", "drug_ax.set_ylim(0,10**4) k+=1 if survive_count > 0: counts_avg = counts_total/survive_count # counts_avg = counts_avg/np.max(counts_avg)", "are at least 10% of the max cell count if any(data_t >= 1):", "'results_' + suffix exp_info_file = 'experiment_info_' + suffix + '.p' exp_folders,exp_info = results_manager.get_experiment_results(data_folder,", "True data = data/max_cells if k==0: drug_kwargs = {'alpha':0.7, 'color':'black', 'linewidth':2, 'label':'Drug Concentration" ]
[ "about the specific entry point.\"\"\" assert isinstance(function, types.FunctionType), \"fix that!\" from rpython.annotator.policy import", "i)): new_ops = op.transform(self) if new_ops is not None: block.operations[i:i+1] = new_ops if", "for # which it is fine to always raise an exception. We then", "= self.binding(block.exitswitch) if s_exitswitch.is_constant(): exits = [link for link in exits if link.exitcase", "renaming = defaultdict(list) for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out, v_input", "if got_blocked_blocks: for graph in self.blocked_graphs.values(): self.blocked_graphs[graph] = True blocked_blocks = [block for", "below self.links_followed = {} # set of links that have ever been followed", "(graph, None) def bindinputargs(self, graph, block, inputcells): # Create the initial bindings for", "self.get_call_parameters(function, args_s, policy) self.build_graph_types(graph, inputcells, complete_now=False) self.complete_helpers(policy) return graph def complete_helpers(self, policy): saved", "renaming = defaultdict(list) for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out in", "exits = block.exits if isinstance(block.exitswitch, Variable): s_exitswitch = self.binding(block.exitswitch) if s_exitswitch.is_constant(): exits =", "to the given Variable or Constant.\" if isinstance(arg, Variable): return arg.annotation elif isinstance(arg,", "type(variable.value) elif isinstance(variable, Variable): s_variable = variable.annotation if s_variable: return s_variable.knowntype else: return", "is_(SomeImpossibleValue, None) -> SomeBool # is_(SomeInstance(not None), None) -> SomeBool(const=False) ... # boom", "the known type of a control flow graph variable, defaulting to 'object'.\"\"\" if", "= False # must re-flow self.blocked_blocks[block] = (graph, None) def bindinputargs(self, graph, block,", "if op.opname in ('simple_call', 'call_args'): yield op # some blocks are partially annotated", "def follow_link(self, graph, link, constraints): assert not (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException))", "= \" block\"+at opid=\"\" if i is not None: opid = \" op=%d\"", "zip(block.inputargs, inputcells): self.setbinding(a, cell) self.annotated[block] = False # must flowin. self.blocked_blocks[block] = (graph,", "= graph if block in self.blocked_blocks: del self.blocked_blocks[block] try: self.flowin(graph, block) except BlockedInference", "blocks are partially annotated if op.result.annotation is None: break # ignore the unannotated", "source_lines) from rpython.flowspace.model import Variable, Constant, checkgraph from rpython.translator import simplify, transform from", "simplify(self, block_subset=None, extra_passes=None): # Generic simplifications transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes) if block_subset is None:", "the type inference engine that the situation is currently blocked, and that it", "link.last_exc_value assert (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) assert v_last_exc_type and v_last_exc_value if", "import Bookkeeper from rpython.rtyper.normalizecalls import perform_normalizations log = AnsiLogger(\"annrpython\") class RPythonAnnotator(object): \"\"\"Block annotator", "The analysis of a block can be in three states: # * block", "to the UnionError e.source = '\\n'.join(source_lines(graph, block, None, long=True)) raise # if the", "prevpolicy = self.policy self.policy = policy self.bookkeeper.enter(None) try: return desc.get_call_parameters(args_s) finally: self.bookkeeper.leave() self.policy", "which it is fine to always raise an exception. We then # swallow", "block.raising_op s_exception = self.get_exception(op) for link in exits: case = link.exitcase if case", "is None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception): \"\"\"This exception signals the", "SomeImpossibleValue enters is_ # is_(SomeImpossibleValue, None) -> SomeBool # is_(SomeInstance(not None), None) ->", "elif v_last_exc_type.annotation.is_constant(): s_out.const = v_last_exc_type.annotation.const inputs_s.append(s_out) else: s_out = self.annotation(v_out) s_out = self.apply_renaming(s_out,", "saved = self.policy, self.added_blocks self.policy = policy try: self.added_blocks = {} self.complete() #", "then # swallow the BlockedInference and that's it. # About 'next': see test_annotate_iter_empty_container().", "= self.apply_renaming(s_out, renaming) inputs_s.append(s_out) if ignore_link: return self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s)", "will hopefully be solved # later by reflowing). Throw the BlockedInference up to", "we must generalize the # input variables). #print '* processblock', block, cells self.annotated[block]", "graphs not to annotate again self.blocked_blocks = {} # set of {blocked_block: (graph,", "Safety-check the new # annotations that are passed in, and don't annotate the", "def setbinding(self, arg, s_value): s_old = arg.annotation if s_old is not None: if", "newgraphs = [self.annotated[block] for block in self.added_blocks] newgraphs = dict.fromkeys(newgraphs) got_blocked_blocks = False", "# boom -- in the assert of setbinding() for arg in op.args: if", "block have bindings but we # still have to consider all the operations", "elif e.op.opname in ('simple_call', 'call_args', 'next'): # XXX warning, keep the name of", "function didn't reach any return statement so far. # (some functions actually never", "None: self.setbinding(v, s_ImpossibleValue) def validate(self): \"\"\"Check that the annotation results are valid\"\"\" self.bookkeeper.check_no_flags_on_instances()", "an exception handler. We then only follow the exceptional # branches. exits =", "self.policy self.policy = policy self.bookkeeper.enter(None) try: return desc.get_call_parameters(args_s) finally: self.bookkeeper.leave() self.policy = prevpolicy", "in sync # with the flow object space. These are the operations for", "self.annotated.get(block) if graph: graphs[graph] = True for graph in graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if", "exceptional # branches. exits = [link for link in block.exits if link.exitcase is", "{}) self.follow_link(graph, link, constraints) if block in self.notify: # reflow from certain positions", "raise else: # dead code removal: don't follow all exits if the exitswitch", "checkgraph from rpython.translator import simplify, transform from rpython.annotator import model as annmodel, signature", "specific entry point.\"\"\" assert isinstance(function, types.FunctionType), \"fix that!\" from rpython.annotator.policy import AnnotatorPolicy policy", "self.binding(a) assert annmodel.unionof(s_oldarg, s_newarg) == s_oldarg else: assert not self.frozen if block not", "= [block for block, done in self.annotated.items() if done is False] assert len(blocked_blocks)", "%s\" % (pos, msg)) #___ interface for annotator.bookkeeper _______ def recursivecall(self, graph, whence,", "self.pendingblocks[block] = graph assert block in self.annotated self.annotated[block] = False # must re-flow", "to this func which triggers a reflow whenever the # return block of", "self.annotated[block] = False # failed, hopefully temporarily self.blocked_blocks[block] = (graph, e.opindex) except Exception", "bindinputargs(self, graph, block, inputcells): # Create the initial bindings for the input args", "will # always raise an exception which is immediately caught by # an", "annotator, op, opindex): self.annotator = annotator try: self.break_at = annotator.bookkeeper.position_key except AttributeError: self.break_at", "if at: blk = \" block\"+at opid=\"\" if i is not None: opid", "SomeBool(const=False) ... # boom -- in the assert of setbinding() for arg in", "flowin(self, graph, block): try: i = 0 while i < len(block.operations): op =", "Throw the BlockedInference up to # processblock(). e.opindex = i raise except annmodel.HarmlesslyBlocked:", "graph has been analysed. callpositions = self.notify.setdefault(graph.returnblock, {}) if whence is not None:", "if block.canraise: op = block.raising_op s_exception = self.get_exception(op) for link in exits: case", "else: s_out = self.annotation(v_out) s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) self.links_followed[link] = True self.addpendingblock(graph,", "keep the name of the call operations in sync # with the flow", "complete_helpers(self, policy): saved = self.policy, self.added_blocks self.policy = policy try: self.added_blocks = {}", "renaming.get(v, []) for new_v in new_vs: renamed_knowntypedata[value][new_v] = s assert isinstance(s_out, annmodel.SomeBool) newcell", "of the block will # always raise an exception which is immediately caught", "with the given input cells.\"\"\" if graph in self.fixed_graphs: # special case for", "op # some blocks are partially annotated if op.result.annotation is None: break #", "graph-containing-it} self.annotated = {} # set of blocks already seen self.added_blocks = None", "given input cells.\"\"\" if graph in self.fixed_graphs: # special case for annotating/rtyping in", "difference(s_exception, s_case) else: if isinstance(block.exitswitch, Variable): knowntypedata = getattr( block.exitswitch.annotation, \"knowntypedata\", {}) else:", "v_last_exc_type and v_last_exc_value if isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value, s_last_exc_value) if isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value]))", "pending blocks until none is left.\"\"\" while True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if not self.pendingblocks:", "!= oldcells: self.bindinputargs(graph, block, unions) def apply_renaming(self, s_out, renaming): if hasattr(s_out, 'is_type_of'): renamed_is_type_of", "op.consider(self) if resultcell is None: resultcell = s_ImpossibleValue elif resultcell == s_ImpossibleValue: raise", "in self.blocked_blocks: del self.blocked_blocks[block] try: self.flowin(graph, block) except BlockedInference as e: self.annotated[block] =", "= {} for block in block_subset: graph = self.annotated.get(block) if graph: graphs[graph] =", "self.setbinding(v_last_exc_value, s_last_exc_value) if isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s = [] renaming = defaultdict(list)", "in self.annotated.values() if got_blocked_blocks: for graph in self.blocked_graphs.values(): self.blocked_graphs[graph] = True blocked_blocks =", "is dict, ( \"%r is not dict. please update %s.__getstate__\" % (key, self.__class__.__name__))", "if v_out == v_last_exc_type: s_out = typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type, Constant): s_out.const = v_last_exc_type.value", "c1, c2 in zip(oldcells,inputcells)] except annmodel.UnionError as e: # Add source code to", "in self.annotated: self.bindinputargs(graph, block, cells) else: self.mergeinputargs(graph, block, cells) if not self.annotated[block]: self.pendingblocks[block]", "knowntypedata = getattr( block.exitswitch.annotation, \"knowntypedata\", {}) else: knowntypedata = {} for link in", "in zip(block.inputargs, cells): s_oldarg = self.binding(a) assert annmodel.unionof(s_oldarg, s_newarg) == s_oldarg else: assert", "dict, ( \"%r is not dict. please update %s.__getstate__\" % (key, self.__class__.__name__)) ret[key]", "newcell = annmodel.SomeBool() if s_out.is_constant(): newcell.const = s_out.const s_out = newcell s_out.set_knowntypedata(renamed_knowntypedata) return", "self.break_at: break_at = \"?\" else: break_at = self.annotator.whereami(self.break_at) return \"<BlockedInference break_at %s [%s]>\"", "try: return desc.get_call_parameters(args_s) finally: self.bookkeeper.leave() self.policy = prevpolicy def annotate_helper(self, function, args_s, policy=None):", "{}) continue if s_exception == s_ImpossibleValue: break s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc = intersection(s_exception,", "def binding(self, arg): \"Gives the SomeValue corresponding to the given Variable or Constant.\"", "new_v in new_vs: renamed_knowntypedata[value][new_v] = s assert isinstance(s_out, annmodel.SomeBool) newcell = annmodel.SomeBool() if", "have bindings but we # still have to consider all the operations in", "False in newgraphs else: newgraphs = self.translator.graphs #all of them got_blocked_blocks = False", "= operation.get_can_only_throw(self) if can_only_throw is None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception):", "if policy is None: from rpython.annotator.policy import AnnotatorPolicy self.policy = AnnotatorPolicy() else: self.policy", "except Exception as e: # hack for debug tools only if not hasattr(e,", "= False in newgraphs else: newgraphs = self.translator.graphs #all of them got_blocked_blocks =", "if op.result.annotation is None: break # ignore the unannotated part #___ simplification (should", "call operations in sync # with the flow object space. These are the", "v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out in link.args: s_out = self.annotation(v_out)", "more general results invariant: e.g. if SomeImpossibleValue enters is_ # is_(SomeImpossibleValue, None) ->", "the annotation for all exceptions that `operation` may raise. \"\"\" can_only_throw = operation.get_can_only_throw(self)", "exits = [link for link in block.exits if link.exitcase is not None] elif", "if resultcell is None: resultcell = s_ImpossibleValue elif resultcell == s_ImpossibleValue: raise BlockedInference(self,", "block): assert not self.frozen assert graph not in self.fixed_graphs self.pendingblocks[block] = graph assert", "whereami(self, position_key): graph, block, i = position_key blk = \"\" if block: at", "# annotations that are passed in, and don't annotate the old # graph", "try: self.added_blocks = {} self.complete() # invoke annotation simplifications for the new blocks", "s_out = newcell if hasattr(s_out, 'knowntypedata'): renamed_knowntypedata = {} for value, constraints in", "self.added_blocks = {} self.complete() # invoke annotation simplifications for the new blocks self.simplify(block_subset=self.added_blocks)", "isinstance(arg, Variable): return arg.annotation elif isinstance(arg, Constant): return self.bookkeeper.immutablevalue(arg.value) else: raise TypeError('Variable or", "new 'cells' with each of the block's existing input # variables. oldcells =", "block.at() if at: blk = \" block\"+at opid=\"\" if i is not None:", "an exception. We then # swallow the BlockedInference and that's it. # About", "input_arg_types, complete_now=True, main_entry_point=False): \"\"\"Recursively build annotations about the specific entry point.\"\"\" assert isinstance(function,", "in s_out.knowntypedata.items(): renamed_knowntypedata[value] = {} for v, s in constraints.items(): new_vs = renaming.get(v,", "name of the call operations in sync # with the flow object space.", "None: block.operations[i:i+1] = new_ops if not new_ops: continue new_ops[-1].result = op.result op =", "self.blocked_graphs = {} # set of graphs that have blocked blocks # ---", "break s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc = intersection(s_exception, s_case) if s_matching_exc != s_ImpossibleValue: self.follow_raise_link(graph,", "# Add source code to the UnionError e.source = '\\n'.join(source_lines(graph, block, None, long=True))", "= position_key blk = \"\" if block: at = block.at() if at: blk", "simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if block_subset is None: perform_normalizations(self) #___ flowing annotations in blocks _____________________", "from rpython.flowspace.model import Variable, Constant, checkgraph from rpython.translator import simplify, transform from rpython.annotator", "for block in newblocks: for op in block.operations: if op.opname in ('simple_call', 'call_args'):", "continue new_ops[-1].result = op.result op = new_ops[0] self.consider_op(op) i += 1 except BlockedInference", "self.addpendinggraph(flowgraph, inputcells) # recursively proceed until no more pending block is left if", "try: unions = [annmodel.unionof(c1,c2) for c1, c2 in zip(oldcells,inputcells)] except annmodel.UnionError as e:", "== len(self.blocked_blocks) text = format_blocked_annotation_error(self, self.blocked_blocks) #raise SystemExit() raise annmodel.AnnotatorError(text) for graph in", "== s_ImpossibleValue: raise BlockedInference(self, op, -1) # the operation cannot succeed assert isinstance(resultcell,", "typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type, Constant): s_out.const = v_last_exc_type.value elif v_last_exc_type.annotation.is_constant(): s_out.const = v_last_exc_type.annotation.const inputs_s.append(s_out)", "or Constant expected, got %r' % (arg,)) def binding(self, arg): \"Gives the SomeValue", "self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s = [] renaming = defaultdict(list) for v_out, v_input in zip(link.args,", "= policy if bookkeeper is None: bookkeeper = Bookkeeper(self) self.bookkeeper = bookkeeper def", "= None # see processblock() below self.links_followed = {} # set of links", "= self.bookkeeper.getdesc(function) prevpolicy = self.policy self.policy = policy self.bookkeeper.enter(None) try: return desc.get_call_parameters(args_s) finally:", "entry point into block with the given input cells.\"\"\" if graph in self.fixed_graphs:", "SomeValue corresponding to the given Variable or Constant.\" if isinstance(arg, Variable): return arg.annotation", "# graph -- it's already low-level operations! for a, s_newarg in zip(block.inputargs, cells):", "bind resultcell to op.result def get_exception(self, operation): \"\"\" Return the annotation for all", "#___ interface for annotator.bookkeeper _______ def recursivecall(self, graph, whence, inputcells): if isinstance(whence, tuple):", "dead code removal: don't follow all exits if the exitswitch # is known", "notify bookkeeper frozen policy added_blocks\"\"\".split() ret = self.__dict__.copy() for key, value in ret.items():", "type(value) is dict, ( \"%r is not dict. please update %s.__getstate__\" % (key,", "None: try: pos = self.bookkeeper.position_key except AttributeError: pos = '?' if pos !=", "# processblock(). e.opindex = i raise except annmodel.HarmlesslyBlocked: return except annmodel.AnnotatorError as e:", "model as annmodel, signature from rpython.annotator.model import ( typeof, s_ImpossibleValue, SomeInstance, intersection, difference)", "if whence is not None: if callable(whence): def callback(): whence(self, graph) else: callback", "the operations in the block. # * self.annotated[block] == graph-containing-block: # analysis done", "for a, cell in zip(block.inputargs, inputcells): self.setbinding(a, cell) self.annotated[block] = False # must", "it. # About 'next': see test_annotate_iter_empty_container(). return else: # other cases are problematic", "op = block.raising_op s_exception = self.get_exception(op) for link in exits: case = link.exitcase", "block. # * self.annotated[block] == False: # the input variables of the block", "the new 'cells' with each of the block's existing input # variables. oldcells", "op, opindex): self.annotator = annotator try: self.break_at = annotator.bookkeeper.position_key except AttributeError: self.break_at =", "\"Gives the SomeValue corresponding to the given Variable or Constant.\" if isinstance(arg, Variable):", "renaming[v_out].append(v_input) for v_out in link.args: s_out = self.annotation(v_out) if v_out in constraints: s_constraint", "BlockedInference and that's it. # About 'next': see test_annotate_iter_empty_container(). return else: # other", "unannotated part #___ simplification (should be moved elsewhere?) _______ def simplify(self, block_subset=None, extra_passes=None):", "s_ImpossibleValue def reflowfromposition(self, position_key): graph, block, index = position_key self.reflowpendingblock(graph, block) def call_sites(self):", "\"knowntypedata\", {}) else: knowntypedata = {} for link in exits: constraints = knowntypedata.get(link.exitcase,", "that!\" from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # make input arguments and", "\"\"\"Return a list of ClassDefs.\"\"\" return self.bookkeeper.classdefs #___ medium-level interface ____________________________ def addpendinggraph(self,", "#print '* processblock', block, cells self.annotated[block] = graph if block in self.blocked_blocks: del", "link, {}) continue if s_exception == s_ImpossibleValue: break s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc =", "position else: callback() def follow_link(self, graph, link, constraints): assert not (isinstance(link.exitcase, (types.ClassType, type))", "op.transform(self) if new_ops is not None: block.operations[i:i+1] = new_ops if not new_ops: continue", "elsewhere.\"\"\" def __init__(self, annotator, op, opindex): self.annotator = annotator try: self.break_at = annotator.bookkeeper.position_key", "pendingblocks annotated links_followed notify bookkeeper frozen policy added_blocks\"\"\".split() ret = self.__dict__.copy() for key,", "not in attrs: assert type(value) is dict, ( \"%r is not dict. please", "key, value in ret.items(): if key not in attrs: assert type(value) is dict,", "'?' if pos != '?': pos = self.whereami(pos) log.WARNING(\"%s/ %s\" % (pos, msg))", "case = link.exitcase if case is None: self.follow_link(graph, link, {}) continue if s_exception", "'__annotator_block', block) raise # The dict 'added_blocks' is used by rpython.annlowlevel to #", "link in exits: constraints = knowntypedata.get(link.exitcase, {}) self.follow_link(graph, link, constraints) if block in", "link.target.inputargs): renaming[v_out].append(v_input) for v_out, v_input in zip(link.args, link.target.inputargs): if v_out == v_last_exc_type: s_out", "invoke annotation simplifications for the new blocks self.simplify(block_subset=self.added_blocks) finally: self.policy, self.added_blocks = saved", "callpositions = self.notify.setdefault(graph.returnblock, {}) if whence is not None: if callable(whence): def callback():", "annmodel.AnnotatorError as e: # note that UnionError is a subclass e.source = gather_error(self,", "difference) from rpython.annotator.bookkeeper import Bookkeeper from rpython.rtyper.normalizecalls import perform_normalizations log = AnsiLogger(\"annrpython\") class", "self.bookkeeper = bookkeeper def __getstate__(self): attrs = \"\"\"translator pendingblocks annotated links_followed notify bookkeeper", "only follow the exceptional # branches. exits = [link for link in block.exits", "annotate again self.blocked_blocks = {} # set of {blocked_block: (graph, index)} # ---", "op.opname in ('simple_call', 'call_args'): yield op # some blocks are partially annotated if", "extra_passes=None): # Generic simplifications transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes) if block_subset is None: graphs =", "if i is not None: opid = \" op=%d\" % i return repr(graph)", "dictionary of call # points to this func which triggers a reflow whenever", "for c1, c2 in zip(oldcells,inputcells)] except annmodel.UnionError as e: # Add source code", "= AnsiLogger(\"annrpython\") class RPythonAnnotator(object): \"\"\"Block annotator for RPython. See description in doc/translation.txt.\"\"\" def", "graph, block, i) raise else: # dead code removal: don't follow all exits", "part #___ simplification (should be moved elsewhere?) _______ def simplify(self, block_subset=None, extra_passes=None): #", "try: self.flowin(graph, block) except BlockedInference as e: self.annotated[block] = False # failed, hopefully", "newcell = typeof(renamed_is_type_of) if s_out.is_constant(): newcell.const = s_out.const s_out = newcell if hasattr(s_out,", "s_out.const = v_last_exc_type.value elif v_last_exc_type.annotation.is_constant(): s_out.const = v_last_exc_type.annotation.const inputs_s.append(s_out) else: s_out = self.annotation(v_out)", "= {} self.complete() # invoke annotation simplifications for the new blocks self.simplify(block_subset=self.added_blocks) finally:", "do, they always raise exceptions) return s_ImpossibleValue def reflowfromposition(self, position_key): graph, block, index", "self.annotation(arg) if s_arg is None: raise KeyError return s_arg def typeannotation(self, t): return", "False # must flowin. self.blocked_blocks[block] = (graph, None) def mergeinputargs(self, graph, block, inputcells):", "getattr( block.exitswitch.annotation, \"knowntypedata\", {}) else: knowntypedata = {} for link in exits: constraints", "a control flow graph variable, defaulting to 'object'.\"\"\" if isinstance(variable, Constant): return type(variable.value)", "t): return signature.annotation(t, self.bookkeeper) def setbinding(self, arg, s_value): s_old = arg.annotation if s_old", "\"\"\"Register an entry point into block with the given input cells.\"\"\" if graph", "% (key, self.__class__.__name__)) ret[key] = {} return ret #___ convenience high-level interface __________________", "try: pos = self.bookkeeper.position_key except AttributeError: pos = '?' if pos != '?':", "exitswitch # is known exits = block.exits if isinstance(block.exitswitch, Variable): s_exitswitch = self.binding(block.exitswitch)", "( \"%r is not dict. please update %s.__getstate__\" % (key, self.__class__.__name__)) ret[key] =", "oldcells: self.bindinputargs(graph, block, unions) def apply_renaming(self, s_out, renaming): if hasattr(s_out, 'is_type_of'): renamed_is_type_of =", "that it should try to progress elsewhere.\"\"\" def __init__(self, annotator, op, opindex): self.annotator", "have blocked blocks # --- end of debugging information --- self.frozen = False", "Variable): return arg.annotation elif isinstance(arg, Constant): return self.bookkeeper.immutablevalue(arg.value) else: raise TypeError('Variable or Constant", "# always raise an exception which is immediately caught by # an exception", "always raise exceptions) return s_ImpossibleValue def reflowfromposition(self, position_key): graph, block, index = position_key", "newcell s_out.set_knowntypedata(renamed_knowntypedata) return s_out def whereami(self, position_key): graph, block, i = position_key blk", "opindex): self.annotator = annotator try: self.break_at = annotator.bookkeeper.position_key except AttributeError: self.break_at = None", "i raise except annmodel.HarmlesslyBlocked: return except annmodel.AnnotatorError as e: # note that UnionError", "block will # always raise an exception which is immediately caught by #", "zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out in link.args: s_out = self.annotation(v_out) if v_out in", "op.args: if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise BlockedInference(self, op, -1) resultcell = op.consider(self) if resultcell", "if not self.break_at: break_at = \"?\" else: break_at = self.annotator.whereami(self.break_at) return \"<BlockedInference break_at", "to # detect which are the new blocks that annotating an additional #", "e: self.annotated[block] = False # failed, hopefully temporarily self.blocked_blocks[block] = (graph, e.opindex) except", "op): # let's be careful about avoiding propagated SomeImpossibleValues # to enter an", "changed, we must redo the analysis if unions != oldcells: self.bindinputargs(graph, block, unions)", "exception. We then # swallow the BlockedInference and that's it. # About 'next':", "this func which triggers a reflow whenever the # return block of this", "None: if callable(whence): def callback(): whence(self, graph) else: callback = whence callpositions[callback] =", "link.target.inputargs): renaming[v_out].append(v_input) for v_out in link.args: s_out = self.annotation(v_out) if v_out in constraints:", "if block in self.blocked_blocks: del self.blocked_blocks[block] try: self.flowin(graph, block) except BlockedInference as e:", "BaseException)) assert v_last_exc_type and v_last_exc_value if isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value, s_last_exc_value) if isinstance(v_last_exc_type, Variable):", "the (current) return value v = graph.getreturnvar() try: return self.binding(v) except KeyError: #", "e: # Add source code to the UnionError e.source = '\\n'.join(source_lines(graph, block, None,", "simplifications for the new blocks self.simplify(block_subset=self.added_blocks) finally: self.policy, self.added_blocks = saved def build_graph_types(self,", "sure that the return variables of all graphs is annotated if self.added_blocks is", "def complete_pending_blocks(self): while self.pendingblocks: block, graph = self.pendingblocks.popitem() self.processblock(graph, block) def complete(self): \"\"\"Process", "be in three states: # * block not in self.annotated: # never seen", "reflowing). Throw the BlockedInference up to # processblock(). e.opindex = i raise except", "def __init__(self, annotator, op, opindex): self.annotator = annotator try: self.break_at = annotator.bookkeeper.position_key except", "s_arg def typeannotation(self, t): return signature.annotation(t, self.bookkeeper) def setbinding(self, arg, s_value): s_old =", "consider all the operations in the block. # * self.annotated[block] == graph-containing-block: #", "convenience high-level interface __________________ def build_types(self, function, input_arg_types, complete_now=True, main_entry_point=False): \"\"\"Recursively build annotations", "flowgraph, inputcells): self.addpendingblock(flowgraph, flowgraph.startblock, inputcells) def addpendingblock(self, graph, block, cells): \"\"\"Register an entry", "block.exits if link.exitcase is not None] elif e.op.opname in ('simple_call', 'call_args', 'next'): #", "of all graphs is annotated if self.added_blocks is not None: newgraphs = [self.annotated[block]", "list of ClassDefs.\"\"\" return self.bookkeeper.classdefs #___ medium-level interface ____________________________ def addpendinggraph(self, flowgraph, inputcells):", "op = new_ops[0] self.consider_op(op) i += 1 except BlockedInference as e: if e.op", "def flowin(self, graph, block): try: i = 0 while i < len(block.operations): op", "= self.policy self.policy = policy self.bookkeeper.enter(None) try: return desc.get_call_parameters(args_s) finally: self.bookkeeper.leave() self.policy =", "self.policy = AnnotatorPolicy() else: self.policy = policy if bookkeeper is None: bookkeeper =", "= annotator.bookkeeper.position_key except AttributeError: self.break_at = None self.op = op self.opindex = opindex", "# set of blocks already seen self.added_blocks = None # see processblock() below", "{} # set of graphs not to annotate again self.blocked_blocks = {} #", "recorded for debugging --- self.blocked_graphs = {} # set of graphs that have", "self.policy, self.added_blocks = saved def build_graph_types(self, flowgraph, inputcells, complete_now=True): checkgraph(flowgraph) nbarg = len(flowgraph.getargs())", "and v_last_exc_value if isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value, s_last_exc_value) if isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s", "variable, defaulting to 'object'.\"\"\" if isinstance(variable, Constant): return type(variable.value) elif isinstance(variable, Variable): s_variable", "in newgraphs else: newgraphs = self.translator.graphs #all of them got_blocked_blocks = False in", "block, cells): \"\"\"Register an entry point into block with the given input cells.\"\"\"", "The dict 'added_blocks' is used by rpython.annlowlevel to # detect which are the", "already seen self.added_blocks = None # see processblock() below self.links_followed = {} #", "triggers a reflow whenever the # return block of this graph has been", "\" op=%d\" % i return repr(graph) + blk + opid def flowin(self, graph,", "absolute_import import types from collections import defaultdict from rpython.tool.ansi_print import AnsiLogger from rpython.tool.pairtype", "complete(self): \"\"\"Process pending blocks until none is left.\"\"\" while True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if", "self.fixed_graphs self.pendingblocks[block] = graph assert block in self.annotated self.annotated[block] = False # must", "= True blocked_blocks = [block for block, done in self.annotated.items() if done is", "translator.annotator = self self.translator = translator self.pendingblocks = {} # map {block: graph-containing-it}", "= defaultdict(list) for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out, v_input in", "graph: graphs[graph] = True for graph in graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if block_subset is", "We then only follow the exceptional # branches. exits = [link for link", "is not None: if not s_value.contains(s_old): log.WARNING(\"%s does not contain %s\" % (s_value,", "def __repr__(self): if not self.break_at: break_at = \"?\" else: break_at = self.annotator.whereami(self.break_at) return", "newblocks: for op in block.operations: if op.opname in ('simple_call', 'call_args'): yield op #", "the case where the last operation of the block will # always raise", "= ( self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s = self.get_call_parameters(function, args_s, policy) if main_entry_point: self.translator.entry_point_graph =", "later by reflowing). Throw the BlockedInference up to # processblock(). e.opindex = i", "a subclass e.source = gather_error(self, graph, block, i) raise else: # dead code", "except AttributeError: pos = '?' if pos != '?': pos = self.whereami(pos) log.WARNING(\"%s/", "{} # set of graphs that have blocked blocks # --- end of", "policy = AnnotatorPolicy() # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) graph, inputcells =", "# XXX warning, keep the name of the call operations in sync #", "whence is not None: if callable(whence): def callback(): whence(self, graph) else: callback =", "graph, tag) # self.notify[graph.returnblock] is a dictionary of call # points to this", "None] elif e.op.opname in ('simple_call', 'call_args', 'next'): # XXX warning, keep the name", "[] renaming = defaultdict(list) for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out", "= self.notify.setdefault(graph.returnblock, {}) if whence is not None: if callable(whence): def callback(): whence(self,", "is left if complete_now: self.complete() return self.annotation(flowgraph.getreturnvar()) def gettype(self, variable): \"\"\"Return the known", "the block will # always raise an exception which is immediately caught by", "%s\" % (s_value, s_old)) log.WARNING(\"%s\" % annmodel.unionof(s_value, s_old)) assert False arg.annotation = s_value", "for debugging --- self.blocked_graphs = {} # set of graphs that have blocked", "to annotate again self.blocked_blocks = {} # set of {blocked_block: (graph, index)} #", "tag = parent_block, parent_index self.translator.update_call_graph(parent_graph, graph, tag) # self.notify[graph.returnblock] is a dictionary of", "all exceptions that `operation` may raise. \"\"\" can_only_throw = operation.get_can_only_throw(self) if can_only_throw is", "= [] for v in s_out.is_type_of: renamed_is_type_of += renaming[v] assert s_out.knowntype is type", "block is left if complete_now: self.complete() return self.annotation(flowgraph.getreturnvar()) def gettype(self, variable): \"\"\"Return the", "AnsiLogger from rpython.tool.pairtype import pair from rpython.tool.error import (format_blocked_annotation_error, gather_error, source_lines) from rpython.flowspace.model", "AnsiLogger(\"annrpython\") class RPythonAnnotator(object): \"\"\"Block annotator for RPython. See description in doc/translation.txt.\"\"\" def __init__(self,", "ret[key] = {} return ret #___ convenience high-level interface __________________ def build_types(self, function,", "`operation` may raise. \"\"\" can_only_throw = operation.get_can_only_throw(self) if can_only_throw is None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception))", "# recursively proceed until no more pending block is left if complete_now: self.complete()", "% (s_value, s_old)) log.WARNING(\"%s\" % annmodel.unionof(s_value, s_old)) assert False arg.annotation = s_value def", "self.op = op self.opindex = opindex def __repr__(self): if not self.break_at: break_at =", "s_exitswitch = self.binding(block.exitswitch) if s_exitswitch.is_constant(): exits = [link for link in exits if", "SystemExit() raise annmodel.AnnotatorError(text) for graph in newgraphs: v = graph.getreturnvar() if v.annotation is", "arguments self.addpendingblock(graph, graph.startblock, inputcells) # get the (current) return value v = graph.getreturnvar()", "s_out = newcell s_out.set_knowntypedata(renamed_knowntypedata) return s_out def whereami(self, position_key): graph, block, i =", "block.raising_op: # this is the case where the last operation of the block", "Exception as e: # hack for debug tools only if not hasattr(e, '__annotator_block'):", "the name of the call operations in sync # with the flow object", "= typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type, Constant): s_out.const = v_last_exc_type.value elif v_last_exc_type.annotation.is_constant(): s_out.const = v_last_exc_type.annotation.const", "block in self.blocked_blocks: del self.blocked_blocks[block] try: self.flowin(graph, block) except BlockedInference as e: self.annotated[block]", "+ opid def flowin(self, graph, block): try: i = 0 while i <", "at: blk = \" block\"+at opid=\"\" if i is not None: opid =", "args of a block. assert len(block.inputargs) == len(inputcells) for a, cell in zip(block.inputargs,", "until we find we must generalize the # input variables). #print '* processblock',", "ignore links that try to pass impossible values if s_out == s_ImpossibleValue: ignore_link", "renamed_is_type_of = [] for v in s_out.is_type_of: renamed_is_type_of += renaming[v] assert s_out.knowntype is", "block, i = position_key blk = \"\" if block: at = block.at() if", "= defaultdict(list) for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out in link.args:", "link, constraints): assert not (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) ignore_link = False", "to self.addpendingblock(). # The analysis of a block can be in three states:", "the merged cells changed, we must redo the analysis if unions != oldcells:", "call_sites(self): newblocks = self.added_blocks if newblocks is None: newblocks = self.annotated # all", "self.addpendingblock(graph, link.target, inputs_s) #___ creating the annotations based on operations ______ def consider_op(self,", "= SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc = intersection(s_exception, s_case) if s_matching_exc != s_ImpossibleValue: self.follow_raise_link(graph, link, s_matching_exc)", "graph, block, i = position_key blk = \"\" if block: at = block.at()", "annotations about the specific entry point.\"\"\" assert isinstance(function, types.FunctionType), \"fix that!\" from rpython.annotator.policy", "main_entry_point: self.translator.entry_point_graph = flowgraph return self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now) def get_call_parameters(self, function, args_s, policy):", "= \"?\" else: break_at = self.annotator.whereami(self.break_at) return \"<BlockedInference break_at %s [%s]>\" %(break_at, self.op)", "else: break_at = self.annotator.whereami(self.break_at) return \"<BlockedInference break_at %s [%s]>\" %(break_at, self.op) __str__ =", "arg.annotation if s_old is not None: if not s_value.contains(s_old): log.WARNING(\"%s does not contain", "self.links_followed = {} # set of links that have ever been followed self.notify", "complete_now: self.complete() return self.annotation(flowgraph.getreturnvar()) def gettype(self, variable): \"\"\"Return the known type of a", "None) def mergeinputargs(self, graph, block, inputcells): # Merge the new 'cells' with each", "self.fixed_graphs = {} # set of graphs not to annotate again self.blocked_blocks =", "in the assert of setbinding() for arg in op.args: if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise", "SomeValue corresponding to the given Variable or Constant.\" s_arg = self.annotation(arg) if s_arg", "block, cells self.annotated[block] = graph if block in self.blocked_blocks: del self.blocked_blocks[block] try: self.flowin(graph,", "def annotate_helper(self, function, args_s, policy=None): if policy is None: from rpython.annotator.policy import AnnotatorPolicy", "annmodel.unionof(s_value, s_old)) assert False arg.annotation = s_value def warning(self, msg, pos=None): if pos", "additional # small helper creates. if self.added_blocks is not None: self.added_blocks[block] = True", "else: if isinstance(block.exitswitch, Variable): knowntypedata = getattr( block.exitswitch.annotation, \"knowntypedata\", {}) else: knowntypedata =", "policy) if main_entry_point: self.translator.entry_point_graph = flowgraph return self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now) def get_call_parameters(self, function,", "{positions-to-reflow-from-when-done}} self.fixed_graphs = {} # set of graphs not to annotate again self.blocked_blocks", "annotator try: self.break_at = annotator.bookkeeper.position_key except AttributeError: self.break_at = None self.op = op", "arg, s_value): s_old = arg.annotation if s_old is not None: if not s_value.contains(s_old):", "not None: if callable(whence): def callback(): whence(self, graph) else: callback = whence callpositions[callback]", "block, unions) def apply_renaming(self, s_out, renaming): if hasattr(s_out, 'is_type_of'): renamed_is_type_of = [] for", "exits = [link for link in exits if link.exitcase == s_exitswitch.const] if block.canraise:", "def bindinputargs(self, graph, block, inputcells): # Create the initial bindings for the input", "nbarg # wrong number of args # register the entry point self.addpendinggraph(flowgraph, inputcells)", "self.policy = policy if bookkeeper is None: bookkeeper = Bookkeeper(self) self.bookkeeper = bookkeeper", "desc = self.bookkeeper.getdesc(function) prevpolicy = self.policy self.policy = policy self.bookkeeper.enter(None) try: return desc.get_call_parameters(args_s)", "return graph def complete_helpers(self, policy): saved = self.policy, self.added_blocks self.policy = policy try:", "in zip(link.args, link.target.inputargs): if v_out == v_last_exc_type: s_out = typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type, Constant):", "annmodel.SomeBool() if s_out.is_constant(): newcell.const = s_out.const s_out = newcell s_out.set_knowntypedata(renamed_knowntypedata) return s_out def", "def whereami(self, position_key): graph, block, i = position_key blk = \"\" if block:", "debugging information --- self.frozen = False if policy is None: from rpython.annotator.policy import", "new_ops is not None: block.operations[i:i+1] = new_ops if not new_ops: continue new_ops[-1].result =", "operations in sync # with the flow object space. These are the operations", "ClassDefs.\"\"\" return self.bookkeeper.classdefs #___ medium-level interface ____________________________ def addpendinggraph(self, flowgraph, inputcells): self.addpendingblock(flowgraph, flowgraph.startblock,", "self.bookkeeper.leave() self.policy = prevpolicy def annotate_helper(self, function, args_s, policy=None): if policy is None:", "never do, they always raise exceptions) return s_ImpossibleValue def reflowfromposition(self, position_key): graph, block,", "v, s in constraints.items(): new_vs = renaming.get(v, []) for new_v in new_vs: renamed_knowntypedata[value][new_v]", "= self.whereami(pos) log.WARNING(\"%s/ %s\" % (pos, msg)) #___ interface for annotator.bookkeeper _______ def", "( self.translator.config.translation.check_str_without_nul) graph, inputcells = self.get_call_parameters(function, args_s, policy) self.build_graph_types(graph, inputcells, complete_now=False) self.complete_helpers(policy) return", "# never seen the block. # * self.annotated[block] == False: # the input", "= True self.addpendingblock(graph, link.target, inputs_s) def follow_raise_link(self, graph, link, s_last_exc_value): v_last_exc_type = link.last_exception", "None: resultcell = s_ImpossibleValue elif resultcell == s_ImpossibleValue: raise BlockedInference(self, op, -1) #", "'next'): # XXX warning, keep the name of the call operations in sync", "__________________ def build_types(self, function, input_arg_types, complete_now=True, main_entry_point=False): \"\"\"Recursively build annotations about the specific", "for new_v in new_vs: renamed_knowntypedata[value][new_v] = s assert isinstance(s_out, annmodel.SomeBool) newcell = annmodel.SomeBool()", "new_ops[0] self.consider_op(op) i += 1 except BlockedInference as e: if e.op is block.raising_op:", "signature from rpython.annotator.model import ( typeof, s_ImpossibleValue, SomeInstance, intersection, difference) from rpython.annotator.bookkeeper import", "then only follow the exceptional # branches. exits = [link for link in", "seen the block. # * self.annotated[block] == False: # the input variables of", "self.frozen assert graph not in self.fixed_graphs self.pendingblocks[block] = graph assert block in self.annotated", "newblocks = self.annotated # all of them for block in newblocks: for op", "in ('simple_call', 'call_args'): yield op # some blocks are partially annotated if op.result.annotation", "graph = self.annotated.get(block) if graph: graphs[graph] = True for graph in graphs: simplify.eliminate_empty_blocks(graph)", "* self.annotated[block] == graph-containing-block: # analysis done (at least until we find we", "args_s, policy=None): if policy is None: from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy()", "policy=None): if policy is None: from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() #", "= {} # map {block: graph-containing-it} self.annotated = {} # set of blocks", "so far. # (some functions actually never do, they always raise exceptions) return", "in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out, v_input in zip(link.args, link.target.inputargs): if v_out ==", "of ClassDefs.\"\"\" return self.bookkeeper.classdefs #___ medium-level interface ____________________________ def addpendinggraph(self, flowgraph, inputcells): self.addpendingblock(flowgraph,", "= {} for value, constraints in s_out.knowntypedata.items(): renamed_knowntypedata[value] = {} for v, s", "the BlockedInference and that's it. # About 'next': see test_annotate_iter_empty_container(). return else: #", "in self.annotated self.annotated[block] = False # must re-flow self.blocked_blocks[block] = (graph, None) def", "self.opindex = opindex def __repr__(self): if not self.break_at: break_at = \"?\" else: break_at", "ever been followed self.notify = {} # {block: {positions-to-reflow-from-when-done}} self.fixed_graphs = {} #", "parent_index self.translator.update_call_graph(parent_graph, graph, tag) # self.notify[graph.returnblock] is a dictionary of call # points", "def validate(self): \"\"\"Check that the annotation results are valid\"\"\" self.bookkeeper.check_no_flags_on_instances() def annotation(self, arg):", "annotated links_followed notify bookkeeper frozen policy added_blocks\"\"\".split() ret = self.__dict__.copy() for key, value", "links_followed notify bookkeeper frozen policy added_blocks\"\"\".split() ret = self.__dict__.copy() for key, value in", "the entry point self.addpendinggraph(flowgraph, inputcells) # recursively proceed until no more pending block", "else: self.policy = policy if bookkeeper is None: bookkeeper = Bookkeeper(self) self.bookkeeper =", "if isinstance(v_last_exc_type, Constant): s_out.const = v_last_exc_type.value elif v_last_exc_type.annotation.is_constant(): s_out.const = v_last_exc_type.annotation.const inputs_s.append(s_out) else:", "recursively proceed until no more pending block is left if complete_now: self.complete() return", "translator = TranslationContext() translator.annotator = self self.translator = translator self.pendingblocks = {} #", "reach any return statement so far. # (some functions actually never do, they", "= s assert isinstance(s_out, annmodel.SomeBool) newcell = annmodel.SomeBool() if s_out.is_constant(): newcell.const = s_out.const", "certain positions when this block is done for callback in self.notify[block]: if isinstance(callback,", "\"\"\"Check that the annotation results are valid\"\"\" self.bookkeeper.check_no_flags_on_instances() def annotation(self, arg): \"Gives the", "s_old)) assert False arg.annotation = s_value def warning(self, msg, pos=None): if pos is", "more pending block is left if complete_now: self.complete() return self.annotation(flowgraph.getreturnvar()) def gettype(self, variable):", "# the function didn't reach any return statement so far. # (some functions", "must redo the analysis if unions != oldcells: self.bindinputargs(graph, block, unions) def apply_renaming(self,", "= True for graph in graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if block_subset is None: perform_normalizations(self)", "AttributeError: pos = '?' if pos != '?': pos = self.whereami(pos) log.WARNING(\"%s/ %s\"", "cells): \"\"\"Register an entry point into block with the given input cells.\"\"\" if", "with each of the block's existing input # variables. oldcells = [self.binding(a) for", "import ( typeof, s_ImpossibleValue, SomeInstance, intersection, difference) from rpython.annotator.bookkeeper import Bookkeeper from rpython.rtyper.normalizecalls", "\"got %r\" % (variable,)) def getuserclassdefinitions(self): \"\"\"Return a list of ClassDefs.\"\"\" return self.bookkeeper.classdefs", "self.added_blocks is not None: self.added_blocks[block] = True def reflowpendingblock(self, graph, block): assert not", "have ever been followed self.notify = {} # {block: {positions-to-reflow-from-when-done}} self.fixed_graphs = {}", "if pos != '?': pos = self.whereami(pos) log.WARNING(\"%s/ %s\" % (pos, msg)) #___", "# The analysis of a block can be in three states: # *", "= [] renaming = defaultdict(list) for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for", "SomeInstance, intersection, difference) from rpython.annotator.bookkeeper import Bookkeeper from rpython.rtyper.normalizecalls import perform_normalizations log =", "(types.ClassType, type)) and issubclass(link.exitcase, BaseException)) ignore_link = False inputs_s = [] renaming =", "= graph def complete_pending_blocks(self): while self.pendingblocks: block, graph = self.pendingblocks.popitem() self.processblock(graph, block) def", "len(block.inputargs) == len(inputcells) for a, cell in zip(block.inputargs, inputcells): self.setbinding(a, cell) self.annotated[block] =", "variables of the block have bindings but we # still have to consider", "# register the entry point self.addpendinggraph(flowgraph, inputcells) # recursively proceed until no more", "True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if not self.pendingblocks: break # finished # make sure that", "of them got_blocked_blocks = False in self.annotated.values() if got_blocked_blocks: for graph in self.blocked_graphs.values():", "in self.fixed_graphs self.pendingblocks[block] = graph assert block in self.annotated self.annotated[block] = False #", "isinstance(variable, Constant): return type(variable.value) elif isinstance(variable, Variable): s_variable = variable.annotation if s_variable: return", "s_exitswitch.const] if block.canraise: op = block.raising_op s_exception = self.get_exception(op) for link in exits:", "link in exits if link.exitcase == s_exitswitch.const] if block.canraise: op = block.raising_op s_exception", "annotating/rtyping in several phases: calling # a graph that has already been rtyped.", "s_out = pair(s_out, s_constraint).improve() # ignore links that try to pass impossible values", "arg.annotation elif isinstance(arg, Constant): return self.bookkeeper.immutablevalue(arg.value) else: raise TypeError('Variable or Constant expected, got", "self.bookkeeper.position_key except AttributeError: pos = '?' if pos != '?': pos = self.whereami(pos)", "hasattr(s_out, 'knowntypedata'): renamed_knowntypedata = {} for value, constraints in s_out.knowntypedata.items(): renamed_knowntypedata[value] = {}", "not None: self.added_blocks[block] = True def reflowpendingblock(self, graph, block): assert not self.frozen assert", "rpython.tool.pairtype import pair from rpython.tool.error import (format_blocked_annotation_error, gather_error, source_lines) from rpython.flowspace.model import Variable,", "\"\"\" can_only_throw = operation.get_can_only_throw(self) if can_only_throw is None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return self.bookkeeper.new_exception(can_only_throw)", "# swallow the BlockedInference and that's it. # About 'next': see test_annotate_iter_empty_container(). return", "False inputs_s = [] renaming = defaultdict(list) for v_out, v_input in zip(link.args, link.target.inputargs):", "already been rtyped. Safety-check the new # annotations that are passed in, and", "v.annotation is None: self.setbinding(v, s_ImpossibleValue) def validate(self): \"\"\"Check that the annotation results are", "graph def complete_helpers(self, policy): saved = self.policy, self.added_blocks self.policy = policy try: self.added_blocks", "else: self.mergeinputargs(graph, block, cells) if not self.annotated[block]: self.pendingblocks[block] = graph def complete_pending_blocks(self): while", "interface for annotator.bookkeeper _______ def recursivecall(self, graph, whence, inputcells): if isinstance(whence, tuple): parent_graph,", "build annotations about the specific entry point.\"\"\" assert isinstance(function, types.FunctionType), \"fix that!\" from", "block in block_subset: graph = self.annotated.get(block) if graph: graphs[graph] = True for graph", "the new # annotations that are passed in, and don't annotate the old", "rpython.annlowlevel to # detect which are the new blocks that annotating an additional", "find we must generalize the # input variables). #print '* processblock', block, cells", "Variable): s_exitswitch = self.binding(block.exitswitch) if s_exitswitch.is_constant(): exits = [link for link in exits", "pos is None: try: pos = self.bookkeeper.position_key except AttributeError: pos = '?' if", "None: if not s_value.contains(s_old): log.WARNING(\"%s does not contain %s\" % (s_value, s_old)) log.WARNING(\"%s\"", "is None: break # ignore the unannotated part #___ simplification (should be moved", "rpython.annotator import model as annmodel, signature from rpython.annotator.model import ( typeof, s_ImpossibleValue, SomeInstance,", "flowgraph return self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now) def get_call_parameters(self, function, args_s, policy): desc = self.bookkeeper.getdesc(function)", "case where the last operation of the block will # always raise an", "'\\n'.join(source_lines(graph, block, None, long=True)) raise # if the merged cells changed, we must", "args_s, policy) self.build_graph_types(graph, inputcells, complete_now=False) self.complete_helpers(policy) return graph def complete_helpers(self, policy): saved =", "flowin. self.blocked_blocks[block] = (graph, None) def mergeinputargs(self, graph, block, inputcells): # Merge the", "% (pos, msg)) #___ interface for annotator.bookkeeper _______ def recursivecall(self, graph, whence, inputcells):", "zip(oldcells,inputcells)] except annmodel.UnionError as e: # Add source code to the UnionError e.source", "self.blocked_blocks) #raise SystemExit() raise annmodel.AnnotatorError(text) for graph in newgraphs: v = graph.getreturnvar() if", "We then # swallow the BlockedInference and that's it. # About 'next': see", "is None: from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # XXX hack annmodel.TLS.check_str_without_nul", "for link in exits if link.exitcase == s_exitswitch.const] if block.canraise: op = block.raising_op", "from rpython.annotator.bookkeeper import Bookkeeper from rpython.rtyper.normalizecalls import perform_normalizations log = AnsiLogger(\"annrpython\") class RPythonAnnotator(object):", "if e.op is block.raising_op: # this is the case where the last operation", "follow the exceptional # branches. exits = [link for link in block.exits if", "__init__(self, annotator, op, opindex): self.annotator = annotator try: self.break_at = annotator.bookkeeper.position_key except AttributeError:", "graph, link, s_last_exc_value): v_last_exc_type = link.last_exception v_last_exc_value = link.last_exc_value assert (isinstance(link.exitcase, (types.ClassType, type))", "typeannotation(self, t): return signature.annotation(t, self.bookkeeper) def setbinding(self, arg, s_value): s_old = arg.annotation if", "in block.inputargs] try: unions = [annmodel.unionof(c1,c2) for c1, c2 in zip(oldcells,inputcells)] except annmodel.UnionError", "UnionError e.source = '\\n'.join(source_lines(graph, block, None, long=True)) raise # if the merged cells", "# input variables). #print '* processblock', block, cells self.annotated[block] = graph if block", "point self.addpendinggraph(flowgraph, inputcells) # recursively proceed until no more pending block is left", "== s_exitswitch.const] if block.canraise: op = block.raising_op s_exception = self.get_exception(op) for link in", "is None: self.follow_link(graph, link, {}) continue if s_exception == s_ImpossibleValue: break s_case =", "elif isinstance(variable, Variable): s_variable = variable.annotation if s_variable: return s_variable.knowntype else: return object", "other cases are problematic (but will hopefully be solved # later by reflowing).", "self.whereami(pos) log.WARNING(\"%s/ %s\" % (pos, msg)) #___ interface for annotator.bookkeeper _______ def recursivecall(self,", "input variables of the block have bindings but we # still have to", "resultcell = op.consider(self) if resultcell is None: resultcell = s_ImpossibleValue elif resultcell ==", "test_annotate_iter_empty_container(). return else: # other cases are problematic (but will hopefully be solved", "removal: don't follow all exits if the exitswitch # is known exits =", "update %s.__getstate__\" % (key, self.__class__.__name__)) ret[key] = {} return ret #___ convenience high-level", "set of graphs that have blocked blocks # --- end of debugging information", "is block.raising_op: # this is the case where the last operation of the", "are valid\"\"\" self.bookkeeper.check_no_flags_on_instances() def annotation(self, arg): \"Gives the SomeValue corresponding to the given", "for link in exits: case = link.exitcase if case is None: self.follow_link(graph, link,", "for op in block.operations: if op.opname in ('simple_call', 'call_args'): yield op # some", "{} for block in block_subset: graph = self.annotated.get(block) if graph: graphs[graph] = True", "# invoke annotation simplifications for the new blocks self.simplify(block_subset=self.added_blocks) finally: self.policy, self.added_blocks =", "build_graph_types(self, flowgraph, inputcells, complete_now=True): checkgraph(flowgraph) nbarg = len(flowgraph.getargs()) assert len(inputcells) == nbarg #", "op=%d\" % i return repr(graph) + blk + opid def flowin(self, graph, block):", "of {blocked_block: (graph, index)} # --- the following information is recorded for debugging", "= [link for link in block.exits if link.exitcase is not None] elif e.op.opname", "blocks that annotating an additional # small helper creates. if self.added_blocks is not", "consider_op(self, op): # let's be careful about avoiding propagated SomeImpossibleValues # to enter", "set of graphs not to annotate again self.blocked_blocks = {} # set of", "self.setbinding(a, cell) self.annotated[block] = False # must flowin. self.blocked_blocks[block] = (graph, None) def", "graph, link, constraints): assert not (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) ignore_link =", "# interface for tests from rpython.translator.translator import TranslationContext translator = TranslationContext() translator.annotator =", "= s_value def warning(self, msg, pos=None): if pos is None: try: pos =", "== False: # the input variables of the block have bindings but we", "e.g. if SomeImpossibleValue enters is_ # is_(SomeImpossibleValue, None) -> SomeBool # is_(SomeInstance(not None),", "isinstance(s_out, annmodel.SomeBool) newcell = annmodel.SomeBool() if s_out.is_constant(): newcell.const = s_out.const s_out = newcell", "self.policy, self.added_blocks self.policy = policy try: self.added_blocks = {} self.complete() # invoke annotation", "isinstance(resultcell, annmodel.SomeObject) assert isinstance(op.result, Variable) self.setbinding(op.result, resultcell) # bind resultcell to op.result def", "e.opindex = i raise except annmodel.HarmlesslyBlocked: return except annmodel.AnnotatorError as e: # note", "s_matching_exc != s_ImpossibleValue: self.follow_raise_link(graph, link, s_matching_exc) s_exception = difference(s_exception, s_case) else: if isinstance(block.exitswitch,", "of links that have ever been followed self.notify = {} # {block: {positions-to-reflow-from-when-done}}", "variables). #print '* processblock', block, cells self.annotated[block] = graph if block in self.blocked_blocks:", "Constant.\" if isinstance(arg, Variable): return arg.annotation elif isinstance(arg, Constant): return self.bookkeeper.immutablevalue(arg.value) else: raise", "XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s = self.get_call_parameters(function, args_s, policy) if", "None: newblocks = self.annotated # all of them for block in newblocks: for", "-- it's already low-level operations! for a, s_newarg in zip(block.inputargs, cells): s_oldarg =", "... # boom -- in the assert of setbinding() for arg in op.args:", "of blocks already seen self.added_blocks = None # see processblock() below self.links_followed =", "of call # points to this func which triggers a reflow whenever the", "= newcell s_out.set_knowntypedata(renamed_knowntypedata) return s_out def whereami(self, position_key): graph, block, i = position_key", "is type newcell = typeof(renamed_is_type_of) if s_out.is_constant(): newcell.const = s_out.const s_out = newcell", "self.blocked_blocks: del self.blocked_blocks[block] try: self.flowin(graph, block) except BlockedInference as e: self.annotated[block] = False", "none is left.\"\"\" while True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if not self.pendingblocks: break # finished", "input_arg_types] # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s = self.get_call_parameters(function, args_s,", "(but will hopefully be solved # later by reflowing). Throw the BlockedInference up", "the input variables of the block have bindings but we # still have", "s_arg is None: raise KeyError return s_arg def typeannotation(self, t): return signature.annotation(t, self.bookkeeper)", "the given Variable or Constant.\" if isinstance(arg, Variable): return arg.annotation elif isinstance(arg, Constant):", "operation of the block will # always raise an exception which is immediately", "= difference(s_exception, s_case) else: if isinstance(block.exitswitch, Variable): knowntypedata = getattr( block.exitswitch.annotation, \"knowntypedata\", {})", "far. # (some functions actually never do, they always raise exceptions) return s_ImpossibleValue", "= {} # {block: {positions-to-reflow-from-when-done}} self.fixed_graphs = {} # set of graphs not", "Variable) self.setbinding(op.result, resultcell) # bind resultcell to op.result def get_exception(self, operation): \"\"\" Return", "s_ImpossibleValue elif resultcell == s_ImpossibleValue: raise BlockedInference(self, op, -1) # the operation cannot", "BaseException)) ignore_link = False inputs_s = [] renaming = defaultdict(list) for v_out, v_input", "newgraphs = dict.fromkeys(newgraphs) got_blocked_blocks = False in newgraphs else: newgraphs = self.translator.graphs #all", "%s.__getstate__\" % (key, self.__class__.__name__)) ret[key] = {} return ret #___ convenience high-level interface", "self.fixed_graphs: # special case for annotating/rtyping in several phases: calling # a graph", "reflowfromposition(self, position_key): graph, block, index = position_key self.reflowpendingblock(graph, block) def call_sites(self): newblocks =", "TranslationContext() translator.annotator = self self.translator = translator self.pendingblocks = {} # map {block:", "policy try: self.added_blocks = {} self.complete() # invoke annotation simplifications for the new", "op; the latter can result in violations of the # more general results", "graphs that have blocked blocks # --- end of debugging information --- self.frozen", "if s_old is not None: if not s_value.contains(s_old): log.WARNING(\"%s does not contain %s\"", "s_oldarg = self.binding(a) assert annmodel.unionof(s_oldarg, s_newarg) == s_oldarg else: assert not self.frozen if", "raise BlockedInference(self, op, -1) resultcell = op.consider(self) if resultcell is None: resultcell =", "block with the given input cells.\"\"\" if graph in self.fixed_graphs: # special case", "= self.apply_renaming(s_out, renaming) inputs_s.append(s_out) self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) #___ creating the", "least until we find we must generalize the # input variables). #print '*", "while True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if not self.pendingblocks: break # finished # make sure", "is False] assert len(blocked_blocks) == len(self.blocked_blocks) text = format_blocked_annotation_error(self, self.blocked_blocks) #raise SystemExit() raise", "__repr__(self): if not self.break_at: break_at = \"?\" else: break_at = self.annotator.whereami(self.break_at) return \"<BlockedInference", "link.last_exception v_last_exc_value = link.last_exc_value assert (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) assert v_last_exc_type", "try to pass impossible values if s_out == s_ImpossibleValue: ignore_link = True s_out", "is None: newblocks = self.annotated # all of them for block in newblocks:", "\"fix that!\" from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # make input arguments", "else: # other cases are problematic (but will hopefully be solved # later", "s_old is not None: if not s_value.contains(s_old): log.WARNING(\"%s does not contain %s\" %", "e.op.opname in ('simple_call', 'call_args', 'next'): # XXX warning, keep the name of the", "by reflowing). Throw the BlockedInference up to # processblock(). e.opindex = i raise", "raise TypeError('Variable or Constant expected, got %r' % (arg,)) def binding(self, arg): \"Gives", "done for callback in self.notify[block]: if isinstance(callback, tuple): self.reflowfromposition(callback) # callback is a", "self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) #___ creating the annotations based on operations", "simplification (should be moved elsewhere?) _______ def simplify(self, block_subset=None, extra_passes=None): # Generic simplifications", "= AnnotatorPolicy() # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) graph, inputcells = self.get_call_parameters(function,", "len(flowgraph.getargs()) assert len(inputcells) == nbarg # wrong number of args # register the", "self.pendingblocks.popitem() self.processblock(graph, block) def complete(self): \"\"\"Process pending blocks until none is left.\"\"\" while", "in three states: # * block not in self.annotated: # never seen the", "input # variables. oldcells = [self.binding(a) for a in block.inputargs] try: unions =", "no more pending block is left if complete_now: self.complete() return self.annotation(flowgraph.getreturnvar()) def gettype(self,", "link.target.inputargs): if v_out == v_last_exc_type: s_out = typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type, Constant): s_out.const =", "to op.result def get_exception(self, operation): \"\"\" Return the annotation for all exceptions that", "resultcell) # bind resultcell to op.result def get_exception(self, operation): \"\"\" Return the annotation", "a block. assert len(block.inputargs) == len(inputcells) for a, cell in zip(block.inputargs, inputcells): self.setbinding(a,", "of the block's existing input # variables. oldcells = [self.binding(a) for a in", "gather_error(self, graph, block, i) raise else: # dead code removal: don't follow all", "self.follow_link(graph, link, constraints) if block in self.notify: # reflow from certain positions when", "if bookkeeper is None: bookkeeper = Bookkeeper(self) self.bookkeeper = bookkeeper def __getstate__(self): attrs", "small helper creates. if self.added_blocks is not None: self.added_blocks[block] = True def reflowpendingblock(self,", "self.bookkeeper.getdesc(function) prevpolicy = self.policy self.policy = policy self.bookkeeper.enter(None) try: return desc.get_call_parameters(args_s) finally: self.bookkeeper.leave()", "self.bookkeeper.immutablevalue(arg.value) else: raise TypeError('Variable or Constant expected, got %r' % (arg,)) def binding(self,", "re-flow self.blocked_blocks[block] = (graph, None) def bindinputargs(self, graph, block, inputcells): # Create the", "v_last_exc_type: s_out = typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type, Constant): s_out.const = v_last_exc_type.value elif v_last_exc_type.annotation.is_constant(): s_out.const", "analysis of a block can be in three states: # * block not", "v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out in link.args: s_out = self.annotation(v_out) if", "inputcells) # get the (current) return value v = graph.getreturnvar() try: return self.binding(v)", "= format_blocked_annotation_error(self, self.blocked_blocks) #raise SystemExit() raise annmodel.AnnotatorError(text) for graph in newgraphs: v =", "self.addpendingblock(flowgraph, flowgraph.startblock, inputcells) def addpendingblock(self, graph, block, cells): \"\"\"Register an entry point into", "cannot succeed assert isinstance(resultcell, annmodel.SomeObject) assert isinstance(op.result, Variable) self.setbinding(op.result, resultcell) # bind resultcell", "for the input args of a block. assert len(block.inputargs) == len(inputcells) for a,", "renaming[v] assert s_out.knowntype is type newcell = typeof(renamed_is_type_of) if s_out.is_constant(): newcell.const = s_out.const", "always raise an exception. We then # swallow the BlockedInference and that's it.", "value in ret.items(): if key not in attrs: assert type(value) is dict, (", "return self.bookkeeper.immutablevalue(arg.value) else: raise TypeError('Variable or Constant expected, got %r' % (arg,)) def", "translator is None: # interface for tests from rpython.translator.translator import TranslationContext translator =", "log.WARNING(\"%s does not contain %s\" % (s_value, s_old)) log.WARNING(\"%s\" % annmodel.unionof(s_value, s_old)) assert", "long=True)) raise # if the merged cells changed, we must redo the analysis", "in doc/translation.txt.\"\"\" def __init__(self, translator=None, policy=None, bookkeeper=None): import rpython.rtyper.extfuncregistry # has side effects", "type)) and issubclass(link.exitcase, BaseException)) ignore_link = False inputs_s = [] renaming = defaultdict(list)", "simplifications transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes) if block_subset is None: graphs = self.translator.graphs else: graphs", "bookkeeper = Bookkeeper(self) self.bookkeeper = bookkeeper def __getstate__(self): attrs = \"\"\"translator pendingblocks annotated", "link.args: s_out = self.annotation(v_out) if v_out in constraints: s_constraint = constraints[v_out] s_out =", "finally: self.policy, self.added_blocks = saved def build_graph_types(self, flowgraph, inputcells, complete_now=True): checkgraph(flowgraph) nbarg =", "else: raise TypeError(\"Variable or Constant instance expected, \" \"got %r\" % (variable,)) def", "# (some functions actually never do, they always raise exceptions) return s_ImpossibleValue def", "Constant instance expected, \" \"got %r\" % (variable,)) def getuserclassdefinitions(self): \"\"\"Return a list", "assert isinstance(op.result, Variable) self.setbinding(op.result, resultcell) # bind resultcell to op.result def get_exception(self, operation):", "raise exceptions) return s_ImpossibleValue def reflowfromposition(self, position_key): graph, block, index = position_key self.reflowpendingblock(graph,", "self.bookkeeper.classdefs #___ medium-level interface ____________________________ def addpendinggraph(self, flowgraph, inputcells): self.addpendingblock(flowgraph, flowgraph.startblock, inputcells) def", "== graph-containing-block: # analysis done (at least until we find we must generalize", "type inference engine that the situation is currently blocked, and that it should", "if graph in self.fixed_graphs: # special case for annotating/rtyping in several phases: calling", "self.annotated[block]: self.pendingblocks[block] = graph def complete_pending_blocks(self): while self.pendingblocks: block, graph = self.pendingblocks.popitem() self.processblock(graph,", "= '\\n'.join(source_lines(graph, block, None, long=True)) raise # if the merged cells changed, we", "self.mergeinputargs(graph, block, cells) if not self.annotated[block]: self.pendingblocks[block] = graph def complete_pending_blocks(self): while self.pendingblocks:", "new blocks that annotating an additional # small helper creates. if self.added_blocks is", "links that have ever been followed self.notify = {} # {block: {positions-to-reflow-from-when-done}} self.fixed_graphs", "c2 in zip(oldcells,inputcells)] except annmodel.UnionError as e: # Add source code to the", "self.follow_link(graph, link, {}) continue if s_exception == s_ImpossibleValue: break s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc", "op.result def get_exception(self, operation): \"\"\" Return the annotation for all exceptions that `operation`", "= [self.typeannotation(t) for t in input_arg_types] # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul)", "block, inputcells): # Merge the new 'cells' with each of the block's existing", "or Constant.\" if isinstance(arg, Variable): return arg.annotation elif isinstance(arg, Constant): return self.bookkeeper.immutablevalue(arg.value) else:", "or Constant.\" s_arg = self.annotation(arg) if s_arg is None: raise KeyError return s_arg", "self.translator.update_call_graph(parent_graph, graph, tag) # self.notify[graph.returnblock] is a dictionary of call # points to", "is a position else: callback() def follow_link(self, graph, link, constraints): assert not (isinstance(link.exitcase,", "# Generic simplifications transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes) if block_subset is None: graphs = self.translator.graphs", "self.complete() # invoke annotation simplifications for the new blocks self.simplify(block_subset=self.added_blocks) finally: self.policy, self.added_blocks", "annotator.bookkeeper.position_key except AttributeError: self.break_at = None self.op = op self.opindex = opindex def", "the SomeValue corresponding to the given Variable or Constant.\" if isinstance(arg, Variable): return", "is None: graphs = self.translator.graphs else: graphs = {} for block in block_subset:", "op, -1) resultcell = op.consider(self) if resultcell is None: resultcell = s_ImpossibleValue elif", "flowgraph, inputs_s = self.get_call_parameters(function, args_s, policy) if main_entry_point: self.translator.entry_point_graph = flowgraph return self.build_graph_types(flowgraph,", "graph in newgraphs: v = graph.getreturnvar() if v.annotation is None: self.setbinding(v, s_ImpossibleValue) def", "not in self.annotated: # never seen the block. # * self.annotated[block] == False:", "'call_args'): yield op # some blocks are partially annotated if op.result.annotation is None:", "if isinstance(block.exitswitch, Variable): s_exitswitch = self.binding(block.exitswitch) if s_exitswitch.is_constant(): exits = [link for link", "if SomeImpossibleValue enters is_ # is_(SomeImpossibleValue, None) -> SomeBool # is_(SomeInstance(not None), None)", "whenever the # return block of this graph has been analysed. callpositions =", "# small helper creates. if self.added_blocks is not None: self.added_blocks[block] = True def", "for v in s_out.is_type_of: renamed_is_type_of += renaming[v] assert s_out.knowntype is type newcell =", "_____________________ def processblock(self, graph, block): # Important: this is not called recursively. #", "whence, inputcells): if isinstance(whence, tuple): parent_graph, parent_block, parent_index = whence tag = parent_block,", "we # still have to consider all the operations in the block. #", "hopefully be solved # later by reflowing). Throw the BlockedInference up to #", "+= 1 except BlockedInference as e: if e.op is block.raising_op: # this is", "[self.annotated[block] for block in self.added_blocks] newgraphs = dict.fromkeys(newgraphs) got_blocked_blocks = False in newgraphs", "graphs = {} for block in block_subset: graph = self.annotated.get(block) if graph: graphs[graph]", "s_old)) log.WARNING(\"%s\" % annmodel.unionof(s_value, s_old)) assert False arg.annotation = s_value def warning(self, msg,", "False if policy is None: from rpython.annotator.policy import AnnotatorPolicy self.policy = AnnotatorPolicy() else:", "from rpython.translator import simplify, transform from rpython.annotator import model as annmodel, signature from", "assert len(blocked_blocks) == len(self.blocked_blocks) text = format_blocked_annotation_error(self, self.blocked_blocks) #raise SystemExit() raise annmodel.AnnotatorError(text) for", "return value v = graph.getreturnvar() try: return self.binding(v) except KeyError: # the function", "return except annmodel.AnnotatorError as e: # note that UnionError is a subclass e.source", "analysed. callpositions = self.notify.setdefault(graph.returnblock, {}) if whence is not None: if callable(whence): def", "detect which are the new blocks that annotating an additional # small helper", "About 'next': see test_annotate_iter_empty_container(). return else: # other cases are problematic (but will", "try to progress elsewhere.\"\"\" def __init__(self, annotator, op, opindex): self.annotator = annotator try:", "rpython.rtyper.extfuncregistry # has side effects if translator is None: # interface for tests", "def annotation(self, arg): \"Gives the SomeValue corresponding to the given Variable or Constant.\"", "if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise BlockedInference(self, op, -1) resultcell = op.consider(self) if resultcell is", "signals the type inference engine that the situation is currently blocked, and that", "AnnotatorPolicy self.policy = AnnotatorPolicy() else: self.policy = policy if bookkeeper is None: bookkeeper", "1 except BlockedInference as e: if e.op is block.raising_op: # this is the", "s_value.contains(s_old): log.WARNING(\"%s does not contain %s\" % (s_value, s_old)) log.WARNING(\"%s\" % annmodel.unionof(s_value, s_old))", "s_matching_exc) s_exception = difference(s_exception, s_case) else: if isinstance(block.exitswitch, Variable): knowntypedata = getattr( block.exitswitch.annotation,", "= knowntypedata.get(link.exitcase, {}) self.follow_link(graph, link, constraints) if block in self.notify: # reflow from", "calls to self.addpendingblock(). # The analysis of a block can be in three", "known type of a control flow graph variable, defaulting to 'object'.\"\"\" if isinstance(variable,", "boom -- in the assert of setbinding() for arg in op.args: if isinstance(self.annotation(arg),", "result in violations of the # more general results invariant: e.g. if SomeImpossibleValue", "dict.fromkeys(newgraphs) got_blocked_blocks = False in newgraphs else: newgraphs = self.translator.graphs #all of them", "inputcells = self.get_call_parameters(function, args_s, policy) self.build_graph_types(graph, inputcells, complete_now=False) self.complete_helpers(policy) return graph def complete_helpers(self,", "setbinding() for arg in op.args: if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise BlockedInference(self, op, -1) resultcell", "if main_entry_point: self.translator.entry_point_graph = flowgraph return self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now) def get_call_parameters(self, function, args_s,", "new # annotations that are passed in, and don't annotate the old #", "if v_out in constraints: s_constraint = constraints[v_out] s_out = pair(s_out, s_constraint).improve() # ignore", "def __init__(self, translator=None, policy=None, bookkeeper=None): import rpython.rtyper.extfuncregistry # has side effects if translator", "given Variable or Constant.\" if isinstance(arg, Variable): return arg.annotation elif isinstance(arg, Constant): return", "block.exits if isinstance(block.exitswitch, Variable): s_exitswitch = self.binding(block.exitswitch) if s_exitswitch.is_constant(): exits = [link for", "blocks already seen self.added_blocks = None # see processblock() below self.links_followed = {}", "= {} for v, s in constraints.items(): new_vs = renaming.get(v, []) for new_v", "graph = self.pendingblocks.popitem() self.processblock(graph, block) def complete(self): \"\"\"Process pending blocks until none is", "e.op is block.raising_op: # this is the case where the last operation of", "ret #___ convenience high-level interface __________________ def build_types(self, function, input_arg_types, complete_now=True, main_entry_point=False): \"\"\"Recursively", "# special case for annotating/rtyping in several phases: calling # a graph that", "not to annotate again self.blocked_blocks = {} # set of {blocked_block: (graph, index)}", "the new blocks self.simplify(block_subset=self.added_blocks) finally: self.policy, self.added_blocks = saved def build_graph_types(self, flowgraph, inputcells,", "main_entry_point=False): \"\"\"Recursively build annotations about the specific entry point.\"\"\" assert isinstance(function, types.FunctionType), \"fix", "see test_annotate_iter_empty_container(). return else: # other cases are problematic (but will hopefully be", "annotation(self, arg): \"Gives the SomeValue corresponding to the given Variable or Constant.\" if", "continue if s_exception == s_ImpossibleValue: break s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc = intersection(s_exception, s_case)", "Constant): return type(variable.value) elif isinstance(variable, Variable): s_variable = variable.annotation if s_variable: return s_variable.knowntype", "RPythonAnnotator(object): \"\"\"Block annotator for RPython. See description in doc/translation.txt.\"\"\" def __init__(self, translator=None, policy=None,", "= '?' if pos != '?': pos = self.whereami(pos) log.WARNING(\"%s/ %s\" % (pos,", "last operation of the block will # always raise an exception which is", "rpython.annotator.model import ( typeof, s_ImpossibleValue, SomeInstance, intersection, difference) from rpython.annotator.bookkeeper import Bookkeeper from", "False] assert len(blocked_blocks) == len(self.blocked_blocks) text = format_blocked_annotation_error(self, self.blocked_blocks) #raise SystemExit() raise annmodel.AnnotatorError(text)", "annotated if self.added_blocks is not None: newgraphs = [self.annotated[block] for block in self.added_blocks]", "block) except BlockedInference as e: self.annotated[block] = False # failed, hopefully temporarily self.blocked_blocks[block]", "register the entry point self.addpendinggraph(flowgraph, inputcells) # recursively proceed until no more pending", "self.reflowfromposition(callback) # callback is a position else: callback() def follow_link(self, graph, link, constraints):", "block): try: i = 0 while i < len(block.operations): op = block.operations[i] with", "class BlockedInference(Exception): \"\"\"This exception signals the type inference engine that the situation is", "block_subset=block_subset, extra_passes=extra_passes) if block_subset is None: graphs = self.translator.graphs else: graphs = {}", "renamed_knowntypedata = {} for value, constraints in s_out.knowntypedata.items(): renamed_knowntypedata[value] = {} for v,", "exits if link.exitcase == s_exitswitch.const] if block.canraise: op = block.raising_op s_exception = self.get_exception(op)", "that the return variables of all graphs is annotated if self.added_blocks is not", "else: callback() def follow_link(self, graph, link, constraints): assert not (isinstance(link.exitcase, (types.ClassType, type)) and", "inputs_s) def follow_raise_link(self, graph, link, s_last_exc_value): v_last_exc_type = link.last_exception v_last_exc_value = link.last_exc_value assert", "= bookkeeper def __getstate__(self): attrs = \"\"\"translator pendingblocks annotated links_followed notify bookkeeper frozen", "self.break_at = None self.op = op self.opindex = opindex def __repr__(self): if not", "# * self.annotated[block] == graph-containing-block: # analysis done (at least until we find", "block, None, long=True)) raise # if the merged cells changed, we must redo", "for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out in link.args: s_out =", "if s_out.is_constant(): newcell.const = s_out.const s_out = newcell s_out.set_knowntypedata(renamed_knowntypedata) return s_out def whereami(self,", "rpython.annotator.policy import AnnotatorPolicy self.policy = AnnotatorPolicy() else: self.policy = policy if bookkeeper is", "\"Gives the SomeValue corresponding to the given Variable or Constant.\" s_arg = self.annotation(arg)", "flow graph variable, defaulting to 'object'.\"\"\" if isinstance(variable, Constant): return type(variable.value) elif isinstance(variable,", "them got_blocked_blocks = False in self.annotated.values() if got_blocked_blocks: for graph in self.blocked_graphs.values(): self.blocked_graphs[graph]", "func which triggers a reflow whenever the # return block of this graph", "graph in self.blocked_graphs.values(): self.blocked_graphs[graph] = True blocked_blocks = [block for block, done in", "= gather_error(self, graph, block, i) raise else: # dead code removal: don't follow", "None) -> SomeBool # is_(SomeInstance(not None), None) -> SomeBool(const=False) ... # boom --", "and issubclass(link.exitcase, BaseException)) assert v_last_exc_type and v_last_exc_value if isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value, s_last_exc_value) if", "self.added_blocks self.policy = policy try: self.added_blocks = {} self.complete() # invoke annotation simplifications", "nbarg = len(flowgraph.getargs()) assert len(inputcells) == nbarg # wrong number of args #", "is None: try: pos = self.bookkeeper.position_key except AttributeError: pos = '?' if pos", "v_input in zip(link.args, link.target.inputargs): if v_out == v_last_exc_type: s_out = typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type,", "ignore_link = False inputs_s = [] renaming = defaultdict(list) for v_out, v_input in", "cell) self.annotated[block] = False # must flowin. self.blocked_blocks[block] = (graph, None) def mergeinputargs(self,", "a list of ClassDefs.\"\"\" return self.bookkeeper.classdefs #___ medium-level interface ____________________________ def addpendinggraph(self, flowgraph,", "self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if not self.pendingblocks: break # finished # make sure that the", "{blocked_block: (graph, index)} # --- the following information is recorded for debugging ---", "return ret #___ convenience high-level interface __________________ def build_types(self, function, input_arg_types, complete_now=True, main_entry_point=False):", "else: raise TypeError('Variable or Constant expected, got %r' % (arg,)) def binding(self, arg):", "link, constraints) if block in self.notify: # reflow from certain positions when this", "cells.\"\"\" if graph in self.fixed_graphs: # special case for annotating/rtyping in several phases:", "\"\"\"translator pendingblocks annotated links_followed notify bookkeeper frozen policy added_blocks\"\"\".split() ret = self.__dict__.copy() for", "newblocks is None: newblocks = self.annotated # all of them for block in", "self.bookkeeper.check_no_flags_on_instances() def annotation(self, arg): \"Gives the SomeValue corresponding to the given Variable or", "# self.notify[graph.returnblock] is a dictionary of call # points to this func which", "may raise. \"\"\" can_only_throw = operation.get_can_only_throw(self) if can_only_throw is None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else:", "while i < len(block.operations): op = block.operations[i] with self.bookkeeper.at_position((graph, block, i)): new_ops =", "debug tools only if not hasattr(e, '__annotator_block'): setattr(e, '__annotator_block', block) raise # The", "{} for v, s in constraints.items(): new_vs = renaming.get(v, []) for new_v in", "general results invariant: e.g. if SomeImpossibleValue enters is_ # is_(SomeImpossibleValue, None) -> SomeBool", "arguments and set their type args_s = [self.typeannotation(t) for t in input_arg_types] #", "not in self.fixed_graphs self.pendingblocks[block] = graph assert block in self.annotated self.annotated[block] = False", "isinstance(op.result, Variable) self.setbinding(op.result, resultcell) # bind resultcell to op.result def get_exception(self, operation): \"\"\"", "# Create the initial bindings for the input args of a block. assert", "desc.get_call_parameters(args_s) finally: self.bookkeeper.leave() self.policy = prevpolicy def annotate_helper(self, function, args_s, policy=None): if policy", "self.blocked_blocks[block] = (graph, None) def bindinputargs(self, graph, block, inputcells): # Create the initial", "not in self.annotated: self.bindinputargs(graph, block, cells) else: self.mergeinputargs(graph, block, cells) if not self.annotated[block]:", "return variables of all graphs is annotated if self.added_blocks is not None: newgraphs", "BlockedInference up to # processblock(). e.opindex = i raise except annmodel.HarmlesslyBlocked: return except", "block in self.annotated self.annotated[block] = False # must re-flow self.blocked_blocks[block] = (graph, None)", "succeed assert isinstance(resultcell, annmodel.SomeObject) assert isinstance(op.result, Variable) self.setbinding(op.result, resultcell) # bind resultcell to", "added_blocks\"\"\".split() ret = self.__dict__.copy() for key, value in ret.items(): if key not in", "# branches. exits = [link for link in block.exits if link.exitcase is not", "isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value, s_last_exc_value) if isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s = [] renaming", "operations ______ def consider_op(self, op): # let's be careful about avoiding propagated SomeImpossibleValues", "s_value def warning(self, msg, pos=None): if pos is None: try: pos = self.bookkeeper.position_key", "0 while i < len(block.operations): op = block.operations[i] with self.bookkeeper.at_position((graph, block, i)): new_ops", "= block.exits if isinstance(block.exitswitch, Variable): s_exitswitch = self.binding(block.exitswitch) if s_exitswitch.is_constant(): exits = [link", "input cells.\"\"\" if graph in self.fixed_graphs: # special case for annotating/rtyping in several", "is None: self.setbinding(v, s_ImpossibleValue) def validate(self): \"\"\"Check that the annotation results are valid\"\"\"", "# if the merged cells changed, we must redo the analysis if unions", "processblock() below self.links_followed = {} # set of links that have ever been", "= whence callpositions[callback] = True # generalize the function's input arguments self.addpendingblock(graph, graph.startblock,", "still have to consider all the operations in the block. # * self.annotated[block]", "= self.annotation(v_out) if v_out in constraints: s_constraint = constraints[v_out] s_out = pair(s_out, s_constraint).improve()", "branches. exits = [link for link in block.exits if link.exitcase is not None]", "interface __________________ def build_types(self, function, input_arg_types, complete_now=True, main_entry_point=False): \"\"\"Recursively build annotations about the", "break # ignore the unannotated part #___ simplification (should be moved elsewhere?) _______", "constraints[v_out] s_out = pair(s_out, s_constraint).improve() # ignore links that try to pass impossible", "return s_arg def typeannotation(self, t): return signature.annotation(t, self.bookkeeper) def setbinding(self, arg, s_value): s_old", "# still have to consider all the operations in the block. # *", "mergeinputargs(self, graph, block, inputcells): # Merge the new 'cells' with each of the", "propagated SomeImpossibleValues # to enter an op; the latter can result in violations", "assert (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) assert v_last_exc_type and v_last_exc_value if isinstance(v_last_exc_value,", "-> SomeBool # is_(SomeInstance(not None), None) -> SomeBool(const=False) ... # boom -- in", "is not None: if callable(whence): def callback(): whence(self, graph) else: callback = whence", "op, -1) # the operation cannot succeed assert isinstance(resultcell, annmodel.SomeObject) assert isinstance(op.result, Variable)", "= i raise except annmodel.HarmlesslyBlocked: return except annmodel.AnnotatorError as e: # note that", "issubclass(link.exitcase, BaseException)) ignore_link = False inputs_s = [] renaming = defaultdict(list) for v_out,", "map {block: graph-containing-it} self.annotated = {} # set of blocks already seen self.added_blocks", "v_out in link.args: s_out = self.annotation(v_out) if v_out in constraints: s_constraint = constraints[v_out]", "graph in self.fixed_graphs: # special case for annotating/rtyping in several phases: calling #", "the last operation of the block will # always raise an exception which", "SomeBool # is_(SomeInstance(not None), None) -> SomeBool(const=False) ... # boom -- in the", "= {} # set of graphs that have blocked blocks # --- end", "build_types(self, function, input_arg_types, complete_now=True, main_entry_point=False): \"\"\"Recursively build annotations about the specific entry point.\"\"\"", "s_case) else: if isinstance(block.exitswitch, Variable): knowntypedata = getattr( block.exitswitch.annotation, \"knowntypedata\", {}) else: knowntypedata", "(isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) ignore_link = False inputs_s = [] renaming", "v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out, v_input in zip(link.args, link.target.inputargs): if", "'call_args', 'next'): # XXX warning, keep the name of the call operations in", "resultcell == s_ImpossibleValue: raise BlockedInference(self, op, -1) # the operation cannot succeed assert", "True # generalize the function's input arguments self.addpendingblock(graph, graph.startblock, inputcells) # get the", "return arg.annotation elif isinstance(arg, Constant): return self.bookkeeper.immutablevalue(arg.value) else: raise TypeError('Variable or Constant expected,", "only issue calls to self.addpendingblock(). # The analysis of a block can be", "sync # with the flow object space. These are the operations for #", "calling # a graph that has already been rtyped. Safety-check the new #", "flowing annotations in blocks _____________________ def processblock(self, graph, block): # Important: this is", "rpython.translator import simplify, transform from rpython.annotator import model as annmodel, signature from rpython.annotator.model", "inputcells): if isinstance(whence, tuple): parent_graph, parent_block, parent_index = whence tag = parent_block, parent_index", "in ret.items(): if key not in attrs: assert type(value) is dict, ( \"%r", "in new_vs: renamed_knowntypedata[value][new_v] = s assert isinstance(s_out, annmodel.SomeBool) newcell = annmodel.SomeBool() if s_out.is_constant():", "into block with the given input cells.\"\"\" if graph in self.fixed_graphs: # special", "for debug tools only if not hasattr(e, '__annotator_block'): setattr(e, '__annotator_block', block) raise #", "graph.getreturnvar() if v.annotation is None: self.setbinding(v, s_ImpossibleValue) def validate(self): \"\"\"Check that the annotation", "must generalize the # input variables). #print '* processblock', block, cells self.annotated[block] =", "it's already low-level operations! for a, s_newarg in zip(block.inputargs, cells): s_oldarg = self.binding(a)", "s_out, renaming): if hasattr(s_out, 'is_type_of'): renamed_is_type_of = [] for v in s_out.is_type_of: renamed_is_type_of", "v in s_out.is_type_of: renamed_is_type_of += renaming[v] assert s_out.knowntype is type newcell = typeof(renamed_is_type_of)", "log.WARNING(\"%s/ %s\" % (pos, msg)) #___ interface for annotator.bookkeeper _______ def recursivecall(self, graph,", "def build_types(self, function, input_arg_types, complete_now=True, main_entry_point=False): \"\"\"Recursively build annotations about the specific entry", "BlockedInference(Exception): \"\"\"This exception signals the type inference engine that the situation is currently", "the block's existing input # variables. oldcells = [self.binding(a) for a in block.inputargs]", "analysis if unions != oldcells: self.bindinputargs(graph, block, unions) def apply_renaming(self, s_out, renaming): if", "to the given Variable or Constant.\" s_arg = self.annotation(arg) if s_arg is None:", "variable): \"\"\"Return the known type of a control flow graph variable, defaulting to", "an op; the latter can result in violations of the # more general", "return object else: raise TypeError(\"Variable or Constant instance expected, \" \"got %r\" %", "special case for annotating/rtyping in several phases: calling # a graph that has", "# points to this func which triggers a reflow whenever the # return", "self.annotated[block] = graph if block in self.blocked_blocks: del self.blocked_blocks[block] try: self.flowin(graph, block) except", "passed in, and don't annotate the old # graph -- it's already low-level", "self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now) def get_call_parameters(self, function, args_s, policy): desc = self.bookkeeper.getdesc(function) prevpolicy =", "corresponding to the given Variable or Constant.\" if isinstance(arg, Variable): return arg.annotation elif", "return statement so far. # (some functions actually never do, they always raise", "inputcells): self.setbinding(a, cell) self.annotated[block] = False # must flowin. self.blocked_blocks[block] = (graph, None)", "left.\"\"\" while True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if not self.pendingblocks: break # finished # make", "# detect which are the new blocks that annotating an additional # small", "entry point self.addpendinggraph(flowgraph, inputcells) # recursively proceed until no more pending block is", "value, constraints in s_out.knowntypedata.items(): renamed_knowntypedata[value] = {} for v, s in constraints.items(): new_vs", "from __future__ import absolute_import import types from collections import defaultdict from rpython.tool.ansi_print import", "is None: bookkeeper = Bookkeeper(self) self.bookkeeper = bookkeeper def __getstate__(self): attrs = \"\"\"translator", "a, cell in zip(block.inputargs, inputcells): self.setbinding(a, cell) self.annotated[block] = False # must flowin.", "return s_ImpossibleValue def reflowfromposition(self, position_key): graph, block, index = position_key self.reflowpendingblock(graph, block) def", "bookkeeper def __getstate__(self): attrs = \"\"\"translator pendingblocks annotated links_followed notify bookkeeper frozen policy", "a dictionary of call # points to this func which triggers a reflow", "BlockedInference(self, op, -1) resultcell = op.consider(self) if resultcell is None: resultcell = s_ImpossibleValue", "corresponding to the given Variable or Constant.\" s_arg = self.annotation(arg) if s_arg is", "a reflow whenever the # return block of this graph has been analysed.", "if new_ops is not None: block.operations[i:i+1] = new_ops if not new_ops: continue new_ops[-1].result", "self.pendingblocks: block, graph = self.pendingblocks.popitem() self.processblock(graph, block) def complete(self): \"\"\"Process pending blocks until", "the return variables of all graphs is annotated if self.added_blocks is not None:", "of a block can be in three states: # * block not in", "len(block.operations): op = block.operations[i] with self.bookkeeper.at_position((graph, block, i)): new_ops = op.transform(self) if new_ops", "inputs_s = self.get_call_parameters(function, args_s, policy) if main_entry_point: self.translator.entry_point_graph = flowgraph return self.build_graph_types(flowgraph, inputs_s,", "self.follow_raise_link(graph, link, s_matching_exc) s_exception = difference(s_exception, s_case) else: if isinstance(block.exitswitch, Variable): knowntypedata =", "block, index = position_key self.reflowpendingblock(graph, block) def call_sites(self): newblocks = self.added_blocks if newblocks", "inputcells): # Merge the new 'cells' with each of the block's existing input", "whence callpositions[callback] = True # generalize the function's input arguments self.addpendingblock(graph, graph.startblock, inputcells)", "been analysed. callpositions = self.notify.setdefault(graph.returnblock, {}) if whence is not None: if callable(whence):", "to consider all the operations in the block. # * self.annotated[block] == graph-containing-block:", "the # more general results invariant: e.g. if SomeImpossibleValue enters is_ # is_(SomeImpossibleValue,", "Bookkeeper from rpython.rtyper.normalizecalls import perform_normalizations log = AnsiLogger(\"annrpython\") class RPythonAnnotator(object): \"\"\"Block annotator for", "raise KeyError return s_arg def typeannotation(self, t): return signature.annotation(t, self.bookkeeper) def setbinding(self, arg,", "if not hasattr(e, '__annotator_block'): setattr(e, '__annotator_block', block) raise # The dict 'added_blocks' is", "if isinstance(callback, tuple): self.reflowfromposition(callback) # callback is a position else: callback() def follow_link(self,", "caught by # an exception handler. We then only follow the exceptional #", "assert graph not in self.fixed_graphs self.pendingblocks[block] = graph assert block in self.annotated self.annotated[block]", "graph assert block in self.annotated self.annotated[block] = False # must re-flow self.blocked_blocks[block] =", "# return block of this graph has been analysed. callpositions = self.notify.setdefault(graph.returnblock, {})", "True blocked_blocks = [block for block, done in self.annotated.items() if done is False]", "args_s = [self.typeannotation(t) for t in input_arg_types] # XXX hack annmodel.TLS.check_str_without_nul = (", "return self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) def follow_raise_link(self, graph, link, s_last_exc_value): v_last_exc_type", "parent_block, parent_index = whence tag = parent_block, parent_index self.translator.update_call_graph(parent_graph, graph, tag) # self.notify[graph.returnblock]", "violations of the # more general results invariant: e.g. if SomeImpossibleValue enters is_", "(at least until we find we must generalize the # input variables). #print", "self.notify[block]: if isinstance(callback, tuple): self.reflowfromposition(callback) # callback is a position else: callback() def", "# --- the following information is recorded for debugging --- self.blocked_graphs = {}", "been rtyped. Safety-check the new # annotations that are passed in, and don't", "raise annmodel.AnnotatorError(text) for graph in newgraphs: v = graph.getreturnvar() if v.annotation is None:", "we find we must generalize the # input variables). #print '* processblock', block,", "the following information is recorded for debugging --- self.blocked_graphs = {} # set", "return else: # other cases are problematic (but will hopefully be solved #", "known exits = block.exits if isinstance(block.exitswitch, Variable): s_exitswitch = self.binding(block.exitswitch) if s_exitswitch.is_constant(): exits", "#___ creating the annotations based on operations ______ def consider_op(self, op): # let's", "-1) # the operation cannot succeed assert isinstance(resultcell, annmodel.SomeObject) assert isinstance(op.result, Variable) self.setbinding(op.result,", "that has already been rtyped. Safety-check the new # annotations that are passed", "where the last operation of the block will # always raise an exception", "solved # later by reflowing). Throw the BlockedInference up to # processblock(). e.opindex", "assert s_out.knowntype is type newcell = typeof(renamed_is_type_of) if s_out.is_constant(): newcell.const = s_out.const s_out", "for link in exits: constraints = knowntypedata.get(link.exitcase, {}) self.follow_link(graph, link, constraints) if block", "can_only_throw = operation.get_can_only_throw(self) if can_only_throw is None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return self.bookkeeper.new_exception(can_only_throw) class", "expected, \" \"got %r\" % (variable,)) def getuserclassdefinitions(self): \"\"\"Return a list of ClassDefs.\"\"\"", "variables. oldcells = [self.binding(a) for a in block.inputargs] try: unions = [annmodel.unionof(c1,c2) for", "= {} for link in exits: constraints = knowntypedata.get(link.exitcase, {}) self.follow_link(graph, link, constraints)", "oldcells = [self.binding(a) for a in block.inputargs] try: unions = [annmodel.unionof(c1,c2) for c1,", "('simple_call', 'call_args'): yield op # some blocks are partially annotated if op.result.annotation is", "for block in block_subset: graph = self.annotated.get(block) if graph: graphs[graph] = True for", "self.annotated: self.bindinputargs(graph, block, cells) else: self.mergeinputargs(graph, block, cells) if not self.annotated[block]: self.pendingblocks[block] =", "exception signals the type inference engine that the situation is currently blocked, and", "link in exits: case = link.exitcase if case is None: self.follow_link(graph, link, {})", "{} for link in exits: constraints = knowntypedata.get(link.exitcase, {}) self.follow_link(graph, link, constraints) if", "Constant): return self.bookkeeper.immutablevalue(arg.value) else: raise TypeError('Variable or Constant expected, got %r' % (arg,))", "block, i) raise else: # dead code removal: don't follow all exits if", "fine to always raise an exception. We then # swallow the BlockedInference and", "# is_(SomeImpossibleValue, None) -> SomeBool # is_(SomeInstance(not None), None) -> SomeBool(const=False) ... #", "the operations for # which it is fine to always raise an exception.", "= policy try: self.added_blocks = {} self.complete() # invoke annotation simplifications for the", "else: return self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception): \"\"\"This exception signals the type inference engine that", "flow object space. These are the operations for # which it is fine", "self.annotated.values() if got_blocked_blocks: for graph in self.blocked_graphs.values(): self.blocked_graphs[graph] = True blocked_blocks = [block", "the assert of setbinding() for arg in op.args: if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise BlockedInference(self,", "annotation for all exceptions that `operation` may raise. \"\"\" can_only_throw = operation.get_can_only_throw(self) if", "blocked, and that it should try to progress elsewhere.\"\"\" def __init__(self, annotator, op,", "else: knowntypedata = {} for link in exits: constraints = knowntypedata.get(link.exitcase, {}) self.follow_link(graph,", "= block.at() if at: blk = \" block\"+at opid=\"\" if i is not", "immediately caught by # an exception handler. We then only follow the exceptional", "< len(block.operations): op = block.operations[i] with self.bookkeeper.at_position((graph, block, i)): new_ops = op.transform(self) if", "block) raise # The dict 'added_blocks' is used by rpython.annlowlevel to # detect", "which triggers a reflow whenever the # return block of this graph has", "newcell.const = s_out.const s_out = newcell if hasattr(s_out, 'knowntypedata'): renamed_knowntypedata = {} for", "progress elsewhere.\"\"\" def __init__(self, annotator, op, opindex): self.annotator = annotator try: self.break_at =", "newcell if hasattr(s_out, 'knowntypedata'): renamed_knowntypedata = {} for value, constraints in s_out.knowntypedata.items(): renamed_knowntypedata[value]", "block_subset=None, extra_passes=None): # Generic simplifications transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes) if block_subset is None: graphs", "( typeof, s_ImpossibleValue, SomeInstance, intersection, difference) from rpython.annotator.bookkeeper import Bookkeeper from rpython.rtyper.normalizecalls import", "s_out.knowntypedata.items(): renamed_knowntypedata[value] = {} for v, s in constraints.items(): new_vs = renaming.get(v, [])", "s_out = self.annotation(v_out) if v_out in constraints: s_constraint = constraints[v_out] s_out = pair(s_out,", "self.break_at = annotator.bookkeeper.position_key except AttributeError: self.break_at = None self.op = op self.opindex =", "(graph, index)} # --- the following information is recorded for debugging --- self.blocked_graphs", "the input args of a block. assert len(block.inputargs) == len(inputcells) for a, cell", "is left.\"\"\" while True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if not self.pendingblocks: break # finished #", "\"\"\"Return the known type of a control flow graph variable, defaulting to 'object'.\"\"\"", "renamed_knowntypedata[value] = {} for v, s in constraints.items(): new_vs = renaming.get(v, []) for", "for a, s_newarg in zip(block.inputargs, cells): s_oldarg = self.binding(a) assert annmodel.unionof(s_oldarg, s_newarg) ==", "newgraphs = self.translator.graphs #all of them got_blocked_blocks = False in self.annotated.values() if got_blocked_blocks:", "# XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s = self.get_call_parameters(function, args_s, policy)", "self.bookkeeper) def setbinding(self, arg, s_value): s_old = arg.annotation if s_old is not None:", "def follow_raise_link(self, graph, link, s_last_exc_value): v_last_exc_type = link.last_exception v_last_exc_value = link.last_exc_value assert (isinstance(link.exitcase,", "hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) graph, inputcells = self.get_call_parameters(function, args_s, policy) self.build_graph_types(graph, inputcells,", "= newcell if hasattr(s_out, 'knowntypedata'): renamed_knowntypedata = {} for value, constraints in s_out.knowntypedata.items():", "high-level interface __________________ def build_types(self, function, input_arg_types, complete_now=True, main_entry_point=False): \"\"\"Recursively build annotations about", "block, i)): new_ops = op.transform(self) if new_ops is not None: block.operations[i:i+1] = new_ops", "from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # XXX hack annmodel.TLS.check_str_without_nul = (", "s_variable.knowntype else: return object else: raise TypeError(\"Variable or Constant instance expected, \" \"got", "a, s_newarg in zip(block.inputargs, cells): s_oldarg = self.binding(a) assert annmodel.unionof(s_oldarg, s_newarg) == s_oldarg", "callable(whence): def callback(): whence(self, graph) else: callback = whence callpositions[callback] = True #", "self.frozen = False if policy is None: from rpython.annotator.policy import AnnotatorPolicy self.policy =", "= self.annotated # all of them for block in newblocks: for op in", "s_out.is_type_of: renamed_is_type_of += renaming[v] assert s_out.knowntype is type newcell = typeof(renamed_is_type_of) if s_out.is_constant():", "s_ImpossibleValue: raise BlockedInference(self, op, -1) # the operation cannot succeed assert isinstance(resultcell, annmodel.SomeObject)", "if isinstance(block.exitswitch, Variable): knowntypedata = getattr( block.exitswitch.annotation, \"knowntypedata\", {}) else: knowntypedata = {}", "if complete_now: self.complete() return self.annotation(flowgraph.getreturnvar()) def gettype(self, variable): \"\"\"Return the known type of", "else: # dead code removal: don't follow all exits if the exitswitch #", "self.bindinputargs(graph, block, unions) def apply_renaming(self, s_out, renaming): if hasattr(s_out, 'is_type_of'): renamed_is_type_of = []", "of debugging information --- self.frozen = False if policy is None: from rpython.annotator.policy", "self.added_blocks if newblocks is None: newblocks = self.annotated # all of them for", "enter an op; the latter can result in violations of the # more", "= constraints[v_out] s_out = pair(s_out, s_constraint).improve() # ignore links that try to pass", "subclass e.source = gather_error(self, graph, block, i) raise else: # dead code removal:", "new_ops[-1].result = op.result op = new_ops[0] self.consider_op(op) i += 1 except BlockedInference as", "valid\"\"\" self.bookkeeper.check_no_flags_on_instances() def annotation(self, arg): \"Gives the SomeValue corresponding to the given Variable", "KeyError return s_arg def typeannotation(self, t): return signature.annotation(t, self.bookkeeper) def setbinding(self, arg, s_value):", "to always raise an exception. We then # swallow the BlockedInference and that's", "pos = '?' if pos != '?': pos = self.whereami(pos) log.WARNING(\"%s/ %s\" %", "annotation results are valid\"\"\" self.bookkeeper.check_no_flags_on_instances() def annotation(self, arg): \"Gives the SomeValue corresponding to", "newgraphs: v = graph.getreturnvar() if v.annotation is None: self.setbinding(v, s_ImpossibleValue) def validate(self): \"\"\"Check", "def call_sites(self): newblocks = self.added_blocks if newblocks is None: newblocks = self.annotated #", "the analysis if unions != oldcells: self.bindinputargs(graph, block, unions) def apply_renaming(self, s_out, renaming):", "= typeof(renamed_is_type_of) if s_out.is_constant(): newcell.const = s_out.const s_out = newcell if hasattr(s_out, 'knowntypedata'):", "up to # processblock(). e.opindex = i raise except annmodel.HarmlesslyBlocked: return except annmodel.AnnotatorError", "v_out == v_last_exc_type: s_out = typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type, Constant): s_out.const = v_last_exc_type.value elif", "is known exits = block.exits if isinstance(block.exitswitch, Variable): s_exitswitch = self.binding(block.exitswitch) if s_exitswitch.is_constant():", "% annmodel.unionof(s_value, s_old)) assert False arg.annotation = s_value def warning(self, msg, pos=None): if", "#___ simplification (should be moved elsewhere?) _______ def simplify(self, block_subset=None, extra_passes=None): # Generic", "isinstance(variable, Variable): s_variable = variable.annotation if s_variable: return s_variable.knowntype else: return object else:", "if s_variable: return s_variable.knowntype else: return object else: raise TypeError(\"Variable or Constant instance", "s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc = intersection(s_exception, s_case) if s_matching_exc != s_ImpossibleValue: self.follow_raise_link(graph, link,", "self.processblock(graph, block) def complete(self): \"\"\"Process pending blocks until none is left.\"\"\" while True:", "it should try to progress elsewhere.\"\"\" def __init__(self, annotator, op, opindex): self.annotator =", "class RPythonAnnotator(object): \"\"\"Block annotator for RPython. See description in doc/translation.txt.\"\"\" def __init__(self, translator=None,", "text = format_blocked_annotation_error(self, self.blocked_blocks) #raise SystemExit() raise annmodel.AnnotatorError(text) for graph in newgraphs: v", "finished # make sure that the return variables of all graphs is annotated", "# wrong number of args # register the entry point self.addpendinggraph(flowgraph, inputcells) #", "else: return object else: raise TypeError(\"Variable or Constant instance expected, \" \"got %r\"", "annmodel, signature from rpython.annotator.model import ( typeof, s_ImpossibleValue, SomeInstance, intersection, difference) from rpython.annotator.bookkeeper", "operation cannot succeed assert isinstance(resultcell, annmodel.SomeObject) assert isinstance(op.result, Variable) self.setbinding(op.result, resultcell) # bind", "= (graph, None) def mergeinputargs(self, graph, block, inputcells): # Merge the new 'cells'", "return desc.get_call_parameters(args_s) finally: self.bookkeeper.leave() self.policy = prevpolicy def annotate_helper(self, function, args_s, policy=None): if", "failed, hopefully temporarily self.blocked_blocks[block] = (graph, e.opindex) except Exception as e: # hack", "the annotations based on operations ______ def consider_op(self, op): # let's be careful", "self.added_blocks[block] = True def reflowpendingblock(self, graph, block): assert not self.frozen assert graph not", "block. # * self.annotated[block] == graph-containing-block: # analysis done (at least until we", "debugging --- self.blocked_graphs = {} # set of graphs that have blocked blocks", "renamed_is_type_of += renaming[v] assert s_out.knowntype is type newcell = typeof(renamed_is_type_of) if s_out.is_constant(): newcell.const", "analysis done (at least until we find we must generalize the # input", "not None: newgraphs = [self.annotated[block] for block in self.added_blocks] newgraphs = dict.fromkeys(newgraphs) got_blocked_blocks", "def simplify(self, block_subset=None, extra_passes=None): # Generic simplifications transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes) if block_subset is", "if s_matching_exc != s_ImpossibleValue: self.follow_raise_link(graph, link, s_matching_exc) s_exception = difference(s_exception, s_case) else: if", "_______ def simplify(self, block_subset=None, extra_passes=None): # Generic simplifications transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes) if block_subset", "in blocks _____________________ def processblock(self, graph, block): # Important: this is not called", "= AnnotatorPolicy() # make input arguments and set their type args_s = [self.typeannotation(t)", "and don't annotate the old # graph -- it's already low-level operations! for", "graph in graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if block_subset is None: perform_normalizations(self) #___ flowing annotations", "if link.exitcase is not None] elif e.op.opname in ('simple_call', 'call_args', 'next'): # XXX", "done (at least until we find we must generalize the # input variables).", "if translator is None: # interface for tests from rpython.translator.translator import TranslationContext translator", "results invariant: e.g. if SomeImpossibleValue enters is_ # is_(SomeImpossibleValue, None) -> SomeBool #", "from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # make input arguments and set", "perform_normalizations(self) #___ flowing annotations in blocks _____________________ def processblock(self, graph, block): # Important:", "Generic simplifications transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes) if block_subset is None: graphs = self.translator.graphs else:", "for v, s in constraints.items(): new_vs = renaming.get(v, []) for new_v in new_vs:", "# this is the case where the last operation of the block will", "from rpython.tool.error import (format_blocked_annotation_error, gather_error, source_lines) from rpython.flowspace.model import Variable, Constant, checkgraph from", "= False # failed, hopefully temporarily self.blocked_blocks[block] = (graph, e.opindex) except Exception as", "get_call_parameters(self, function, args_s, policy): desc = self.bookkeeper.getdesc(function) prevpolicy = self.policy self.policy = policy", "= (graph, e.opindex) except Exception as e: # hack for debug tools only", "= policy self.bookkeeper.enter(None) try: return desc.get_call_parameters(args_s) finally: self.bookkeeper.leave() self.policy = prevpolicy def annotate_helper(self,", "position_key): graph, block, i = position_key blk = \"\" if block: at =", "inputs_s.append(s_out) if ignore_link: return self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) def follow_raise_link(self, graph,", "is not None: newgraphs = [self.annotated[block] for block in self.added_blocks] newgraphs = dict.fromkeys(newgraphs)", "op in block.operations: if op.opname in ('simple_call', 'call_args'): yield op # some blocks", "link.exitcase == s_exitswitch.const] if block.canraise: op = block.raising_op s_exception = self.get_exception(op) for link", "s_out.knowntype is type newcell = typeof(renamed_is_type_of) if s_out.is_constant(): newcell.const = s_out.const s_out =", "exceptions that `operation` may raise. \"\"\" can_only_throw = operation.get_can_only_throw(self) if can_only_throw is None:", "Variable): self.setbinding(v_last_exc_value, s_last_exc_value) if isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s = [] renaming =", "defaultdict(list) for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out, v_input in zip(link.args,", "'knowntypedata'): renamed_knowntypedata = {} for value, constraints in s_out.knowntypedata.items(): renamed_knowntypedata[value] = {} for", "None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception): \"\"\"This exception signals the type", "block in newblocks: for op in block.operations: if op.opname in ('simple_call', 'call_args'): yield", "self.policy = policy try: self.added_blocks = {} self.complete() # invoke annotation simplifications for", "and set their type args_s = [self.typeannotation(t) for t in input_arg_types] # XXX", "assert annmodel.unionof(s_oldarg, s_newarg) == s_oldarg else: assert not self.frozen if block not in", "self.build_graph_types(graph, inputcells, complete_now=False) self.complete_helpers(policy) return graph def complete_helpers(self, policy): saved = self.policy, self.added_blocks", "self.bookkeeper.compute_at_fixpoint() if block_subset is None: perform_normalizations(self) #___ flowing annotations in blocks _____________________ def", "Variable or Constant.\" s_arg = self.annotation(arg) if s_arg is None: raise KeyError return", "= op.result op = new_ops[0] self.consider_op(op) i += 1 except BlockedInference as e:", "in self.added_blocks] newgraphs = dict.fromkeys(newgraphs) got_blocked_blocks = False in newgraphs else: newgraphs =", "e: if e.op is block.raising_op: # this is the case where the last", "low-level operations! for a, s_newarg in zip(block.inputargs, cells): s_oldarg = self.binding(a) assert annmodel.unionof(s_oldarg,", "already low-level operations! for a, s_newarg in zip(block.inputargs, cells): s_oldarg = self.binding(a) assert", "+= renaming[v] assert s_out.knowntype is type newcell = typeof(renamed_is_type_of) if s_out.is_constant(): newcell.const =", "in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out in link.args: s_out = self.annotation(v_out) if v_out", "at = block.at() if at: blk = \" block\"+at opid=\"\" if i is", "are passed in, and don't annotate the old # graph -- it's already", "import model as annmodel, signature from rpython.annotator.model import ( typeof, s_ImpossibleValue, SomeInstance, intersection,", "self.added_blocks = saved def build_graph_types(self, flowgraph, inputcells, complete_now=True): checkgraph(flowgraph) nbarg = len(flowgraph.getargs()) assert", "assert not self.frozen assert graph not in self.fixed_graphs self.pendingblocks[block] = graph assert block", "Constant.\" s_arg = self.annotation(arg) if s_arg is None: raise KeyError return s_arg def", "if self.added_blocks is not None: newgraphs = [self.annotated[block] for block in self.added_blocks] newgraphs", "wrong number of args # register the entry point self.addpendinggraph(flowgraph, inputcells) # recursively", "rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul)", "parent_graph, parent_block, parent_index = whence tag = parent_block, parent_index self.translator.update_call_graph(parent_graph, graph, tag) #", "s_case) if s_matching_exc != s_ImpossibleValue: self.follow_raise_link(graph, link, s_matching_exc) s_exception = difference(s_exception, s_case) else:", "renaming) inputs_s.append(s_out) if ignore_link: return self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) def follow_raise_link(self,", "set of {blocked_block: (graph, index)} # --- the following information is recorded for", "AttributeError: self.break_at = None self.op = op self.opindex = opindex def __repr__(self): if", "with the flow object space. These are the operations for # which it", "make sure that the return variables of all graphs is annotated if self.added_blocks", "in newblocks: for op in block.operations: if op.opname in ('simple_call', 'call_args'): yield op", "UnionError is a subclass e.source = gather_error(self, graph, block, i) raise else: #", "SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception): \"\"\"This exception signals the type inference engine", "rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # make input arguments and set their", "enters is_ # is_(SomeImpossibleValue, None) -> SomeBool # is_(SomeInstance(not None), None) -> SomeBool(const=False)", "simplify, transform from rpython.annotator import model as annmodel, signature from rpython.annotator.model import (", "the situation is currently blocked, and that it should try to progress elsewhere.\"\"\"", "renaming[v_out].append(v_input) for v_out, v_input in zip(link.args, link.target.inputargs): if v_out == v_last_exc_type: s_out =", "raise # if the merged cells changed, we must redo the analysis if", "import pair from rpython.tool.error import (format_blocked_annotation_error, gather_error, source_lines) from rpython.flowspace.model import Variable, Constant,", "in constraints.items(): new_vs = renaming.get(v, []) for new_v in new_vs: renamed_knowntypedata[value][new_v] = s", "block, cells) else: self.mergeinputargs(graph, block, cells) if not self.annotated[block]: self.pendingblocks[block] = graph def", "isinstance(whence, tuple): parent_graph, parent_block, parent_index = whence tag = parent_block, parent_index self.translator.update_call_graph(parent_graph, graph,", "the initial bindings for the input args of a block. assert len(block.inputargs) ==", "callback() def follow_link(self, graph, link, constraints): assert not (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase,", "self.annotated[block] = False # must flowin. self.blocked_blocks[block] = (graph, None) def mergeinputargs(self, graph,", "= graph assert block in self.annotated self.annotated[block] = False # must re-flow self.blocked_blocks[block]", "is the case where the last operation of the block will # always", "block.exitswitch.annotation, \"knowntypedata\", {}) else: knowntypedata = {} for link in exits: constraints =", "statement so far. # (some functions actually never do, they always raise exceptions)", "an exception which is immediately caught by # an exception handler. We then", "operation.get_can_only_throw(self) if can_only_throw is None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception): \"\"\"This", "def gettype(self, variable): \"\"\"Return the known type of a control flow graph variable,", "graph that has already been rtyped. Safety-check the new # annotations that are", "called recursively. # self.flowin() can only issue calls to self.addpendingblock(). # The analysis", "# Merge the new 'cells' with each of the block's existing input #", "are partially annotated if op.result.annotation is None: break # ignore the unannotated part", "problematic (but will hopefully be solved # later by reflowing). Throw the BlockedInference", "v = graph.getreturnvar() try: return self.binding(v) except KeyError: # the function didn't reach", "the function's input arguments self.addpendingblock(graph, graph.startblock, inputcells) # get the (current) return value", "intersection(s_exception, s_case) if s_matching_exc != s_ImpossibleValue: self.follow_raise_link(graph, link, s_matching_exc) s_exception = difference(s_exception, s_case)", "{}) if whence is not None: if callable(whence): def callback(): whence(self, graph) else:", "[annmodel.unionof(c1,c2) for c1, c2 in zip(oldcells,inputcells)] except annmodel.UnionError as e: # Add source", "i < len(block.operations): op = block.operations[i] with self.bookkeeper.at_position((graph, block, i)): new_ops = op.transform(self)", "warning, keep the name of the call operations in sync # with the", "if s_out == s_ImpossibleValue: ignore_link = True s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) if", "None self.op = op self.opindex = opindex def __repr__(self): if not self.break_at: break_at", "if link.exitcase == s_exitswitch.const] if block.canraise: op = block.raising_op s_exception = self.get_exception(op) for", "parent_block, parent_index self.translator.update_call_graph(parent_graph, graph, tag) # self.notify[graph.returnblock] is a dictionary of call #", "inputcells): # Create the initial bindings for the input args of a block.", "= False in self.annotated.values() if got_blocked_blocks: for graph in self.blocked_graphs.values(): self.blocked_graphs[graph] = True", "self.setbinding(op.result, resultcell) # bind resultcell to op.result def get_exception(self, operation): \"\"\" Return the", "BlockedInference(self, op, -1) # the operation cannot succeed assert isinstance(resultcell, annmodel.SomeObject) assert isinstance(op.result,", "this is the case where the last operation of the block will #", "* self.annotated[block] == False: # the input variables of the block have bindings", "newcell.const = s_out.const s_out = newcell s_out.set_knowntypedata(renamed_knowntypedata) return s_out def whereami(self, position_key): graph,", "graph, block): assert not self.frozen assert graph not in self.fixed_graphs self.pendingblocks[block] = graph", "raise TypeError(\"Variable or Constant instance expected, \" \"got %r\" % (variable,)) def getuserclassdefinitions(self):", "is_ # is_(SomeImpossibleValue, None) -> SomeBool # is_(SomeInstance(not None), None) -> SomeBool(const=False) ...", "until no more pending block is left if complete_now: self.complete() return self.annotation(flowgraph.getreturnvar()) def", "True def reflowpendingblock(self, graph, block): assert not self.frozen assert graph not in self.fixed_graphs", "if case is None: self.follow_link(graph, link, {}) continue if s_exception == s_ImpossibleValue: break", "cells self.annotated[block] = graph if block in self.blocked_blocks: del self.blocked_blocks[block] try: self.flowin(graph, block)", "(should be moved elsewhere?) _______ def simplify(self, block_subset=None, extra_passes=None): # Generic simplifications transform.transform_graph(self,", "self.reflowpendingblock(graph, block) def call_sites(self): newblocks = self.added_blocks if newblocks is None: newblocks =", "is not None] elif e.op.opname in ('simple_call', 'call_args', 'next'): # XXX warning, keep", "self.annotation(v_out) s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) #___", "= True # generalize the function's input arguments self.addpendingblock(graph, graph.startblock, inputcells) # get", "# * self.annotated[block] == False: # the input variables of the block have", "SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc = intersection(s_exception, s_case) if s_matching_exc != s_ImpossibleValue: self.follow_raise_link(graph, link, s_matching_exc) s_exception", "checkgraph(flowgraph) nbarg = len(flowgraph.getargs()) assert len(inputcells) == nbarg # wrong number of args", "tools only if not hasattr(e, '__annotator_block'): setattr(e, '__annotator_block', block) raise # The dict", "# variables. oldcells = [self.binding(a) for a in block.inputargs] try: unions = [annmodel.unionof(c1,c2)", "for all exceptions that `operation` may raise. \"\"\" can_only_throw = operation.get_can_only_throw(self) if can_only_throw", "graph, inputcells = self.get_call_parameters(function, args_s, policy) self.build_graph_types(graph, inputcells, complete_now=False) self.complete_helpers(policy) return graph def", "self self.translator = translator self.pendingblocks = {} # map {block: graph-containing-it} self.annotated =", "information --- self.frozen = False if policy is None: from rpython.annotator.policy import AnnotatorPolicy", "transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes) if block_subset is None: graphs = self.translator.graphs else: graphs =", "an additional # small helper creates. if self.added_blocks is not None: self.added_blocks[block] =", "inputcells) def addpendingblock(self, graph, block, cells): \"\"\"Register an entry point into block with", "{} # {block: {positions-to-reflow-from-when-done}} self.fixed_graphs = {} # set of graphs not to", "if self.added_blocks is not None: self.added_blocks[block] = True def reflowpendingblock(self, graph, block): assert", "= len(flowgraph.getargs()) assert len(inputcells) == nbarg # wrong number of args # register", "if pos is None: try: pos = self.bookkeeper.position_key except AttributeError: pos = '?'", "isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s = [] renaming = defaultdict(list) for v_out, v_input", "for the new blocks self.simplify(block_subset=self.added_blocks) finally: self.policy, self.added_blocks = saved def build_graph_types(self, flowgraph,", "graph, block, inputcells): # Create the initial bindings for the input args of", "set of blocks already seen self.added_blocks = None # see processblock() below self.links_followed", "op.result op = new_ops[0] self.consider_op(op) i += 1 except BlockedInference as e: if", "which are the new blocks that annotating an additional # small helper creates.", "not None] elif e.op.opname in ('simple_call', 'call_args', 'next'): # XXX warning, keep the", "links that try to pass impossible values if s_out == s_ImpossibleValue: ignore_link =", "cell in zip(block.inputargs, inputcells): self.setbinding(a, cell) self.annotated[block] = False # must flowin. self.blocked_blocks[block]", "arg): \"Gives the SomeValue corresponding to the given Variable or Constant.\" if isinstance(arg,", "elsewhere?) _______ def simplify(self, block_subset=None, extra_passes=None): # Generic simplifications transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes) if", "is None: perform_normalizations(self) #___ flowing annotations in blocks _____________________ def processblock(self, graph, block):", "gather_error, source_lines) from rpython.flowspace.model import Variable, Constant, checkgraph from rpython.translator import simplify, transform", "source code to the UnionError e.source = '\\n'.join(source_lines(graph, block, None, long=True)) raise #", "self.pendingblocks[block] = graph def complete_pending_blocks(self): while self.pendingblocks: block, graph = self.pendingblocks.popitem() self.processblock(graph, block)", "# all of them for block in newblocks: for op in block.operations: if", "# reflow from certain positions when this block is done for callback in", "the latter can result in violations of the # more general results invariant:", "= v_last_exc_type.value elif v_last_exc_type.annotation.is_constant(): s_out.const = v_last_exc_type.annotation.const inputs_s.append(s_out) else: s_out = self.annotation(v_out) s_out", "None: break # ignore the unannotated part #___ simplification (should be moved elsewhere?)", "in exits: case = link.exitcase if case is None: self.follow_link(graph, link, {}) continue", "= False inputs_s = [] renaming = defaultdict(list) for v_out, v_input in zip(link.args,", "for link in block.exits if link.exitcase is not None] elif e.op.opname in ('simple_call',", "from certain positions when this block is done for callback in self.notify[block]: if", "{block: {positions-to-reflow-from-when-done}} self.fixed_graphs = {} # set of graphs not to annotate again", "self.policy = prevpolicy def annotate_helper(self, function, args_s, policy=None): if policy is None: from", "an entry point into block with the given input cells.\"\"\" if graph in", "# get the (current) return value v = graph.getreturnvar() try: return self.binding(v) except", "block. assert len(block.inputargs) == len(inputcells) for a, cell in zip(block.inputargs, inputcells): self.setbinding(a, cell)", "annotating an additional # small helper creates. if self.added_blocks is not None: self.added_blocks[block]", "link.target, inputs_s) #___ creating the annotations based on operations ______ def consider_op(self, op):", "effects if translator is None: # interface for tests from rpython.translator.translator import TranslationContext", "inputs_s, complete_now=complete_now) def get_call_parameters(self, function, args_s, policy): desc = self.bookkeeper.getdesc(function) prevpolicy = self.policy", "s_last_exc_value): v_last_exc_type = link.last_exception v_last_exc_value = link.last_exc_value assert (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase,", "inputs_s.append(s_out) else: s_out = self.annotation(v_out) s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) self.links_followed[link] = True", "is None: from rpython.annotator.policy import AnnotatorPolicy self.policy = AnnotatorPolicy() else: self.policy = policy", "('simple_call', 'call_args', 'next'): # XXX warning, keep the name of the call operations", "of this graph has been analysed. callpositions = self.notify.setdefault(graph.returnblock, {}) if whence is", "has already been rtyped. Safety-check the new # annotations that are passed in,", "__getstate__(self): attrs = \"\"\"translator pendingblocks annotated links_followed notify bookkeeper frozen policy added_blocks\"\"\".split() ret", "v_last_exc_value = link.last_exc_value assert (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) assert v_last_exc_type and", "assert not self.frozen if block not in self.annotated: self.bindinputargs(graph, block, cells) else: self.mergeinputargs(graph,", "for value, constraints in s_out.knowntypedata.items(): renamed_knowntypedata[value] = {} for v, s in constraints.items():", "(types.ClassType, type)) and issubclass(link.exitcase, BaseException)) assert v_last_exc_type and v_last_exc_value if isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value,", "finally: self.bookkeeper.leave() self.policy = prevpolicy def annotate_helper(self, function, args_s, policy=None): if policy is", "complete_pending_blocks(self): while self.pendingblocks: block, graph = self.pendingblocks.popitem() self.processblock(graph, block) def complete(self): \"\"\"Process pending", "s_exception = difference(s_exception, s_case) else: if isinstance(block.exitswitch, Variable): knowntypedata = getattr( block.exitswitch.annotation, \"knowntypedata\",", "{} # set of links that have ever been followed self.notify = {}", "= False if policy is None: from rpython.annotator.policy import AnnotatorPolicy self.policy = AnnotatorPolicy()", "graph not in self.fixed_graphs self.pendingblocks[block] = graph assert block in self.annotated self.annotated[block] =", "self.complete_helpers(policy) return graph def complete_helpers(self, policy): saved = self.policy, self.added_blocks self.policy = policy", "opid=\"\" if i is not None: opid = \" op=%d\" % i return", "assert False arg.annotation = s_value def warning(self, msg, pos=None): if pos is None:", "in op.args: if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise BlockedInference(self, op, -1) resultcell = op.consider(self) if", "must re-flow self.blocked_blocks[block] = (graph, None) def bindinputargs(self, graph, block, inputcells): # Create", "= new_ops[0] self.consider_op(op) i += 1 except BlockedInference as e: if e.op is", "all of them for block in newblocks: for op in block.operations: if op.opname", "Variable): knowntypedata = getattr( block.exitswitch.annotation, \"knowntypedata\", {}) else: knowntypedata = {} for link", "None: self.follow_link(graph, link, {}) continue if s_exception == s_ImpossibleValue: break s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case))", "that the situation is currently blocked, and that it should try to progress", "raise an exception. We then # swallow the BlockedInference and that's it. #", "rpython.rtyper.normalizecalls import perform_normalizations log = AnsiLogger(\"annrpython\") class RPythonAnnotator(object): \"\"\"Block annotator for RPython. See", "case for annotating/rtyping in several phases: calling # a graph that has already", "type)) and issubclass(link.exitcase, BaseException)) assert v_last_exc_type and v_last_exc_value if isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value, s_last_exc_value)", "None: bookkeeper = Bookkeeper(self) self.bookkeeper = bookkeeper def __getstate__(self): attrs = \"\"\"translator pendingblocks", "that `operation` may raise. \"\"\" can_only_throw = operation.get_can_only_throw(self) if can_only_throw is None: return", "that the annotation results are valid\"\"\" self.bookkeeper.check_no_flags_on_instances() def annotation(self, arg): \"Gives the SomeValue", "raise an exception which is immediately caught by # an exception handler. We", "= False # must flowin. self.blocked_blocks[block] = (graph, None) def mergeinputargs(self, graph, block,", "s_value): s_old = arg.annotation if s_old is not None: if not s_value.contains(s_old): log.WARNING(\"%s", "s_arg = self.annotation(arg) if s_arg is None: raise KeyError return s_arg def typeannotation(self,", "rpython.flowspace.model import Variable, Constant, checkgraph from rpython.translator import simplify, transform from rpython.annotator import", "block not in self.annotated: # never seen the block. # * self.annotated[block] ==", "s_out.is_constant(): newcell.const = s_out.const s_out = newcell s_out.set_knowntypedata(renamed_knowntypedata) return s_out def whereami(self, position_key):", "blocks until none is left.\"\"\" while True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if not self.pendingblocks: break", "for graph in self.blocked_graphs.values(): self.blocked_graphs[graph] = True blocked_blocks = [block for block, done", "KeyError: # the function didn't reach any return statement so far. # (some", "{} self.complete() # invoke annotation simplifications for the new blocks self.simplify(block_subset=self.added_blocks) finally: self.policy,", "is not None: self.added_blocks[block] = True def reflowpendingblock(self, graph, block): assert not self.frozen", "annmodel.SomeObject) assert isinstance(op.result, Variable) self.setbinding(op.result, resultcell) # bind resultcell to op.result def get_exception(self,", "None, long=True)) raise # if the merged cells changed, we must redo the", "graph, whence, inputcells): if isinstance(whence, tuple): parent_graph, parent_block, parent_index = whence tag =", "return block of this graph has been analysed. callpositions = self.notify.setdefault(graph.returnblock, {}) if", "annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) graph, inputcells = self.get_call_parameters(function, args_s, policy) self.build_graph_types(graph, inputcells, complete_now=False)", "True for graph in graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if block_subset is None: perform_normalizations(self) #___", "point.\"\"\" assert isinstance(function, types.FunctionType), \"fix that!\" from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy()", "is_(SomeInstance(not None), None) -> SomeBool(const=False) ... # boom -- in the assert of", "knowntypedata = {} for link in exits: constraints = knowntypedata.get(link.exitcase, {}) self.follow_link(graph, link,", "the UnionError e.source = '\\n'.join(source_lines(graph, block, None, long=True)) raise # if the merged", "processblock', block, cells self.annotated[block] = graph if block in self.blocked_blocks: del self.blocked_blocks[block] try:", "break # finished # make sure that the return variables of all graphs", "policy is None: from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # XXX hack", "from rpython.tool.ansi_print import AnsiLogger from rpython.tool.pairtype import pair from rpython.tool.error import (format_blocked_annotation_error, gather_error,", "self.policy.no_more_blocks_to_annotate(self) if not self.pendingblocks: break # finished # make sure that the return", "# has side effects if translator is None: # interface for tests from", "done in self.annotated.items() if done is False] assert len(blocked_blocks) == len(self.blocked_blocks) text =", "args_s, policy) if main_entry_point: self.translator.entry_point_graph = flowgraph return self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now) def get_call_parameters(self,", "this is not called recursively. # self.flowin() can only issue calls to self.addpendingblock().", "= self.annotation(arg) if s_arg is None: raise KeyError return s_arg def typeannotation(self, t):", "block, graph = self.pendingblocks.popitem() self.processblock(graph, block) def complete(self): \"\"\"Process pending blocks until none", "def addpendingblock(self, graph, block, cells): \"\"\"Register an entry point into block with the", "the # input variables). #print '* processblock', block, cells self.annotated[block] = graph if", "def warning(self, msg, pos=None): if pos is None: try: pos = self.bookkeeper.position_key except", "s_ImpossibleValue: break s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc = intersection(s_exception, s_case) if s_matching_exc != s_ImpossibleValue:", "a block can be in three states: # * block not in self.annotated:", "self.annotated[block] == False: # the input variables of the block have bindings but", "--- the following information is recorded for debugging --- self.blocked_graphs = {} #", "= s_ImpossibleValue elif resultcell == s_ImpossibleValue: raise BlockedInference(self, op, -1) # the operation", "index = position_key self.reflowpendingblock(graph, block) def call_sites(self): newblocks = self.added_blocks if newblocks is", "i = position_key blk = \"\" if block: at = block.at() if at:", "the unannotated part #___ simplification (should be moved elsewhere?) _______ def simplify(self, block_subset=None,", "some blocks are partially annotated if op.result.annotation is None: break # ignore the", "yield op # some blocks are partially annotated if op.result.annotation is None: break", "but we # still have to consider all the operations in the block.", "constraints) if block in self.notify: # reflow from certain positions when this block", "def reflowpendingblock(self, graph, block): assert not self.frozen assert graph not in self.fixed_graphs self.pendingblocks[block]", "s_exception == s_ImpossibleValue: break s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc = intersection(s_exception, s_case) if s_matching_exc", "self.addpendingblock(graph, link.target, inputs_s) def follow_raise_link(self, graph, link, s_last_exc_value): v_last_exc_type = link.last_exception v_last_exc_value =", "self.translator.graphs else: graphs = {} for block in block_subset: graph = self.annotated.get(block) if", "the exceptional # branches. exits = [link for link in block.exits if link.exitcase", "arg): \"Gives the SomeValue corresponding to the given Variable or Constant.\" s_arg =", "typeof(renamed_is_type_of) if s_out.is_constant(): newcell.const = s_out.const s_out = newcell if hasattr(s_out, 'knowntypedata'): renamed_knowntypedata", "self.blocked_graphs[graph] = True blocked_blocks = [block for block, done in self.annotated.items() if done", "type newcell = typeof(renamed_is_type_of) if s_out.is_constant(): newcell.const = s_out.const s_out = newcell if", "block.canraise: op = block.raising_op s_exception = self.get_exception(op) for link in exits: case =", "a position else: callback() def follow_link(self, graph, link, constraints): assert not (isinstance(link.exitcase, (types.ClassType,", "s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) #___ creating", "None: newgraphs = [self.annotated[block] for block in self.added_blocks] newgraphs = dict.fromkeys(newgraphs) got_blocked_blocks =", "False # failed, hopefully temporarily self.blocked_blocks[block] = (graph, e.opindex) except Exception as e:", "creates. if self.added_blocks is not None: self.added_blocks[block] = True def reflowpendingblock(self, graph, block):", "follow_raise_link(self, graph, link, s_last_exc_value): v_last_exc_type = link.last_exception v_last_exc_value = link.last_exc_value assert (isinstance(link.exitcase, (types.ClassType,", "# map {block: graph-containing-it} self.annotated = {} # set of blocks already seen", "operation): \"\"\" Return the annotation for all exceptions that `operation` may raise. \"\"\"", "# to enter an op; the latter can result in violations of the", "follow all exits if the exitswitch # is known exits = block.exits if", "False: # the input variables of the block have bindings but we #", "in self.fixed_graphs: # special case for annotating/rtyping in several phases: calling # a", "v_last_exc_type.annotation.const inputs_s.append(s_out) else: s_out = self.annotation(v_out) s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) self.links_followed[link] =", "graphs is annotated if self.added_blocks is not None: newgraphs = [self.annotated[block] for block", "positions when this block is done for callback in self.notify[block]: if isinstance(callback, tuple):", "== s_ImpossibleValue: break s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc = intersection(s_exception, s_case) if s_matching_exc !=", "block: at = block.at() if at: blk = \" block\"+at opid=\"\" if i", "def recursivecall(self, graph, whence, inputcells): if isinstance(whence, tuple): parent_graph, parent_block, parent_index = whence", "= translator self.pendingblocks = {} # map {block: graph-containing-it} self.annotated = {} #", "constraints in s_out.knowntypedata.items(): renamed_knowntypedata[value] = {} for v, s in constraints.items(): new_vs =", "values if s_out == s_ImpossibleValue: ignore_link = True s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out)", "self.apply_renaming(s_out, renaming) inputs_s.append(s_out) self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) #___ creating the annotations", "= v_last_exc_type.annotation.const inputs_s.append(s_out) else: s_out = self.annotation(v_out) s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) self.links_followed[link]", "self.notify.setdefault(graph.returnblock, {}) if whence is not None: if callable(whence): def callback(): whence(self, graph)", "= ( self.translator.config.translation.check_str_without_nul) graph, inputcells = self.get_call_parameters(function, args_s, policy) self.build_graph_types(graph, inputcells, complete_now=False) self.complete_helpers(policy)", "input args of a block. assert len(block.inputargs) == len(inputcells) for a, cell in", "and that it should try to progress elsewhere.\"\"\" def __init__(self, annotator, op, opindex):", "s_ImpossibleValue: self.follow_raise_link(graph, link, s_matching_exc) s_exception = difference(s_exception, s_case) else: if isinstance(block.exitswitch, Variable): knowntypedata", "for RPython. See description in doc/translation.txt.\"\"\" def __init__(self, translator=None, policy=None, bookkeeper=None): import rpython.rtyper.extfuncregistry", "= op.consider(self) if resultcell is None: resultcell = s_ImpossibleValue elif resultcell == s_ImpossibleValue:", "new_ops if not new_ops: continue new_ops[-1].result = op.result op = new_ops[0] self.consider_op(op) i", "not None: if not s_value.contains(s_old): log.WARNING(\"%s does not contain %s\" % (s_value, s_old))", "e: # hack for debug tools only if not hasattr(e, '__annotator_block'): setattr(e, '__annotator_block',", "False in self.annotated.values() if got_blocked_blocks: for graph in self.blocked_graphs.values(): self.blocked_graphs[graph] = True blocked_blocks", "that's it. # About 'next': see test_annotate_iter_empty_container(). return else: # other cases are", "True s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) if ignore_link: return self.links_followed[link] = True self.addpendingblock(graph,", "to progress elsewhere.\"\"\" def __init__(self, annotator, op, opindex): self.annotator = annotator try: self.break_at", "import simplify, transform from rpython.annotator import model as annmodel, signature from rpython.annotator.model import", "import rpython.rtyper.extfuncregistry # has side effects if translator is None: # interface for", "annotated if op.result.annotation is None: break # ignore the unannotated part #___ simplification", "if hasattr(s_out, 'knowntypedata'): renamed_knowntypedata = {} for value, constraints in s_out.knowntypedata.items(): renamed_knowntypedata[value] =", "of args # register the entry point self.addpendinggraph(flowgraph, inputcells) # recursively proceed until", "\" block\"+at opid=\"\" if i is not None: opid = \" op=%d\" %", "should try to progress elsewhere.\"\"\" def __init__(self, annotator, op, opindex): self.annotator = annotator", "return self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception): \"\"\"This exception signals the type inference engine that the", "the block. # * self.annotated[block] == graph-containing-block: # analysis done (at least until", "# {block: {positions-to-reflow-from-when-done}} self.fixed_graphs = {} # set of graphs not to annotate", "in, and don't annotate the old # graph -- it's already low-level operations!", "zip(link.args, link.target.inputargs): if v_out == v_last_exc_type: s_out = typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type, Constant): s_out.const", "return self.bookkeeper.classdefs #___ medium-level interface ____________________________ def addpendinggraph(self, flowgraph, inputcells): self.addpendingblock(flowgraph, flowgraph.startblock, inputcells)", "block\"+at opid=\"\" if i is not None: opid = \" op=%d\" % i", "the operation cannot succeed assert isinstance(resultcell, annmodel.SomeObject) assert isinstance(op.result, Variable) self.setbinding(op.result, resultcell) #", "graphs = self.translator.graphs else: graphs = {} for block in block_subset: graph =", "new_ops: continue new_ops[-1].result = op.result op = new_ops[0] self.consider_op(op) i += 1 except", "# bind resultcell to op.result def get_exception(self, operation): \"\"\" Return the annotation for", "= annotator try: self.break_at = annotator.bookkeeper.position_key except AttributeError: self.break_at = None self.op =", "only if not hasattr(e, '__annotator_block'): setattr(e, '__annotator_block', block) raise # The dict 'added_blocks'", "latter can result in violations of the # more general results invariant: e.g.", "self.annotated # all of them for block in newblocks: for op in block.operations:", "and issubclass(link.exitcase, BaseException)) ignore_link = False inputs_s = [] renaming = defaultdict(list) for", "is annotated if self.added_blocks is not None: newgraphs = [self.annotated[block] for block in", "if done is False] assert len(blocked_blocks) == len(self.blocked_blocks) text = format_blocked_annotation_error(self, self.blocked_blocks) #raise", "import types from collections import defaultdict from rpython.tool.ansi_print import AnsiLogger from rpython.tool.pairtype import", "AnnotatorPolicy policy = AnnotatorPolicy() # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) graph, inputcells", "def getuserclassdefinitions(self): \"\"\"Return a list of ClassDefs.\"\"\" return self.bookkeeper.classdefs #___ medium-level interface ____________________________", "= {} # set of links that have ever been followed self.notify =", "proceed until no more pending block is left if complete_now: self.complete() return self.annotation(flowgraph.getreturnvar())", "cells): s_oldarg = self.binding(a) assert annmodel.unionof(s_oldarg, s_newarg) == s_oldarg else: assert not self.frozen", "-- in the assert of setbinding() for arg in op.args: if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue):", "assert isinstance(s_out, annmodel.SomeBool) newcell = annmodel.SomeBool() if s_out.is_constant(): newcell.const = s_out.const s_out =", "= self.get_call_parameters(function, args_s, policy) self.build_graph_types(graph, inputcells, complete_now=False) self.complete_helpers(policy) return graph def complete_helpers(self, policy):", "got_blocked_blocks = False in newgraphs else: newgraphs = self.translator.graphs #all of them got_blocked_blocks", "let's be careful about avoiding propagated SomeImpossibleValues # to enter an op; the", "# dead code removal: don't follow all exits if the exitswitch # is", "for callback in self.notify[block]: if isinstance(callback, tuple): self.reflowfromposition(callback) # callback is a position", "(pos, msg)) #___ interface for annotator.bookkeeper _______ def recursivecall(self, graph, whence, inputcells): if", "from rpython.rtyper.normalizecalls import perform_normalizations log = AnsiLogger(\"annrpython\") class RPythonAnnotator(object): \"\"\"Block annotator for RPython.", "new_vs: renamed_knowntypedata[value][new_v] = s assert isinstance(s_out, annmodel.SomeBool) newcell = annmodel.SomeBool() if s_out.is_constant(): newcell.const", "{} for value, constraints in s_out.knowntypedata.items(): renamed_knowntypedata[value] = {} for v, s in", "s_last_exc_value) if isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s = [] renaming = defaultdict(list) for", "# set of graphs not to annotate again self.blocked_blocks = {} # set", "information is recorded for debugging --- self.blocked_graphs = {} # set of graphs", "if the exitswitch # is known exits = block.exits if isinstance(block.exitswitch, Variable): s_exitswitch", "self.notify: # reflow from certain positions when this block is done for callback", "is a subclass e.source = gather_error(self, graph, block, i) raise else: # dead", "policy self.bookkeeper.enter(None) try: return desc.get_call_parameters(args_s) finally: self.bookkeeper.leave() self.policy = prevpolicy def annotate_helper(self, function,", "<filename>rpython/annotator/annrpython.py from __future__ import absolute_import import types from collections import defaultdict from rpython.tool.ansi_print", "zip(block.inputargs, cells): s_oldarg = self.binding(a) assert annmodel.unionof(s_oldarg, s_newarg) == s_oldarg else: assert not", "self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s = self.get_call_parameters(function, args_s, policy) if main_entry_point: self.translator.entry_point_graph = flowgraph return", "None: graphs = self.translator.graphs else: graphs = {} for block in block_subset: graph", "moved elsewhere?) _______ def simplify(self, block_subset=None, extra_passes=None): # Generic simplifications transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes)", "# later by reflowing). Throw the BlockedInference up to # processblock(). e.opindex =", "# Important: this is not called recursively. # self.flowin() can only issue calls", "% (variable,)) def getuserclassdefinitions(self): \"\"\"Return a list of ClassDefs.\"\"\" return self.bookkeeper.classdefs #___ medium-level", "= annmodel.SomeBool() if s_out.is_constant(): newcell.const = s_out.const s_out = newcell s_out.set_knowntypedata(renamed_knowntypedata) return s_out", "is done for callback in self.notify[block]: if isinstance(callback, tuple): self.reflowfromposition(callback) # callback is", "is not None: block.operations[i:i+1] = new_ops if not new_ops: continue new_ops[-1].result = op.result", "for block, done in self.annotated.items() if done is False] assert len(blocked_blocks) == len(self.blocked_blocks)", "return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception): \"\"\"This exception signals the type inference", "in s_out.is_type_of: renamed_is_type_of += renaming[v] assert s_out.knowntype is type newcell = typeof(renamed_is_type_of) if", "annotations in blocks _____________________ def processblock(self, graph, block): # Important: this is not", "self.setbinding(v, s_ImpossibleValue) def validate(self): \"\"\"Check that the annotation results are valid\"\"\" self.bookkeeper.check_no_flags_on_instances() def", "except annmodel.HarmlesslyBlocked: return except annmodel.AnnotatorError as e: # note that UnionError is a", "#all of them got_blocked_blocks = False in self.annotated.values() if got_blocked_blocks: for graph in", "for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out, v_input in zip(link.args, link.target.inputargs):", "self.translator = translator self.pendingblocks = {} # map {block: graph-containing-it} self.annotated = {}", "the flow object space. These are the operations for # which it is", "= self.translator.graphs else: graphs = {} for block in block_subset: graph = self.annotated.get(block)", "translator=None, policy=None, bookkeeper=None): import rpython.rtyper.extfuncregistry # has side effects if translator is None:", "for tests from rpython.translator.translator import TranslationContext translator = TranslationContext() translator.annotator = self self.translator", "self.frozen if block not in self.annotated: self.bindinputargs(graph, block, cells) else: self.mergeinputargs(graph, block, cells)", "self.notify[graph.returnblock] is a dictionary of call # points to this func which triggers", "as e: # Add source code to the UnionError e.source = '\\n'.join(source_lines(graph, block,", "= position_key self.reflowpendingblock(graph, block) def call_sites(self): newblocks = self.added_blocks if newblocks is None:", "be moved elsewhere?) _______ def simplify(self, block_subset=None, extra_passes=None): # Generic simplifications transform.transform_graph(self, block_subset=block_subset,", "opid def flowin(self, graph, block): try: i = 0 while i < len(block.operations):", "v_last_exc_type.value elif v_last_exc_type.annotation.is_constant(): s_out.const = v_last_exc_type.annotation.const inputs_s.append(s_out) else: s_out = self.annotation(v_out) s_out =", "v_last_exc_type.annotation.is_constant(): s_out.const = v_last_exc_type.annotation.const inputs_s.append(s_out) else: s_out = self.annotation(v_out) s_out = self.apply_renaming(s_out, renaming)", "raise. \"\"\" can_only_throw = operation.get_can_only_throw(self) if can_only_throw is None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return", "of the # more general results invariant: e.g. if SomeImpossibleValue enters is_ #", "if key not in attrs: assert type(value) is dict, ( \"%r is not", "if block_subset is None: perform_normalizations(self) #___ flowing annotations in blocks _____________________ def processblock(self,", "knowntypedata.get(link.exitcase, {}) self.follow_link(graph, link, constraints) if block in self.notify: # reflow from certain", "= {} return ret #___ convenience high-level interface __________________ def build_types(self, function, input_arg_types,", "s_exitswitch.is_constant(): exits = [link for link in exits if link.exitcase == s_exitswitch.const] if", "from rpython.translator.translator import TranslationContext translator = TranslationContext() translator.annotator = self self.translator = translator", "new_ops = op.transform(self) if new_ops is not None: block.operations[i:i+1] = new_ops if not", "blocks # --- end of debugging information --- self.frozen = False if policy", "# callback is a position else: callback() def follow_link(self, graph, link, constraints): assert", "be careful about avoiding propagated SomeImpossibleValues # to enter an op; the latter", "import AnnotatorPolicy policy = AnnotatorPolicy() # make input arguments and set their type", "XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) graph, inputcells = self.get_call_parameters(function, args_s, policy) self.build_graph_types(graph,", "interface ____________________________ def addpendinggraph(self, flowgraph, inputcells): self.addpendingblock(flowgraph, flowgraph.startblock, inputcells) def addpendingblock(self, graph, block,", "in newgraphs: v = graph.getreturnvar() if v.annotation is None: self.setbinding(v, s_ImpossibleValue) def validate(self):", "if isinstance(whence, tuple): parent_graph, parent_block, parent_index = whence tag = parent_block, parent_index self.translator.update_call_graph(parent_graph,", "def processblock(self, graph, block): # Important: this is not called recursively. # self.flowin()", "callback in self.notify[block]: if isinstance(callback, tuple): self.reflowfromposition(callback) # callback is a position else:", "self.binding(v) except KeyError: # the function didn't reach any return statement so far.", "[self.binding(a) for a in block.inputargs] try: unions = [annmodel.unionof(c1,c2) for c1, c2 in", "defaultdict(list) for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out in link.args: s_out", "as e: # note that UnionError is a subclass e.source = gather_error(self, graph,", "renaming) inputs_s.append(s_out) self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) #___ creating the annotations based", "ignore_link: return self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) def follow_raise_link(self, graph, link, s_last_exc_value):", "in several phases: calling # a graph that has already been rtyped. Safety-check", "Bookkeeper(self) self.bookkeeper = bookkeeper def __getstate__(self): attrs = \"\"\"translator pendingblocks annotated links_followed notify", "exceptions) return s_ImpossibleValue def reflowfromposition(self, position_key): graph, block, index = position_key self.reflowpendingblock(graph, block)", "# an exception handler. We then only follow the exceptional # branches. exits", "= flowgraph return self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now) def get_call_parameters(self, function, args_s, policy): desc =", "cells) else: self.mergeinputargs(graph, block, cells) if not self.annotated[block]: self.pendingblocks[block] = graph def complete_pending_blocks(self):", "position_key): graph, block, index = position_key self.reflowpendingblock(graph, block) def call_sites(self): newblocks = self.added_blocks", "not new_ops: continue new_ops[-1].result = op.result op = new_ops[0] self.consider_op(op) i += 1", "inputcells, complete_now=True): checkgraph(flowgraph) nbarg = len(flowgraph.getargs()) assert len(inputcells) == nbarg # wrong number", "s_newarg) == s_oldarg else: assert not self.frozen if block not in self.annotated: self.bindinputargs(graph,", "# --- end of debugging information --- self.frozen = False if policy is", "\"%r is not dict. please update %s.__getstate__\" % (key, self.__class__.__name__)) ret[key] = {}", "didn't reach any return statement so far. # (some functions actually never do,", "except BlockedInference as e: if e.op is block.raising_op: # this is the case", "# which it is fine to always raise an exception. We then #", "that UnionError is a subclass e.source = gather_error(self, graph, block, i) raise else:", "block is done for callback in self.notify[block]: if isinstance(callback, tuple): self.reflowfromposition(callback) # callback", "s_ImpossibleValue: ignore_link = True s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) if ignore_link: return self.links_followed[link]", "annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s = self.get_call_parameters(function, args_s, policy) if main_entry_point: self.translator.entry_point_graph", "medium-level interface ____________________________ def addpendinggraph(self, flowgraph, inputcells): self.addpendingblock(flowgraph, flowgraph.startblock, inputcells) def addpendingblock(self, graph,", "value v = graph.getreturnvar() try: return self.binding(v) except KeyError: # the function didn't", "annmodel.unionof(s_oldarg, s_newarg) == s_oldarg else: assert not self.frozen if block not in self.annotated:", "in self.annotated: # never seen the block. # * self.annotated[block] == False: #", "{} return ret #___ convenience high-level interface __________________ def build_types(self, function, input_arg_types, complete_now=True,", "self.translator.graphs #all of them got_blocked_blocks = False in self.annotated.values() if got_blocked_blocks: for graph", "redo the analysis if unions != oldcells: self.bindinputargs(graph, block, unions) def apply_renaming(self, s_out,", "None: # interface for tests from rpython.translator.translator import TranslationContext translator = TranslationContext() translator.annotator", "s_out.const = v_last_exc_type.annotation.const inputs_s.append(s_out) else: s_out = self.annotation(v_out) s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out)", "None # see processblock() below self.links_followed = {} # set of links that", "self.pendingblocks = {} # map {block: graph-containing-it} self.annotated = {} # set of", "def complete_helpers(self, policy): saved = self.policy, self.added_blocks self.policy = policy try: self.added_blocks =", "the SomeValue corresponding to the given Variable or Constant.\" s_arg = self.annotation(arg) if", "= dict.fromkeys(newgraphs) got_blocked_blocks = False in newgraphs else: newgraphs = self.translator.graphs #all of", "inputcells): self.addpendingblock(flowgraph, flowgraph.startblock, inputcells) def addpendingblock(self, graph, block, cells): \"\"\"Register an entry point", "return signature.annotation(t, self.bookkeeper) def setbinding(self, arg, s_value): s_old = arg.annotation if s_old is", "op = block.operations[i] with self.bookkeeper.at_position((graph, block, i)): new_ops = op.transform(self) if new_ops is", "that are passed in, and don't annotate the old # graph -- it's", "= self.pendingblocks.popitem() self.processblock(graph, block) def complete(self): \"\"\"Process pending blocks until none is left.\"\"\"", "s_out.is_constant(): newcell.const = s_out.const s_out = newcell if hasattr(s_out, 'knowntypedata'): renamed_knowntypedata = {}", "rpython.tool.error import (format_blocked_annotation_error, gather_error, source_lines) from rpython.flowspace.model import Variable, Constant, checkgraph from rpython.translator", "issubclass(link.exitcase, BaseException)) assert v_last_exc_type and v_last_exc_value if isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value, s_last_exc_value) if isinstance(v_last_exc_type,", "== v_last_exc_type: s_out = typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type, Constant): s_out.const = v_last_exc_type.value elif v_last_exc_type.annotation.is_constant():", "that annotating an additional # small helper creates. if self.added_blocks is not None:", "else: graphs = {} for block in block_subset: graph = self.annotated.get(block) if graph:", "BlockedInference as e: if e.op is block.raising_op: # this is the case where", "(format_blocked_annotation_error, gather_error, source_lines) from rpython.flowspace.model import Variable, Constant, checkgraph from rpython.translator import simplify,", "attrs: assert type(value) is dict, ( \"%r is not dict. please update %s.__getstate__\"", "self.flowin() can only issue calls to self.addpendingblock(). # The analysis of a block", "i is not None: opid = \" op=%d\" % i return repr(graph) +", "operations for # which it is fine to always raise an exception. We", "assert of setbinding() for arg in op.args: if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise BlockedInference(self, op,", "inputs_s) #___ creating the annotations based on operations ______ def consider_op(self, op): #", "= self.added_blocks if newblocks is None: newblocks = self.annotated # all of them", "input arguments self.addpendingblock(graph, graph.startblock, inputcells) # get the (current) return value v =", "\"\"\"Recursively build annotations about the specific entry point.\"\"\" assert isinstance(function, types.FunctionType), \"fix that!\"", "opid = \" op=%d\" % i return repr(graph) + blk + opid def", "if block not in self.annotated: self.bindinputargs(graph, block, cells) else: self.mergeinputargs(graph, block, cells) if", "we must redo the analysis if unions != oldcells: self.bindinputargs(graph, block, unions) def", "None: self.added_blocks[block] = True def reflowpendingblock(self, graph, block): assert not self.frozen assert graph", "situation is currently blocked, and that it should try to progress elsewhere.\"\"\" def", "generalize the # input variables). #print '* processblock', block, cells self.annotated[block] = graph", "to 'object'.\"\"\" if isinstance(variable, Constant): return type(variable.value) elif isinstance(variable, Variable): s_variable = variable.annotation", "about avoiding propagated SomeImpossibleValues # to enter an op; the latter can result", "= saved def build_graph_types(self, flowgraph, inputcells, complete_now=True): checkgraph(flowgraph) nbarg = len(flowgraph.getargs()) assert len(inputcells)", "policy if bookkeeper is None: bookkeeper = Bookkeeper(self) self.bookkeeper = bookkeeper def __getstate__(self):", "TypeError('Variable or Constant expected, got %r' % (arg,)) def binding(self, arg): \"Gives the", "= self.binding(a) assert annmodel.unionof(s_oldarg, s_newarg) == s_oldarg else: assert not self.frozen if block", "for block in self.added_blocks] newgraphs = dict.fromkeys(newgraphs) got_blocked_blocks = False in newgraphs else:", "self.blocked_blocks[block] = (graph, e.opindex) except Exception as e: # hack for debug tools", "== s_oldarg else: assert not self.frozen if block not in self.annotated: self.bindinputargs(graph, block,", "code to the UnionError e.source = '\\n'.join(source_lines(graph, block, None, long=True)) raise # if", "side effects if translator is None: # interface for tests from rpython.translator.translator import", "%r\" % (variable,)) def getuserclassdefinitions(self): \"\"\"Return a list of ClassDefs.\"\"\" return self.bookkeeper.classdefs #___", "if s_arg is None: raise KeyError return s_arg def typeannotation(self, t): return signature.annotation(t,", "# hack for debug tools only if not hasattr(e, '__annotator_block'): setattr(e, '__annotator_block', block)", "saved def build_graph_types(self, flowgraph, inputcells, complete_now=True): checkgraph(flowgraph) nbarg = len(flowgraph.getargs()) assert len(inputcells) ==", "in self.notify: # reflow from certain positions when this block is done for", "= self.policy, self.added_blocks self.policy = policy try: self.added_blocks = {} self.complete() # invoke", "_______ def recursivecall(self, graph, whence, inputcells): if isinstance(whence, tuple): parent_graph, parent_block, parent_index =", "= new_ops if not new_ops: continue new_ops[-1].result = op.result op = new_ops[0] self.consider_op(op)", "# must flowin. self.blocked_blocks[block] = (graph, None) def mergeinputargs(self, graph, block, inputcells): #", "args_s, policy): desc = self.bookkeeper.getdesc(function) prevpolicy = self.policy self.policy = policy self.bookkeeper.enter(None) try:", "# must re-flow self.blocked_blocks[block] = (graph, None) def bindinputargs(self, graph, block, inputcells): #", "self.annotated[block] == graph-containing-block: # analysis done (at least until we find we must", "ignore_link = True s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) if ignore_link: return self.links_followed[link] =", "v_out, v_input in zip(link.args, link.target.inputargs): if v_out == v_last_exc_type: s_out = typeof(renaming[v_last_exc_value]) if", "Constant expected, got %r' % (arg,)) def binding(self, arg): \"Gives the SomeValue corresponding", "repr(graph) + blk + opid def flowin(self, graph, block): try: i = 0", "= self.get_call_parameters(function, args_s, policy) if main_entry_point: self.translator.entry_point_graph = flowgraph return self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now)", "if isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s = [] renaming = defaultdict(list) for v_out,", "__init__(self, translator=None, policy=None, bookkeeper=None): import rpython.rtyper.extfuncregistry # has side effects if translator is", "don't follow all exits if the exitswitch # is known exits = block.exits", "not s_value.contains(s_old): log.WARNING(\"%s does not contain %s\" % (s_value, s_old)) log.WARNING(\"%s\" % annmodel.unionof(s_value,", "None: raise KeyError return s_arg def typeannotation(self, t): return signature.annotation(t, self.bookkeeper) def setbinding(self,", "instance expected, \" \"got %r\" % (variable,)) def getuserclassdefinitions(self): \"\"\"Return a list of", "in zip(oldcells,inputcells)] except annmodel.UnionError as e: # Add source code to the UnionError", "or Constant instance expected, \" \"got %r\" % (variable,)) def getuserclassdefinitions(self): \"\"\"Return a", "= graph.getreturnvar() if v.annotation is None: self.setbinding(v, s_ImpossibleValue) def validate(self): \"\"\"Check that the", "are problematic (but will hopefully be solved # later by reflowing). Throw the", "(variable,)) def getuserclassdefinitions(self): \"\"\"Return a list of ClassDefs.\"\"\" return self.bookkeeper.classdefs #___ medium-level interface", "by # an exception handler. We then only follow the exceptional # branches.", "(current) return value v = graph.getreturnvar() try: return self.binding(v) except KeyError: # the", "until none is left.\"\"\" while True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if not self.pendingblocks: break #", "'object'.\"\"\" if isinstance(variable, Constant): return type(variable.value) elif isinstance(variable, Variable): s_variable = variable.annotation if", "based on operations ______ def consider_op(self, op): # let's be careful about avoiding", "{}) else: knowntypedata = {} for link in exits: constraints = knowntypedata.get(link.exitcase, {})", "done is False] assert len(blocked_blocks) == len(self.blocked_blocks) text = format_blocked_annotation_error(self, self.blocked_blocks) #raise SystemExit()", "block of this graph has been analysed. callpositions = self.notify.setdefault(graph.returnblock, {}) if whence", "see processblock() below self.links_followed = {} # set of links that have ever", "= self.translator.graphs #all of them got_blocked_blocks = False in self.annotated.values() if got_blocked_blocks: for", "= 0 while i < len(block.operations): op = block.operations[i] with self.bookkeeper.at_position((graph, block, i)):", "not None: block.operations[i:i+1] = new_ops if not new_ops: continue new_ops[-1].result = op.result op", "def get_exception(self, operation): \"\"\" Return the annotation for all exceptions that `operation` may", "= True self.addpendingblock(graph, link.target, inputs_s) #___ creating the annotations based on operations ______", "s_out.const s_out = newcell if hasattr(s_out, 'knowntypedata'): renamed_knowntypedata = {} for value, constraints", "# self.flowin() can only issue calls to self.addpendingblock(). # The analysis of a", "e.opindex) except Exception as e: # hack for debug tools only if not", "'* processblock', block, cells self.annotated[block] = graph if block in self.blocked_blocks: del self.blocked_blocks[block]", "call # points to this func which triggers a reflow whenever the #", "\"\" if block: at = block.at() if at: blk = \" block\"+at opid=\"\"", "block) def complete(self): \"\"\"Process pending blocks until none is left.\"\"\" while True: self.complete_pending_blocks()", "# is known exits = block.exits if isinstance(block.exitswitch, Variable): s_exitswitch = self.binding(block.exitswitch) if", "block in self.added_blocks] newgraphs = dict.fromkeys(newgraphs) got_blocked_blocks = False in newgraphs else: newgraphs", "if s_exception == s_ImpossibleValue: break s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc = intersection(s_exception, s_case) if", "= renaming.get(v, []) for new_v in new_vs: renamed_knowntypedata[value][new_v] = s assert isinstance(s_out, annmodel.SomeBool)", "typeof, s_ImpossibleValue, SomeInstance, intersection, difference) from rpython.annotator.bookkeeper import Bookkeeper from rpython.rtyper.normalizecalls import perform_normalizations", "callback is a position else: callback() def follow_link(self, graph, link, constraints): assert not", "#___ convenience high-level interface __________________ def build_types(self, function, input_arg_types, complete_now=True, main_entry_point=False): \"\"\"Recursively build", "in exits if link.exitcase == s_exitswitch.const] if block.canraise: op = block.raising_op s_exception =", "can be in three states: # * block not in self.annotated: # never", "\"\"\" Return the annotation for all exceptions that `operation` may raise. \"\"\" can_only_throw", "if isinstance(variable, Constant): return type(variable.value) elif isinstance(variable, Variable): s_variable = variable.annotation if s_variable:", "# set of links that have ever been followed self.notify = {} #", "Merge the new 'cells' with each of the block's existing input # variables.", "= intersection(s_exception, s_case) if s_matching_exc != s_ImpossibleValue: self.follow_raise_link(graph, link, s_matching_exc) s_exception = difference(s_exception,", "this block is done for callback in self.notify[block]: if isinstance(callback, tuple): self.reflowfromposition(callback) #", "None: opid = \" op=%d\" % i return repr(graph) + blk + opid", "== nbarg # wrong number of args # register the entry point self.addpendinggraph(flowgraph,", "= {} # set of graphs not to annotate again self.blocked_blocks = {}", "i) raise else: # dead code removal: don't follow all exits if the", "= block.raising_op s_exception = self.get_exception(op) for link in exits: case = link.exitcase if", "= pair(s_out, s_constraint).improve() # ignore links that try to pass impossible values if", "is immediately caught by # an exception handler. We then only follow the", "except BlockedInference as e: self.annotated[block] = False # failed, hopefully temporarily self.blocked_blocks[block] =", "log.WARNING(\"%s\" % annmodel.unionof(s_value, s_old)) assert False arg.annotation = s_value def warning(self, msg, pos=None):", "[] for v in s_out.is_type_of: renamed_is_type_of += renaming[v] assert s_out.knowntype is type newcell", "blk = \" block\"+at opid=\"\" if i is not None: opid = \"", "new blocks self.simplify(block_subset=self.added_blocks) finally: self.policy, self.added_blocks = saved def build_graph_types(self, flowgraph, inputcells, complete_now=True):", "block): # Important: this is not called recursively. # self.flowin() can only issue", "self.notify = {} # {block: {positions-to-reflow-from-when-done}} self.fixed_graphs = {} # set of graphs", "self.added_blocks] newgraphs = dict.fromkeys(newgraphs) got_blocked_blocks = False in newgraphs else: newgraphs = self.translator.graphs", "pair(s_out, s_constraint).improve() # ignore links that try to pass impossible values if s_out", "= link.last_exc_value assert (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) assert v_last_exc_type and v_last_exc_value", "s_exception = self.get_exception(op) for link in exits: case = link.exitcase if case is", "False arg.annotation = s_value def warning(self, msg, pos=None): if pos is None: try:", "= link.exitcase if case is None: self.follow_link(graph, link, {}) continue if s_exception ==", "!= s_ImpossibleValue: self.follow_raise_link(graph, link, s_matching_exc) s_exception = difference(s_exception, s_case) else: if isinstance(block.exitswitch, Variable):", "SomeImpossibleValues # to enter an op; the latter can result in violations of", "get_exception(self, operation): \"\"\" Return the annotation for all exceptions that `operation` may raise.", "self.__class__.__name__)) ret[key] = {} return ret #___ convenience high-level interface __________________ def build_types(self,", "self.complete() return self.annotation(flowgraph.getreturnvar()) def gettype(self, variable): \"\"\"Return the known type of a control", "not self.annotated[block]: self.pendingblocks[block] = graph def complete_pending_blocks(self): while self.pendingblocks: block, graph = self.pendingblocks.popitem()", "= s_out.const s_out = newcell s_out.set_knowntypedata(renamed_knowntypedata) return s_out def whereami(self, position_key): graph, block,", "'added_blocks' is used by rpython.annlowlevel to # detect which are the new blocks", "addpendingblock(self, graph, block, cells): \"\"\"Register an entry point into block with the given", "except AttributeError: self.break_at = None self.op = op self.opindex = opindex def __repr__(self):", "warning(self, msg, pos=None): if pos is None: try: pos = self.bookkeeper.position_key except AttributeError:", "i = 0 while i < len(block.operations): op = block.operations[i] with self.bookkeeper.at_position((graph, block,", "v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out, v_input in zip(link.args, link.target.inputargs): if v_out", "dict 'added_blocks' is used by rpython.annlowlevel to # detect which are the new", "tag) # self.notify[graph.returnblock] is a dictionary of call # points to this func", "Variable, Constant, checkgraph from rpython.translator import simplify, transform from rpython.annotator import model as", "--- end of debugging information --- self.frozen = False if policy is None:", "= variable.annotation if s_variable: return s_variable.knowntype else: return object else: raise TypeError(\"Variable or", "isinstance(block.exitswitch, Variable): s_exitswitch = self.binding(block.exitswitch) if s_exitswitch.is_constant(): exits = [link for link in", "s_matching_exc = intersection(s_exception, s_case) if s_matching_exc != s_ImpossibleValue: self.follow_raise_link(graph, link, s_matching_exc) s_exception =", "position_key blk = \"\" if block: at = block.at() if at: blk =", "parent_index = whence tag = parent_block, parent_index self.translator.update_call_graph(parent_graph, graph, tag) # self.notify[graph.returnblock] is", "block can be in three states: # * block not in self.annotated: #", "AnnotatorPolicy() # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) graph, inputcells = self.get_call_parameters(function, args_s,", "self.blocked_blocks = {} # set of {blocked_block: (graph, index)} # --- the following", "import AnsiLogger from rpython.tool.pairtype import pair from rpython.tool.error import (format_blocked_annotation_error, gather_error, source_lines) from", "bindings for the input args of a block. assert len(block.inputargs) == len(inputcells) for", "prevpolicy def annotate_helper(self, function, args_s, policy=None): if policy is None: from rpython.annotator.policy import", "the given Variable or Constant.\" s_arg = self.annotation(arg) if s_arg is None: raise", "not self.frozen if block not in self.annotated: self.bindinputargs(graph, block, cells) else: self.mergeinputargs(graph, block,", "[self.typeannotation(t) for t in input_arg_types] # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) flowgraph,", "= op.transform(self) if new_ops is not None: block.operations[i:i+1] = new_ops if not new_ops:", "all exits if the exitswitch # is known exits = block.exits if isinstance(block.exitswitch,", "(s_value, s_old)) log.WARNING(\"%s\" % annmodel.unionof(s_value, s_old)) assert False arg.annotation = s_value def warning(self,", "function, args_s, policy): desc = self.bookkeeper.getdesc(function) prevpolicy = self.policy self.policy = policy self.bookkeeper.enter(None)", "exits: constraints = knowntypedata.get(link.exitcase, {}) self.follow_link(graph, link, constraints) if block in self.notify: #", "self.bookkeeper.enter(None) try: return desc.get_call_parameters(args_s) finally: self.bookkeeper.leave() self.policy = prevpolicy def annotate_helper(self, function, args_s,", "elif isinstance(arg, Constant): return self.bookkeeper.immutablevalue(arg.value) else: raise TypeError('Variable or Constant expected, got %r'", "can_only_throw is None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception): \"\"\"This exception signals", "have to consider all the operations in the block. # * self.annotated[block] ==", "self.policy = policy self.bookkeeper.enter(None) try: return desc.get_call_parameters(args_s) finally: self.bookkeeper.leave() self.policy = prevpolicy def", "s_variable = variable.annotation if s_variable: return s_variable.knowntype else: return object else: raise TypeError(\"Variable", "False # must re-flow self.blocked_blocks[block] = (graph, None) def bindinputargs(self, graph, block, inputcells):", "self.translator.config.translation.check_str_without_nul) graph, inputcells = self.get_call_parameters(function, args_s, policy) self.build_graph_types(graph, inputcells, complete_now=False) self.complete_helpers(policy) return graph", "'cells' with each of the block's existing input # variables. oldcells = [self.binding(a)", "in ('simple_call', 'call_args', 'next'): # XXX warning, keep the name of the call", "def get_call_parameters(self, function, args_s, policy): desc = self.bookkeeper.getdesc(function) prevpolicy = self.policy self.policy =", "complete_now=False) self.complete_helpers(policy) return graph def complete_helpers(self, policy): saved = self.policy, self.added_blocks self.policy =", "arg in op.args: if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise BlockedInference(self, op, -1) resultcell = op.consider(self)", "\" \"got %r\" % (variable,)) def getuserclassdefinitions(self): \"\"\"Return a list of ClassDefs.\"\"\" return", "self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) def follow_raise_link(self, graph, link, s_last_exc_value): v_last_exc_type =", "bookkeeper=None): import rpython.rtyper.extfuncregistry # has side effects if translator is None: # interface", "(some functions actually never do, they always raise exceptions) return s_ImpossibleValue def reflowfromposition(self,", "phases: calling # a graph that has already been rtyped. Safety-check the new", "self.annotated self.annotated[block] = False # must re-flow self.blocked_blocks[block] = (graph, None) def bindinputargs(self,", "v_last_exc_value if isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value, s_last_exc_value) if isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s =", "if ignore_link: return self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) def follow_raise_link(self, graph, link,", "block, inputcells): # Create the initial bindings for the input args of a", "None) -> SomeBool(const=False) ... # boom -- in the assert of setbinding() for", "partially annotated if op.result.annotation is None: break # ignore the unannotated part #___", "try: self.break_at = annotator.bookkeeper.position_key except AttributeError: self.break_at = None self.op = op self.opindex", "for annotator.bookkeeper _______ def recursivecall(self, graph, whence, inputcells): if isinstance(whence, tuple): parent_graph, parent_block,", "# set of graphs that have blocked blocks # --- end of debugging", "raise BlockedInference(self, op, -1) # the operation cannot succeed assert isinstance(resultcell, annmodel.SomeObject) assert", "to pass impossible values if s_out == s_ImpossibleValue: ignore_link = True s_out =", "flowgraph.startblock, inputcells) def addpendingblock(self, graph, block, cells): \"\"\"Register an entry point into block", "'__annotator_block'): setattr(e, '__annotator_block', block) raise # The dict 'added_blocks' is used by rpython.annlowlevel", "( self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s = self.get_call_parameters(function, args_s, policy) if main_entry_point: self.translator.entry_point_graph = flowgraph", "# more general results invariant: e.g. if SomeImpossibleValue enters is_ # is_(SomeImpossibleValue, None)", "tests from rpython.translator.translator import TranslationContext translator = TranslationContext() translator.annotator = self self.translator =", "inputcells) # recursively proceed until no more pending block is left if complete_now:", "intersection, difference) from rpython.annotator.bookkeeper import Bookkeeper from rpython.rtyper.normalizecalls import perform_normalizations log = AnsiLogger(\"annrpython\")", "number of args # register the entry point self.addpendinggraph(flowgraph, inputcells) # recursively proceed", "if not s_value.contains(s_old): log.WARNING(\"%s does not contain %s\" % (s_value, s_old)) log.WARNING(\"%s\" %", "temporarily self.blocked_blocks[block] = (graph, e.opindex) except Exception as e: # hack for debug", "while self.pendingblocks: block, graph = self.pendingblocks.popitem() self.processblock(graph, block) def complete(self): \"\"\"Process pending blocks", "= self.annotated.get(block) if graph: graphs[graph] = True for graph in graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint()", "ret.items(): if key not in attrs: assert type(value) is dict, ( \"%r is", "isinstance(function, types.FunctionType), \"fix that!\" from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # make", "getuserclassdefinitions(self): \"\"\"Return a list of ClassDefs.\"\"\" return self.bookkeeper.classdefs #___ medium-level interface ____________________________ def", "block, cells) if not self.annotated[block]: self.pendingblocks[block] = graph def complete_pending_blocks(self): while self.pendingblocks: block,", "= s_out.const s_out = newcell if hasattr(s_out, 'knowntypedata'): renamed_knowntypedata = {} for value,", "s assert isinstance(s_out, annmodel.SomeBool) newcell = annmodel.SomeBool() if s_out.is_constant(): newcell.const = s_out.const s_out", "= True def reflowpendingblock(self, graph, block): assert not self.frozen assert graph not in", "and that's it. # About 'next': see test_annotate_iter_empty_container(). return else: # other cases", "always raise an exception which is immediately caught by # an exception handler.", "pending block is left if complete_now: self.complete() return self.annotation(flowgraph.getreturnvar()) def gettype(self, variable): \"\"\"Return", "from rpython.annotator.model import ( typeof, s_ImpossibleValue, SomeInstance, intersection, difference) from rpython.annotator.bookkeeper import Bookkeeper", "(arg,)) def binding(self, arg): \"Gives the SomeValue corresponding to the given Variable or", "is a dictionary of call # points to this func which triggers a", "annotate the old # graph -- it's already low-level operations! for a, s_newarg", "isinstance(v_last_exc_type, Constant): s_out.const = v_last_exc_type.value elif v_last_exc_type.annotation.is_constant(): s_out.const = v_last_exc_type.annotation.const inputs_s.append(s_out) else: s_out", "assert isinstance(resultcell, annmodel.SomeObject) assert isinstance(op.result, Variable) self.setbinding(op.result, resultcell) # bind resultcell to op.result", "block_subset: graph = self.annotated.get(block) if graph: graphs[graph] = True for graph in graphs:", "= \"\"\"translator pendingblocks annotated links_followed notify bookkeeper frozen policy added_blocks\"\"\".split() ret = self.__dict__.copy()", "transform from rpython.annotator import model as annmodel, signature from rpython.annotator.model import ( typeof,", "if unions != oldcells: self.bindinputargs(graph, block, unions) def apply_renaming(self, s_out, renaming): if hasattr(s_out,", "= {} # set of {blocked_block: (graph, index)} # --- the following information", "i return repr(graph) + blk + opid def flowin(self, graph, block): try: i", "if can_only_throw is None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception): \"\"\"This exception", "= self.__dict__.copy() for key, value in ret.items(): if key not in attrs: assert", "isinstance(callback, tuple): self.reflowfromposition(callback) # callback is a position else: callback() def follow_link(self, graph,", "in violations of the # more general results invariant: e.g. if SomeImpossibleValue enters", "if s_out.is_constant(): newcell.const = s_out.const s_out = newcell if hasattr(s_out, 'knowntypedata'): renamed_knowntypedata =", "self.bookkeeper.at_position((graph, block, i)): new_ops = op.transform(self) if new_ops is not None: block.operations[i:i+1] =", "constraints = knowntypedata.get(link.exitcase, {}) self.follow_link(graph, link, constraints) if block in self.notify: # reflow", "signature.annotation(t, self.bookkeeper) def setbinding(self, arg, s_value): s_old = arg.annotation if s_old is not", "except KeyError: # the function didn't reach any return statement so far. #", "None: from rpython.annotator.policy import AnnotatorPolicy self.policy = AnnotatorPolicy() else: self.policy = policy if", "is recorded for debugging --- self.blocked_graphs = {} # set of graphs that", "link in block.exits if link.exitcase is not None] elif e.op.opname in ('simple_call', 'call_args',", "return type(variable.value) elif isinstance(variable, Variable): s_variable = variable.annotation if s_variable: return s_variable.knowntype else:", "format_blocked_annotation_error(self, self.blocked_blocks) #raise SystemExit() raise annmodel.AnnotatorError(text) for graph in newgraphs: v = graph.getreturnvar()", "[block for block, done in self.annotated.items() if done is False] assert len(blocked_blocks) ==", "return self.annotation(flowgraph.getreturnvar()) def gettype(self, variable): \"\"\"Return the known type of a control flow", "def complete(self): \"\"\"Process pending blocks until none is left.\"\"\" while True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self)", "variables of all graphs is annotated if self.added_blocks is not None: newgraphs =", "for v_out, v_input in zip(link.args, link.target.inputargs): if v_out == v_last_exc_type: s_out = typeof(renaming[v_last_exc_value])", "not self.break_at: break_at = \"?\" else: break_at = self.annotator.whereami(self.break_at) return \"<BlockedInference break_at %s", "def callback(): whence(self, graph) else: callback = whence callpositions[callback] = True # generalize", "(graph, e.opindex) except Exception as e: # hack for debug tools only if", "in attrs: assert type(value) is dict, ( \"%r is not dict. please update", "resultcell to op.result def get_exception(self, operation): \"\"\" Return the annotation for all exceptions", "self.get_exception(op) for link in exits: case = link.exitcase if case is None: self.follow_link(graph,", "op self.opindex = opindex def __repr__(self): if not self.break_at: break_at = \"?\" else:", "to enter an op; the latter can result in violations of the #", "defaulting to 'object'.\"\"\" if isinstance(variable, Constant): return type(variable.value) elif isinstance(variable, Variable): s_variable =", "block not in self.annotated: self.bindinputargs(graph, block, cells) else: self.mergeinputargs(graph, block, cells) if not", "__future__ import absolute_import import types from collections import defaultdict from rpython.tool.ansi_print import AnsiLogger", "exception which is immediately caught by # an exception handler. We then only", "does not contain %s\" % (s_value, s_old)) log.WARNING(\"%s\" % annmodel.unionof(s_value, s_old)) assert False", "left if complete_now: self.complete() return self.annotation(flowgraph.getreturnvar()) def gettype(self, variable): \"\"\"Return the known type", "'is_type_of'): renamed_is_type_of = [] for v in s_out.is_type_of: renamed_is_type_of += renaming[v] assert s_out.knowntype", "graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if block_subset is None: perform_normalizations(self) #___ flowing annotations in blocks", "the BlockedInference up to # processblock(). e.opindex = i raise except annmodel.HarmlesslyBlocked: return", "--- self.frozen = False if policy is None: from rpython.annotator.policy import AnnotatorPolicy self.policy", "Add source code to the UnionError e.source = '\\n'.join(source_lines(graph, block, None, long=True)) raise", "has side effects if translator is None: # interface for tests from rpython.translator.translator", "annmodel.SomeImpossibleValue): raise BlockedInference(self, op, -1) resultcell = op.consider(self) if resultcell is None: resultcell", "graph.startblock, inputcells) # get the (current) return value v = graph.getreturnvar() try: return", "t in input_arg_types] # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s =", "True self.addpendingblock(graph, link.target, inputs_s) def follow_raise_link(self, graph, link, s_last_exc_value): v_last_exc_type = link.last_exception v_last_exc_value", "\"\"\"This exception signals the type inference engine that the situation is currently blocked,", "that have blocked blocks # --- end of debugging information --- self.frozen =", "if block: at = block.at() if at: blk = \" block\"+at opid=\"\" if", "inference engine that the situation is currently blocked, and that it should try", "actually never do, they always raise exceptions) return s_ImpossibleValue def reflowfromposition(self, position_key): graph,", "graph, block, index = position_key self.reflowpendingblock(graph, block) def call_sites(self): newblocks = self.added_blocks if", "BlockedInference as e: self.annotated[block] = False # failed, hopefully temporarily self.blocked_blocks[block] = (graph,", "{block: graph-containing-it} self.annotated = {} # set of blocks already seen self.added_blocks =", "# note that UnionError is a subclass e.source = gather_error(self, graph, block, i)", "= opindex def __repr__(self): if not self.break_at: break_at = \"?\" else: break_at =", "all the operations in the block. # * self.annotated[block] == graph-containing-block: # analysis", "(graph, None) def mergeinputargs(self, graph, block, inputcells): # Merge the new 'cells' with", "= (graph, None) def bindinputargs(self, graph, block, inputcells): # Create the initial bindings", "import absolute_import import types from collections import defaultdict from rpython.tool.ansi_print import AnsiLogger from", "True self.addpendingblock(graph, link.target, inputs_s) #___ creating the annotations based on operations ______ def", "their type args_s = [self.typeannotation(t) for t in input_arg_types] # XXX hack annmodel.TLS.check_str_without_nul", "if hasattr(s_out, 'is_type_of'): renamed_is_type_of = [] for v in s_out.is_type_of: renamed_is_type_of += renaming[v]", "flowgraph, inputcells, complete_now=True): checkgraph(flowgraph) nbarg = len(flowgraph.getargs()) assert len(inputcells) == nbarg # wrong", "from rpython.annotator.policy import AnnotatorPolicy self.policy = AnnotatorPolicy() else: self.policy = policy if bookkeeper", "self.annotation(v_out) if v_out in constraints: s_constraint = constraints[v_out] s_out = pair(s_out, s_constraint).improve() #", "# other cases are problematic (but will hopefully be solved # later by", "self.annotated.items() if done is False] assert len(blocked_blocks) == len(self.blocked_blocks) text = format_blocked_annotation_error(self, self.blocked_blocks)", "the new blocks that annotating an additional # small helper creates. if self.added_blocks", "v = graph.getreturnvar() if v.annotation is None: self.setbinding(v, s_ImpossibleValue) def validate(self): \"\"\"Check that", "self.simplify(block_subset=self.added_blocks) finally: self.policy, self.added_blocks = saved def build_graph_types(self, flowgraph, inputcells, complete_now=True): checkgraph(flowgraph) nbarg", "graph if block in self.blocked_blocks: del self.blocked_blocks[block] try: self.flowin(graph, block) except BlockedInference as", "in link.args: s_out = self.annotation(v_out) if v_out in constraints: s_constraint = constraints[v_out] s_out", "in self.notify[block]: if isinstance(callback, tuple): self.reflowfromposition(callback) # callback is a position else: callback()", "that try to pass impossible values if s_out == s_ImpossibleValue: ignore_link = True", "if not self.pendingblocks: break # finished # make sure that the return variables", "v_out in constraints: s_constraint = constraints[v_out] s_out = pair(s_out, s_constraint).improve() # ignore links", "%r' % (arg,)) def binding(self, arg): \"Gives the SomeValue corresponding to the given", "msg, pos=None): if pos is None: try: pos = self.bookkeeper.position_key except AttributeError: pos", "issue calls to self.addpendingblock(). # The analysis of a block can be in", "% i return repr(graph) + blk + opid def flowin(self, graph, block): try:", "type args_s = [self.typeannotation(t) for t in input_arg_types] # XXX hack annmodel.TLS.check_str_without_nul =", "not called recursively. # self.flowin() can only issue calls to self.addpendingblock(). # The", "that have ever been followed self.notify = {} # {block: {positions-to-reflow-from-when-done}} self.fixed_graphs =", "assert len(inputcells) == nbarg # wrong number of args # register the entry", "link.exitcase is not None] elif e.op.opname in ('simple_call', 'call_args', 'next'): # XXX warning,", "inputs_s = [] renaming = defaultdict(list) for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input)", "is not called recursively. # self.flowin() can only issue calls to self.addpendingblock(). #", "not self.frozen assert graph not in self.fixed_graphs self.pendingblocks[block] = graph assert block in", "self.apply_renaming(s_out, renaming) inputs_s.append(s_out) if ignore_link: return self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) def", "return s_variable.knowntype else: return object else: raise TypeError(\"Variable or Constant instance expected, \"", "hasattr(e, '__annotator_block'): setattr(e, '__annotator_block', block) raise # The dict 'added_blocks' is used by", "= \"\" if block: at = block.at() if at: blk = \" block\"+at", "if block in self.notify: # reflow from certain positions when this block is", "bindings but we # still have to consider all the operations in the", "generalize the function's input arguments self.addpendingblock(graph, graph.startblock, inputcells) # get the (current) return", "in graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if block_subset is None: perform_normalizations(self) #___ flowing annotations in", "______ def consider_op(self, op): # let's be careful about avoiding propagated SomeImpossibleValues #", "self.get_call_parameters(function, args_s, policy) if main_entry_point: self.translator.entry_point_graph = flowgraph return self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now) def", "contain %s\" % (s_value, s_old)) log.WARNING(\"%s\" % annmodel.unionof(s_value, s_old)) assert False arg.annotation =", "of graphs not to annotate again self.blocked_blocks = {} # set of {blocked_block:", "# About 'next': see test_annotate_iter_empty_container(). return else: # other cases are problematic (but", "annotator.bookkeeper _______ def recursivecall(self, graph, whence, inputcells): if isinstance(whence, tuple): parent_graph, parent_block, parent_index", "annotation simplifications for the new blocks self.simplify(block_subset=self.added_blocks) finally: self.policy, self.added_blocks = saved def", "in input_arg_types] # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s = self.get_call_parameters(function,", "AnnotatorPolicy() # make input arguments and set their type args_s = [self.typeannotation(t) for", "can only issue calls to self.addpendingblock(). # The analysis of a block can", "annmodel.HarmlesslyBlocked: return except annmodel.AnnotatorError as e: # note that UnionError is a subclass", "== s_ImpossibleValue: ignore_link = True s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) if ignore_link: return", "% (arg,)) def binding(self, arg): \"Gives the SomeValue corresponding to the given Variable", "self.blocked_blocks[block] = (graph, None) def mergeinputargs(self, graph, block, inputcells): # Merge the new", "constraints: s_constraint = constraints[v_out] s_out = pair(s_out, s_constraint).improve() # ignore links that try", "graph def complete_pending_blocks(self): while self.pendingblocks: block, graph = self.pendingblocks.popitem() self.processblock(graph, block) def complete(self):", "got_blocked_blocks = False in self.annotated.values() if got_blocked_blocks: for graph in self.blocked_graphs.values(): self.blocked_graphs[graph] =", "all graphs is annotated if self.added_blocks is not None: newgraphs = [self.annotated[block] for", "not hasattr(e, '__annotator_block'): setattr(e, '__annotator_block', block) raise # The dict 'added_blocks' is used", "not self.pendingblocks: break # finished # make sure that the return variables of", "= [self.binding(a) for a in block.inputargs] try: unions = [annmodel.unionof(c1,c2) for c1, c2", "for v_out in link.args: s_out = self.annotation(v_out) if v_out in constraints: s_constraint =", "self.consider_op(op) i += 1 except BlockedInference as e: if e.op is block.raising_op: #", "for t in input_arg_types] # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s", "gettype(self, variable): \"\"\"Return the known type of a control flow graph variable, defaulting", "any return statement so far. # (some functions actually never do, they always", "self.blocked_blocks[block] try: self.flowin(graph, block) except BlockedInference as e: self.annotated[block] = False # failed,", "function, input_arg_types, complete_now=True, main_entry_point=False): \"\"\"Recursively build annotations about the specific entry point.\"\"\" assert", "blk + opid def flowin(self, graph, block): try: i = 0 while i", "# is_(SomeInstance(not None), None) -> SomeBool(const=False) ... # boom -- in the assert", "Constant, checkgraph from rpython.translator import simplify, transform from rpython.annotator import model as annmodel,", "newblocks = self.added_blocks if newblocks is None: newblocks = self.annotated # all of", "not None: opid = \" op=%d\" % i return repr(graph) + blk +", "extra_passes=extra_passes) if block_subset is None: graphs = self.translator.graphs else: graphs = {} for", "s in constraints.items(): new_vs = renaming.get(v, []) for new_v in new_vs: renamed_knowntypedata[value][new_v] =", "if not new_ops: continue new_ops[-1].result = op.result op = new_ops[0] self.consider_op(op) i +=", "ret = self.__dict__.copy() for key, value in ret.items(): if key not in attrs:", "if newblocks is None: newblocks = self.annotated # all of them for block", "Variable): s_variable = variable.annotation if s_variable: return s_variable.knowntype else: return object else: raise", "RPython. See description in doc/translation.txt.\"\"\" def __init__(self, translator=None, policy=None, bookkeeper=None): import rpython.rtyper.extfuncregistry #", "policy = AnnotatorPolicy() # make input arguments and set their type args_s =", "zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out, v_input in zip(link.args, link.target.inputargs): if v_out == v_last_exc_type:", "import perform_normalizations log = AnsiLogger(\"annrpython\") class RPythonAnnotator(object): \"\"\"Block annotator for RPython. See description", "#___ flowing annotations in blocks _____________________ def processblock(self, graph, block): # Important: this", "except annmodel.AnnotatorError as e: # note that UnionError is a subclass e.source =", "# a graph that has already been rtyped. Safety-check the new # annotations", "in self.blocked_graphs.values(): self.blocked_graphs[graph] = True blocked_blocks = [block for block, done in self.annotated.items()", "self.blocked_graphs.values(): self.blocked_graphs[graph] = True blocked_blocks = [block for block, done in self.annotated.items() if", "to # processblock(). e.opindex = i raise except annmodel.HarmlesslyBlocked: return except annmodel.AnnotatorError as", "import Variable, Constant, checkgraph from rpython.translator import simplify, transform from rpython.annotator import model", "each of the block's existing input # variables. oldcells = [self.binding(a) for a", "are the new blocks that annotating an additional # small helper creates. if", "of them for block in newblocks: for op in block.operations: if op.opname in", "follow_link(self, graph, link, constraints): assert not (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) ignore_link", "Constant): s_out.const = v_last_exc_type.value elif v_last_exc_type.annotation.is_constant(): s_out.const = v_last_exc_type.annotation.const inputs_s.append(s_out) else: s_out =", "None: from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # XXX hack annmodel.TLS.check_str_without_nul =", "import TranslationContext translator = TranslationContext() translator.annotator = self self.translator = translator self.pendingblocks =", "function, args_s, policy=None): if policy is None: from rpython.annotator.policy import AnnotatorPolicy policy =", "assert v_last_exc_type and v_last_exc_value if isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value, s_last_exc_value) if isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type,", "never seen the block. # * self.annotated[block] == False: # the input variables", "for graph in graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if block_subset is None: perform_normalizations(self) #___ flowing", "policy) self.build_graph_types(graph, inputcells, complete_now=False) self.complete_helpers(policy) return graph def complete_helpers(self, policy): saved = self.policy,", "of a control flow graph variable, defaulting to 'object'.\"\"\" if isinstance(variable, Constant): return", "raise # The dict 'added_blocks' is used by rpython.annlowlevel to # detect which", "is None: resultcell = s_ImpossibleValue elif resultcell == s_ImpossibleValue: raise BlockedInference(self, op, -1)", "is not dict. please update %s.__getstate__\" % (key, self.__class__.__name__)) ret[key] = {} return", "graph, block): try: i = 0 while i < len(block.operations): op = block.operations[i]", "= parent_block, parent_index self.translator.update_call_graph(parent_graph, graph, tag) # self.notify[graph.returnblock] is a dictionary of call", "= self self.translator = translator self.pendingblocks = {} # map {block: graph-containing-it} self.annotated", "processblock(self, graph, block): # Important: this is not called recursively. # self.flowin() can", "rtyped. Safety-check the new # annotations that are passed in, and don't annotate", "____________________________ def addpendinggraph(self, flowgraph, inputcells): self.addpendingblock(flowgraph, flowgraph.startblock, inputcells) def addpendingblock(self, graph, block, cells):", "careful about avoiding propagated SomeImpossibleValues # to enter an op; the latter can", "old # graph -- it's already low-level operations! for a, s_newarg in zip(block.inputargs,", "if isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value, s_last_exc_value) if isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s = []", "ignore the unannotated part #___ simplification (should be moved elsewhere?) _______ def simplify(self,", "link.exitcase if case is None: self.follow_link(graph, link, {}) continue if s_exception == s_ImpossibleValue:", "index)} # --- the following information is recorded for debugging --- self.blocked_graphs =", "unions = [annmodel.unionof(c1,c2) for c1, c2 in zip(oldcells,inputcells)] except annmodel.UnionError as e: #", "avoiding propagated SomeImpossibleValues # to enter an op; the latter can result in", "policy added_blocks\"\"\".split() ret = self.__dict__.copy() for key, value in ret.items(): if key not", "end of debugging information --- self.frozen = False if policy is None: from", "binding(self, arg): \"Gives the SomeValue corresponding to the given Variable or Constant.\" s_arg", "= AnnotatorPolicy() else: self.policy = policy if bookkeeper is None: bookkeeper = Bookkeeper(self)", "\"\"\"Block annotator for RPython. See description in doc/translation.txt.\"\"\" def __init__(self, translator=None, policy=None, bookkeeper=None):", "assert type(value) is dict, ( \"%r is not dict. please update %s.__getstate__\" %", "of the block have bindings but we # still have to consider all", "operations in the block. # * self.annotated[block] == graph-containing-block: # analysis done (at", "as e: # hack for debug tools only if not hasattr(e, '__annotator_block'): setattr(e,", "cells changed, we must redo the analysis if unions != oldcells: self.bindinputargs(graph, block,", "link, s_matching_exc) s_exception = difference(s_exception, s_case) else: if isinstance(block.exitswitch, Variable): knowntypedata = getattr(", "input variables). #print '* processblock', block, cells self.annotated[block] = graph if block in", "assert block in self.annotated self.annotated[block] = False # must re-flow self.blocked_blocks[block] = (graph,", "v_last_exc_type = link.last_exception v_last_exc_value = link.last_exc_value assert (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException))", "s_out.set_knowntypedata(renamed_knowntypedata) return s_out def whereami(self, position_key): graph, block, i = position_key blk =", "graph -- it's already low-level operations! for a, s_newarg in zip(block.inputargs, cells): s_oldarg", "again self.blocked_blocks = {} # set of {blocked_block: (graph, index)} # --- the", "if graph: graphs[graph] = True for graph in graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if block_subset", "# * block not in self.annotated: # never seen the block. # *", "block.operations: if op.opname in ('simple_call', 'call_args'): yield op # some blocks are partially", "block's existing input # variables. oldcells = [self.binding(a) for a in block.inputargs] try:", "self.annotated[block] = False # must re-flow self.blocked_blocks[block] = (graph, None) def bindinputargs(self, graph,", "import (format_blocked_annotation_error, gather_error, source_lines) from rpython.flowspace.model import Variable, Constant, checkgraph from rpython.translator import", "annotate_helper(self, function, args_s, policy=None): if policy is None: from rpython.annotator.policy import AnnotatorPolicy policy", "blocked_blocks = [block for block, done in self.annotated.items() if done is False] assert", "is currently blocked, and that it should try to progress elsewhere.\"\"\" def __init__(self,", "Important: this is not called recursively. # self.flowin() can only issue calls to", "if s_exitswitch.is_constant(): exits = [link for link in exits if link.exitcase == s_exitswitch.const]", "def mergeinputargs(self, graph, block, inputcells): # Merge the new 'cells' with each of", "# analysis done (at least until we find we must generalize the #", "if callable(whence): def callback(): whence(self, graph) else: callback = whence callpositions[callback] = True", "invariant: e.g. if SomeImpossibleValue enters is_ # is_(SomeImpossibleValue, None) -> SomeBool # is_(SomeInstance(not", "is fine to always raise an exception. We then # swallow the BlockedInference", "# failed, hopefully temporarily self.blocked_blocks[block] = (graph, e.opindex) except Exception as e: #", "be solved # later by reflowing). Throw the BlockedInference up to # processblock().", "self.annotator = annotator try: self.break_at = annotator.bookkeeper.position_key except AttributeError: self.break_at = None self.op", "graph, block, cells): \"\"\"Register an entry point into block with the given input", "the # return block of this graph has been analysed. callpositions = self.notify.setdefault(graph.returnblock,", "s_variable: return s_variable.knowntype else: return object else: raise TypeError(\"Variable or Constant instance expected,", "msg)) #___ interface for annotator.bookkeeper _______ def recursivecall(self, graph, whence, inputcells): if isinstance(whence,", "self.addpendingblock(). # The analysis of a block can be in three states: #", "# let's be careful about avoiding propagated SomeImpossibleValues # to enter an op;", "# finished # make sure that the return variables of all graphs is", "it is fine to always raise an exception. We then # swallow the", "def build_graph_types(self, flowgraph, inputcells, complete_now=True): checkgraph(flowgraph) nbarg = len(flowgraph.getargs()) assert len(inputcells) == nbarg", "is used by rpython.annlowlevel to # detect which are the new blocks that", "attrs = \"\"\"translator pendingblocks annotated links_followed notify bookkeeper frozen policy added_blocks\"\"\".split() ret =", "isinstance(block.exitswitch, Variable): knowntypedata = getattr( block.exitswitch.annotation, \"knowntypedata\", {}) else: knowntypedata = {} for", "this graph has been analysed. callpositions = self.notify.setdefault(graph.returnblock, {}) if whence is not", "= self.get_exception(op) for link in exits: case = link.exitcase if case is None:", "self.annotated: # never seen the block. # * self.annotated[block] == False: # the", "* block not in self.annotated: # never seen the block. # * self.annotated[block]", "given Variable or Constant.\" s_arg = self.annotation(arg) if s_arg is None: raise KeyError", "self.translator.entry_point_graph = flowgraph return self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now) def get_call_parameters(self, function, args_s, policy): desc", "whence tag = parent_block, parent_index self.translator.update_call_graph(parent_graph, graph, tag) # self.notify[graph.returnblock] is a dictionary", "they always raise exceptions) return s_ImpossibleValue def reflowfromposition(self, position_key): graph, block, index =", "set their type args_s = [self.typeannotation(t) for t in input_arg_types] # XXX hack", "typeof([v_last_exc_value])) inputs_s = [] renaming = defaultdict(list) for v_out, v_input in zip(link.args, link.target.inputargs):", "position_key self.reflowpendingblock(graph, block) def call_sites(self): newblocks = self.added_blocks if newblocks is None: newblocks", "'next': see test_annotate_iter_empty_container(). return else: # other cases are problematic (but will hopefully", "for annotating/rtyping in several phases: calling # a graph that has already been", "self.annotation(flowgraph.getreturnvar()) def gettype(self, variable): \"\"\"Return the known type of a control flow graph", "complete_now=complete_now) def get_call_parameters(self, function, args_s, policy): desc = self.bookkeeper.getdesc(function) prevpolicy = self.policy self.policy", "block_subset is None: graphs = self.translator.graphs else: graphs = {} for block in", "\"\"\"Process pending blocks until none is left.\"\"\" while True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if not", "complete_now=True, main_entry_point=False): \"\"\"Recursively build annotations about the specific entry point.\"\"\" assert isinstance(function, types.FunctionType),", "not (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) ignore_link = False inputs_s = []", "#raise SystemExit() raise annmodel.AnnotatorError(text) for graph in newgraphs: v = graph.getreturnvar() if v.annotation", "block in self.notify: # reflow from certain positions when this block is done", "for a in block.inputargs] try: unions = [annmodel.unionof(c1,c2) for c1, c2 in zip(oldcells,inputcells)]", "graph-containing-block: # analysis done (at least until we find we must generalize the", "newgraphs else: newgraphs = self.translator.graphs #all of them got_blocked_blocks = False in self.annotated.values()", "not dict. please update %s.__getstate__\" % (key, self.__class__.__name__)) ret[key] = {} return ret", "#___ medium-level interface ____________________________ def addpendinggraph(self, flowgraph, inputcells): self.addpendingblock(flowgraph, flowgraph.startblock, inputcells) def addpendingblock(self,", "of graphs that have blocked blocks # --- end of debugging information ---", "processblock(). e.opindex = i raise except annmodel.HarmlesslyBlocked: return except annmodel.AnnotatorError as e: #", "if policy is None: from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # XXX", "len(blocked_blocks) == len(self.blocked_blocks) text = format_blocked_annotation_error(self, self.blocked_blocks) #raise SystemExit() raise annmodel.AnnotatorError(text) for graph", "= [link for link in exits if link.exitcase == s_exitswitch.const] if block.canraise: op", "pos = self.whereami(pos) log.WARNING(\"%s/ %s\" % (pos, msg)) #___ interface for annotator.bookkeeper _______", "on operations ______ def consider_op(self, op): # let's be careful about avoiding propagated", "inputs_s.append(s_out) self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) #___ creating the annotations based on", "operations! for a, s_newarg in zip(block.inputargs, cells): s_oldarg = self.binding(a) assert annmodel.unionof(s_oldarg, s_newarg)", "def addpendinggraph(self, flowgraph, inputcells): self.addpendingblock(flowgraph, flowgraph.startblock, inputcells) def addpendingblock(self, graph, block, cells): \"\"\"Register", "[link for link in block.exits if link.exitcase is not None] elif e.op.opname in", "pos=None): if pos is None: try: pos = self.bookkeeper.position_key except AttributeError: pos =", "= [self.annotated[block] for block in self.added_blocks] newgraphs = dict.fromkeys(newgraphs) got_blocked_blocks = False in", "graph) else: callback = whence callpositions[callback] = True # generalize the function's input", "inputcells, complete_now=False) self.complete_helpers(policy) return graph def complete_helpers(self, policy): saved = self.policy, self.added_blocks self.policy", "def __getstate__(self): attrs = \"\"\"translator pendingblocks annotated links_followed notify bookkeeper frozen policy added_blocks\"\"\".split()", "s_ImpossibleValue) def validate(self): \"\"\"Check that the annotation results are valid\"\"\" self.bookkeeper.check_no_flags_on_instances() def annotation(self,", "is not None: opid = \" op=%d\" % i return repr(graph) + blk", "followed self.notify = {} # {block: {positions-to-reflow-from-when-done}} self.fixed_graphs = {} # set of", "got %r' % (arg,)) def binding(self, arg): \"Gives the SomeValue corresponding to the", "note that UnionError is a subclass e.source = gather_error(self, graph, block, i) raise", "# the input variables of the block have bindings but we # still", "# some blocks are partially annotated if op.result.annotation is None: break # ignore", "link.target, inputs_s) def follow_raise_link(self, graph, link, s_last_exc_value): v_last_exc_type = link.last_exception v_last_exc_value = link.last_exc_value", "seen self.added_blocks = None # see processblock() below self.links_followed = {} # set", "a graph that has already been rtyped. Safety-check the new # annotations that", "annmodel.SomeBool) newcell = annmodel.SomeBool() if s_out.is_constant(): newcell.const = s_out.const s_out = newcell s_out.set_knowntypedata(renamed_knowntypedata)", "assert isinstance(function, types.FunctionType), \"fix that!\" from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() #", "creating the annotations based on operations ______ def consider_op(self, op): # let's be", "s_constraint = constraints[v_out] s_out = pair(s_out, s_constraint).improve() # ignore links that try to", "them for block in newblocks: for op in block.operations: if op.opname in ('simple_call',", "the specific entry point.\"\"\" assert isinstance(function, types.FunctionType), \"fix that!\" from rpython.annotator.policy import AnnotatorPolicy", "-1) resultcell = op.consider(self) if resultcell is None: resultcell = s_ImpossibleValue elif resultcell", "= {} # set of blocks already seen self.added_blocks = None # see", "pair from rpython.tool.error import (format_blocked_annotation_error, gather_error, source_lines) from rpython.flowspace.model import Variable, Constant, checkgraph", "None) def bindinputargs(self, graph, block, inputcells): # Create the initial bindings for the", "types from collections import defaultdict from rpython.tool.ansi_print import AnsiLogger from rpython.tool.pairtype import pair", "tuple): parent_graph, parent_block, parent_index = whence tag = parent_block, parent_index self.translator.update_call_graph(parent_graph, graph, tag)", "blocked blocks # --- end of debugging information --- self.frozen = False if", "block.operations[i] with self.bookkeeper.at_position((graph, block, i)): new_ops = op.transform(self) if new_ops is not None:", "addpendinggraph(self, flowgraph, inputcells): self.addpendingblock(flowgraph, flowgraph.startblock, inputcells) def addpendingblock(self, graph, block, cells): \"\"\"Register an", "s_ImpossibleValue, SomeInstance, intersection, difference) from rpython.annotator.bookkeeper import Bookkeeper from rpython.rtyper.normalizecalls import perform_normalizations log", "policy is None: from rpython.annotator.policy import AnnotatorPolicy self.policy = AnnotatorPolicy() else: self.policy =", "used by rpython.annlowlevel to # detect which are the new blocks that annotating", "bookkeeper frozen policy added_blocks\"\"\".split() ret = self.__dict__.copy() for key, value in ret.items(): if", "= block.operations[i] with self.bookkeeper.at_position((graph, block, i)): new_ops = op.transform(self) if new_ops is not", "TypeError(\"Variable or Constant instance expected, \" \"got %r\" % (variable,)) def getuserclassdefinitions(self): \"\"\"Return", "apply_renaming(self, s_out, renaming): if hasattr(s_out, 'is_type_of'): renamed_is_type_of = [] for v in s_out.is_type_of:", "pass impossible values if s_out == s_ImpossibleValue: ignore_link = True s_out = self.apply_renaming(s_out,", "type of a control flow graph variable, defaulting to 'object'.\"\"\" if isinstance(variable, Constant):", "which is immediately caught by # an exception handler. We then only follow", "[] renaming = defaultdict(list) for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out,", "if the merged cells changed, we must redo the analysis if unions !=", "defaultdict from rpython.tool.ansi_print import AnsiLogger from rpython.tool.pairtype import pair from rpython.tool.error import (format_blocked_annotation_error,", "Return the annotation for all exceptions that `operation` may raise. \"\"\" can_only_throw =", "been followed self.notify = {} # {block: {positions-to-reflow-from-when-done}} self.fixed_graphs = {} # set", "input arguments and set their type args_s = [self.typeannotation(t) for t in input_arg_types]", "-> SomeBool(const=False) ... # boom -- in the assert of setbinding() for arg", "initial bindings for the input args of a block. assert len(block.inputargs) == len(inputcells)", "graph, block): # Important: this is not called recursively. # self.flowin() can only", "assert not (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) ignore_link = False inputs_s =", "handler. We then only follow the exceptional # branches. exits = [link for", "policy): desc = self.bookkeeper.getdesc(function) prevpolicy = self.policy self.policy = policy self.bookkeeper.enter(None) try: return", "!= '?': pos = self.whereami(pos) log.WARNING(\"%s/ %s\" % (pos, msg)) #___ interface for", "functions actually never do, they always raise exceptions) return s_ImpossibleValue def reflowfromposition(self, position_key):", "in the block. # * self.annotated[block] == graph-containing-block: # analysis done (at least", "annotations that are passed in, and don't annotate the old # graph --", "exception handler. We then only follow the exceptional # branches. exits = [link", "results are valid\"\"\" self.bookkeeper.check_no_flags_on_instances() def annotation(self, arg): \"Gives the SomeValue corresponding to the", "assert len(block.inputargs) == len(inputcells) for a, cell in zip(block.inputargs, inputcells): self.setbinding(a, cell) self.annotated[block]", "reflowpendingblock(self, graph, block): assert not self.frozen assert graph not in self.fixed_graphs self.pendingblocks[block] =", "self.binding(block.exitswitch) if s_exitswitch.is_constant(): exits = [link for link in exits if link.exitcase ==", "# see processblock() below self.links_followed = {} # set of links that have", "the block. # * self.annotated[block] == False: # the input variables of the", "callback(): whence(self, graph) else: callback = whence callpositions[callback] = True # generalize the", "def apply_renaming(self, s_out, renaming): if hasattr(s_out, 'is_type_of'): renamed_is_type_of = [] for v in", "# ignore links that try to pass impossible values if s_out == s_ImpossibleValue:", "rpython.annotator.bookkeeper import Bookkeeper from rpython.rtyper.normalizecalls import perform_normalizations log = AnsiLogger(\"annrpython\") class RPythonAnnotator(object): \"\"\"Block", "break_at = self.annotator.whereami(self.break_at) return \"<BlockedInference break_at %s [%s]>\" %(break_at, self.op) __str__ = __repr__", "annmodel.UnionError as e: # Add source code to the UnionError e.source = '\\n'.join(source_lines(graph,", "space. These are the operations for # which it is fine to always", "s_newarg in zip(block.inputargs, cells): s_oldarg = self.binding(a) assert annmodel.unionof(s_oldarg, s_newarg) == s_oldarg else:", "doc/translation.txt.\"\"\" def __init__(self, translator=None, policy=None, bookkeeper=None): import rpython.rtyper.extfuncregistry # has side effects if", "graph.getreturnvar() try: return self.binding(v) except KeyError: # the function didn't reach any return", "except annmodel.UnionError as e: # Add source code to the UnionError e.source =", "description in doc/translation.txt.\"\"\" def __init__(self, translator=None, policy=None, bookkeeper=None): import rpython.rtyper.extfuncregistry # has side", "+ blk + opid def flowin(self, graph, block): try: i = 0 while", "collections import defaultdict from rpython.tool.ansi_print import AnsiLogger from rpython.tool.pairtype import pair from rpython.tool.error", "must flowin. self.blocked_blocks[block] = (graph, None) def mergeinputargs(self, graph, block, inputcells): # Merge", "new_vs = renaming.get(v, []) for new_v in new_vs: renamed_knowntypedata[value][new_v] = s assert isinstance(s_out,", "dict. please update %s.__getstate__\" % (key, self.__class__.__name__)) ret[key] = {} return ret #___", "don't annotate the old # graph -- it's already low-level operations! for a,", "return s_out def whereami(self, position_key): graph, block, i = position_key blk = \"\"", "for key, value in ret.items(): if key not in attrs: assert type(value) is", "hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s = self.get_call_parameters(function, args_s, policy) if main_entry_point:", "s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) if ignore_link: return self.links_followed[link] = True self.addpendingblock(graph, link.target,", "as e: self.annotated[block] = False # failed, hopefully temporarily self.blocked_blocks[block] = (graph, e.opindex)", "del self.blocked_blocks[block] try: self.flowin(graph, block) except BlockedInference as e: self.annotated[block] = False #", "# The dict 'added_blocks' is used by rpython.annlowlevel to # detect which are", "bookkeeper is None: bookkeeper = Bookkeeper(self) self.bookkeeper = bookkeeper def __getstate__(self): attrs =", "These are the operations for # which it is fine to always raise", "object space. These are the operations for # which it is fine to", "reflow whenever the # return block of this graph has been analysed. callpositions", "block) def call_sites(self): newblocks = self.added_blocks if newblocks is None: newblocks = self.annotated", "renamed_knowntypedata[value][new_v] = s assert isinstance(s_out, annmodel.SomeBool) newcell = annmodel.SomeBool() if s_out.is_constant(): newcell.const =", "block.inputargs] try: unions = [annmodel.unionof(c1,c2) for c1, c2 in zip(oldcells,inputcells)] except annmodel.UnionError as", "reflow from certain positions when this block is done for callback in self.notify[block]:", "callpositions[callback] = True # generalize the function's input arguments self.addpendingblock(graph, graph.startblock, inputcells) #", "= self.bookkeeper.position_key except AttributeError: pos = '?' if pos != '?': pos =", "elif resultcell == s_ImpossibleValue: raise BlockedInference(self, op, -1) # the operation cannot succeed", "AnnotatorPolicy() else: self.policy = policy if bookkeeper is None: bookkeeper = Bookkeeper(self) self.bookkeeper", "None), None) -> SomeBool(const=False) ... # boom -- in the assert of setbinding()", "break_at = \"?\" else: break_at = self.annotator.whereami(self.break_at) return \"<BlockedInference break_at %s [%s]>\" %(break_at,", "is None: # interface for tests from rpython.translator.translator import TranslationContext translator = TranslationContext()", "please update %s.__getstate__\" % (key, self.__class__.__name__)) ret[key] = {} return ret #___ convenience", "def reflowfromposition(self, position_key): graph, block, index = position_key self.reflowpendingblock(graph, block) def call_sites(self): newblocks", "block_subset is None: perform_normalizations(self) #___ flowing annotations in blocks _____________________ def processblock(self, graph,", "are the operations for # which it is fine to always raise an", "existing input # variables. oldcells = [self.binding(a) for a in block.inputargs] try: unions", "a in block.inputargs] try: unions = [annmodel.unionof(c1,c2) for c1, c2 in zip(oldcells,inputcells)] except", "swallow the BlockedInference and that's it. # About 'next': see test_annotate_iter_empty_container(). return else:", "by rpython.annlowlevel to # detect which are the new blocks that annotating an", "e.source = gather_error(self, graph, block, i) raise else: # dead code removal: don't", "case is None: self.follow_link(graph, link, {}) continue if s_exception == s_ImpossibleValue: break s_case", "validate(self): \"\"\"Check that the annotation results are valid\"\"\" self.bookkeeper.check_no_flags_on_instances() def annotation(self, arg): \"Gives", "isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise BlockedInference(self, op, -1) resultcell = op.consider(self) if resultcell is None:", "rpython.translator.translator import TranslationContext translator = TranslationContext() translator.annotator = self self.translator = translator self.pendingblocks", "entry point.\"\"\" assert isinstance(function, types.FunctionType), \"fix that!\" from rpython.annotator.policy import AnnotatorPolicy policy =", "s_old = arg.annotation if s_old is not None: if not s_value.contains(s_old): log.WARNING(\"%s does", "several phases: calling # a graph that has already been rtyped. Safety-check the", "callback = whence callpositions[callback] = True # generalize the function's input arguments self.addpendingblock(graph,", "pos != '?': pos = self.whereami(pos) log.WARNING(\"%s/ %s\" % (pos, msg)) #___ interface", "of a block. assert len(block.inputargs) == len(inputcells) for a, cell in zip(block.inputargs, inputcells):", "types.FunctionType), \"fix that!\" from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # make input", "if isinstance(arg, Variable): return arg.annotation elif isinstance(arg, Constant): return self.bookkeeper.immutablevalue(arg.value) else: raise TypeError('Variable", "of the call operations in sync # with the flow object space. These", "unions != oldcells: self.bindinputargs(graph, block, unions) def apply_renaming(self, s_out, renaming): if hasattr(s_out, 'is_type_of'):", "else: newgraphs = self.translator.graphs #all of them got_blocked_blocks = False in self.annotated.values() if", "hasattr(s_out, 'is_type_of'): renamed_is_type_of = [] for v in s_out.is_type_of: renamed_is_type_of += renaming[v] assert", "See description in doc/translation.txt.\"\"\" def __init__(self, translator=None, policy=None, bookkeeper=None): import rpython.rtyper.extfuncregistry # has", "block.operations[i:i+1] = new_ops if not new_ops: continue new_ops[-1].result = op.result op = new_ops[0]", "hopefully temporarily self.blocked_blocks[block] = (graph, e.opindex) except Exception as e: # hack for", "following information is recorded for debugging --- self.blocked_graphs = {} # set of", "perform_normalizations log = AnsiLogger(\"annrpython\") class RPythonAnnotator(object): \"\"\"Block annotator for RPython. See description in", "= [annmodel.unionof(c1,c2) for c1, c2 in zip(oldcells,inputcells)] except annmodel.UnionError as e: # Add", "self.pendingblocks: break # finished # make sure that the return variables of all", "make input arguments and set their type args_s = [self.typeannotation(t) for t in", "XXX warning, keep the name of the call operations in sync # with", "set of links that have ever been followed self.notify = {} # {block:", "setattr(e, '__annotator_block', block) raise # The dict 'added_blocks' is used by rpython.annlowlevel to", "= prevpolicy def annotate_helper(self, function, args_s, policy=None): if policy is None: from rpython.annotator.policy", "AnnotatorPolicy policy = AnnotatorPolicy() # make input arguments and set their type args_s", "= Bookkeeper(self) self.bookkeeper = bookkeeper def __getstate__(self): attrs = \"\"\"translator pendingblocks annotated links_followed", "as e: if e.op is block.raising_op: # this is the case where the", "setbinding(self, arg, s_value): s_old = arg.annotation if s_old is not None: if not", "in exits: constraints = knowntypedata.get(link.exitcase, {}) self.follow_link(graph, link, constraints) if block in self.notify:", "variable.annotation if s_variable: return s_variable.knowntype else: return object else: raise TypeError(\"Variable or Constant", "of setbinding() for arg in op.args: if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise BlockedInference(self, op, -1)", "opindex def __repr__(self): if not self.break_at: break_at = \"?\" else: break_at = self.annotator.whereami(self.break_at)", "as annmodel, signature from rpython.annotator.model import ( typeof, s_ImpossibleValue, SomeInstance, intersection, difference) from", "graph variable, defaulting to 'object'.\"\"\" if isinstance(variable, Constant): return type(variable.value) elif isinstance(variable, Variable):", "graph, block, inputcells): # Merge the new 'cells' with each of the block's", "return self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now) def get_call_parameters(self, function, args_s, policy): desc = self.bookkeeper.getdesc(function) prevpolicy", "exits: case = link.exitcase if case is None: self.follow_link(graph, link, {}) continue if", "states: # * block not in self.annotated: # never seen the block. #", "expected, got %r' % (arg,)) def binding(self, arg): \"Gives the SomeValue corresponding to", "try: return self.binding(v) except KeyError: # the function didn't reach any return statement", "len(inputcells) == nbarg # wrong number of args # register the entry point", "= arg.annotation if s_old is not None: if not s_value.contains(s_old): log.WARNING(\"%s does not", "try: i = 0 while i < len(block.operations): op = block.operations[i] with self.bookkeeper.at_position((graph,", "translator self.pendingblocks = {} # map {block: graph-containing-it} self.annotated = {} # set", "helper creates. if self.added_blocks is not None: self.added_blocks[block] = True def reflowpendingblock(self, graph,", "for arg in op.args: if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise BlockedInference(self, op, -1) resultcell =", "the exitswitch # is known exits = block.exits if isinstance(block.exitswitch, Variable): s_exitswitch =", "hack for debug tools only if not hasattr(e, '__annotator_block'): setattr(e, '__annotator_block', block) raise", "len(self.blocked_blocks) text = format_blocked_annotation_error(self, self.blocked_blocks) #raise SystemExit() raise annmodel.AnnotatorError(text) for graph in newgraphs:", "# make sure that the return variables of all graphs is annotated if", "in zip(block.inputargs, inputcells): self.setbinding(a, cell) self.annotated[block] = False # must flowin. self.blocked_blocks[block] =", "= TranslationContext() translator.annotator = self self.translator = translator self.pendingblocks = {} # map", "resultcell is None: resultcell = s_ImpossibleValue elif resultcell == s_ImpossibleValue: raise BlockedInference(self, op,", "recursively. # self.flowin() can only issue calls to self.addpendingblock(). # The analysis of", "object else: raise TypeError(\"Variable or Constant instance expected, \" \"got %r\" % (variable,))", "recursivecall(self, graph, whence, inputcells): if isinstance(whence, tuple): parent_graph, parent_block, parent_index = whence tag", "annotator for RPython. See description in doc/translation.txt.\"\"\" def __init__(self, translator=None, policy=None, bookkeeper=None): import", "= op self.opindex = opindex def __repr__(self): if not self.break_at: break_at = \"?\"", "constraints.items(): new_vs = renaming.get(v, []) for new_v in new_vs: renamed_knowntypedata[value][new_v] = s assert", "s_out = self.annotation(v_out) s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) self.links_followed[link] = True self.addpendingblock(graph, link.target,", "else: callback = whence callpositions[callback] = True # generalize the function's input arguments", "if not self.annotated[block]: self.pendingblocks[block] = graph def complete_pending_blocks(self): while self.pendingblocks: block, graph =", "s_out def whereami(self, position_key): graph, block, i = position_key blk = \"\" if", "Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s = [] renaming = defaultdict(list) for v_out, v_input in", "# XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) graph, inputcells = self.get_call_parameters(function, args_s, policy)", "= \" op=%d\" % i return repr(graph) + blk + opid def flowin(self,", "s_out == s_ImpossibleValue: ignore_link = True s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) if ignore_link:", "s_out.const s_out = newcell s_out.set_knowntypedata(renamed_knowntypedata) return s_out def whereami(self, position_key): graph, block, i", "the block have bindings but we # still have to consider all the", "frozen policy added_blocks\"\"\".split() ret = self.__dict__.copy() for key, value in ret.items(): if key", "self.bindinputargs(graph, block, cells) else: self.mergeinputargs(graph, block, cells) if not self.annotated[block]: self.pendingblocks[block] = graph", "self.annotated = {} # set of blocks already seen self.added_blocks = None #", "tuple): self.reflowfromposition(callback) # callback is a position else: callback() def follow_link(self, graph, link,", "arg.annotation = s_value def warning(self, msg, pos=None): if pos is None: try: pos", "= whence tag = parent_block, parent_index self.translator.update_call_graph(parent_graph, graph, tag) # self.notify[graph.returnblock] is a", "Variable or Constant.\" if isinstance(arg, Variable): return arg.annotation elif isinstance(arg, Constant): return self.bookkeeper.immutablevalue(arg.value)", "= getattr( block.exitswitch.annotation, \"knowntypedata\", {}) else: knowntypedata = {} for link in exits:", "resultcell = s_ImpossibleValue elif resultcell == s_ImpossibleValue: raise BlockedInference(self, op, -1) # the", "raise except annmodel.HarmlesslyBlocked: return except annmodel.AnnotatorError as e: # note that UnionError is", "def typeannotation(self, t): return signature.annotation(t, self.bookkeeper) def setbinding(self, arg, s_value): s_old = arg.annotation", "if v.annotation is None: self.setbinding(v, s_ImpossibleValue) def validate(self): \"\"\"Check that the annotation results", "blocks self.simplify(block_subset=self.added_blocks) finally: self.policy, self.added_blocks = saved def build_graph_types(self, flowgraph, inputcells, complete_now=True): checkgraph(flowgraph)", "return self.binding(v) except KeyError: # the function didn't reach any return statement so", "currently blocked, and that it should try to progress elsewhere.\"\"\" def __init__(self, annotator,", "# make input arguments and set their type args_s = [self.typeannotation(t) for t", "len(inputcells) for a, cell in zip(block.inputargs, inputcells): self.setbinding(a, cell) self.annotated[block] = False #", "from rpython.annotator import model as annmodel, signature from rpython.annotator.model import ( typeof, s_ImpossibleValue,", "for graph in newgraphs: v = graph.getreturnvar() if v.annotation is None: self.setbinding(v, s_ImpossibleValue)", "can result in violations of the # more general results invariant: e.g. if", "in block.operations: if op.opname in ('simple_call', 'call_args'): yield op # some blocks are", "'?': pos = self.whereami(pos) log.WARNING(\"%s/ %s\" % (pos, msg)) #___ interface for annotator.bookkeeper", "the old # graph -- it's already low-level operations! for a, s_newarg in", "engine that the situation is currently blocked, and that it should try to", "block, done in self.annotated.items() if done is False] assert len(blocked_blocks) == len(self.blocked_blocks) text", "None: perform_normalizations(self) #___ flowing annotations in blocks _____________________ def processblock(self, graph, block): #", "in constraints: s_constraint = constraints[v_out] s_out = pair(s_out, s_constraint).improve() # ignore links that", "self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception): \"\"\"This exception signals the type inference engine that the situation", "blocks _____________________ def processblock(self, graph, block): # Important: this is not called recursively.", "annotations based on operations ______ def consider_op(self, op): # let's be careful about", "the function didn't reach any return statement so far. # (some functions actually", "return repr(graph) + blk + opid def flowin(self, graph, block): try: i =", "has been analysed. callpositions = self.notify.setdefault(graph.returnblock, {}) if whence is not None: if", "graphs[graph] = True for graph in graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if block_subset is None:", "e: # note that UnionError is a subclass e.source = gather_error(self, graph, block,", "# ignore the unannotated part #___ simplification (should be moved elsewhere?) _______ def", "if block_subset is None: graphs = self.translator.graphs else: graphs = {} for block", "def consider_op(self, op): # let's be careful about avoiding propagated SomeImpossibleValues # to", "[link for link in exits if link.exitcase == s_exitswitch.const] if block.canraise: op =", "import AnnotatorPolicy self.policy = AnnotatorPolicy() else: self.policy = policy if bookkeeper is None:", "else: assert not self.frozen if block not in self.annotated: self.bindinputargs(graph, block, cells) else:", "got_blocked_blocks: for graph in self.blocked_graphs.values(): self.blocked_graphs[graph] = True blocked_blocks = [block for block,", "is None: raise KeyError return s_arg def typeannotation(self, t): return signature.annotation(t, self.bookkeeper) def", "Create the initial bindings for the input args of a block. assert len(block.inputargs)", "annmodel.AnnotatorError(text) for graph in newgraphs: v = graph.getreturnvar() if v.annotation is None: self.setbinding(v,", "s_oldarg else: assert not self.frozen if block not in self.annotated: self.bindinputargs(graph, block, cells)", "log = AnsiLogger(\"annrpython\") class RPythonAnnotator(object): \"\"\"Block annotator for RPython. See description in doc/translation.txt.\"\"\"", "self.addpendingblock(graph, graph.startblock, inputcells) # get the (current) return value v = graph.getreturnvar() try:", "rpython.tool.ansi_print import AnsiLogger from rpython.tool.pairtype import pair from rpython.tool.error import (format_blocked_annotation_error, gather_error, source_lines)", "s_constraint).improve() # ignore links that try to pass impossible values if s_out ==", "from collections import defaultdict from rpython.tool.ansi_print import AnsiLogger from rpython.tool.pairtype import pair from", "{} # map {block: graph-containing-it} self.annotated = {} # set of blocks already", "isinstance(arg, Constant): return self.bookkeeper.immutablevalue(arg.value) else: raise TypeError('Variable or Constant expected, got %r' %", "three states: # * block not in self.annotated: # never seen the block.", "link, s_last_exc_value): v_last_exc_type = link.last_exception v_last_exc_value = link.last_exc_value assert (isinstance(link.exitcase, (types.ClassType, type)) and", "policy): saved = self.policy, self.added_blocks self.policy = policy try: self.added_blocks = {} self.complete()", "blk = \"\" if block: at = block.at() if at: blk = \"", "self.flowin(graph, block) except BlockedInference as e: self.annotated[block] = False # failed, hopefully temporarily", "(isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) assert v_last_exc_type and v_last_exc_value if isinstance(v_last_exc_value, Variable):", "cells) if not self.annotated[block]: self.pendingblocks[block] = graph def complete_pending_blocks(self): while self.pendingblocks: block, graph", "in block.exits if link.exitcase is not None] elif e.op.opname in ('simple_call', 'call_args', 'next'):", "= True s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) if ignore_link: return self.links_followed[link] = True", "# generalize the function's input arguments self.addpendingblock(graph, graph.startblock, inputcells) # get the (current)", "with self.bookkeeper.at_position((graph, block, i)): new_ops = op.transform(self) if new_ops is not None: block.operations[i:i+1]", "constraints): assert not (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) ignore_link = False inputs_s", "the call operations in sync # with the flow object space. These are", "unions) def apply_renaming(self, s_out, renaming): if hasattr(s_out, 'is_type_of'): renamed_is_type_of = [] for v", "import AnnotatorPolicy policy = AnnotatorPolicy() # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) graph,", "self.added_blocks is not None: newgraphs = [self.annotated[block] for block in self.added_blocks] newgraphs =", "# the operation cannot succeed assert isinstance(resultcell, annmodel.SomeObject) assert isinstance(op.result, Variable) self.setbinding(op.result, resultcell)", "\"?\" else: break_at = self.annotator.whereami(self.break_at) return \"<BlockedInference break_at %s [%s]>\" %(break_at, self.op) __str__", "complete_now=True): checkgraph(flowgraph) nbarg = len(flowgraph.getargs()) assert len(inputcells) == nbarg # wrong number of", "= graph.getreturnvar() try: return self.binding(v) except KeyError: # the function didn't reach any", "key not in attrs: assert type(value) is dict, ( \"%r is not dict.", "op.result.annotation is None: break # ignore the unannotated part #___ simplification (should be", "exits if the exitswitch # is known exits = block.exits if isinstance(block.exitswitch, Variable):", "= None self.op = op self.opindex = opindex def __repr__(self): if not self.break_at:", "control flow graph variable, defaulting to 'object'.\"\"\" if isinstance(variable, Constant): return type(variable.value) elif", "the annotation results are valid\"\"\" self.bookkeeper.check_no_flags_on_instances() def annotation(self, arg): \"Gives the SomeValue corresponding", "self.__dict__.copy() for key, value in ret.items(): if key not in attrs: assert type(value)", "interface for tests from rpython.translator.translator import TranslationContext translator = TranslationContext() translator.annotator = self", "whence(self, graph) else: callback = whence callpositions[callback] = True # generalize the function's", "merged cells changed, we must redo the analysis if unions != oldcells: self.bindinputargs(graph,", "i += 1 except BlockedInference as e: if e.op is block.raising_op: # this", "point into block with the given input cells.\"\"\" if graph in self.fixed_graphs: #", "[]) for new_v in new_vs: renamed_knowntypedata[value][new_v] = s assert isinstance(s_out, annmodel.SomeBool) newcell =", "in self.annotated.items() if done is False] assert len(blocked_blocks) == len(self.blocked_blocks) text = format_blocked_annotation_error(self,", "args # register the entry point self.addpendinggraph(flowgraph, inputcells) # recursively proceed until no", "(key, self.__class__.__name__)) ret[key] = {} return ret #___ convenience high-level interface __________________ def", "# with the flow object space. These are the operations for # which", "s_out = typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type, Constant): s_out.const = v_last_exc_type.value elif v_last_exc_type.annotation.is_constant(): s_out.const =", "when this block is done for callback in self.notify[block]: if isinstance(callback, tuple): self.reflowfromposition(callback)", "function's input arguments self.addpendingblock(graph, graph.startblock, inputcells) # get the (current) return value v", "TranslationContext translator = TranslationContext() translator.annotator = self self.translator = translator self.pendingblocks = {}", "impossible values if s_out == s_ImpossibleValue: ignore_link = True s_out = self.apply_renaming(s_out, renaming)", "self.added_blocks = None # see processblock() below self.links_followed = {} # set of", "in block_subset: graph = self.annotated.get(block) if graph: graphs[graph] = True for graph in", "not contain %s\" % (s_value, s_old)) log.WARNING(\"%s\" % annmodel.unionof(s_value, s_old)) assert False arg.annotation", "get the (current) return value v = graph.getreturnvar() try: return self.binding(v) except KeyError:", "renaming): if hasattr(s_out, 'is_type_of'): renamed_is_type_of = [] for v in s_out.is_type_of: renamed_is_type_of +=", "# set of {blocked_block: (graph, index)} # --- the following information is recorded", "{} # set of {blocked_block: (graph, index)} # --- the following information is", "cases are problematic (but will hopefully be solved # later by reflowing). Throw", "from rpython.tool.pairtype import pair from rpython.tool.error import (format_blocked_annotation_error, gather_error, source_lines) from rpython.flowspace.model import", "the given input cells.\"\"\" if graph in self.fixed_graphs: # special case for annotating/rtyping", "= link.last_exception v_last_exc_value = link.last_exc_value assert (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) assert", "--- self.blocked_graphs = {} # set of graphs that have blocked blocks #", "code removal: don't follow all exits if the exitswitch # is known exits", "= self.annotation(v_out) s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s)", "{} # set of blocks already seen self.added_blocks = None # see processblock()", "e.source = '\\n'.join(source_lines(graph, block, None, long=True)) raise # if the merged cells changed,", "pos = self.bookkeeper.position_key except AttributeError: pos = '?' if pos != '?': pos", "points to this func which triggers a reflow whenever the # return block", "== len(inputcells) for a, cell in zip(block.inputargs, inputcells): self.setbinding(a, cell) self.annotated[block] = False", "import defaultdict from rpython.tool.ansi_print import AnsiLogger from rpython.tool.pairtype import pair from rpython.tool.error import", "policy=None, bookkeeper=None): import rpython.rtyper.extfuncregistry # has side effects if translator is None: #" ]
[ "'type': '{object}'}, 'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem', 'type': 'bool'} } def __init__(self, contribution_id=None, height=None, inputs=None,", "inherited=None, is_contribution=None, label=None, order=None, overridden=None, visible=None): super(Group, self).__init__() self.contribution = contribution self.controls =", "state_category=None, url=None): super(WorkItemStateResultModel, self).__init__() self.color = color self.hidden = hidden self.id = id", "'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key':", "name=None, type=None, url=None): super(FieldModel, self).__init__() self.description = description self.id = id self.is_identity =", "'bool'} } def __init__(self, groups=None, id=None, overridden=None): super(Section, self).__init__() self.groups = groups self.id", "Gets and sets extensions list :type extensions: list of :class:`Extension <work-item-tracking.v4_0.models.Extension>` :param pages:", "{'key': 'overridden', 'type': 'bool'}, 'page_type': {'key': 'pageType', 'type': 'object'}, 'sections': {'key': 'sections', 'type':", "class WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel. :param behaviors: :type behaviors: list of :class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param class_:", "layout node is contribution are not. :type is_contribution: bool :param label: Label for", "'id', 'type': 'str'}, 'overridden': {'key': 'overridden', 'type': 'bool'} } def __init__(self, groups=None, id=None,", "'[WorkItemBehaviorField]'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'WorkItemBehaviorReference'}, 'name': {'key':", "self.groups = groups self.id = id self.overridden = overridden class UpdateProcessModel(Model): \"\"\"UpdateProcessModel. :param", "'type': 'str'}, 'version': {'key': 'version', 'type': 'str'} } def __init__(self, class_=None, is_default=None, is_enabled=None,", "for contribution inputs. :type inputs: dict :param show_on_deleted_work_item: A value indicating if the", "{'key': 'pageType', 'type': 'object'}, 'sections': {'key': 'sections', 'type': '[Section]'}, 'visible': {'key': 'visible', 'type':", "self.is_system = is_system class FormLayout(Model): \"\"\"FormLayout. :param extensions: Gets and sets extensions list", ":param description: :type description: str :param is_default: :type is_default: bool :param is_enabled: :type", "'str'}, 'icon': {'key': 'icon', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key':", "{'key': 'description', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_identity': {'key': 'isIdentity', 'type':", "description self.name = name self.parent_process_type_id = parent_process_type_id self.reference_name = reference_name class Extension(Model): \"\"\"Extension.", "{'key': 'id', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, id=None,", "str :param locked: A value indicating whether any user operations are permitted on", "\"\"\"WorkItemBehavior. :param abstract: :type abstract: bool :param color: :type color: str :param description:", "overridden by a child layout. :type overridden: bool \"\"\" _attribute_map = { 'groups':", "'system_controls': {'key': 'systemControls', 'type': '[Control]'} } def __init__(self, extensions=None, pages=None, system_controls=None): super(FormLayout, self).__init__()", "field=None, value=None): super(RuleConditionModel, self).__init__() self.condition_type = condition_type self.field = field self.value = value", "'overriden': {'key': 'overriden', 'type': 'bool'}, 'rank': {'key': 'rank', 'type': 'int'}, 'url': {'key': 'url',", "of :class:`Group <work-item-tracking.v4_0.models.Group>` :param id: The id for the layout node. :type id:", "{'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'page_type': {'key': 'pageType', 'type':", "= overridden self.visible = visible class Page(Model): \"\"\"Page. :param contribution: Contribution for the", "'bool'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'order': {'key':", "'name': {'key': 'name', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'state_category': {'key': 'stateCategory',", "self.conditions = conditions self.friendly_name = friendly_name self.id = id self.is_disabled = is_disabled self.is_system", "cause incorrect behavior and will be lost if the code is regenerated. #", "str :param type_id: :type type_id: str \"\"\" _attribute_map = { 'description': {'key': 'description',", "'description', 'type': 'str'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'},", "'bool'}, 'read_only': {'key': 'readOnly', 'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'}, 'watermark': {'key':", "the group. :type label: str :param order: Order in which the group should", "\"\"\" _attribute_map = { 'condition_type': {'key': 'conditionType', 'type': 'str'}, 'field': {'key': 'field', 'type':", "} def __init__(self, description=None, name=None, projects=None, properties=None, reference_name=None, type_id=None): super(ProcessModel, self).__init__() self.description =", "self).__init__() self.contribution = contribution self.id = id self.inherited = inherited self.is_contribution = is_contribution", "= inherited self.is_contribution = is_contribution self.label = label self.locked = locked self.order =", "id for the layout node. :type id: str :param overridden: A value indicating", "self.url = url class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param color: :type color: str :param hidden:", "name: :type name: str :param states: :type states: list of :class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param", "'overridden': {'key': 'overridden', 'type': 'bool'}, 'read_only': {'key': 'readOnly', 'type': 'bool'}, 'visible': {'key': 'visible',", "is_disabled: bool :param is_system: :type is_system: bool \"\"\" _attribute_map = { 'actions': {'key':", "= description self.name = name self.projects = projects self.properties = properties self.reference_name =", ":param is_system: :type is_system: bool \"\"\" _attribute_map = { 'actions': {'key': 'actions', 'type':", "} def __init__(self, groups=None, id=None, overridden=None): super(Section, self).__init__() self.groups = groups self.id =", "self.visible = visible class ProcessModel(Model): \"\"\"ProcessModel. :param description: :type description: str :param name:", "self.extensions = extensions self.pages = pages self.system_controls = system_controls class Group(Model): \"\"\"Group. :param", "id self.inherited = inherited self.is_contribution = is_contribution self.label = label self.order = order", ":param is_enabled: :type is_enabled: bool :param name: :type name: str \"\"\" _attribute_map =", "bool :param order: Order in which the page should appear in the layout.", "license information. # -------------------------------------------------------------------------------------------- # Generated file, DO NOT EDIT # Changes may", ":type overriden: bool :param rank: :type rank: int :param url: :type url: str", "id: str :param url: :type url: str \"\"\" _attribute_map = { 'id': {'key':", "str :param field: :type field: str :param value: :type value: str \"\"\" _attribute_map", "url: str \"\"\" _attribute_map = { 'behavior_field_id': {'key': 'behaviorFieldId', 'type': 'str'}, 'id': {'key':", "node has been overridden by a child layout. :type overridden: bool :param visible:", "'bool'}, 'is_contribution': {'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'locked': {'key':", "version=None): super(ProcessProperties, self).__init__() self.class_ = class_ self.is_default = is_default self.is_enabled = is_enabled self.parent_process_type_id", "order=None, state_category=None, url=None): super(WorkItemStateResultModel, self).__init__() self.color = color self.hidden = hidden self.id =", "label=None, order=None, overridden=None, visible=None): super(Group, self).__init__() self.contribution = contribution self.controls = controls self.height", "the layout. :type pages: list of :class:`Page <work-item-tracking.v4_0.models.Page>` :param system_controls: Headers controls of", "self.locked = locked self.order = order self.overridden = overridden self.page_type = page_type self.sections", ":type is_default: bool :param url: :type url: str \"\"\" _attribute_map = { 'behavior':", "state_category: :type state_category: str :param url: :type url: str \"\"\" _attribute_map = {", "order: int :param overridden: A value indicating whether this layout node has been", "'properties', 'type': 'ProcessProperties'}, 'reference_name': {'key': 'referenceName', 'type': 'str'}, 'type_id': {'key': 'typeId', 'type': 'str'}", "name: str :param overriden: :type overriden: bool :param rank: :type rank: int :param", ":type contribution_id: str :param height: The height for the contribution. :type height: int", "extensions=None, pages=None, system_controls=None): super(FormLayout, self).__init__() self.extensions = extensions self.pages = pages self.system_controls =", "fields=None, id=None, inherits=None, name=None, overriden=None, rank=None, url=None): super(WorkItemBehavior, self).__init__() self.abstract = abstract self.color", "{'key': 'behaviors', 'type': '[WorkItemTypeBehavior]'}, 'class_': {'key': 'class', 'type': 'object'}, 'color': {'key': 'color', 'type':", ":param pages: Top level tabs of the layout. :type pages: list of :class:`Page", "\"\"\" _attribute_map = { 'behavior_field_id': {'key': 'behaviorFieldId', 'type': 'str'}, 'id': {'key': 'id', 'type':", "'type': 'object'}, 'color': {'key': 'color', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'icon':", "'type': 'str'} } def __init__(self, behaviors=None, class_=None, color=None, description=None, icon=None, id=None, inherits=None, is_disabled=None,", "{'key': 'inherits', 'type': 'WorkItemBehaviorReference'}, 'name': {'key': 'name', 'type': 'str'}, 'overriden': {'key': 'overriden', 'type':", "url class FieldRuleModel(Model): \"\"\"FieldRuleModel. :param actions: :type actions: list of :class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>` :param", "'type': 'str'}, 'fields': {'key': 'fields', 'type': '[WorkItemBehaviorField]'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits':", "url: :type url: str \"\"\" _attribute_map = { 'id': {'key': 'id', 'type': 'str'},", "str :param is_identity: :type is_identity: bool :param name: :type name: str :param type:", ":param overriden: :type overriden: bool :param rank: :type rank: int :param url: :type", "class Extension(Model): \"\"\"Extension. :param id: :type id: str \"\"\" _attribute_map = { 'id':", "description self.id = id self.is_identity = is_identity self.name = name self.type = type", "'controlType', 'type': 'str'}, 'height': {'key': 'height', 'type': 'int'}, 'id': {'key': 'id', 'type': 'str'},", ":param properties: :type properties: :class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>` :param reference_name: :type reference_name: str :param type_id:", "self.id = id self.is_disabled = is_disabled self.is_system = is_system class FormLayout(Model): \"\"\"FormLayout. :param", "contribution_id: str :param height: The height for the contribution. :type height: int :param", "'[WorkItemStateResultModel]'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, behaviors=None, class_=None, color=None, description=None,", "class RuleActionModel(Model): \"\"\"RuleActionModel. :param action_type: :type action_type: str :param target_field: :type target_field: str", "'str'}, 'description': {'key': 'description', 'type': 'str'}, 'icon': {'key': 'icon', 'type': 'str'}, 'id': {'key':", "self.is_default = is_default self.is_enabled = is_enabled self.name = name class WitContribution(Model): \"\"\"WitContribution. :param", "'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'is_system':", "layout. :type overridden: bool :param visible: A value indicating if the group should", "self.is_default = is_default self.url = url class WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel. :param behaviors: :type behaviors:", "id=None, name=None, url=None): super(ProjectReference, self).__init__() self.description = description self.id = id self.name =", "description: str :param icon: :type icon: str :param id: :type id: str :param", "'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'name': {'key': 'name',", ":param color: :type color: str :param description: :type description: str :param icon: :type", "= behaviors self.class_ = class_ self.color = color self.description = description self.icon =", "'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, description=None, id=None, name=None, url=None):", "list of :class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param id: :type id: str :param inherits: :type inherits:", "= is_contribution self.label = label self.locked = locked self.order = order self.overridden =", "indicating whether any user operations are permitted on this page and the contents", "self.visible = visible self.watermark = watermark class CreateProcessModel(Model): \"\"\"CreateProcessModel. :param description: :type description:", "class_=None, is_default=None, is_enabled=None, parent_process_type_id=None, version=None): super(ProcessProperties, self).__init__() self.class_ = class_ self.is_default = is_default", "workItem. :type show_on_deleted_work_item: bool \"\"\" _attribute_map = { 'contribution_id': {'key': 'contributionId', 'type': 'str'},", "= inherits self.name = name self.overriden = overriden self.rank = rank self.url =", "'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'visible': {'key':", "'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'},", ":param behavior: :type behavior: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param is_default: :type is_default: bool :param url:", "locked: A value indicating whether any user operations are permitted on this page", "{'key': 'description', 'type': 'str'}, 'fields': {'key': 'fields', 'type': '[WorkItemBehaviorField]'}, 'id': {'key': 'id', 'type':", "node has been overridden by a child layout. :type overridden: bool :param read_only:", "is_disabled self.is_system = is_system class FormLayout(Model): \"\"\"FormLayout. :param extensions: Gets and sets extensions", "page_type: The icon for the page. :type page_type: object :param sections: The sections", "'pageType', 'type': 'object'}, 'sections': {'key': 'sections', 'type': '[Section]'}, 'visible': {'key': 'visible', 'type': 'bool'}", "str :param url: :type url: str \"\"\" _attribute_map = { 'id': {'key': 'id',", "} def __init__(self, description=None, id=None, is_identity=None, name=None, type=None, url=None): super(FieldModel, self).__init__() self.description =", "id self.url = url class WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference. :param id: :type id: str :param", "self.is_contribution = is_contribution self.label = label self.order = order self.overridden = overridden self.visible", ":param id: :type id: str :param name: :type name: str :param order: :type", "Group(Model): \"\"\"Group. :param contribution: Contribution for the group. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param", "str \"\"\" _attribute_map = { 'behavior_field_id': {'key': 'behaviorFieldId', 'type': 'str'}, 'id': {'key': 'id',", "str :param inherited: A value indicating whether this layout node has been inherited", "# Changes may cause incorrect behavior and will be lost if the code", "{'key': 'label', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type':", "{'key': 'isIdentity', 'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type':", "inputs=None, show_on_deleted_work_item=None): super(WitContribution, self).__init__() self.contribution_id = contribution_id self.height = height self.inputs = inputs", ":param is_contribution: A value indicating if the layout node is contribution or not.", "description: str :param id: :type id: str :param is_identity: :type is_identity: bool :param", "self).__init__() self.contribution = contribution self.controls = controls self.height = height self.id = id", "id for the layout node. :type id: str :param inherited: A value indicating", ":param order: :type order: int :param state_category: :type state_category: str :param url: :type", "'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'order': {'key': 'order',", "'bool'}, 'watermark': {'key': 'watermark', 'type': 'str'} } def __init__(self, contribution=None, control_type=None, height=None, id=None,", "self).__init__() self.behavior_field_id = behavior_field_id self.id = id self.url = url class WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference.", "<work-item-tracking.v4_0.models.RuleConditionModel>` :param friendly_name: :type friendly_name: str :param id: :type id: str :param is_disabled:", "url: :type url: str \"\"\" _attribute_map = { 'behavior_field_id': {'key': 'behaviorFieldId', 'type': 'str'},", "or not. :type visible: bool :param watermark: Watermark text for the textbox. :type", ":param id: :type id: str :param is_identity: :type is_identity: bool :param name: :type", "{'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'visible': {'key': 'visible', 'type':", "'inherits', 'type': 'WorkItemBehaviorReference'}, 'name': {'key': 'name', 'type': 'str'}, 'overriden': {'key': 'overriden', 'type': 'bool'},", "value class Section(Model): \"\"\"Section. :param groups: :type groups: list of :class:`Group <work-item-tracking.v4_0.models.Group>` :param", "self.friendly_name = friendly_name self.id = id self.is_disabled = is_disabled self.is_system = is_system class", "'str'}, 'value': {'key': 'value', 'type': 'str'} } def __init__(self, condition_type=None, field=None, value=None): super(RuleConditionModel,", ":type is_enabled: bool :param parent_process_type_id: :type parent_process_type_id: str :param version: :type version: str", "_attribute_map = { 'abstract': {'key': 'abstract', 'type': 'bool'}, 'color': {'key': 'color', 'type': 'str'},", ":type is_contribution: bool :param label: Label for the field :type label: str :param", "= description self.id = id self.is_identity = is_identity self.name = name self.type =", "{'key': 'label', 'type': 'str'}, 'locked': {'key': 'locked', 'type': 'bool'}, 'order': {'key': 'order', 'type':", "} def __init__(self, action_type=None, target_field=None, value=None): super(RuleActionModel, self).__init__() self.action_type = action_type self.target_field =", ":param inputs: A dictionary holding key value pairs for contribution inputs. :type inputs:", "for the page. :type page_type: object :param sections: The sections of the page.", ":type sections: list of :class:`Section <work-item-tracking.v4_0.models.Section>` :param visible: A value indicating if the", "list of :class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>` :param conditions: :type conditions: list of :class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>` :param", "project root for license information. # -------------------------------------------------------------------------------------------- # Generated file, DO NOT EDIT", "= behavior_field_id self.id = id self.url = url class WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference. :param id:", "label=None, metadata=None, order=None, overridden=None, read_only=None, visible=None, watermark=None): super(Control, self).__init__() self.contribution = contribution self.control_type", "{'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'object'}, 'url': {'key': 'url', 'type':", "{'key': 'visible', 'type': 'bool'}, 'watermark': {'key': 'watermark', 'type': 'str'} } def __init__(self, contribution=None,", "= hidden self.id = id self.name = name self.order = order self.state_category =", "'type': 'WorkItemBehaviorReference'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'url': {'key': 'url', 'type': 'str'} }", "rank self.url = url class WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField. :param behavior_field_id: :type behavior_field_id: str :param", "A value indicating whether any user operations are permitted on this page and", "'color', 'type': 'str'}, 'hidden': {'key': 'hidden', 'type': 'bool'}, 'id': {'key': 'id', 'type': 'str'},", "= url class WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference. :param id: :type id: str :param url: :type", ":type groups: list of :class:`Group <work-item-tracking.v4_0.models.Group>` :param id: The id for the layout", "{'key': 'inputs', 'type': '{object}'}, 'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem', 'type': 'bool'} } def __init__(self, contribution_id=None,", "of :class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param class_: :type class_: object :param color: :type color: str", "'contribution', 'type': 'WitContribution'}, 'control_type': {'key': 'controlType', 'type': 'str'}, 'height': {'key': 'height', 'type': 'int'},", "id=None, overridden=None): super(Section, self).__init__() self.groups = groups self.id = id self.overridden = overridden", "'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'layout': {'key': 'layout', 'type': 'FormLayout'}, 'name': {'key': 'name',", "= height self.id = id self.inherited = inherited self.is_contribution = is_contribution self.label =", "abstract: :type abstract: bool :param color: :type color: str :param description: :type description:", ":param fields: :type fields: list of :class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param id: :type id: str", "{ 'actions': {'key': 'actions', 'type': '[RuleActionModel]'}, 'conditions': {'key': 'conditions', 'type': '[RuleConditionModel]'}, 'friendly_name': {'key':", "self).__init__() self.id = id self.url = url class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param color: :type", "controls of the layout. :type system_controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` \"\"\" _attribute_map =", "name self.url = url class RuleActionModel(Model): \"\"\"RuleActionModel. :param action_type: :type action_type: str :param", "overridden: bool :param page_type: The icon for the page. :type page_type: object :param", "__init__(self, contribution=None, id=None, inherited=None, is_contribution=None, label=None, locked=None, order=None, overridden=None, page_type=None, sections=None, visible=None): super(Page,", "'type': 'str'} } def __init__(self, behavior=None, is_default=None, url=None): super(WorkItemTypeBehavior, self).__init__() self.behavior = behavior", "EDIT # Changes may cause incorrect behavior and will be lost if the", "_attribute_map = { 'id': {'key': 'id', 'type': 'str'} } def __init__(self, id=None): super(Extension,", "page. :type page_type: object :param sections: The sections of the page. :type sections:", "the contribution. :type height: int :param inputs: A dictionary holding key value pairs", "'type': 'str'}, 'height': {'key': 'height', 'type': 'int'}, 'inputs': {'key': 'inputs', 'type': '{object}'}, 'show_on_deleted_work_item':", "name: :type name: str :param overriden: :type overriden: bool :param rank: :type rank:", "layout: :class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>` :param name: :type name: str :param states: :type states: list", "_attribute_map = { 'action_type': {'key': 'actionType', 'type': 'str'}, 'target_field': {'key': 'targetField', 'type': 'str'},", ":param visible: A value indicating if the group should be hidden or not.", "= overriden self.rank = rank self.url = url class WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField. :param behavior_field_id:", "} def __init__(self, description=None, name=None, parent_process_type_id=None, reference_name=None): super(CreateProcessModel, self).__init__() self.description = description self.name", "self.is_contribution = is_contribution self.label = label self.metadata = metadata self.order = order self.overridden", "int :param overridden: A value indicating whether this layout node has been overridden", ":param is_enabled: :type is_enabled: bool :param parent_process_type_id: :type parent_process_type_id: str :param version: :type", "description=None, name=None, projects=None, properties=None, reference_name=None, type_id=None): super(ProcessModel, self).__init__() self.description = description self.name =", "layout. :type system_controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` \"\"\" _attribute_map = { 'extensions': {'key':", "and sets extensions list :type extensions: list of :class:`Extension <work-item-tracking.v4_0.models.Extension>` :param pages: Top", "'str'} } def __init__(self, class_=None, is_default=None, is_enabled=None, parent_process_type_id=None, version=None): super(ProcessProperties, self).__init__() self.class_ =", "'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'is_system': {'key':", ":type target_field: str :param value: :type value: str \"\"\" _attribute_map = { 'action_type':", "id=None, inherited=None, is_contribution=None, label=None, locked=None, order=None, overridden=None, page_type=None, sections=None, visible=None): super(Page, self).__init__() self.contribution", "'[ProjectReference]'}, 'properties': {'key': 'properties', 'type': 'ProcessProperties'}, 'reference_name': {'key': 'referenceName', 'type': 'str'}, 'type_id': {'key':", "sections self.visible = visible class ProcessModel(Model): \"\"\"ProcessModel. :param description: :type description: str :param", "int :param inputs: A dictionary holding key value pairs for contribution inputs. :type", "'str'}, 'states': {'key': 'states', 'type': '[WorkItemStateResultModel]'}, 'url': {'key': 'url', 'type': 'str'} } def", "'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'version': {'key':", "name: :type name: str :param parent_process_type_id: :type parent_process_type_id: str :param reference_name: :type reference_name:", "'bool'}, 'is_system': {'key': 'isSystem', 'type': 'bool'} } def __init__(self, actions=None, conditions=None, friendly_name=None, id=None,", "{'key': 'contribution', 'type': 'WitContribution'}, 'controls': {'key': 'controls', 'type': '[Control]'}, 'height': {'key': 'height', 'type':", "layout. This is expected to only be only set by the combiner. :type", "= properties self.reference_name = reference_name self.type_id = type_id class ProcessProperties(Model): \"\"\"ProcessProperties. :param class_:", "'visible': {'key': 'visible', 'type': 'bool'} } def __init__(self, contribution=None, id=None, inherited=None, is_contribution=None, label=None,", "'object'}, 'color': {'key': 'color', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'icon': {'key':", "{'key': 'id', 'type': 'str'}, 'is_identity': {'key': 'isIdentity', 'type': 'bool'}, 'name': {'key': 'name', 'type':", "ReferenceName that it inherits from :type inherits: str :param is_disabled: :type is_disabled: bool", "# Generated file, DO NOT EDIT # Changes may cause incorrect behavior and", "control is readonly. :type read_only: bool :param visible: A value indicating if the", ":param extensions: Gets and sets extensions list :type extensions: list of :class:`Extension <work-item-tracking.v4_0.models.Extension>`", "order: Order in which the page should appear in the layout. :type order:", "label: str :param metadata: Inner text of the control. :type metadata: str :param", "RuleActionModel(Model): \"\"\"RuleActionModel. :param action_type: :type action_type: str :param target_field: :type target_field: str :param", "reference_name: :type reference_name: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'},", "The height for the contribution. :type height: int :param id: The id for", ":type description: str :param fields: :type fields: list of :class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param id:", "'[RuleActionModel]'}, 'conditions': {'key': 'conditions', 'type': '[RuleConditionModel]'}, 'friendly_name': {'key': 'friendlyName', 'type': 'str'}, 'id': {'key':", "the contribution. :type height: int :param id: The id for the layout node.", "{'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'order': {'key': 'order', 'type':", "'bool'}, 'page_type': {'key': 'pageType', 'type': 'object'}, 'sections': {'key': 'sections', 'type': '[Section]'}, 'visible': {'key':", "order: Order in which the group should appear in the section. :type order:", "The sections of the page. :type sections: list of :class:`Section <work-item-tracking.v4_0.models.Section>` :param visible:", "self.is_identity = is_identity self.name = name self.type = type self.url = url class", ":type name: str :param projects: :type projects: list of :class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>` :param properties:", ":param url: :type url: str \"\"\" _attribute_map = { 'behavior': {'key': 'behavior', 'type':", "'label': {'key': 'label', 'type': 'str'}, 'locked': {'key': 'locked', 'type': 'bool'}, 'order': {'key': 'order',", "self.parent_process_type_id = parent_process_type_id self.version = version class ProjectReference(Model): \"\"\"ProjectReference. :param description: :type description:", "WitContribution(Model): \"\"\"WitContribution. :param contribution_id: The id for the contribution. :type contribution_id: str :param", "{'key': 'url', 'type': 'str'} } def __init__(self, description=None, id=None, is_identity=None, name=None, type=None, url=None):", "self.type_id = type_id class ProcessProperties(Model): \"\"\"ProcessProperties. :param class_: :type class_: object :param is_default:", "'int'}, 'inputs': {'key': 'inputs', 'type': '{object}'}, 'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem', 'type': 'bool'} } def", "{'key': 'contribution', 'type': 'WitContribution'}, 'control_type': {'key': 'controlType', 'type': 'str'}, 'height': {'key': 'height', 'type':", "fields: list of :class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param id: :type id: str :param inherits: :type", "class_ self.color = color self.description = description self.icon = icon self.id = id", "is_default: :type is_default: bool :param url: :type url: str \"\"\" _attribute_map = {", ":param value: :type value: str \"\"\" _attribute_map = { 'action_type': {'key': 'actionType', 'type':", "self.is_disabled = is_disabled self.layout = layout self.name = name self.states = states self.url", "super(WorkItemBehaviorReference, self).__init__() self.id = id self.url = url class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param color:", "is_disabled=None, layout=None, name=None, states=None, url=None): super(WorkItemTypeModel, self).__init__() self.behaviors = behaviors self.class_ = class_", "'color': {'key': 'color', 'type': 'str'}, 'hidden': {'key': 'hidden', 'type': 'bool'}, 'id': {'key': 'id',", "the page should appear in the layout. :type order: int :param overridden: A", ":param parent_process_type_id: :type parent_process_type_id: str :param reference_name: :type reference_name: str \"\"\" _attribute_map =", "self.order = order self.overridden = overridden self.page_type = page_type self.sections = sections self.visible", "{'key': 'type', 'type': 'object'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, description=None,", "def __init__(self, contribution_id=None, height=None, inputs=None, show_on_deleted_work_item=None): super(WitContribution, self).__init__() self.contribution_id = contribution_id self.height =", "self.url = url class WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior. :param behavior: :type behavior: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param", "color self.hidden = hidden self.id = id self.name = name self.order = order", ":param is_default: :type is_default: bool :param is_enabled: :type is_enabled: bool :param parent_process_type_id: :type", "} def __init__(self, extensions=None, pages=None, system_controls=None): super(FormLayout, self).__init__() self.extensions = extensions self.pages =", "lost if the code is regenerated. # -------------------------------------------------------------------------------------------- from msrest.serialization import Model class", "for the layout node. :type id: str :param inherited: A value indicating whether", "'bool'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'object'}, 'url': {'key':", "'conditions', 'type': '[RuleConditionModel]'}, 'friendly_name': {'key': 'friendlyName', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'},", "self.behavior_field_id = behavior_field_id self.id = id self.url = url class WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference. :param", "icon: :type icon: str :param id: :type id: str :param inherits: Parent WIT", "'referenceName', 'type': 'str'}, 'type_id': {'key': 'typeId', 'type': 'str'} } def __init__(self, description=None, name=None,", "class Page(Model): \"\"\"Page. :param contribution: Contribution for the page. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>`", ":type name: str :param url: :type url: str \"\"\" _attribute_map = { 'description':", "'type': 'str'}, 'inherited': {'key': 'inherited', 'type': 'bool'}, 'is_contribution': {'key': 'isContribution', 'type': 'bool'}, 'label':", "= rank self.url = url class WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField. :param behavior_field_id: :type behavior_field_id: str", "= target_field self.value = value class RuleConditionModel(Model): \"\"\"RuleConditionModel. :param condition_type: :type condition_type: str", "{'key': 'visible', 'type': 'bool'} } def __init__(self, contribution=None, id=None, inherited=None, is_contribution=None, label=None, locked=None,", "'action_type': {'key': 'actionType', 'type': 'str'}, 'target_field': {'key': 'targetField', 'type': 'str'}, 'value': {'key': 'value',", "id=None, name=None, order=None, state_category=None, url=None): super(WorkItemStateResultModel, self).__init__() self.color = color self.hidden = hidden", "{ 'description': {'key': 'description', 'type': 'str'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key':", "{ 'behaviors': {'key': 'behaviors', 'type': '[WorkItemTypeBehavior]'}, 'class_': {'key': 'class', 'type': 'object'}, 'color': {'key':", "self.is_enabled = is_enabled self.parent_process_type_id = parent_process_type_id self.version = version class ProjectReference(Model): \"\"\"ProjectReference. :param", "layout node. :type id: str :param inherited: A value indicating whether this layout", "_attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'is_default': {'key': 'isDefault', 'type': 'bool'},", "groups: list of :class:`Group <work-item-tracking.v4_0.models.Group>` :param id: The id for the layout node.", "is_identity: bool :param name: :type name: str :param type: :type type: object :param", "= is_disabled self.is_system = is_system class FormLayout(Model): \"\"\"FormLayout. :param extensions: Gets and sets", "'url', 'type': 'str'} } def __init__(self, behaviors=None, class_=None, color=None, description=None, icon=None, id=None, inherits=None,", "page. :type sections: list of :class:`Section <work-item-tracking.v4_0.models.Section>` :param visible: A value indicating if", "'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'url':", "'groups', 'type': '[Group]'}, 'id': {'key': 'id', 'type': 'str'}, 'overridden': {'key': 'overridden', 'type': 'bool'}", "{'key': 'metadata', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type':", ":type name: str :param overriden: :type overriden: bool :param rank: :type rank: int", "'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'metadata': {'key': 'metadata', 'type': 'str'}, 'order':", "self.url = url class WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField. :param behavior_field_id: :type behavior_field_id: str :param id:", ":type states: list of :class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param url: :type url: str \"\"\" _attribute_map", "{'key': 'controls', 'type': '[Control]'}, 'height': {'key': 'height', 'type': 'int'}, 'id': {'key': 'id', 'type':", ":type overridden: bool :param read_only: A value indicating if the control is readonly.", "'WitContribution'}, 'control_type': {'key': 'controlType', 'type': 'str'}, 'height': {'key': 'height', 'type': 'int'}, 'id': {'key':", "the layout. :type order: int :param overridden: A value indicating whether this layout", "which the group should appear in the section. :type order: int :param overridden:", "action_type: str :param target_field: :type target_field: str :param value: :type value: str \"\"\"", "name=None, parent_process_type_id=None, reference_name=None): super(CreateProcessModel, self).__init__() self.description = description self.name = name self.parent_process_type_id =", "self.contribution_id = contribution_id self.height = height self.inputs = inputs self.show_on_deleted_work_item = show_on_deleted_work_item class", ":type condition_type: str :param field: :type field: str :param value: :type value: str", "WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference. :param id: :type id: str :param url: :type url: str \"\"\"", "color=None, description=None, icon=None, id=None, inherits=None, is_disabled=None, layout=None, name=None, states=None, url=None): super(WorkItemTypeModel, self).__init__() self.behaviors", ":type layout: :class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>` :param name: :type name: str :param states: :type states:", ":type watermark: str \"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'control_type':", "__init__(self, contribution=None, control_type=None, height=None, id=None, inherited=None, is_contribution=None, label=None, metadata=None, order=None, overridden=None, read_only=None, visible=None,", "'type': 'bool'}, 'is_contribution': {'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'locked':", "= abstract self.color = color self.description = description self.fields = fields self.id =", "class UpdateProcessModel(Model): \"\"\"UpdateProcessModel. :param description: :type description: str :param is_default: :type is_default: bool", "{ 'behavior': {'key': 'behavior', 'type': 'WorkItemBehaviorReference'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'url': {'key':", "'type': 'bool'}, 'watermark': {'key': 'watermark', 'type': 'str'} } def __init__(self, contribution=None, control_type=None, height=None,", "'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'page_type': {'key': 'pageType', 'type': 'object'},", "'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'}, 'watermark': {'key': 'watermark', 'type': 'str'} }", "watermark: Watermark text for the textbox. :type watermark: str \"\"\" _attribute_map = {", "be only set by the combiner. :type inherited: bool :param is_contribution: A value", "'id', 'type': 'str'} } def __init__(self, id=None): super(Extension, self).__init__() self.id = id class", "layout. :type overridden: bool \"\"\" _attribute_map = { 'groups': {'key': 'groups', 'type': '[Group]'},", "<work-item-tracking.v4_0.models.WitContribution>` :param id: The id for the layout node. :type id: str :param", "See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # Generated", "'name', 'type': 'str'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'reference_name': {'key': 'referenceName', 'type': 'str'}", "'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, color=None, hidden=None, id=None,", "description: str :param name: :type name: str :param parent_process_type_id: :type parent_process_type_id: str :param", "url class WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField. :param behavior_field_id: :type behavior_field_id: str :param id: :type id:", "\"\"\"FieldModel. :param description: :type description: str :param id: :type id: str :param is_identity:", "name=None, url=None): super(ProjectReference, self).__init__() self.description = description self.id = id self.name = name", "str :param reference_name: :type reference_name: str \"\"\" _attribute_map = { 'description': {'key': 'description',", "'type': 'bool'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, behavior=None, is_default=None, url=None):", "the control. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param control_type: Type of the control. :type", "sections of the page. :type sections: list of :class:`Section <work-item-tracking.v4_0.models.Section>` :param visible: A", "metadata: str :param order: :type order: int :param overridden: A value indicating whether", "= contribution self.id = id self.inherited = inherited self.is_contribution = is_contribution self.label =", "bool :param is_enabled: :type is_enabled: bool :param name: :type name: str \"\"\" _attribute_map", ":param class_: :type class_: object :param is_default: :type is_default: bool :param is_enabled: :type", "'inherits', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'layout': {'key': 'layout', 'type': 'FormLayout'},", "'overridden', 'type': 'bool'}, 'page_type': {'key': 'pageType', 'type': 'object'}, 'sections': {'key': 'sections', 'type': '[Section]'},", "<work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param name: :type name: str :param overriden: :type overriden: bool :param rank:", "hidden: bool :param id: :type id: str :param name: :type name: str :param", "group. :type label: str :param order: Order in which the group should appear", "{'key': 'id', 'type': 'str'}, 'overridden': {'key': 'overridden', 'type': 'bool'} } def __init__(self, groups=None,", "'type': '[WorkItemTypeBehavior]'}, 'class_': {'key': 'class', 'type': 'object'}, 'color': {'key': 'color', 'type': 'str'}, 'description':", "= { 'condition_type': {'key': 'conditionType', 'type': 'str'}, 'field': {'key': 'field', 'type': 'str'}, 'value':", "{'key': 'inherited', 'type': 'bool'}, 'is_contribution': {'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type':", "dictionary holding key value pairs for contribution inputs. :type inputs: dict :param show_on_deleted_work_item:", "of the page. :type sections: list of :class:`Section <work-item-tracking.v4_0.models.Section>` :param visible: A value", ":type color: str :param description: :type description: str :param fields: :type fields: list", "{'key': 'overriden', 'type': 'bool'}, 'rank': {'key': 'rank', 'type': 'int'}, 'url': {'key': 'url', 'type':", "= { 'groups': {'key': 'groups', 'type': '[Group]'}, 'id': {'key': 'id', 'type': 'str'}, 'overridden':", "= friendly_name self.id = id self.is_disabled = is_disabled self.is_system = is_system class FormLayout(Model):", "self).__init__() self.description = description self.name = name self.projects = projects self.properties = properties", ":param read_only: A value indicating if the control is readonly. :type read_only: bool", "actions self.conditions = conditions self.friendly_name = friendly_name self.id = id self.is_disabled = is_disabled", "url=None): super(ProjectReference, self).__init__() self.description = description self.id = id self.name = name self.url", "the layout node is contribution or not. :type is_contribution: bool :param label: Label", ":type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param control_type: Type of the control. :type control_type: str", ":param description: :type description: str :param id: :type id: str :param name: :type", "= overridden self.read_only = read_only self.visible = visible self.watermark = watermark class CreateProcessModel(Model):", "str \"\"\" _attribute_map = { 'id': {'key': 'id', 'type': 'str'} } def __init__(self,", "msrest.serialization import Model class Control(Model): \"\"\"Control. :param contribution: Contribution for the control. :type", "{'key': 'showOnDeletedWorkItem', 'type': 'bool'} } def __init__(self, contribution_id=None, height=None, inputs=None, show_on_deleted_work_item=None): super(WitContribution, self).__init__()", "'description': {'key': 'description', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_identity': {'key': 'isIdentity',", "{'key': 'description', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'projects': {'key': 'projects', 'type':", "value pairs for contribution inputs. :type inputs: dict :param show_on_deleted_work_item: A value indicating", ":param inherited: A value indicating whether this layout node has been inherited from", "def __init__(self, description=None, name=None, projects=None, properties=None, reference_name=None, type_id=None): super(ProcessModel, self).__init__() self.description = description", "= reference_name class Extension(Model): \"\"\"Extension. :param id: :type id: str \"\"\" _attribute_map =", "is_disabled self.layout = layout self.name = name self.states = states self.url = url", ":type description: str :param id: :type id: str :param name: :type name: str", "label: Label for the field :type label: str :param metadata: Inner text of", "str :param name: :type name: str :param parent_process_type_id: :type parent_process_type_id: str :param reference_name:", "bool :param url: :type url: str \"\"\" _attribute_map = { 'behavior': {'key': 'behavior',", "{'key': 'isDefault', 'type': 'bool'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, behavior=None,", "is_identity self.name = name self.type = type self.url = url class FieldRuleModel(Model): \"\"\"FieldRuleModel.", "'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'},", "class WorkItemBehavior(Model): \"\"\"WorkItemBehavior. :param abstract: :type abstract: bool :param color: :type color: str", "'type': 'object'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'parent_process_type_id':", "icon self.id = id self.inherits = inherits self.is_disabled = is_disabled self.layout = layout", "'type': 'str'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'name':", "'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'page_type': {'key': 'pageType',", "from a parent layout. This is expected to only be only set by", "'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'layout': {'key': 'layout', 'type': 'FormLayout'}, 'name':", "= read_only self.visible = visible self.watermark = watermark class CreateProcessModel(Model): \"\"\"CreateProcessModel. :param description:", "'type': 'bool'} } def __init__(self, contribution=None, id=None, inherited=None, is_contribution=None, label=None, locked=None, order=None, overridden=None,", "{'key': 'controlType', 'type': 'str'}, 'height': {'key': 'height', 'type': 'int'}, 'id': {'key': 'id', 'type':", "root for license information. # -------------------------------------------------------------------------------------------- # Generated file, DO NOT EDIT #", "= type self.url = url class FieldRuleModel(Model): \"\"\"FieldRuleModel. :param actions: :type actions: list", "id: str :param name: :type name: str :param url: :type url: str \"\"\"", "self.reference_name = reference_name self.type_id = type_id class ProcessProperties(Model): \"\"\"ProcessProperties. :param class_: :type class_:", "class ProjectReference(Model): \"\"\"ProjectReference. :param description: :type description: str :param id: :type id: str", "type: object :param url: :type url: str \"\"\" _attribute_map = { 'description': {'key':", "self.order = order self.state_category = state_category self.url = url class WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior. :param", "contribution are not. :type is_contribution: bool :param label: The label for the page.", ":param description: :type description: str :param fields: :type fields: list of :class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>`", "} def __init__(self, color=None, hidden=None, id=None, name=None, order=None, state_category=None, url=None): super(WorkItemStateResultModel, self).__init__() self.color", "= id self.inherited = inherited self.is_contribution = is_contribution self.label = label self.order =", "'overridden': {'key': 'overridden', 'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'} } def __init__(self,", "rank: int :param url: :type url: str \"\"\" _attribute_map = { 'abstract': {'key':", "order=None, overridden=None, read_only=None, visible=None, watermark=None): super(Control, self).__init__() self.contribution = contribution self.control_type = control_type", "field: str :param value: :type value: str \"\"\" _attribute_map = { 'condition_type': {'key':", "{'key': 'name', 'type': 'str'}, 'projects': {'key': 'projects', 'type': '[ProjectReference]'}, 'properties': {'key': 'properties', 'type':", "str :param version: :type version: str \"\"\" _attribute_map = { 'class_': {'key': 'class',", "by a child layout. :type overridden: bool :param visible: A value indicating if", "'target_field': {'key': 'targetField', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'} } def __init__(self,", ":type value: str \"\"\" _attribute_map = { 'action_type': {'key': 'actionType', 'type': 'str'}, 'target_field':", "bool :param is_contribution: A value indicating if the layout node is contribution or", "id: :type id: str :param name: :type name: str :param url: :type url:", "{'key': 'overridden', 'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'} } def __init__(self, contribution=None,", "'state_category': {'key': 'stateCategory', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self,", "description=None, id=None, name=None, url=None): super(ProjectReference, self).__init__() self.description = description self.id = id self.name", "'overridden': {'key': 'overridden', 'type': 'bool'}, 'page_type': {'key': 'pageType', 'type': 'object'}, 'sections': {'key': 'sections',", "} def __init__(self, description=None, id=None, name=None, url=None): super(ProjectReference, self).__init__() self.description = description self.id", "def __init__(self, behavior=None, is_default=None, url=None): super(WorkItemTypeBehavior, self).__init__() self.behavior = behavior self.is_default = is_default", "bool :param rank: :type rank: int :param url: :type url: str \"\"\" _attribute_map", "'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} }", ":type id: str :param name: :type name: str :param order: :type order: int", "of the control, for html controls. :type height: int :param id: The id", "contribution_id=None, height=None, inputs=None, show_on_deleted_work_item=None): super(WitContribution, self).__init__() self.contribution_id = contribution_id self.height = height self.inputs", "Changes may cause incorrect behavior and will be lost if the code is", "the control, for html controls. :type height: int :param id: The id for", "\"\"\"RuleConditionModel. :param condition_type: :type condition_type: str :param field: :type field: str :param value:", ":param version: :type version: str \"\"\" _attribute_map = { 'class_': {'key': 'class', 'type':", "= visible self.watermark = watermark class CreateProcessModel(Model): \"\"\"CreateProcessModel. :param description: :type description: str", "str :param states: :type states: list of :class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param url: :type url:", "class WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField. :param behavior_field_id: :type behavior_field_id: str :param id: :type id: str", "if the layout node is contribution or not. :type is_contribution: bool :param label:", ":type id: str :param is_identity: :type is_identity: bool :param name: :type name: str", "control. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param control_type: Type of the control. :type control_type:", ":param contribution_id: The id for the contribution. :type contribution_id: str :param height: The", "'targetField', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'} } def __init__(self, action_type=None, target_field=None,", "'str'} } def __init__(self, description=None, name=None, parent_process_type_id=None, reference_name=None): super(CreateProcessModel, self).__init__() self.description = description", "'friendlyName', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'},", "name=None, overriden=None, rank=None, url=None): super(WorkItemBehavior, self).__init__() self.abstract = abstract self.color = color self.description", "def __init__(self, abstract=None, color=None, description=None, fields=None, id=None, inherits=None, name=None, overriden=None, rank=None, url=None): super(WorkItemBehavior,", "'url', 'type': 'str'} } def __init__(self, abstract=None, color=None, description=None, fields=None, id=None, inherits=None, name=None,", "_attribute_map = { 'color': {'key': 'color', 'type': 'str'}, 'hidden': {'key': 'hidden', 'type': 'bool'},", "'bool'}, 'visible': {'key': 'visible', 'type': 'bool'} } def __init__(self, contribution=None, controls=None, height=None, id=None,", "= visible class ProcessModel(Model): \"\"\"ProcessModel. :param description: :type description: str :param name: :type", "= { 'action_type': {'key': 'actionType', 'type': 'str'}, 'target_field': {'key': 'targetField', 'type': 'str'}, 'value':", "str :param name: :type name: str :param projects: :type projects: list of :class:`ProjectReference", "{'key': 'layout', 'type': 'FormLayout'}, 'name': {'key': 'name', 'type': 'str'}, 'states': {'key': 'states', 'type':", "'url': {'key': 'url', 'type': 'str'} } def __init__(self, id=None, url=None): super(WorkItemBehaviorReference, self).__init__() self.id", ":param description: :type description: str :param icon: :type icon: str :param id: :type", "= { 'behaviors': {'key': 'behaviors', 'type': '[WorkItemTypeBehavior]'}, 'class_': {'key': 'class', 'type': 'object'}, 'color':", "object :param sections: The sections of the page. :type sections: list of :class:`Section", "description: :type description: str :param name: :type name: str :param parent_process_type_id: :type parent_process_type_id:", ":param rank: :type rank: int :param url: :type url: str \"\"\" _attribute_map =", "of the layout. :type pages: list of :class:`Page <work-item-tracking.v4_0.models.Page>` :param system_controls: Headers controls", ":param name: :type name: str :param order: :type order: int :param state_category: :type", "{'key': 'typeId', 'type': 'str'} } def __init__(self, description=None, name=None, projects=None, properties=None, reference_name=None, type_id=None):", "'reference_name': {'key': 'referenceName', 'type': 'str'} } def __init__(self, description=None, name=None, parent_process_type_id=None, reference_name=None): super(CreateProcessModel,", "Inner text of the control. :type metadata: str :param order: :type order: int", "hidden self.id = id self.name = name self.order = order self.state_category = state_category", ":param friendly_name: :type friendly_name: str :param id: :type id: str :param is_disabled: :type", "value indicating if the control is readonly. :type read_only: bool :param visible: A", "self.sections = sections self.visible = visible class ProcessModel(Model): \"\"\"ProcessModel. :param description: :type description:", "self.watermark = watermark class CreateProcessModel(Model): \"\"\"CreateProcessModel. :param description: :type description: str :param name:", ":param type: :type type: object :param url: :type url: str \"\"\" _attribute_map =", "reference_name: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'name': {'key':", "label: The label for the page. :type label: str :param locked: A value", "bool \"\"\" _attribute_map = { 'contribution_id': {'key': 'contributionId', 'type': 'str'}, 'height': {'key': 'height',", "= actions self.conditions = conditions self.friendly_name = friendly_name self.id = id self.is_disabled =", "description: :type description: str :param fields: :type fields: list of :class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param", "'fields': {'key': 'fields', 'type': '[WorkItemBehaviorField]'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits',", "'str'} } def __init__(self, description=None, id=None, name=None, url=None): super(ProjectReference, self).__init__() self.description = description", "= projects self.properties = properties self.reference_name = reference_name self.type_id = type_id class ProcessProperties(Model):", "def __init__(self, behavior_field_id=None, id=None, url=None): super(WorkItemBehaviorField, self).__init__() self.behavior_field_id = behavior_field_id self.id = id", "page should be hidden or not. :type visible: bool \"\"\" _attribute_map = {", "'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'read_only': {'key': 'readOnly', 'type': 'bool'},", "= version class ProjectReference(Model): \"\"\"ProjectReference. :param description: :type description: str :param id: :type", "self.show_on_deleted_work_item = show_on_deleted_work_item class WorkItemBehavior(Model): \"\"\"WorkItemBehavior. :param abstract: :type abstract: bool :param color:", "'overridden': {'key': 'overridden', 'type': 'bool'} } def __init__(self, groups=None, id=None, overridden=None): super(Section, self).__init__()", "'type': 'str'} } def __init__(self, contribution=None, control_type=None, height=None, id=None, inherited=None, is_contribution=None, label=None, metadata=None,", "def __init__(self, description=None, id=None, name=None, url=None): super(ProjectReference, self).__init__() self.description = description self.id =", "is_contribution: bool :param label: Label for the group. :type label: str :param order:", "description: str :param fields: :type fields: list of :class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param id: :type", "is_disabled: :type is_disabled: bool :param is_system: :type is_system: bool \"\"\" _attribute_map = {", "inherited self.is_contribution = is_contribution self.label = label self.order = order self.overridden = overridden", ":param color: :type color: str :param hidden: :type hidden: bool :param id: :type", "= { 'actions': {'key': 'actions', 'type': '[RuleActionModel]'}, 'conditions': {'key': 'conditions', 'type': '[RuleConditionModel]'}, 'friendly_name':", "'inherits': {'key': 'inherits', 'type': 'WorkItemBehaviorReference'}, 'name': {'key': 'name', 'type': 'str'}, 'overriden': {'key': 'overriden',", ":class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>` :param reference_name: :type reference_name: str :param type_id: :type type_id: str \"\"\"", "type_id=None): super(ProcessModel, self).__init__() self.description = description self.name = name self.projects = projects self.properties", "'name': {'key': 'name', 'type': 'str'}, 'states': {'key': 'states', 'type': '[WorkItemStateResultModel]'}, 'url': {'key': 'url',", "abstract=None, color=None, description=None, fields=None, id=None, inherits=None, name=None, overriden=None, rank=None, url=None): super(WorkItemBehavior, self).__init__() self.abstract", "id: str :param url: :type url: str \"\"\" _attribute_map = { 'behavior_field_id': {'key':", "= contribution self.controls = controls self.height = height self.id = id self.inherited =", "properties: :type properties: :class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>` :param reference_name: :type reference_name: str :param type_id: :type", "# -------------------------------------------------------------------------------------------- # Generated file, DO NOT EDIT # Changes may cause incorrect", "name=None, order=None, state_category=None, url=None): super(WorkItemStateResultModel, self).__init__() self.color = color self.hidden = hidden self.id", "= label self.order = order self.overridden = overridden self.visible = visible class Page(Model):", "bool :param is_system: :type is_system: bool \"\"\" _attribute_map = { 'actions': {'key': 'actions',", "class WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference. :param id: :type id: str :param url: :type url: str", "str \"\"\" _attribute_map = { 'behaviors': {'key': 'behaviors', 'type': '[WorkItemTypeBehavior]'}, 'class_': {'key': 'class',", "child layout. :type overridden: bool :param read_only: A value indicating if the control", ":param height: The height for the contribution. :type height: int :param inputs: A", "'url': {'key': 'url', 'type': 'str'} } def __init__(self, color=None, hidden=None, id=None, name=None, order=None,", "list of :class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param url: :type url: str \"\"\" _attribute_map = {", ":type projects: list of :class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>` :param properties: :type properties: :class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>` :param", "self.id = id self.is_identity = is_identity self.name = name self.type = type self.url", "{'key': 'conditions', 'type': '[RuleConditionModel]'}, 'friendly_name': {'key': 'friendlyName', 'type': 'str'}, 'id': {'key': 'id', 'type':", "is expected to only be only set by the combiner. :type inherited: bool", "rights reserved. # Licensed under the MIT License. See License.txt in the project", "<work-item-tracking.v4_0.models.ProcessProperties>` :param reference_name: :type reference_name: str :param type_id: :type type_id: str \"\"\" _attribute_map", ":param label: Label for the group. :type label: str :param order: Order in", "self.label = label self.order = order self.overridden = overridden self.visible = visible class", "'type': 'WitContribution'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key': 'inherited', 'type': 'bool'}, 'is_contribution':", "{'key': 'projects', 'type': '[ProjectReference]'}, 'properties': {'key': 'properties', 'type': 'ProcessProperties'}, 'reference_name': {'key': 'referenceName', 'type':", "{ 'contribution_id': {'key': 'contributionId', 'type': 'str'}, 'height': {'key': 'height', 'type': 'int'}, 'inputs': {'key':", "{'key': 'watermark', 'type': 'str'} } def __init__(self, contribution=None, control_type=None, height=None, id=None, inherited=None, is_contribution=None,", "'type': 'bool'}, 'layout': {'key': 'layout', 'type': 'FormLayout'}, 'name': {'key': 'name', 'type': 'str'}, 'states':", ":type reference_name: str :param type_id: :type type_id: str \"\"\" _attribute_map = { 'description':", "= is_system class FormLayout(Model): \"\"\"FormLayout. :param extensions: Gets and sets extensions list :type", "show_on_deleted_work_item=None): super(WitContribution, self).__init__() self.contribution_id = contribution_id self.height = height self.inputs = inputs self.show_on_deleted_work_item", "name self.overriden = overriden self.rank = rank self.url = url class WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField.", "overridden=None, visible=None): super(Group, self).__init__() self.contribution = contribution self.controls = controls self.height = height", "projects: :type projects: list of :class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>` :param properties: :type properties: :class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>`", ":class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param name: :type name: str :param overriden: :type overriden: bool :param", "layout node is contribution or not. :type is_contribution: bool :param label: Label for", "{'key': 'name', 'type': 'str'}, 'overriden': {'key': 'overriden', 'type': 'bool'}, 'rank': {'key': 'rank', 'type':", "'str'} } def __init__(self, description=None, id=None, is_identity=None, name=None, type=None, url=None): super(FieldModel, self).__init__() self.description", "ProcessModel(Model): \"\"\"ProcessModel. :param description: :type description: str :param name: :type name: str :param", "class Section(Model): \"\"\"Section. :param groups: :type groups: list of :class:`Group <work-item-tracking.v4_0.models.Group>` :param id:", "str :param height: Height of the control, for html controls. :type height: int", "'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'object'}, 'url': {'key': 'url',", "bool :param is_enabled: :type is_enabled: bool :param parent_process_type_id: :type parent_process_type_id: str :param version:", "Generated file, DO NOT EDIT # Changes may cause incorrect behavior and will", "contribution inputs. :type inputs: dict :param show_on_deleted_work_item: A value indicating if the contribution", "'type': {'key': 'type', 'type': 'object'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self,", "whether any user operations are permitted on this page and the contents of", "value indicating if the page should be hidden or not. :type visible: bool", "url=None): super(FieldModel, self).__init__() self.description = description self.id = id self.is_identity = is_identity self.name", "'id', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'is_system': {'key': 'isSystem', 'type': 'bool'}", "class_: :type class_: object :param is_default: :type is_default: bool :param is_enabled: :type is_enabled:", "'type': 'object'}, 'sections': {'key': 'sections', 'type': '[Section]'}, 'visible': {'key': 'visible', 'type': 'bool'} }", "'label': {'key': 'label', 'type': 'str'}, 'metadata': {'key': 'metadata', 'type': 'str'}, 'order': {'key': 'order',", "is_enabled self.parent_process_type_id = parent_process_type_id self.version = version class ProjectReference(Model): \"\"\"ProjectReference. :param description: :type", "str :param description: :type description: str :param icon: :type icon: str :param id:", "the contribution. :type contribution_id: str :param height: The height for the contribution. :type", "'type': 'int'}, 'inputs': {'key': 'inputs', 'type': '{object}'}, 'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem', 'type': 'bool'} }", "{'key': 'color', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'icon': {'key': 'icon', 'type':", "if the layout node is contribution are not. :type is_contribution: bool :param label:", "id: str :param inherited: A value indicating whether this layout node has been", "= is_enabled self.name = name class WitContribution(Model): \"\"\"WitContribution. :param contribution_id: The id for", "str \"\"\" _attribute_map = { 'abstract': {'key': 'abstract', 'type': 'bool'}, 'color': {'key': 'color',", "'reference_name': {'key': 'referenceName', 'type': 'str'}, 'type_id': {'key': 'typeId', 'type': 'str'} } def __init__(self,", "self.color = color self.description = description self.icon = icon self.id = id self.inherits", "node is contribution are not. :type is_contribution: bool :param label: The label for", "= { 'description': {'key': 'description', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'projects':", "def __init__(self, extensions=None, pages=None, system_controls=None): super(FormLayout, self).__init__() self.extensions = extensions self.pages = pages", "str :param url: :type url: str \"\"\" _attribute_map = { 'description': {'key': 'description',", "'parentProcessTypeId', 'type': 'str'}, 'reference_name': {'key': 'referenceName', 'type': 'str'} } def __init__(self, description=None, name=None,", "id: :type id: str :param is_disabled: :type is_disabled: bool :param is_system: :type is_system:", ":type read_only: bool :param visible: A value indicating if the control should be", ":type url: str \"\"\" _attribute_map = { 'abstract': {'key': 'abstract', 'type': 'bool'}, 'color':", "\"\"\"WorkItemBehaviorField. :param behavior_field_id: :type behavior_field_id: str :param id: :type id: str :param url:", ":type is_system: bool \"\"\" _attribute_map = { 'actions': {'key': 'actions', 'type': '[RuleActionModel]'}, 'conditions':", "text for the textbox. :type watermark: str \"\"\" _attribute_map = { 'contribution': {'key':", "appear in the layout. :type order: int :param overridden: A value indicating whether", "self.overridden = overridden class UpdateProcessModel(Model): \"\"\"UpdateProcessModel. :param description: :type description: str :param is_default:", "'name': {'key': 'name', 'type': 'str'} } def __init__(self, description=None, is_default=None, is_enabled=None, name=None): super(UpdateProcessModel,", "{ 'abstract': {'key': 'abstract', 'type': 'bool'}, 'color': {'key': 'color', 'type': 'str'}, 'description': {'key':", "'bool'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'version': {'key': 'version', 'type': 'str'} } def", "The label for the page. :type label: str :param locked: A value indicating", "description=None, is_default=None, is_enabled=None, name=None): super(UpdateProcessModel, self).__init__() self.description = description self.is_default = is_default self.is_enabled", "'description', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'projects': {'key': 'projects', 'type': '[ProjectReference]'},", "'str'}, 'metadata': {'key': 'metadata', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key':", "'bool'}, 'color': {'key': 'color', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'fields': {'key':", ":class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>` :param name: :type name: str :param states: :type states: list of", "description=None, icon=None, id=None, inherits=None, is_disabled=None, layout=None, name=None, states=None, url=None): super(WorkItemTypeModel, self).__init__() self.behaviors =", "'isDisabled', 'type': 'bool'}, 'is_system': {'key': 'isSystem', 'type': 'bool'} } def __init__(self, actions=None, conditions=None,", "'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'} }", "'height', 'type': 'int'}, 'inputs': {'key': 'inputs', 'type': '{object}'}, 'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem', 'type': 'bool'}", ":param id: :type id: str :param is_disabled: :type is_disabled: bool :param is_system: :type", "self.type = type self.url = url class FieldRuleModel(Model): \"\"\"FieldRuleModel. :param actions: :type actions:", "CreateProcessModel(Model): \"\"\"CreateProcessModel. :param description: :type description: str :param name: :type name: str :param", "visible=None): super(Group, self).__init__() self.contribution = contribution self.controls = controls self.height = height self.id", "contribution=None, id=None, inherited=None, is_contribution=None, label=None, locked=None, order=None, overridden=None, page_type=None, sections=None, visible=None): super(Page, self).__init__()", ":param label: Label for the field :type label: str :param metadata: Inner text", "projects: list of :class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>` :param properties: :type properties: :class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>` :param reference_name:", "locked=None, order=None, overridden=None, page_type=None, sections=None, visible=None): super(Page, self).__init__() self.contribution = contribution self.id =", "= state_category self.url = url class WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior. :param behavior: :type behavior: :class:`WorkItemBehaviorReference", "str :param id: :type id: str :param is_identity: :type is_identity: bool :param name:", "'pages': {'key': 'pages', 'type': '[Page]'}, 'system_controls': {'key': 'systemControls', 'type': '[Control]'} } def __init__(self,", "= control_type self.height = height self.id = id self.inherited = inherited self.is_contribution =", "} def __init__(self, description=None, is_default=None, is_enabled=None, name=None): super(UpdateProcessModel, self).__init__() self.description = description self.is_default", "be put in the group. :type controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` :param height:", "'str'} } def __init__(self, abstract=None, color=None, description=None, fields=None, id=None, inherits=None, name=None, overriden=None, rank=None,", "'url', 'type': 'str'} } def __init__(self, id=None, url=None): super(WorkItemBehaviorReference, self).__init__() self.id = id", "the group should be hidden or not. :type visible: bool \"\"\" _attribute_map =", "'sections', 'type': '[Section]'}, 'visible': {'key': 'visible', 'type': 'bool'} } def __init__(self, contribution=None, id=None,", "id=None, url=None): super(WorkItemBehaviorField, self).__init__() self.behavior_field_id = behavior_field_id self.id = id self.url = url", "visible: A value indicating if the group should be hidden or not. :type", "{'key': 'url', 'type': 'str'} } def __init__(self, abstract=None, color=None, description=None, fields=None, id=None, inherits=None,", "color self.description = description self.icon = icon self.id = id self.inherits = inherits", "'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'is_system': {'key': 'isSystem', 'type': 'bool'} } def", "'url', 'type': 'str'} } def __init__(self, behavior=None, is_default=None, url=None): super(WorkItemTypeBehavior, self).__init__() self.behavior =", "self).__init__() self.behavior = behavior self.is_default = is_default self.url = url class WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel.", "controls self.height = height self.id = id self.inherited = inherited self.is_contribution = is_contribution", ":type is_disabled: bool :param is_system: :type is_system: bool \"\"\" _attribute_map = { 'actions':", "Order in which the group should appear in the section. :type order: int", ":param sections: The sections of the page. :type sections: list of :class:`Section <work-item-tracking.v4_0.models.Section>`", "visible: A value indicating if the page should be hidden or not. :type", "name class WitContribution(Model): \"\"\"WitContribution. :param contribution_id: The id for the contribution. :type contribution_id:", "str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'name': {'key': 'name',", "Contribution for the group. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param controls: Controls to be", ":param show_on_deleted_work_item: A value indicating if the contribution should be show on deleted", ":param id: :type id: str :param inherits: Parent WIT Id/Internal ReferenceName that it", "to be put in the group. :type controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` :param", "level tabs of the layout. :type pages: list of :class:`Page <work-item-tracking.v4_0.models.Page>` :param system_controls:", ":param inherits: :type inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param name: :type name: str :param overriden:", "'str'}, 'name': {'key': 'name', 'type': 'str'}, 'projects': {'key': 'projects', 'type': '[ProjectReference]'}, 'properties': {'key':", "self.hidden = hidden self.id = id self.name = name self.order = order self.state_category", ":type is_identity: bool :param name: :type name: str :param type: :type type: object", "target_field: :type target_field: str :param value: :type value: str \"\"\" _attribute_map = {", "inherited from a parent layout. This is expected to only be only set", "'str'}, 'hidden': {'key': 'hidden', 'type': 'bool'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key':", "description=None, id=None, is_identity=None, name=None, type=None, url=None): super(FieldModel, self).__init__() self.description = description self.id =", "if the code is regenerated. # -------------------------------------------------------------------------------------------- from msrest.serialization import Model class Control(Model):", "{ 'extensions': {'key': 'extensions', 'type': '[Extension]'}, 'pages': {'key': 'pages', 'type': '[Page]'}, 'system_controls': {'key':", ":type visible: bool :param watermark: Watermark text for the textbox. :type watermark: str", "'str'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'url': {'key':", "= id self.is_disabled = is_disabled self.is_system = is_system class FormLayout(Model): \"\"\"FormLayout. :param extensions:", ":param height: Height of the control, for html controls. :type height: int :param", "id self.is_disabled = is_disabled self.is_system = is_system class FormLayout(Model): \"\"\"FormLayout. :param extensions: Gets", "self.color = color self.description = description self.fields = fields self.id = id self.inherits", "'bool'} } def __init__(self, contribution=None, id=None, inherited=None, is_contribution=None, label=None, locked=None, order=None, overridden=None, page_type=None,", "id=None, inherited=None, is_contribution=None, label=None, metadata=None, order=None, overridden=None, read_only=None, visible=None, watermark=None): super(Control, self).__init__() self.contribution", "behavior=None, is_default=None, url=None): super(WorkItemTypeBehavior, self).__init__() self.behavior = behavior self.is_default = is_default self.url =", "= reference_name self.type_id = type_id class ProcessProperties(Model): \"\"\"ProcessProperties. :param class_: :type class_: object", "target_field self.value = value class RuleConditionModel(Model): \"\"\"RuleConditionModel. :param condition_type: :type condition_type: str :param", "not. :type visible: bool :param watermark: Watermark text for the textbox. :type watermark:", "is_enabled self.name = name class WitContribution(Model): \"\"\"WitContribution. :param contribution_id: The id for the", "'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'state_category': {'key': 'stateCategory', 'type': 'str'}, 'url':", "id: str :param inherits: :type inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param name: :type name: str", "str :param id: :type id: str :param name: :type name: str :param url:", "'[Section]'}, 'visible': {'key': 'visible', 'type': 'bool'} } def __init__(self, contribution=None, id=None, inherited=None, is_contribution=None,", "= label self.locked = locked self.order = order self.overridden = overridden self.page_type =", "self.pages = pages self.system_controls = system_controls class Group(Model): \"\"\"Group. :param contribution: Contribution for", "'order', 'type': 'int'}, 'state_category': {'key': 'stateCategory', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'}", "\"\"\" _attribute_map = { 'actions': {'key': 'actions', 'type': '[RuleActionModel]'}, 'conditions': {'key': 'conditions', 'type':", "type: :type type: object :param url: :type url: str \"\"\" _attribute_map = {", ":type height: int :param inputs: A dictionary holding key value pairs for contribution", "= id self.url = url class WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference. :param id: :type id: str", "{'key': 'behaviorFieldId', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'url': {'key': 'url', 'type':", "the page. :type label: str :param locked: A value indicating whether any user", ":param is_disabled: :type is_disabled: bool :param layout: :type layout: :class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>` :param name:", "'description': {'key': 'description', 'type': 'str'}, 'icon': {'key': 'icon', 'type': 'str'}, 'id': {'key': 'id',", "is_contribution=None, label=None, order=None, overridden=None, visible=None): super(Group, self).__init__() self.contribution = contribution self.controls = controls", "int :param url: :type url: str \"\"\" _attribute_map = { 'abstract': {'key': 'abstract',", "id=None, is_disabled=None, is_system=None): super(FieldRuleModel, self).__init__() self.actions = actions self.conditions = conditions self.friendly_name =", "'type': 'str'} } def __init__(self, description=None, id=None, is_identity=None, name=None, type=None, url=None): super(FieldModel, self).__init__()", "for the group. :type label: str :param order: Order in which the group", "\"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'control_type': {'key': 'controlType', 'type':", "indicating if the control is readonly. :type read_only: bool :param visible: A value", "\"\"\"ProjectReference. :param description: :type description: str :param id: :type id: str :param name:", "'visible', 'type': 'bool'} } def __init__(self, contribution=None, controls=None, height=None, id=None, inherited=None, is_contribution=None, label=None,", "value: str \"\"\" _attribute_map = { 'action_type': {'key': 'actionType', 'type': 'str'}, 'target_field': {'key':", "'id': {'key': 'id', 'type': 'str'}, 'overridden': {'key': 'overridden', 'type': 'bool'} } def __init__(self,", "= inherited self.is_contribution = is_contribution self.label = label self.order = order self.overridden =", "id: :type id: str :param is_identity: :type is_identity: bool :param name: :type name:", "list :type extensions: list of :class:`Extension <work-item-tracking.v4_0.models.Extension>` :param pages: Top level tabs of", "'is_contribution': {'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'metadata': {'key': 'metadata',", ":param url: :type url: str \"\"\" _attribute_map = { 'behavior_field_id': {'key': 'behaviorFieldId', 'type':", "UpdateProcessModel(Model): \"\"\"UpdateProcessModel. :param description: :type description: str :param is_default: :type is_default: bool :param", "bool :param visible: A value indicating if the control should be hidden or", "'str'}, 'height': {'key': 'height', 'type': 'int'}, 'inputs': {'key': 'inputs', 'type': '{object}'}, 'show_on_deleted_work_item': {'key':", "'name': {'key': 'name', 'type': 'str'}, 'overriden': {'key': 'overriden', 'type': 'bool'}, 'rank': {'key': 'rank',", "_attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'},", ":type is_default: bool :param is_enabled: :type is_enabled: bool :param parent_process_type_id: :type parent_process_type_id: str", "'str'} } def __init__(self, action_type=None, target_field=None, value=None): super(RuleActionModel, self).__init__() self.action_type = action_type self.target_field", "'color': {'key': 'color', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'icon': {'key': 'icon',", ":class:`Extension <work-item-tracking.v4_0.models.Extension>` :param pages: Top level tabs of the layout. :type pages: list", "friendly_name=None, id=None, is_disabled=None, is_system=None): super(FieldRuleModel, self).__init__() self.actions = actions self.conditions = conditions self.friendly_name", "page_type: object :param sections: The sections of the page. :type sections: list of", "are not. :type is_contribution: bool :param label: The label for the page. :type", "'str'} } def __init__(self, behavior=None, is_default=None, url=None): super(WorkItemTypeBehavior, self).__init__() self.behavior = behavior self.is_default", "'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'icon': {'key': 'icon', 'type': 'str'}, 'id':", "description self.name = name self.projects = projects self.properties = properties self.reference_name = reference_name", "color: str :param description: :type description: str :param fields: :type fields: list of", "'id', 'type': 'str'}, 'inherited': {'key': 'inherited', 'type': 'bool'}, 'is_contribution': {'key': 'isContribution', 'type': 'bool'},", "'field': {'key': 'field', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'} } def __init__(self,", "'description': {'key': 'description', 'type': 'str'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled',", "\"\"\" _attribute_map = { 'class_': {'key': 'class', 'type': 'object'}, 'is_default': {'key': 'isDefault', 'type':", "= color self.hidden = hidden self.id = id self.name = name self.order =", "contribution_id self.height = height self.inputs = inputs self.show_on_deleted_work_item = show_on_deleted_work_item class WorkItemBehavior(Model): \"\"\"WorkItemBehavior.", "a child layout. :type overridden: bool :param read_only: A value indicating if the", ":param id: :type id: str \"\"\" _attribute_map = { 'id': {'key': 'id', 'type':", ":param locked: A value indicating whether any user operations are permitted on this", "'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'metadata': {'key': 'metadata', 'type': 'str'},", "<work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param id: :type id: str :param inherits: :type inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param", "for the group. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param controls: Controls to be put", "contribution self.controls = controls self.height = height self.id = id self.inherited = inherited", "been overridden by a child layout. :type overridden: bool \"\"\" _attribute_map = {", "is_disabled: bool :param layout: :type layout: :class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>` :param name: :type name: str", "behaviors=None, class_=None, color=None, description=None, icon=None, id=None, inherits=None, is_disabled=None, layout=None, name=None, states=None, url=None): super(WorkItemTypeModel,", "'str'}, 'description': {'key': 'description', 'type': 'str'}, 'fields': {'key': 'fields', 'type': '[WorkItemBehaviorField]'}, 'id': {'key':", "str :param is_disabled: :type is_disabled: bool :param layout: :type layout: :class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>` :param", "is_system class FormLayout(Model): \"\"\"FormLayout. :param extensions: Gets and sets extensions list :type extensions:", "version class ProjectReference(Model): \"\"\"ProjectReference. :param description: :type description: str :param id: :type id:", "'str'}, 'type_id': {'key': 'typeId', 'type': 'str'} } def __init__(self, description=None, name=None, projects=None, properties=None,", "'type': 'WitContribution'}, 'controls': {'key': 'controls', 'type': '[Control]'}, 'height': {'key': 'height', 'type': 'int'}, 'id':", "should appear in the layout. :type order: int :param overridden: A value indicating", "type=None, url=None): super(FieldModel, self).__init__() self.description = description self.id = id self.is_identity = is_identity", "behavior_field_id=None, id=None, url=None): super(WorkItemBehaviorField, self).__init__() self.behavior_field_id = behavior_field_id self.id = id self.url =", "self.url = url class WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel. :param behaviors: :type behaviors: list of :class:`WorkItemTypeBehavior", "value indicating if the layout node is contribution or not. :type is_contribution: bool", "self.order = order self.overridden = overridden self.read_only = read_only self.visible = visible self.watermark", ":param reference_name: :type reference_name: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type':", "= { 'description': {'key': 'description', 'type': 'str'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled':", "= { 'color': {'key': 'color', 'type': 'str'}, 'hidden': {'key': 'hidden', 'type': 'bool'}, 'id':", "group should be hidden or not. :type visible: bool \"\"\" _attribute_map = {", "description=None, fields=None, id=None, inherits=None, name=None, overriden=None, rank=None, url=None): super(WorkItemBehavior, self).__init__() self.abstract = abstract", "contribution=None, controls=None, height=None, id=None, inherited=None, is_contribution=None, label=None, order=None, overridden=None, visible=None): super(Group, self).__init__() self.contribution", "self.id = id self.overridden = overridden class UpdateProcessModel(Model): \"\"\"UpdateProcessModel. :param description: :type description:", "str :param overriden: :type overriden: bool :param rank: :type rank: int :param url:", "'name': {'key': 'name', 'type': 'str'}, 'projects': {'key': 'projects', 'type': '[ProjectReference]'}, 'properties': {'key': 'properties',", "self.url = url class WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference. :param id: :type id: str :param url:", ":type inherited: bool :param is_contribution: A value indicating if the layout node is", ":param is_default: :type is_default: bool :param is_enabled: :type is_enabled: bool :param name: :type", ":type abstract: bool :param color: :type color: str :param description: :type description: str", "overridden: bool :param visible: A value indicating if the group should be hidden", "pages: list of :class:`Page <work-item-tracking.v4_0.models.Page>` :param system_controls: Headers controls of the layout. :type", "= parent_process_type_id self.version = version class ProjectReference(Model): \"\"\"ProjectReference. :param description: :type description: str", "self).__init__() self.description = description self.id = id self.is_identity = is_identity self.name = name", "{ 'description': {'key': 'description', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key':", "{'key': 'conditionType', 'type': 'str'}, 'field': {'key': 'field', 'type': 'str'}, 'value': {'key': 'value', 'type':", "This is expected to only be only set by the combiner. :type inherited:", "type_id: :type type_id: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'},", "= inputs self.show_on_deleted_work_item = show_on_deleted_work_item class WorkItemBehavior(Model): \"\"\"WorkItemBehavior. :param abstract: :type abstract: bool", "is regenerated. # -------------------------------------------------------------------------------------------- from msrest.serialization import Model class Control(Model): \"\"\"Control. :param contribution:", "list of :class:`Extension <work-item-tracking.v4_0.models.Extension>` :param pages: Top level tabs of the layout. :type", "super(Group, self).__init__() self.contribution = contribution self.controls = controls self.height = height self.id =", "'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'read_only': {'key': 'readOnly',", "= inherited self.is_contribution = is_contribution self.label = label self.metadata = metadata self.order =", "_attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'control_type': {'key': 'controlType', 'type': 'str'},", "'visible': {'key': 'visible', 'type': 'bool'}, 'watermark': {'key': 'watermark', 'type': 'str'} } def __init__(self,", "'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'}", "id self.overridden = overridden class UpdateProcessModel(Model): \"\"\"UpdateProcessModel. :param description: :type description: str :param", "class WitContribution(Model): \"\"\"WitContribution. :param contribution_id: The id for the contribution. :type contribution_id: str", "'is_identity': {'key': 'isIdentity', 'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type',", "self.properties = properties self.reference_name = reference_name self.type_id = type_id class ProcessProperties(Model): \"\"\"ProcessProperties. :param", "= { 'contribution_id': {'key': 'contributionId', 'type': 'str'}, 'height': {'key': 'height', 'type': 'int'}, 'inputs':", "order=None, overridden=None, page_type=None, sections=None, visible=None): super(Page, self).__init__() self.contribution = contribution self.id = id", ":type type_id: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'name':", "'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'read_only': {'key': 'readOnly', 'type': 'bool'}, 'visible':", "= name class WitContribution(Model): \"\"\"WitContribution. :param contribution_id: The id for the contribution. :type", "name: str :param parent_process_type_id: :type parent_process_type_id: str :param reference_name: :type reference_name: str \"\"\"", "contribution are not. :type is_contribution: bool :param label: Label for the group. :type", "'inputs': {'key': 'inputs', 'type': '{object}'}, 'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem', 'type': 'bool'} } def __init__(self,", "{'key': 'url', 'type': 'str'} } def __init__(self, id=None, url=None): super(WorkItemBehaviorReference, self).__init__() self.id =", "= icon self.id = id self.inherits = inherits self.is_disabled = is_disabled self.layout =", "self.id = id self.inherited = inherited self.is_contribution = is_contribution self.label = label self.metadata", ":type overridden: bool \"\"\" _attribute_map = { 'groups': {'key': 'groups', 'type': '[Group]'}, 'id':", "WIT Id/Internal ReferenceName that it inherits from :type inherits: str :param is_disabled: :type", "key value pairs for contribution inputs. :type inputs: dict :param show_on_deleted_work_item: A value", "inherits: :type inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param name: :type name: str :param overriden: :type", ":class:`Group <work-item-tracking.v4_0.models.Group>` :param id: The id for the layout node. :type id: str", "self).__init__() self.behaviors = behaviors self.class_ = class_ self.color = color self.description = description", "'str'}, 'type': {'key': 'type', 'type': 'object'}, 'url': {'key': 'url', 'type': 'str'} } def", "overridden self.read_only = read_only self.visible = visible self.watermark = watermark class CreateProcessModel(Model): \"\"\"CreateProcessModel.", "} def __init__(self, contribution_id=None, height=None, inputs=None, show_on_deleted_work_item=None): super(WitContribution, self).__init__() self.contribution_id = contribution_id self.height", "{'key': 'actionType', 'type': 'str'}, 'target_field': {'key': 'targetField', 'type': 'str'}, 'value': {'key': 'value', 'type':", "for the contribution. :type height: int :param id: The id for the layout", "it inherits from :type inherits: str :param is_disabled: :type is_disabled: bool :param layout:", "self.system_controls = system_controls class Group(Model): \"\"\"Group. :param contribution: Contribution for the group. :type", "description=None, name=None, parent_process_type_id=None, reference_name=None): super(CreateProcessModel, self).__init__() self.description = description self.name = name self.parent_process_type_id", "super(RuleConditionModel, self).__init__() self.condition_type = condition_type self.field = field self.value = value class Section(Model):", "rank=None, url=None): super(WorkItemBehavior, self).__init__() self.abstract = abstract self.color = color self.description = description", "self.name = name self.url = url class RuleActionModel(Model): \"\"\"RuleActionModel. :param action_type: :type action_type:", "super(ProcessModel, self).__init__() self.description = description self.name = name self.projects = projects self.properties =", "groups: :type groups: list of :class:`Group <work-item-tracking.v4_0.models.Group>` :param id: The id for the", "set by the combiner. :type inherited: bool :param is_contribution: A value indicating if", "'name', 'type': 'str'}, 'projects': {'key': 'projects', 'type': '[ProjectReference]'}, 'properties': {'key': 'properties', 'type': 'ProcessProperties'},", "show_on_deleted_work_item class WorkItemBehavior(Model): \"\"\"WorkItemBehavior. :param abstract: :type abstract: bool :param color: :type color:", "in the group. :type controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` :param height: The height", ":type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param id: The id for the layout node. :type", "field: :type field: str :param value: :type value: str \"\"\" _attribute_map = {", ":type system_controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` \"\"\" _attribute_map = { 'extensions': {'key': 'extensions',", "'metadata', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'},", ":class:`Page <work-item-tracking.v4_0.models.Page>` :param system_controls: Headers controls of the layout. :type system_controls: list of", ":type icon: str :param id: :type id: str :param inherits: Parent WIT Id/Internal", "'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'layout':", "contribution. :type height: int :param inputs: A dictionary holding key value pairs for", "str :param order: Order in which the group should appear in the section.", "str :param type: :type type: object :param url: :type url: str \"\"\" _attribute_map", "system_controls class Group(Model): \"\"\"Group. :param contribution: Contribution for the group. :type contribution: :class:`WitContribution", "self.name = name self.type = type self.url = url class FieldRuleModel(Model): \"\"\"FieldRuleModel. :param", ":param is_identity: :type is_identity: bool :param name: :type name: str :param type: :type", "height: int :param inputs: A dictionary holding key value pairs for contribution inputs.", "self.actions = actions self.conditions = conditions self.friendly_name = friendly_name self.id = id self.is_disabled", "is_system: bool \"\"\" _attribute_map = { 'actions': {'key': 'actions', 'type': '[RuleActionModel]'}, 'conditions': {'key':", "'extensions': {'key': 'extensions', 'type': '[Extension]'}, 'pages': {'key': 'pages', 'type': '[Page]'}, 'system_controls': {'key': 'systemControls',", "'type': '[Extension]'}, 'pages': {'key': 'pages', 'type': '[Page]'}, 'system_controls': {'key': 'systemControls', 'type': '[Control]'} }", "'behaviors', 'type': '[WorkItemTypeBehavior]'}, 'class_': {'key': 'class', 'type': 'object'}, 'color': {'key': 'color', 'type': 'str'},", "super(WorkItemTypeModel, self).__init__() self.behaviors = behaviors self.class_ = class_ self.color = color self.description =", "= extensions self.pages = pages self.system_controls = system_controls class Group(Model): \"\"\"Group. :param contribution:", "super(ProcessProperties, self).__init__() self.class_ = class_ self.is_default = is_default self.is_enabled = is_enabled self.parent_process_type_id =", "\"\"\"ProcessProperties. :param class_: :type class_: object :param is_default: :type is_default: bool :param is_enabled:", "url: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'id': {'key':", "'type': 'bool'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'page_type':", "'str'} } def __init__(self, contribution=None, control_type=None, height=None, id=None, inherited=None, is_contribution=None, label=None, metadata=None, order=None,", "class Group(Model): \"\"\"Group. :param contribution: Contribution for the group. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>`", "__init__(self, class_=None, is_default=None, is_enabled=None, parent_process_type_id=None, version=None): super(ProcessProperties, self).__init__() self.class_ = class_ self.is_default =", "<work-item-tracking.v4_0.models.Group>` :param id: The id for the layout node. :type id: str :param", "id=None, inherited=None, is_contribution=None, label=None, order=None, overridden=None, visible=None): super(Group, self).__init__() self.contribution = contribution self.controls", "= id self.inherited = inherited self.is_contribution = is_contribution self.label = label self.metadata =", "= { 'extensions': {'key': 'extensions', 'type': '[Extension]'}, 'pages': {'key': 'pages', 'type': '[Page]'}, 'system_controls':", "height for the contribution. :type height: int :param id: The id for the", "'str'}, 'overriden': {'key': 'overriden', 'type': 'bool'}, 'rank': {'key': 'rank', 'type': 'int'}, 'url': {'key':", ":param control_type: Type of the control. :type control_type: str :param height: Height of", "Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt", "controls: Controls to be put in the group. :type controls: list of :class:`Control", "'bool'} } def __init__(self, actions=None, conditions=None, friendly_name=None, id=None, is_disabled=None, is_system=None): super(FieldRuleModel, self).__init__() self.actions", "{'key': 'url', 'type': 'str'} } def __init__(self, description=None, id=None, name=None, url=None): super(ProjectReference, self).__init__()", "contribution: Contribution for the control. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param control_type: Type of", "str :param is_default: :type is_default: bool :param is_enabled: :type is_enabled: bool :param name:", "'conditionType', 'type': 'str'}, 'field': {'key': 'field', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}", "url: str \"\"\" _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'url': {'key':", "'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'version': {'key': 'version', 'type': 'str'} } def __init__(self,", "'layout': {'key': 'layout', 'type': 'FormLayout'}, 'name': {'key': 'name', 'type': 'str'}, 'states': {'key': 'states',", "appear in the section. :type order: int :param overridden: A value indicating whether", "super(WorkItemBehavior, self).__init__() self.abstract = abstract self.color = color self.description = description self.fields =", "url: :type url: str \"\"\" _attribute_map = { 'behavior': {'key': 'behavior', 'type': 'WorkItemBehaviorReference'},", "'str'} } def __init__(self, behavior_field_id=None, id=None, url=None): super(WorkItemBehaviorField, self).__init__() self.behavior_field_id = behavior_field_id self.id", "contribution self.id = id self.inherited = inherited self.is_contribution = is_contribution self.label = label", "information. # -------------------------------------------------------------------------------------------- # Generated file, DO NOT EDIT # Changes may cause", "= fields self.id = id self.inherits = inherits self.name = name self.overriden =", "\"\"\"Control. :param contribution: Contribution for the control. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param control_type:", "super(UpdateProcessModel, self).__init__() self.description = description self.is_default = is_default self.is_enabled = is_enabled self.name =", "a child layout. :type overridden: bool :param visible: A value indicating if the", "id self.name = name self.url = url class RuleActionModel(Model): \"\"\"RuleActionModel. :param action_type: :type", "this page and the contents of this page :type locked: bool :param order:", "inherits: str :param is_disabled: :type is_disabled: bool :param layout: :type layout: :class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>`", "contribution=None, control_type=None, height=None, id=None, inherited=None, is_contribution=None, label=None, metadata=None, order=None, overridden=None, read_only=None, visible=None, watermark=None):", "'value', 'type': 'str'} } def __init__(self, action_type=None, target_field=None, value=None): super(RuleActionModel, self).__init__() self.action_type =", "'read_only': {'key': 'readOnly', 'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'}, 'watermark': {'key': 'watermark',", "visible class Page(Model): \"\"\"Page. :param contribution: Contribution for the page. :type contribution: :class:`WitContribution", "'type': 'bool'} } def __init__(self, contribution=None, controls=None, height=None, id=None, inherited=None, is_contribution=None, label=None, order=None,", "the combiner. :type inherited: bool :param is_contribution: A value indicating if the layout", "url class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param color: :type color: str :param hidden: :type hidden:", "'id', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, id=None, url=None):", "reference_name: str :param type_id: :type type_id: str \"\"\" _attribute_map = { 'description': {'key':", "self).__init__() self.description = description self.is_default = is_default self.is_enabled = is_enabled self.name = name", "hidden=None, id=None, name=None, order=None, state_category=None, url=None): super(WorkItemStateResultModel, self).__init__() self.color = color self.hidden =", "self.class_ = class_ self.color = color self.description = description self.icon = icon self.id", "groups=None, id=None, overridden=None): super(Section, self).__init__() self.groups = groups self.id = id self.overridden =", "\"\"\" _attribute_map = { 'behaviors': {'key': 'behaviors', 'type': '[WorkItemTypeBehavior]'}, 'class_': {'key': 'class', 'type':", "{'key': 'isEnabled', 'type': 'bool'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'version': {'key': 'version', 'type':", ":param is_contribution: A value indicating if the layout node is contribution are not.", "locked: bool :param order: Order in which the page should appear in the", "id: :type id: str :param inherits: Parent WIT Id/Internal ReferenceName that it inherits", "FormLayout(Model): \"\"\"FormLayout. :param extensions: Gets and sets extensions list :type extensions: list of", "<work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param class_: :type class_: object :param color: :type color: str :param description:", ":type inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param name: :type name: str :param overriden: :type overriden:", "self.description = description self.fields = fields self.id = id self.inherits = inherits self.name", "layout node. :type id: str :param overridden: A value indicating whether this layout", "states: list of :class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param url: :type url: str \"\"\" _attribute_map =", "Order in which the page should appear in the layout. :type order: int", "{'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'order': {'key': 'order', 'type':", "behaviors self.class_ = class_ self.color = color self.description = description self.icon = icon", "id: :type id: str :param url: :type url: str \"\"\" _attribute_map = {", "for html controls. :type height: int :param id: The id for the layout", "FieldRuleModel(Model): \"\"\"FieldRuleModel. :param actions: :type actions: list of :class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>` :param conditions: :type", "for license information. # -------------------------------------------------------------------------------------------- # Generated file, DO NOT EDIT # Changes", "url: :type url: str \"\"\" _attribute_map = { 'abstract': {'key': 'abstract', 'type': 'bool'},", "parent_process_type_id=None, version=None): super(ProcessProperties, self).__init__() self.class_ = class_ self.is_default = is_default self.is_enabled = is_enabled", "# Licensed under the MIT License. See License.txt in the project root for", "{'key': 'overridden', 'type': 'bool'} } def __init__(self, groups=None, id=None, overridden=None): super(Section, self).__init__() self.groups", ":class:`Control <work-item-tracking.v4_0.models.Control>` :param height: The height for the contribution. :type height: int :param", "the page. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param id: The id for the layout", "parent_process_type_id: str :param reference_name: :type reference_name: str \"\"\" _attribute_map = { 'description': {'key':", "'abstract', 'type': 'bool'}, 'color': {'key': 'color', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'},", ":param name: :type name: str :param parent_process_type_id: :type parent_process_type_id: str :param reference_name: :type", ":type id: str :param inherited: A value indicating whether this layout node has", "= { 'description': {'key': 'description', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'name':", "'str'} } def __init__(self, id=None, url=None): super(WorkItemBehaviorReference, self).__init__() self.id = id self.url =", "the page. :type sections: list of :class:`Section <work-item-tracking.v4_0.models.Section>` :param visible: A value indicating", ":type is_enabled: bool :param name: :type name: str \"\"\" _attribute_map = { 'description':", "{'key': 'parentProcessTypeId', 'type': 'str'}, 'version': {'key': 'version', 'type': 'str'} } def __init__(self, class_=None,", "= { 'description': {'key': 'description', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_identity':", "} def __init__(self, contribution=None, id=None, inherited=None, is_contribution=None, label=None, locked=None, order=None, overridden=None, page_type=None, sections=None,", ":type extensions: list of :class:`Extension <work-item-tracking.v4_0.models.Extension>` :param pages: Top level tabs of the", "been overridden by a child layout. :type overridden: bool :param read_only: A value", "incorrect behavior and will be lost if the code is regenerated. # --------------------------------------------------------------------------------------------", "self.color = color self.hidden = hidden self.id = id self.name = name self.order", "in which the group should appear in the section. :type order: int :param", ":type control_type: str :param height: Height of the control, for html controls. :type", "'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'WorkItemBehaviorReference'}, 'name': {'key': 'name',", "\"\"\" _attribute_map = { 'groups': {'key': 'groups', 'type': '[Group]'}, 'id': {'key': 'id', 'type':", "properties: :class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>` :param reference_name: :type reference_name: str :param type_id: :type type_id: str", "str :param url: :type url: str \"\"\" _attribute_map = { 'behavior_field_id': {'key': 'behaviorFieldId',", "not. :type is_contribution: bool :param label: The label for the page. :type label:", "contribution self.control_type = control_type self.height = height self.id = id self.inherited = inherited", "'behavior', 'type': 'WorkItemBehaviorReference'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'url': {'key': 'url', 'type': 'str'}", "'contribution', 'type': 'WitContribution'}, 'controls': {'key': 'controls', 'type': '[Control]'}, 'height': {'key': 'height', 'type': 'int'},", "{'key': 'url', 'type': 'str'} } def __init__(self, behavior_field_id=None, id=None, url=None): super(WorkItemBehaviorField, self).__init__() self.behavior_field_id", "'str'}, 'is_identity': {'key': 'isIdentity', 'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key':", "overriden: :type overriden: bool :param rank: :type rank: int :param url: :type url:", "control_type=None, height=None, id=None, inherited=None, is_contribution=None, label=None, metadata=None, order=None, overridden=None, read_only=None, visible=None, watermark=None): super(Control,", ":param name: :type name: str :param type: :type type: object :param url: :type", "'str'} } def __init__(self, description=None, is_default=None, is_enabled=None, name=None): super(UpdateProcessModel, self).__init__() self.description = description", "self.contribution = contribution self.control_type = control_type self.height = height self.id = id self.inherited", "{'key': 'name', 'type': 'str'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'reference_name': {'key': 'referenceName', 'type':", "'locked': {'key': 'locked', 'type': 'bool'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden',", ":type id: str :param inherits: :type inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param name: :type name:", "'inherits': {'key': 'inherits', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'layout': {'key': 'layout',", "def __init__(self, id=None, url=None): super(WorkItemBehaviorReference, self).__init__() self.id = id self.url = url class", "'is_system': {'key': 'isSystem', 'type': 'bool'} } def __init__(self, actions=None, conditions=None, friendly_name=None, id=None, is_disabled=None,", "layout=None, name=None, states=None, url=None): super(WorkItemTypeModel, self).__init__() self.behaviors = behaviors self.class_ = class_ self.color", "visible: bool :param watermark: Watermark text for the textbox. :type watermark: str \"\"\"", "__init__(self, abstract=None, color=None, description=None, fields=None, id=None, inherits=None, name=None, overriden=None, rank=None, url=None): super(WorkItemBehavior, self).__init__()", "watermark: str \"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'control_type': {'key':", "list of :class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>` :param friendly_name: :type friendly_name: str :param id: :type id:", ":type state_category: str :param url: :type url: str \"\"\" _attribute_map = { 'color':", "\"\"\" _attribute_map = { 'abstract': {'key': 'abstract', 'type': 'bool'}, 'color': {'key': 'color', 'type':", "reference_name: :type reference_name: str :param type_id: :type type_id: str \"\"\" _attribute_map = {", "behaviors: list of :class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param class_: :type class_: object :param color: :type", "bool :param visible: A value indicating if the group should be hidden or", "'behavior': {'key': 'behavior', 'type': 'WorkItemBehaviorReference'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'url': {'key': 'url',", "name: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'is_default': {'key':", "<work-item-tracking.v4_0.models.WitContribution>` :param control_type: Type of the control. :type control_type: str :param height: Height", "= description self.name = name self.parent_process_type_id = parent_process_type_id self.reference_name = reference_name class Extension(Model):", ":type name: str :param type: :type type: object :param url: :type url: str", "str :param metadata: Inner text of the control. :type metadata: str :param order:", "layout: :type layout: :class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>` :param name: :type name: str :param states: :type", "self).__init__() self.contribution_id = contribution_id self.height = height self.inputs = inputs self.show_on_deleted_work_item = show_on_deleted_work_item", "value=None): super(RuleConditionModel, self).__init__() self.condition_type = condition_type self.field = field self.value = value class", "'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, id=None, url=None): super(WorkItemBehaviorReference,", "'url': {'key': 'url', 'type': 'str'} } def __init__(self, description=None, id=None, is_identity=None, name=None, type=None,", "and will be lost if the code is regenerated. # -------------------------------------------------------------------------------------------- from msrest.serialization", "{ 'description': {'key': 'description', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'parent_process_type_id': {'key':", ":type name: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'is_default':", "str :param fields: :type fields: list of :class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param id: :type id:", "def __init__(self, actions=None, conditions=None, friendly_name=None, id=None, is_disabled=None, is_system=None): super(FieldRuleModel, self).__init__() self.actions = actions", "of :class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>` :param friendly_name: :type friendly_name: str :param id: :type id: str", "bool \"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'id': {'key': 'id',", "a child layout. :type overridden: bool \"\"\" _attribute_map = { 'groups': {'key': 'groups',", "conditions: :type conditions: list of :class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>` :param friendly_name: :type friendly_name: str :param", "_attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'controls': {'key': 'controls', 'type': '[Control]'},", "url=None): super(WorkItemTypeBehavior, self).__init__() self.behavior = behavior self.is_default = is_default self.url = url class", "_attribute_map = { 'actions': {'key': 'actions', 'type': '[RuleActionModel]'}, 'conditions': {'key': 'conditions', 'type': '[RuleConditionModel]'},", "inherits=None, is_disabled=None, layout=None, name=None, states=None, url=None): super(WorkItemTypeModel, self).__init__() self.behaviors = behaviors self.class_ =", "should be hidden or not. :type visible: bool \"\"\" _attribute_map = { 'contribution':", "'value', 'type': 'str'} } def __init__(self, condition_type=None, field=None, value=None): super(RuleConditionModel, self).__init__() self.condition_type =", "system_controls: Headers controls of the layout. :type system_controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` \"\"\"", "{'key': 'extensions', 'type': '[Extension]'}, 'pages': {'key': 'pages', 'type': '[Page]'}, 'system_controls': {'key': 'systemControls', 'type':", "id=None, url=None): super(WorkItemBehaviorReference, self).__init__() self.id = id self.url = url class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel.", "inherited=None, is_contribution=None, label=None, metadata=None, order=None, overridden=None, read_only=None, visible=None, watermark=None): super(Control, self).__init__() self.contribution =", "class ProcessModel(Model): \"\"\"ProcessModel. :param description: :type description: str :param name: :type name: str", "bool :param name: :type name: str \"\"\" _attribute_map = { 'description': {'key': 'description',", "icon=None, id=None, inherits=None, is_disabled=None, layout=None, name=None, states=None, url=None): super(WorkItemTypeModel, self).__init__() self.behaviors = behaviors", ":param target_field: :type target_field: str :param value: :type value: str \"\"\" _attribute_map =", "'type': 'str'}, 'value': {'key': 'value', 'type': 'str'} } def __init__(self, condition_type=None, field=None, value=None):", "super(WorkItemBehaviorField, self).__init__() self.behavior_field_id = behavior_field_id self.id = id self.url = url class WorkItemBehaviorReference(Model):", "'url': {'key': 'url', 'type': 'str'} } def __init__(self, behaviors=None, class_=None, color=None, description=None, icon=None,", "actions: :type actions: list of :class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>` :param conditions: :type conditions: list of", "inherited=None, is_contribution=None, label=None, locked=None, order=None, overridden=None, page_type=None, sections=None, visible=None): super(Page, self).__init__() self.contribution =", "name: :type name: str :param order: :type order: int :param state_category: :type state_category:", "color: str :param hidden: :type hidden: bool :param id: :type id: str :param", ":type overridden: bool :param page_type: The icon for the page. :type page_type: object", "= is_enabled self.parent_process_type_id = parent_process_type_id self.version = version class ProjectReference(Model): \"\"\"ProjectReference. :param description:", "'states', 'type': '[WorkItemStateResultModel]'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, behaviors=None, class_=None,", "url: str \"\"\" _attribute_map = { 'behavior': {'key': 'behavior', 'type': 'WorkItemBehaviorReference'}, 'is_default': {'key':", "self.read_only = read_only self.visible = visible self.watermark = watermark class CreateProcessModel(Model): \"\"\"CreateProcessModel. :param", "= { 'behavior_field_id': {'key': 'behaviorFieldId', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'url':", "(c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See", "description: str :param name: :type name: str :param projects: :type projects: list of", "{'key': 'behavior', 'type': 'WorkItemBehaviorReference'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'url': {'key': 'url', 'type':", "self.order = order self.overridden = overridden self.visible = visible class Page(Model): \"\"\"Page. :param", "def __init__(self, description=None, is_default=None, is_enabled=None, name=None): super(UpdateProcessModel, self).__init__() self.description = description self.is_default =", "'behaviors': {'key': 'behaviors', 'type': '[WorkItemTypeBehavior]'}, 'class_': {'key': 'class', 'type': 'object'}, 'color': {'key': 'color',", "= id self.inherits = inherits self.is_disabled = is_disabled self.layout = layout self.name =", "\"\"\"Group. :param contribution: Contribution for the group. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param controls:", "Page(Model): \"\"\"Page. :param contribution: Contribution for the page. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param", "inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param name: :type name: str :param overriden: :type overriden: bool", "= type_id class ProcessProperties(Model): \"\"\"ProcessProperties. :param class_: :type class_: object :param is_default: :type", "-------------------------------------------------------------------------------------------- # Generated file, DO NOT EDIT # Changes may cause incorrect behavior", "{'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'url': {'key': 'url', 'type':", "str :param projects: :type projects: list of :class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>` :param properties: :type properties:", "group. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param controls: Controls to be put in the", "name: str :param type: :type type: object :param url: :type url: str \"\"\"", "control_type: str :param height: Height of the control, for html controls. :type height:", "child layout. :type overridden: bool :param page_type: The icon for the page. :type", "'type': 'object'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, description=None, id=None, is_identity=None,", "permitted on this page and the contents of this page :type locked: bool", "'description', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'},", "'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'projects': {'key': 'projects', 'type': '[ProjectReference]'}, 'properties':", "The id for the layout node. :type id: str :param overridden: A value", "} def __init__(self, actions=None, conditions=None, friendly_name=None, id=None, is_disabled=None, is_system=None): super(FieldRuleModel, self).__init__() self.actions =", "= id self.inherited = inherited self.is_contribution = is_contribution self.label = label self.locked =", ":type rank: int :param url: :type url: str \"\"\" _attribute_map = { 'abstract':", "code is regenerated. # -------------------------------------------------------------------------------------------- from msrest.serialization import Model class Control(Model): \"\"\"Control. :param", "'id': {'key': 'id', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self,", "self.visible = visible class Page(Model): \"\"\"Page. :param contribution: Contribution for the page. :type", "been overridden by a child layout. :type overridden: bool :param visible: A value", "label self.metadata = metadata self.order = order self.overridden = overridden self.read_only = read_only", "node. :type id: str :param inherited: A value indicating whether this layout node", "id=None): super(Extension, self).__init__() self.id = id class FieldModel(Model): \"\"\"FieldModel. :param description: :type description:", "bool :param label: Label for the group. :type label: str :param order: Order", "'contribution', 'type': 'WitContribution'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key': 'inherited', 'type': 'bool'},", "state_category: str :param url: :type url: str \"\"\" _attribute_map = { 'color': {'key':", ":type is_contribution: bool :param label: Label for the group. :type label: str :param", "__init__(self, condition_type=None, field=None, value=None): super(RuleConditionModel, self).__init__() self.condition_type = condition_type self.field = field self.value", "super(Page, self).__init__() self.contribution = contribution self.id = id self.inherited = inherited self.is_contribution =", "'str'}, 'projects': {'key': 'projects', 'type': '[ProjectReference]'}, 'properties': {'key': 'properties', 'type': 'ProcessProperties'}, 'reference_name': {'key':", ":type id: str :param overridden: A value indicating whether this layout node has", "be lost if the code is regenerated. # -------------------------------------------------------------------------------------------- from msrest.serialization import Model", "overridden class UpdateProcessModel(Model): \"\"\"UpdateProcessModel. :param description: :type description: str :param is_default: :type is_default:", "overriden: bool :param rank: :type rank: int :param url: :type url: str \"\"\"", "{'key': 'overridden', 'type': 'bool'}, 'read_only': {'key': 'readOnly', 'type': 'bool'}, 'visible': {'key': 'visible', 'type':", "page_type self.sections = sections self.visible = visible class ProcessModel(Model): \"\"\"ProcessModel. :param description: :type", "id: str \"\"\" _attribute_map = { 'id': {'key': 'id', 'type': 'str'} } def", "name: :type name: str :param type: :type type: object :param url: :type url:", "contribution. :type contribution_id: str :param height: The height for the contribution. :type height:", "'inherited', 'type': 'bool'}, 'is_contribution': {'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'},", "{'key': 'id', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, behavior_field_id=None,", "version: :type version: str \"\"\" _attribute_map = { 'class_': {'key': 'class', 'type': 'object'},", "label: str :param locked: A value indicating whether any user operations are permitted", "if the group should be hidden or not. :type visible: bool \"\"\" _attribute_map", "inputs. :type inputs: dict :param show_on_deleted_work_item: A value indicating if the contribution should", "self.name = name class WitContribution(Model): \"\"\"WitContribution. :param contribution_id: The id for the contribution.", "'bool'} } def __init__(self, contribution_id=None, height=None, inputs=None, show_on_deleted_work_item=None): super(WitContribution, self).__init__() self.contribution_id = contribution_id", "visible=None): super(Page, self).__init__() self.contribution = contribution self.id = id self.inherited = inherited self.is_contribution", "= color self.description = description self.fields = fields self.id = id self.inherits =", "= url class WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior. :param behavior: :type behavior: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param is_default:", "order=None, overridden=None, visible=None): super(Group, self).__init__() self.contribution = contribution self.controls = controls self.height =", "\"\"\"WorkItemTypeModel. :param behaviors: :type behaviors: list of :class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param class_: :type class_:", ":param id: :type id: str :param url: :type url: str \"\"\" _attribute_map =", "under the MIT License. See License.txt in the project root for license information.", "'str'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'reference_name': {'key': 'referenceName', 'type': 'str'} } def", "'properties': {'key': 'properties', 'type': 'ProcessProperties'}, 'reference_name': {'key': 'referenceName', 'type': 'str'}, 'type_id': {'key': 'typeId',", "class CreateProcessModel(Model): \"\"\"CreateProcessModel. :param description: :type description: str :param name: :type name: str", "WorkItemBehavior(Model): \"\"\"WorkItemBehavior. :param abstract: :type abstract: bool :param color: :type color: str :param", "control_type self.height = height self.id = id self.inherited = inherited self.is_contribution = is_contribution", "'height': {'key': 'height', 'type': 'int'}, 'inputs': {'key': 'inputs', 'type': '{object}'}, 'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem',", "= class_ self.is_default = is_default self.is_enabled = is_enabled self.parent_process_type_id = parent_process_type_id self.version =", "the page should be hidden or not. :type visible: bool \"\"\" _attribute_map =", "'type': 'str'} } def __init__(self, description=None, name=None, parent_process_type_id=None, reference_name=None): super(CreateProcessModel, self).__init__() self.description =", "only be only set by the combiner. :type inherited: bool :param is_contribution: A", "{'key': 'height', 'type': 'int'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key': 'inherited', 'type':", "def __init__(self, condition_type=None, field=None, value=None): super(RuleConditionModel, self).__init__() self.condition_type = condition_type self.field = field", "'type': 'FormLayout'}, 'name': {'key': 'name', 'type': 'str'}, 'states': {'key': 'states', 'type': '[WorkItemStateResultModel]'}, 'url':", "\"\"\"CreateProcessModel. :param description: :type description: str :param name: :type name: str :param parent_process_type_id:", "{'key': 'version', 'type': 'str'} } def __init__(self, class_=None, is_default=None, is_enabled=None, parent_process_type_id=None, version=None): super(ProcessProperties,", "this layout node has been overridden by a child layout. :type overridden: bool", "class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param color: :type color: str :param hidden: :type hidden: bool", "'str'} } def __init__(self, condition_type=None, field=None, value=None): super(RuleConditionModel, self).__init__() self.condition_type = condition_type self.field", "self).__init__() self.action_type = action_type self.target_field = target_field self.value = value class RuleConditionModel(Model): \"\"\"RuleConditionModel.", "name self.type = type self.url = url class FieldRuleModel(Model): \"\"\"FieldRuleModel. :param actions: :type", "child layout. :type overridden: bool \"\"\" _attribute_map = { 'groups': {'key': 'groups', 'type':", "'rank', 'type': 'int'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, abstract=None, color=None,", "is_default=None, is_enabled=None, name=None): super(UpdateProcessModel, self).__init__() self.description = description self.is_default = is_default self.is_enabled =", "'controls': {'key': 'controls', 'type': '[Control]'}, 'height': {'key': 'height', 'type': 'int'}, 'id': {'key': 'id',", ":param id: :type id: str :param inherits: :type inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param name:", "bool :param read_only: A value indicating if the control is readonly. :type read_only:", "by a child layout. :type overridden: bool :param page_type: The icon for the", "'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'version':", "'url': {'key': 'url', 'type': 'str'} } def __init__(self, description=None, id=None, name=None, url=None): super(ProjectReference,", "= description self.fields = fields self.id = id self.inherits = inherits self.name =", "contribution should be show on deleted workItem. :type show_on_deleted_work_item: bool \"\"\" _attribute_map =", "str :param inherits: :type inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param name: :type name: str :param", ":type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param controls: Controls to be put in the group.", "<work-item-tracking.v4_0.models.Extension>` :param pages: Top level tabs of the layout. :type pages: list of", "'version': {'key': 'version', 'type': 'str'} } def __init__(self, class_=None, is_default=None, is_enabled=None, parent_process_type_id=None, version=None):", "{'key': 'height', 'type': 'int'}, 'inputs': {'key': 'inputs', 'type': '{object}'}, 'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem', 'type':", ":param contribution: Contribution for the group. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param controls: Controls", ":type order: int :param state_category: :type state_category: str :param url: :type url: str", ":param description: :type description: str :param name: :type name: str :param projects: :type", "been inherited from a parent layout. This is expected to only be only", "control_type: Type of the control. :type control_type: str :param height: Height of the", "{'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type':", "def __init__(self, class_=None, is_default=None, is_enabled=None, parent_process_type_id=None, version=None): super(ProcessProperties, self).__init__() self.class_ = class_ self.is_default", "will be lost if the code is regenerated. # -------------------------------------------------------------------------------------------- from msrest.serialization import", "\"\"\"WitContribution. :param contribution_id: The id for the contribution. :type contribution_id: str :param height:", ":type description: str :param id: :type id: str :param is_identity: :type is_identity: bool", "= { 'description': {'key': 'description', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'parent_process_type_id':", "id: :type id: str :param inherits: :type inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param name: :type", "of the layout. :type system_controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` \"\"\" _attribute_map = {", "def __init__(self, action_type=None, target_field=None, value=None): super(RuleActionModel, self).__init__() self.action_type = action_type self.target_field = target_field", "'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'} } def __init__(self,", "'url', 'type': 'str'} } def __init__(self, description=None, id=None, name=None, url=None): super(ProjectReference, self).__init__() self.description", "= contribution self.control_type = control_type self.height = height self.id = id self.inherited =", "= conditions self.friendly_name = friendly_name self.id = id self.is_disabled = is_disabled self.is_system =", "'type': 'bool'}, 'is_contribution': {'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'order':", "'str'} } def __init__(self, color=None, hidden=None, id=None, name=None, order=None, state_category=None, url=None): super(WorkItemStateResultModel, self).__init__()", "'version', 'type': 'str'} } def __init__(self, class_=None, is_default=None, is_enabled=None, parent_process_type_id=None, version=None): super(ProcessProperties, self).__init__()", "<work-item-tracking.v4_0.models.Control>` \"\"\" _attribute_map = { 'extensions': {'key': 'extensions', 'type': '[Extension]'}, 'pages': {'key': 'pages',", "= { 'id': {'key': 'id', 'type': 'str'} } def __init__(self, id=None): super(Extension, self).__init__()", "url: str \"\"\" _attribute_map = { 'behaviors': {'key': 'behaviors', 'type': '[WorkItemTypeBehavior]'}, 'class_': {'key':", "overridden by a child layout. :type overridden: bool :param read_only: A value indicating", "'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key': 'inherited',", "'str'} } def __init__(self, behaviors=None, class_=None, color=None, description=None, icon=None, id=None, inherits=None, is_disabled=None, layout=None,", ":param overridden: A value indicating whether this layout node has been overridden by", "str \"\"\" _attribute_map = { 'class_': {'key': 'class', 'type': 'object'}, 'is_default': {'key': 'isDefault',", "is_contribution: A value indicating if the layout node is contribution are not. :type", "'pages', 'type': '[Page]'}, 'system_controls': {'key': 'systemControls', 'type': '[Control]'} } def __init__(self, extensions=None, pages=None,", "system_controls=None): super(FormLayout, self).__init__() self.extensions = extensions self.pages = pages self.system_controls = system_controls class", "the layout node is contribution are not. :type is_contribution: bool :param label: Label", "'[RuleConditionModel]'}, 'friendly_name': {'key': 'friendlyName', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_disabled': {'key':", "{'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'locked': {'key': 'locked', 'type':", "_attribute_map = { 'condition_type': {'key': 'conditionType', 'type': 'str'}, 'field': {'key': 'field', 'type': 'str'},", "id self.name = name self.order = order self.state_category = state_category self.url = url", "super(FieldModel, self).__init__() self.description = description self.id = id self.is_identity = is_identity self.name =", "'description': {'key': 'description', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name',", "states=None, url=None): super(WorkItemTypeModel, self).__init__() self.behaviors = behaviors self.class_ = class_ self.color = color", "__init__(self, id=None, url=None): super(WorkItemBehaviorReference, self).__init__() self.id = id self.url = url class WorkItemStateResultModel(Model):", "'type': 'bool'}, 'is_contribution': {'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'metadata':", ":class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param id: The id for the layout node. :type id: str", "{'key': 'value', 'type': 'str'} } def __init__(self, condition_type=None, field=None, value=None): super(RuleConditionModel, self).__init__() self.condition_type", "of the control. :type metadata: str :param order: :type order: int :param overridden:", "= description self.is_default = is_default self.is_enabled = is_enabled self.name = name class WitContribution(Model):", ":type url: str \"\"\" _attribute_map = { 'behaviors': {'key': 'behaviors', 'type': '[WorkItemTypeBehavior]'}, 'class_':", "conditions self.friendly_name = friendly_name self.id = id self.is_disabled = is_disabled self.is_system = is_system", "'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'is_system': {'key': 'isSystem', 'type': 'bool'} }", ":type label: str :param order: Order in which the group should appear in", "is_default: bool :param is_enabled: :type is_enabled: bool :param name: :type name: str \"\"\"", "name: str :param order: :type order: int :param state_category: :type state_category: str :param", "'friendly_name': {'key': 'friendlyName', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled',", ":param id: :type id: str :param name: :type name: str :param url: :type", "'type': 'bool'} } def __init__(self, contribution_id=None, height=None, inputs=None, show_on_deleted_work_item=None): super(WitContribution, self).__init__() self.contribution_id =", "label self.order = order self.overridden = overridden self.visible = visible class Page(Model): \"\"\"Page.", "_attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'}", "is_contribution self.label = label self.order = order self.overridden = overridden self.visible = visible", "class FieldModel(Model): \"\"\"FieldModel. :param description: :type description: str :param id: :type id: str", "<work-item-tracking.v4_0.models.Section>` :param visible: A value indicating if the page should be hidden or", "'type': 'bool'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'order':", "show on deleted workItem. :type show_on_deleted_work_item: bool \"\"\" _attribute_map = { 'contribution_id': {'key':", "label for the page. :type label: str :param locked: A value indicating whether", "FieldModel(Model): \"\"\"FieldModel. :param description: :type description: str :param id: :type id: str :param", "{'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'name': {'key': 'name', 'type':", "'type_id': {'key': 'typeId', 'type': 'str'} } def __init__(self, description=None, name=None, projects=None, properties=None, reference_name=None,", "'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'} } def", "import Model class Control(Model): \"\"\"Control. :param contribution: Contribution for the control. :type contribution:", "= id class FieldModel(Model): \"\"\"FieldModel. :param description: :type description: str :param id: :type", ":class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param id: :type id: str :param inherits: :type inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>`", "is_default self.is_enabled = is_enabled self.name = name class WitContribution(Model): \"\"\"WitContribution. :param contribution_id: The", "the control. :type control_type: str :param height: Height of the control, for html", "overridden=None, page_type=None, sections=None, visible=None): super(Page, self).__init__() self.contribution = contribution self.id = id self.inherited", "'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'page_type': {'key': 'pageType', 'type': 'object'}, 'sections':", "'type': 'str'} } def __init__(self, action_type=None, target_field=None, value=None): super(RuleActionModel, self).__init__() self.action_type = action_type", "= is_contribution self.label = label self.metadata = metadata self.order = order self.overridden =", "str \"\"\" _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'url': {'key': 'url',", "value class RuleConditionModel(Model): \"\"\"RuleConditionModel. :param condition_type: :type condition_type: str :param field: :type field:", "str :param order: :type order: int :param overridden: A value indicating whether this", "self).__init__() self.abstract = abstract self.color = color self.description = description self.fields = fields", "id self.inherits = inherits self.name = name self.overriden = overriden self.rank = rank", "read_only: A value indicating if the control is readonly. :type read_only: bool :param", "'icon': {'key': 'icon', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits',", "page. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param id: The id for the layout node.", ":param label: The label for the page. :type label: str :param locked: A", "pages: Top level tabs of the layout. :type pages: list of :class:`Page <work-item-tracking.v4_0.models.Page>`", "def __init__(self, contribution=None, control_type=None, height=None, id=None, inherited=None, is_contribution=None, label=None, metadata=None, order=None, overridden=None, read_only=None,", "id: str :param is_disabled: :type is_disabled: bool :param is_system: :type is_system: bool \"\"\"", "{'key': 'states', 'type': '[WorkItemStateResultModel]'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, behaviors=None,", "def __init__(self, contribution=None, id=None, inherited=None, is_contribution=None, label=None, locked=None, order=None, overridden=None, page_type=None, sections=None, visible=None):", "'parentProcessTypeId', 'type': 'str'}, 'version': {'key': 'version', 'type': 'str'} } def __init__(self, class_=None, is_default=None,", "= id self.inherits = inherits self.name = name self.overriden = overriden self.rank =", "'type': 'str'} } def __init__(self, class_=None, is_default=None, is_enabled=None, parent_process_type_id=None, version=None): super(ProcessProperties, self).__init__() self.class_", "= name self.parent_process_type_id = parent_process_type_id self.reference_name = reference_name class Extension(Model): \"\"\"Extension. :param id:", "str :param value: :type value: str \"\"\" _attribute_map = { 'condition_type': {'key': 'conditionType',", "'type': 'WorkItemBehaviorReference'}, 'name': {'key': 'name', 'type': 'str'}, 'overriden': {'key': 'overriden', 'type': 'bool'}, 'rank':", "of :class:`Page <work-item-tracking.v4_0.models.Page>` :param system_controls: Headers controls of the layout. :type system_controls: list", "DO NOT EDIT # Changes may cause incorrect behavior and will be lost", ":type actions: list of :class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>` :param conditions: :type conditions: list of :class:`RuleConditionModel", "visible: A value indicating if the control should be hidden or not. :type", ":type fields: list of :class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param id: :type id: str :param inherits:", "overridden by a child layout. :type overridden: bool :param visible: A value indicating", "{'key': 'inherits', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'layout': {'key': 'layout', 'type':", ":param name: :type name: str :param states: :type states: list of :class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>`", "'typeId', 'type': 'str'} } def __init__(self, description=None, name=None, projects=None, properties=None, reference_name=None, type_id=None): super(ProcessModel,", "on this page and the contents of this page :type locked: bool :param", "is_contribution: A value indicating if the layout node is contribution or not. :type", ":param url: :type url: str \"\"\" _attribute_map = { 'color': {'key': 'color', 'type':", "layout. :type overridden: bool :param read_only: A value indicating if the control is", "'type': 'str'}, 'is_identity': {'key': 'isIdentity', 'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'}, 'type':", "'class_': {'key': 'class', 'type': 'object'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled',", "indicating if the page should be hidden or not. :type visible: bool \"\"\"", "{ 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'controls': {'key': 'controls', 'type': '[Control]'}, 'height': {'key':", "= system_controls class Group(Model): \"\"\"Group. :param contribution: Contribution for the group. :type contribution:", "'is_default': {'key': 'isDefault', 'type': 'bool'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self,", "is_enabled: bool :param parent_process_type_id: :type parent_process_type_id: str :param version: :type version: str \"\"\"", ":class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param controls: Controls to be put in the group. :type controls:", "'type': 'str'}, 'icon': {'key': 'icon', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits':", "{ 'action_type': {'key': 'actionType', 'type': 'str'}, 'target_field': {'key': 'targetField', 'type': 'str'}, 'value': {'key':", "is_identity=None, name=None, type=None, url=None): super(FieldModel, self).__init__() self.description = description self.id = id self.is_identity", "__init__(self, description=None, name=None, projects=None, properties=None, reference_name=None, type_id=None): super(ProcessModel, self).__init__() self.description = description self.name", "{'key': 'properties', 'type': 'ProcessProperties'}, 'reference_name': {'key': 'referenceName', 'type': 'str'}, 'type_id': {'key': 'typeId', 'type':", "self.inherited = inherited self.is_contribution = is_contribution self.label = label self.order = order self.overridden", "MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------------------------------", "'projects', 'type': '[ProjectReference]'}, 'properties': {'key': 'properties', 'type': 'ProcessProperties'}, 'reference_name': {'key': 'referenceName', 'type': 'str'},", "'type': 'str'}, 'metadata': {'key': 'metadata', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden':", "'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, behavior_field_id=None, id=None, url=None):", "= overridden class UpdateProcessModel(Model): \"\"\"UpdateProcessModel. :param description: :type description: str :param is_default: :type", "indicating if the control should be hidden or not. :type visible: bool :param", "of :class:`Control <work-item-tracking.v4_0.models.Control>` \"\"\" _attribute_map = { 'extensions': {'key': 'extensions', 'type': '[Extension]'}, 'pages':", "'type', 'type': 'object'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, description=None, id=None,", "from msrest.serialization import Model class Control(Model): \"\"\"Control. :param contribution: Contribution for the control.", "The id for the layout node. :type id: str :param inherited: A value", "'isEnabled', 'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'} } def __init__(self, description=None, is_default=None,", ":type inherits: str :param is_disabled: :type is_disabled: bool :param layout: :type layout: :class:`FormLayout", "= { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited':", "'states': {'key': 'states', 'type': '[WorkItemStateResultModel]'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self,", "'str'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'name': {'key':", ":param behaviors: :type behaviors: list of :class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param class_: :type class_: object", "not. :type is_contribution: bool :param label: Label for the field :type label: str", "'referenceName', 'type': 'str'} } def __init__(self, description=None, name=None, parent_process_type_id=None, reference_name=None): super(CreateProcessModel, self).__init__() self.description", "Contribution for the control. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param control_type: Type of the", "'watermark', 'type': 'str'} } def __init__(self, contribution=None, control_type=None, height=None, id=None, inherited=None, is_contribution=None, label=None,", "id=None, is_identity=None, name=None, type=None, url=None): super(FieldModel, self).__init__() self.description = description self.id = id", "self.is_enabled = is_enabled self.name = name class WitContribution(Model): \"\"\"WitContribution. :param contribution_id: The id", ":param url: :type url: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type':", "or not. :type visible: bool \"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type':", "whether this layout node has been overridden by a child layout. :type overridden:", "value=None): super(RuleActionModel, self).__init__() self.action_type = action_type self.target_field = target_field self.value = value class", "name: str :param projects: :type projects: list of :class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>` :param properties: :type", "is_default: bool :param is_enabled: :type is_enabled: bool :param parent_process_type_id: :type parent_process_type_id: str :param", "'type': 'str'}, 'reference_name': {'key': 'referenceName', 'type': 'str'} } def __init__(self, description=None, name=None, parent_process_type_id=None,", "self.height = height self.id = id self.inherited = inherited self.is_contribution = is_contribution self.label", "'str'}, 'field': {'key': 'field', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'} } def", "A value indicating if the contribution should be show on deleted workItem. :type", "to only be only set by the combiner. :type inherited: bool :param is_contribution:", "inherits from :type inherits: str :param is_disabled: :type is_disabled: bool :param layout: :type", "type self.url = url class FieldRuleModel(Model): \"\"\"FieldRuleModel. :param actions: :type actions: list of", "_attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'id': {'key': 'id', 'type': 'str'},", "description: :type description: str :param is_default: :type is_default: bool :param is_enabled: :type is_enabled:", ":param is_default: :type is_default: bool :param url: :type url: str \"\"\" _attribute_map =", "{'key': 'id', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'is_system': {'key': 'isSystem', 'type':", "has been overridden by a child layout. :type overridden: bool :param visible: A", "visible: bool \"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'id': {'key':", "'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'},", "that it inherits from :type inherits: str :param is_disabled: :type is_disabled: bool :param", "class FieldRuleModel(Model): \"\"\"FieldRuleModel. :param actions: :type actions: list of :class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>` :param conditions:", "'name', 'type': 'str'}, 'states': {'key': 'states', 'type': '[WorkItemStateResultModel]'}, 'url': {'key': 'url', 'type': 'str'}", ":class:`Section <work-item-tracking.v4_0.models.Section>` :param visible: A value indicating if the page should be hidden", "super(WorkItemTypeBehavior, self).__init__() self.behavior = behavior self.is_default = is_default self.url = url class WorkItemTypeModel(Model):", "inherits: Parent WIT Id/Internal ReferenceName that it inherits from :type inherits: str :param", "= order self.overridden = overridden self.visible = visible class Page(Model): \"\"\"Page. :param contribution:", "condition_type: :type condition_type: str :param field: :type field: str :param value: :type value:", "overridden=None, read_only=None, visible=None, watermark=None): super(Control, self).__init__() self.contribution = contribution self.control_type = control_type self.height", "self.value = value class RuleConditionModel(Model): \"\"\"RuleConditionModel. :param condition_type: :type condition_type: str :param field:", "super(ProjectReference, self).__init__() self.description = description self.id = id self.name = name self.url =", "{'key': 'value', 'type': 'str'} } def __init__(self, action_type=None, target_field=None, value=None): super(RuleActionModel, self).__init__() self.action_type", "'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'reference_name': {'key': 'referenceName', 'type': 'str'} } def __init__(self,", "description: :type description: str :param id: :type id: str :param name: :type name:", "self.version = version class ProjectReference(Model): \"\"\"ProjectReference. :param description: :type description: str :param id:", "self.controls = controls self.height = height self.id = id self.inherited = inherited self.is_contribution", "{'key': 'url', 'type': 'str'} } def __init__(self, behavior=None, is_default=None, url=None): super(WorkItemTypeBehavior, self).__init__() self.behavior", ":class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param class_: :type class_: object :param color: :type color: str :param", "{'key': 'referenceName', 'type': 'str'} } def __init__(self, description=None, name=None, parent_process_type_id=None, reference_name=None): super(CreateProcessModel, self).__init__()", "\"\"\" _attribute_map = { 'behavior': {'key': 'behavior', 'type': 'WorkItemBehaviorReference'}, 'is_default': {'key': 'isDefault', 'type':", "'type': '[WorkItemStateResultModel]'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, behaviors=None, class_=None, color=None,", "order: :type order: int :param overridden: A value indicating whether this layout node", "\"\"\"Extension. :param id: :type id: str \"\"\" _attribute_map = { 'id': {'key': 'id',", "_attribute_map = { 'behavior_field_id': {'key': 'behaviorFieldId', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'},", "for the control. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param control_type: Type of the control.", "controls=None, height=None, id=None, inherited=None, is_contribution=None, label=None, order=None, overridden=None, visible=None): super(Group, self).__init__() self.contribution =", "class_: object :param color: :type color: str :param description: :type description: str :param", "\"\"\" _attribute_map = { 'id': {'key': 'id', 'type': 'str'} } def __init__(self, id=None):", "'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'locked': {'key': 'locked', 'type': 'bool'}, 'order':", "'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled',", "order: :type order: int :param state_category: :type state_category: str :param url: :type url:", ":type visible: bool \"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'id':", "id: str :param name: :type name: str :param order: :type order: int :param", "\"\"\"RuleActionModel. :param action_type: :type action_type: str :param target_field: :type target_field: str :param value:", "'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'object'}, 'url': {'key': 'url', 'type': 'str'}", "overridden: bool \"\"\" _attribute_map = { 'groups': {'key': 'groups', 'type': '[Group]'}, 'id': {'key':", "is_system: :type is_system: bool \"\"\" _attribute_map = { 'actions': {'key': 'actions', 'type': '[RuleActionModel]'},", "self.reference_name = reference_name class Extension(Model): \"\"\"Extension. :param id: :type id: str \"\"\" _attribute_map", "contribution or not. :type is_contribution: bool :param label: Label for the field :type", "contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param controls: Controls to be put in the group. :type", "'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} }", "= metadata self.order = order self.overridden = overridden self.read_only = read_only self.visible =", "= color self.description = description self.icon = icon self.id = id self.inherits =", "id: str :param inherits: Parent WIT Id/Internal ReferenceName that it inherits from :type", "{'key': 'description', 'type': 'str'}, 'icon': {'key': 'icon', 'type': 'str'}, 'id': {'key': 'id', 'type':", ":param name: :type name: str :param overriden: :type overriden: bool :param rank: :type", "'type': 'WitContribution'}, 'control_type': {'key': 'controlType', 'type': 'str'}, 'height': {'key': 'height', 'type': 'int'}, 'id':", "object :param is_default: :type is_default: bool :param is_enabled: :type is_enabled: bool :param parent_process_type_id:", "'name', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'state_category': {'key': 'stateCategory', 'type': 'str'},", "Section(Model): \"\"\"Section. :param groups: :type groups: list of :class:`Group <work-item-tracking.v4_0.models.Group>` :param id: The", "'description': {'key': 'description', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'parent_process_type_id': {'key': 'parentProcessTypeId',", "control, for html controls. :type height: int :param id: The id for the", "bool :param name: :type name: str :param type: :type type: object :param url:", "'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'state_category':", "= id self.name = name self.order = order self.state_category = state_category self.url =", "this layout node has been inherited from a parent layout. This is expected", "overridden: A value indicating whether this layout node has been overridden by a", "str :param value: :type value: str \"\"\" _attribute_map = { 'action_type': {'key': 'actionType',", "self).__init__() self.description = description self.name = name self.parent_process_type_id = parent_process_type_id self.reference_name = reference_name", "locked self.order = order self.overridden = overridden self.page_type = page_type self.sections = sections", "= url class RuleActionModel(Model): \"\"\"RuleActionModel. :param action_type: :type action_type: str :param target_field: :type", "height=None, id=None, inherited=None, is_contribution=None, label=None, metadata=None, order=None, overridden=None, read_only=None, visible=None, watermark=None): super(Control, self).__init__()", "visible: bool \"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'controls': {'key':", "reserved. # Licensed under the MIT License. See License.txt in the project root", ":param name: :type name: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type':", "'sections': {'key': 'sections', 'type': '[Section]'}, 'visible': {'key': 'visible', 'type': 'bool'} } def __init__(self,", "self.name = name self.parent_process_type_id = parent_process_type_id self.reference_name = reference_name class Extension(Model): \"\"\"Extension. :param", ":param conditions: :type conditions: list of :class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>` :param friendly_name: :type friendly_name: str", "indicating if the layout node is contribution or not. :type is_contribution: bool :param", "is_contribution=None, label=None, metadata=None, order=None, overridden=None, read_only=None, visible=None, watermark=None): super(Control, self).__init__() self.contribution = contribution", "\"\"\"FieldRuleModel. :param actions: :type actions: list of :class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>` :param conditions: :type conditions:", "'bool'}, 'name': {'key': 'name', 'type': 'str'} } def __init__(self, description=None, is_default=None, is_enabled=None, name=None):", "'bool'}, 'is_contribution': {'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'order': {'key':", "self.is_default = is_default self.is_enabled = is_enabled self.parent_process_type_id = parent_process_type_id self.version = version class", "'id': {'key': 'id', 'type': 'str'} } def __init__(self, id=None): super(Extension, self).__init__() self.id =", ":param is_disabled: :type is_disabled: bool :param is_system: :type is_system: bool \"\"\" _attribute_map =", "A value indicating whether this layout node has been overridden by a child", "self.parent_process_type_id = parent_process_type_id self.reference_name = reference_name class Extension(Model): \"\"\"Extension. :param id: :type id:", "description: :type description: str :param icon: :type icon: str :param id: :type id:", "self.id = id self.url = url class WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference. :param id: :type id:", ":param order: :type order: int :param overridden: A value indicating whether this layout", "visible self.watermark = watermark class CreateProcessModel(Model): \"\"\"CreateProcessModel. :param description: :type description: str :param", "'type': 'str'} } def __init__(self, id=None): super(Extension, self).__init__() self.id = id class FieldModel(Model):", "sets extensions list :type extensions: list of :class:`Extension <work-item-tracking.v4_0.models.Extension>` :param pages: Top level", ":param abstract: :type abstract: bool :param color: :type color: str :param description: :type", "'visible', 'type': 'bool'}, 'watermark': {'key': 'watermark', 'type': 'str'} } def __init__(self, contribution=None, control_type=None,", "'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key': 'inherited', 'type': 'bool'}, 'is_contribution': {'key': 'isContribution',", "'object'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, description=None, id=None, is_identity=None, name=None,", ":type url: str \"\"\" _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'url':", "url: :type url: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'},", "layout node has been overridden by a child layout. :type overridden: bool :param", "fields self.id = id self.inherits = inherits self.name = name self.overriden = overriden", "= order self.overridden = overridden self.page_type = page_type self.sections = sections self.visible =", "_attribute_map = { 'groups': {'key': 'groups', 'type': '[Group]'}, 'id': {'key': 'id', 'type': 'str'},", ":type reference_name: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'name':", "{'key': 'label', 'type': 'str'}, 'metadata': {'key': 'metadata', 'type': 'str'}, 'order': {'key': 'order', 'type':", "list of :class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>` :param properties: :type properties: :class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>` :param reference_name: :type", "indicating whether this layout node has been inherited from a parent layout. This", "value: :type value: str \"\"\" _attribute_map = { 'action_type': {'key': 'actionType', 'type': 'str'},", ":type is_disabled: bool :param layout: :type layout: :class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>` :param name: :type name:", "A value indicating whether this layout node has been inherited from a parent", "self.target_field = target_field self.value = value class RuleConditionModel(Model): \"\"\"RuleConditionModel. :param condition_type: :type condition_type:", "RuleConditionModel(Model): \"\"\"RuleConditionModel. :param condition_type: :type condition_type: str :param field: :type field: str :param", "'str'}, 'fields': {'key': 'fields', 'type': '[WorkItemBehaviorField]'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key':", "'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'} }", "'value': {'key': 'value', 'type': 'str'} } def __init__(self, action_type=None, target_field=None, value=None): super(RuleActionModel, self).__init__()", "'height', 'type': 'int'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key': 'inherited', 'type': 'bool'},", "not. :type visible: bool \"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'},", "= url class WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField. :param behavior_field_id: :type behavior_field_id: str :param id: :type", "url=None): super(WorkItemBehaviorReference, self).__init__() self.id = id self.url = url class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param", "'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem', 'type': 'bool'} } def __init__(self, contribution_id=None, height=None, inputs=None, show_on_deleted_work_item=None): super(WitContribution,", "bool :param is_contribution: A value indicating if the layout node is contribution are", "be show on deleted workItem. :type show_on_deleted_work_item: bool \"\"\" _attribute_map = { 'contribution_id':", ":param controls: Controls to be put in the group. :type controls: list of", "of :class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param id: :type id: str :param inherits: :type inherits: :class:`WorkItemBehaviorReference", "order self.overridden = overridden self.read_only = read_only self.visible = visible self.watermark = watermark", "'type': '[Control]'} } def __init__(self, extensions=None, pages=None, system_controls=None): super(FormLayout, self).__init__() self.extensions = extensions", "'type': 'str'} } def __init__(self, abstract=None, color=None, description=None, fields=None, id=None, inherits=None, name=None, overriden=None,", "'stateCategory', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, color=None, hidden=None,", "self.overridden = overridden self.page_type = page_type self.sections = sections self.visible = visible class", "str \"\"\" _attribute_map = { 'color': {'key': 'color', 'type': 'str'}, 'hidden': {'key': 'hidden',", "metadata: Inner text of the control. :type metadata: str :param order: :type order:", "Contribution for the page. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param id: The id for", "control should be hidden or not. :type visible: bool :param watermark: Watermark text", "= controls self.height = height self.id = id self.inherited = inherited self.is_contribution =", "group should appear in the section. :type order: int :param overridden: A value", "'str'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'str'}, 'is_disabled': {'key':", ":param projects: :type projects: list of :class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>` :param properties: :type properties: :class:`ProcessProperties", "reference_name=None, type_id=None): super(ProcessModel, self).__init__() self.description = description self.name = name self.projects = projects", "= pages self.system_controls = system_controls class Group(Model): \"\"\"Group. :param contribution: Contribution for the", "'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'read_only': {'key':", "'class', 'type': 'object'}, 'color': {'key': 'color', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'},", "has been inherited from a parent layout. This is expected to only be", "state_category self.url = url class WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior. :param behavior: :type behavior: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>`", ":type label: str :param locked: A value indicating whether any user operations are", "self.label = label self.locked = locked self.order = order self.overridden = overridden self.page_type", "'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'} } def", "'type': 'str'}, 'type_id': {'key': 'typeId', 'type': 'str'} } def __init__(self, description=None, name=None, projects=None,", "put in the group. :type controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` :param height: The", "'inherited': {'key': 'inherited', 'type': 'bool'}, 'is_contribution': {'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label',", "'condition_type': {'key': 'conditionType', 'type': 'str'}, 'field': {'key': 'field', 'type': 'str'}, 'value': {'key': 'value',", "value indicating whether this layout node has been inherited from a parent layout.", "been overridden by a child layout. :type overridden: bool :param page_type: The icon", "'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'parent_process_type_id': {'key': 'parentProcessTypeId',", "'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'visible':", "{ 'behavior_field_id': {'key': 'behaviorFieldId', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'url': {'key':", ":type friendly_name: str :param id: :type id: str :param is_disabled: :type is_disabled: bool", "= id self.name = name self.url = url class RuleActionModel(Model): \"\"\"RuleActionModel. :param action_type:", "control. :type metadata: str :param order: :type order: int :param overridden: A value", "super(Section, self).__init__() self.groups = groups self.id = id self.overridden = overridden class UpdateProcessModel(Model):", "self.description = description self.id = id self.name = name self.url = url class", "= label self.metadata = metadata self.order = order self.overridden = overridden self.read_only =", "name=None, states=None, url=None): super(WorkItemTypeModel, self).__init__() self.behaviors = behaviors self.class_ = class_ self.color =", "id class FieldModel(Model): \"\"\"FieldModel. :param description: :type description: str :param id: :type id:", "description: :type description: str :param id: :type id: str :param is_identity: :type is_identity:", "= contribution_id self.height = height self.inputs = inputs self.show_on_deleted_work_item = show_on_deleted_work_item class WorkItemBehavior(Model):", "if the control should be hidden or not. :type visible: bool :param watermark:", "= is_default self.is_enabled = is_enabled self.name = name class WitContribution(Model): \"\"\"WitContribution. :param contribution_id:", "is_enabled: bool :param name: :type name: str \"\"\" _attribute_map = { 'description': {'key':", "bool :param color: :type color: str :param description: :type description: str :param fields:", "'order': {'key': 'order', 'type': 'int'}, 'state_category': {'key': 'stateCategory', 'type': 'str'}, 'url': {'key': 'url',", "{'key': 'fields', 'type': '[WorkItemBehaviorField]'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type':", "= description self.id = id self.name = name self.url = url class RuleActionModel(Model):", "of this page :type locked: bool :param order: Order in which the page", "} def __init__(self, behaviors=None, class_=None, color=None, description=None, icon=None, id=None, inherits=None, is_disabled=None, layout=None, name=None,", "'[Page]'}, 'system_controls': {'key': 'systemControls', 'type': '[Control]'} } def __init__(self, extensions=None, pages=None, system_controls=None): super(FormLayout,", "} def __init__(self, behavior_field_id=None, id=None, url=None): super(WorkItemBehaviorField, self).__init__() self.behavior_field_id = behavior_field_id self.id =", "page should appear in the layout. :type order: int :param overridden: A value", "A value indicating if the control should be hidden or not. :type visible:", ":type url: str \"\"\" _attribute_map = { 'behavior': {'key': 'behavior', 'type': 'WorkItemBehaviorReference'}, 'is_default':", "<work-item-tracking.v4_0.models.Page>` :param system_controls: Headers controls of the layout. :type system_controls: list of :class:`Control", "url class RuleActionModel(Model): \"\"\"RuleActionModel. :param action_type: :type action_type: str :param target_field: :type target_field:", "= field self.value = value class Section(Model): \"\"\"Section. :param groups: :type groups: list", "condition_type=None, field=None, value=None): super(RuleConditionModel, self).__init__() self.condition_type = condition_type self.field = field self.value =", "'str'}, 'name': {'key': 'name', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def", "'color', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'fields': {'key': 'fields', 'type': '[WorkItemBehaviorField]'},", "'int'}, 'state_category': {'key': 'stateCategory', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def", "'bool'}, 'rank': {'key': 'rank', 'type': 'int'}, 'url': {'key': 'url', 'type': 'str'} } def", "url class WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel. :param behaviors: :type behaviors: list of :class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param", "height for the contribution. :type height: int :param inputs: A dictionary holding key", "'type': 'bool'}, 'read_only': {'key': 'readOnly', 'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'}, 'watermark':", "Label for the group. :type label: str :param order: Order in which the", "'type': '[Section]'}, 'visible': {'key': 'visible', 'type': 'bool'} } def __init__(self, contribution=None, id=None, inherited=None,", "{'key': 'isSystem', 'type': 'bool'} } def __init__(self, actions=None, conditions=None, friendly_name=None, id=None, is_disabled=None, is_system=None):", "= { 'class_': {'key': 'class', 'type': 'object'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled':", "self).__init__() self.class_ = class_ self.is_default = is_default self.is_enabled = is_enabled self.parent_process_type_id = parent_process_type_id", "of :class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>` :param conditions: :type conditions: list of :class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>` :param friendly_name:", "'systemControls', 'type': '[Control]'} } def __init__(self, extensions=None, pages=None, system_controls=None): super(FormLayout, self).__init__() self.extensions =", "self.abstract = abstract self.color = color self.description = description self.fields = fields self.id", "should be show on deleted workItem. :type show_on_deleted_work_item: bool \"\"\" _attribute_map = {", "is_contribution self.label = label self.locked = locked self.order = order self.overridden = overridden", "self.is_disabled = is_disabled self.is_system = is_system class FormLayout(Model): \"\"\"FormLayout. :param extensions: Gets and", ":param state_category: :type state_category: str :param url: :type url: str \"\"\" _attribute_map =", "bool :param page_type: The icon for the page. :type page_type: object :param sections:", "'str'}, 'height': {'key': 'height', 'type': 'int'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key':", "'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'WorkItemBehaviorReference'}, 'name': {'key': 'name', 'type': 'str'}, 'overriden':", ":type behavior: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param is_default: :type is_default: bool :param url: :type url:", "control. :type control_type: str :param height: Height of the control, for html controls.", ":type id: str :param url: :type url: str \"\"\" _attribute_map = { 'id':", ":param hidden: :type hidden: bool :param id: :type id: str :param name: :type", "'type': '[Group]'}, 'id': {'key': 'id', 'type': 'str'}, 'overridden': {'key': 'overridden', 'type': 'bool'} }", "description self.is_default = is_default self.is_enabled = is_enabled self.name = name class WitContribution(Model): \"\"\"WitContribution.", "self.metadata = metadata self.order = order self.overridden = overridden self.read_only = read_only self.visible", "parent_process_type_id self.version = version class ProjectReference(Model): \"\"\"ProjectReference. :param description: :type description: str :param", ":param actions: :type actions: list of :class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>` :param conditions: :type conditions: list", "color=None, hidden=None, id=None, name=None, order=None, state_category=None, url=None): super(WorkItemStateResultModel, self).__init__() self.color = color self.hidden", "for the field :type label: str :param metadata: Inner text of the control.", "group. :type controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` :param height: The height for the", "inherited self.is_contribution = is_contribution self.label = label self.metadata = metadata self.order = order", "'isDisabled', 'type': 'bool'}, 'layout': {'key': 'layout', 'type': 'FormLayout'}, 'name': {'key': 'name', 'type': 'str'},", "contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param control_type: Type of the control. :type control_type: str :param", ":param states: :type states: list of :class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param url: :type url: str", "behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------------------------- from", "\"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'id': {'key': 'id', 'type':", "the contents of this page :type locked: bool :param order: Order in which", "of the control. :type control_type: str :param height: Height of the control, for", "'str'}, 'inherited': {'key': 'inherited', 'type': 'bool'}, 'is_contribution': {'key': 'isContribution', 'type': 'bool'}, 'label': {'key':", "str :param id: :type id: str :param is_disabled: :type is_disabled: bool :param is_system:", "inputs: dict :param show_on_deleted_work_item: A value indicating if the contribution should be show", "projects=None, properties=None, reference_name=None, type_id=None): super(ProcessModel, self).__init__() self.description = description self.name = name self.projects", "{'key': 'name', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'state_category': {'key': 'stateCategory', 'type':", "_attribute_map = { 'contribution_id': {'key': 'contributionId', 'type': 'str'}, 'height': {'key': 'height', 'type': 'int'},", "'type': '[Page]'}, 'system_controls': {'key': 'systemControls', 'type': '[Control]'} } def __init__(self, extensions=None, pages=None, system_controls=None):", ":type metadata: str :param order: :type order: int :param overridden: A value indicating", "'type': 'str'}, 'projects': {'key': 'projects', 'type': '[ProjectReference]'}, 'properties': {'key': 'properties', 'type': 'ProcessProperties'}, 'reference_name':", "'description', 'type': 'str'}, 'fields': {'key': 'fields', 'type': '[WorkItemBehaviorField]'}, 'id': {'key': 'id', 'type': 'str'},", "url: str \"\"\" _attribute_map = { 'color': {'key': 'color', 'type': 'str'}, 'hidden': {'key':", "= parent_process_type_id self.reference_name = reference_name class Extension(Model): \"\"\"Extension. :param id: :type id: str", ":type hidden: bool :param id: :type id: str :param name: :type name: str", "self.inherited = inherited self.is_contribution = is_contribution self.label = label self.locked = locked self.order", "by the combiner. :type inherited: bool :param is_contribution: A value indicating if the", "for the page. :type label: str :param locked: A value indicating whether any", "actions: list of :class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>` :param conditions: :type conditions: list of :class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>`", ":type properties: :class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>` :param reference_name: :type reference_name: str :param type_id: :type type_id:", "'type': '[WorkItemBehaviorField]'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'WorkItemBehaviorReference'}, 'name':", "extensions self.pages = pages self.system_controls = system_controls class Group(Model): \"\"\"Group. :param contribution: Contribution", "'is_contribution': {'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'locked': {'key': 'locked',", ":param reference_name: :type reference_name: str :param type_id: :type type_id: str \"\"\" _attribute_map =", "'type': 'int'}, 'state_category': {'key': 'stateCategory', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} }", "pairs for contribution inputs. :type inputs: dict :param show_on_deleted_work_item: A value indicating if", ":type id: str :param name: :type name: str :param url: :type url: str", "for the contribution. :type contribution_id: str :param height: The height for the contribution.", "'hidden': {'key': 'hidden', 'type': 'bool'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name',", "name self.projects = projects self.properties = properties self.reference_name = reference_name self.type_id = type_id", "{'key': 'readOnly', 'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'}, 'watermark': {'key': 'watermark', 'type':", "'WitContribution'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key': 'inherited', 'type': 'bool'}, 'is_contribution': {'key':", "the page. :type page_type: object :param sections: The sections of the page. :type", "{'key': 'color', 'type': 'str'}, 'hidden': {'key': 'hidden', 'type': 'bool'}, 'id': {'key': 'id', 'type':", "be hidden or not. :type visible: bool :param watermark: Watermark text for the", ":type label: str :param metadata: Inner text of the control. :type metadata: str", "projects self.properties = properties self.reference_name = reference_name self.type_id = type_id class ProcessProperties(Model): \"\"\"ProcessProperties.", "'str'}, 'order': {'key': 'order', 'type': 'int'}, 'state_category': {'key': 'stateCategory', 'type': 'str'}, 'url': {'key':", "{'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type':", "is_default self.url = url class WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel. :param behaviors: :type behaviors: list of", "value: str \"\"\" _attribute_map = { 'condition_type': {'key': 'conditionType', 'type': 'str'}, 'field': {'key':", ":type id: str :param url: :type url: str \"\"\" _attribute_map = { 'behavior_field_id':", "'hidden', 'type': 'bool'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'},", "url class WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior. :param behavior: :type behavior: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param is_default: :type", "for the layout node. :type id: str :param overridden: A value indicating whether", ":type parent_process_type_id: str :param version: :type version: str \"\"\" _attribute_map = { 'class_':", "{'key': 'isDisabled', 'type': 'bool'}, 'is_system': {'key': 'isSystem', 'type': 'bool'} } def __init__(self, actions=None,", "inputs self.show_on_deleted_work_item = show_on_deleted_work_item class WorkItemBehavior(Model): \"\"\"WorkItemBehavior. :param abstract: :type abstract: bool :param", "'type': '[RuleConditionModel]'}, 'friendly_name': {'key': 'friendlyName', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_disabled':", "'url', 'type': 'str'} } def __init__(self, behavior_field_id=None, id=None, url=None): super(WorkItemBehaviorField, self).__init__() self.behavior_field_id =", "{'key': 'name', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, description=None,", "whether this layout node has been inherited from a parent layout. This is", "behavior: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param is_default: :type is_default: bool :param url: :type url: str", "= class_ self.color = color self.description = description self.icon = icon self.id =", "= url class FieldRuleModel(Model): \"\"\"FieldRuleModel. :param actions: :type actions: list of :class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>`", ":class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param control_type: Type of the control. :type control_type: str :param height:", "{ 'description': {'key': 'description', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'projects': {'key':", ":param description: :type description: str :param name: :type name: str :param parent_process_type_id: :type", "parent_process_type_id: str :param version: :type version: str \"\"\" _attribute_map = { 'class_': {'key':", "super(Control, self).__init__() self.contribution = contribution self.control_type = control_type self.height = height self.id =", "{'key': 'id', 'type': 'str'} } def __init__(self, id=None): super(Extension, self).__init__() self.id = id", "super(RuleActionModel, self).__init__() self.action_type = action_type self.target_field = target_field self.value = value class RuleConditionModel(Model):", "'isSystem', 'type': 'bool'} } def __init__(self, actions=None, conditions=None, friendly_name=None, id=None, is_disabled=None, is_system=None): super(FieldRuleModel,", "'visible': {'key': 'visible', 'type': 'bool'} } def __init__(self, contribution=None, controls=None, height=None, id=None, inherited=None,", "are permitted on this page and the contents of this page :type locked:", "'type': 'bool'} } def __init__(self, groups=None, id=None, overridden=None): super(Section, self).__init__() self.groups = groups", "__init__(self, color=None, hidden=None, id=None, name=None, order=None, state_category=None, url=None): super(WorkItemStateResultModel, self).__init__() self.color = color", "'behavior_field_id': {'key': 'behaviorFieldId', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'url': {'key': 'url',", "indicating if the layout node is contribution are not. :type is_contribution: bool :param", "'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'},", "= value class RuleConditionModel(Model): \"\"\"RuleConditionModel. :param condition_type: :type condition_type: str :param field: :type", "any user operations are permitted on this page and the contents of this", "'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'object'}, 'url':", "<work-item-tracking.v4_0.models.ProjectReference>` :param properties: :type properties: :class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>` :param reference_name: :type reference_name: str :param", "= is_contribution self.label = label self.order = order self.overridden = overridden self.visible =", "self.class_ = class_ self.is_default = is_default self.is_enabled = is_enabled self.parent_process_type_id = parent_process_type_id self.version", "description self.fields = fields self.id = id self.inherits = inherits self.name = name", "sections: The sections of the page. :type sections: list of :class:`Section <work-item-tracking.v4_0.models.Section>` :param", "the project root for license information. # -------------------------------------------------------------------------------------------- # Generated file, DO NOT", ":type type: object :param url: :type url: str \"\"\" _attribute_map = { 'description':", "id self.url = url class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param color: :type color: str :param", "parent_process_type_id=None, reference_name=None): super(CreateProcessModel, self).__init__() self.description = description self.name = name self.parent_process_type_id = parent_process_type_id", "__init__(self, groups=None, id=None, overridden=None): super(Section, self).__init__() self.groups = groups self.id = id self.overridden", "'url': {'key': 'url', 'type': 'str'} } def __init__(self, abstract=None, color=None, description=None, fields=None, id=None,", "{'key': 'groups', 'type': '[Group]'}, 'id': {'key': 'id', 'type': 'str'}, 'overridden': {'key': 'overridden', 'type':", "layout node has been inherited from a parent layout. This is expected to", "visible=None, watermark=None): super(Control, self).__init__() self.contribution = contribution self.control_type = control_type self.height = height", "'actionType', 'type': 'str'}, 'target_field': {'key': 'targetField', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}", "'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, id=None, url=None): super(WorkItemBehaviorReference, self).__init__()", "self.url = url class FieldRuleModel(Model): \"\"\"FieldRuleModel. :param actions: :type actions: list of :class:`RuleActionModel", "color: :type color: str :param description: :type description: str :param fields: :type fields:", "def __init__(self, description=None, id=None, is_identity=None, name=None, type=None, url=None): super(FieldModel, self).__init__() self.description = description", "node is contribution or not. :type is_contribution: bool :param label: Label for the", "# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under", "url: :type url: str \"\"\" _attribute_map = { 'color': {'key': 'color', 'type': 'str'},", "url: str \"\"\" _attribute_map = { 'abstract': {'key': 'abstract', 'type': 'bool'}, 'color': {'key':", "{'key': 'class', 'type': 'object'}, 'color': {'key': 'color', 'type': 'str'}, 'description': {'key': 'description', 'type':", "label: str :param order: Order in which the group should appear in the", "'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'}", "'name', 'type': 'str'}, 'overriden': {'key': 'overriden', 'type': 'bool'}, 'rank': {'key': 'rank', 'type': 'int'},", "name self.parent_process_type_id = parent_process_type_id self.reference_name = reference_name class Extension(Model): \"\"\"Extension. :param id: :type", "bool \"\"\" _attribute_map = { 'actions': {'key': 'actions', 'type': '[RuleActionModel]'}, 'conditions': {'key': 'conditions',", "'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'} } def __init__(self, contribution=None, controls=None, height=None,", ":type overridden: bool :param visible: A value indicating if the group should be", "value indicating if the layout node is contribution are not. :type is_contribution: bool", "__init__(self, description=None, name=None, parent_process_type_id=None, reference_name=None): super(CreateProcessModel, self).__init__() self.description = description self.name = name", ":type order: int :param overridden: A value indicating whether this layout node has", "label: Label for the group. :type label: str :param order: Order in which", "__init__(self, actions=None, conditions=None, friendly_name=None, id=None, is_disabled=None, is_system=None): super(FieldRuleModel, self).__init__() self.actions = actions self.conditions", "url=None): super(WorkItemBehavior, self).__init__() self.abstract = abstract self.color = color self.description = description self.fields", "'abstract': {'key': 'abstract', 'type': 'bool'}, 'color': {'key': 'color', 'type': 'str'}, 'description': {'key': 'description',", "operations are permitted on this page and the contents of this page :type", "'type': 'bool'}, 'page_type': {'key': 'pageType', 'type': 'object'}, 'sections': {'key': 'sections', 'type': '[Section]'}, 'visible':", "id: str :param is_identity: :type is_identity: bool :param name: :type name: str :param", "'readOnly', 'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'}, 'watermark': {'key': 'watermark', 'type': 'str'}", "'description', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'},", "'type': 'str'}, 'states': {'key': 'states', 'type': '[WorkItemStateResultModel]'}, 'url': {'key': 'url', 'type': 'str'} }", "conditions=None, friendly_name=None, id=None, is_disabled=None, is_system=None): super(FieldRuleModel, self).__init__() self.actions = actions self.conditions = conditions", "'object'}, 'sections': {'key': 'sections', 'type': '[Section]'}, 'visible': {'key': 'visible', 'type': 'bool'} } def", "'str'}, 'value': {'key': 'value', 'type': 'str'} } def __init__(self, action_type=None, target_field=None, value=None): super(RuleActionModel,", "'field', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'} } def __init__(self, condition_type=None, field=None,", "= locked self.order = order self.overridden = overridden self.page_type = page_type self.sections =", "Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License.", "int :param state_category: :type state_category: str :param url: :type url: str \"\"\" _attribute_map", "indicating if the contribution should be show on deleted workItem. :type show_on_deleted_work_item: bool", "str \"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'control_type': {'key': 'controlType',", ":type behavior_field_id: str :param id: :type id: str :param url: :type url: str", "for the contribution. :type height: int :param inputs: A dictionary holding key value", "'type': 'str'}, 'overriden': {'key': 'overriden', 'type': 'bool'}, 'rank': {'key': 'rank', 'type': 'int'}, 'url':", "Parent WIT Id/Internal ReferenceName that it inherits from :type inherits: str :param is_disabled:", "child layout. :type overridden: bool :param visible: A value indicating if the group", "is contribution are not. :type is_contribution: bool :param label: The label for the", "contribution. :type height: int :param id: The id for the layout node. :type", "target_field=None, value=None): super(RuleActionModel, self).__init__() self.action_type = action_type self.target_field = target_field self.value = value", "self.overriden = overriden self.rank = rank self.url = url class WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField. :param", "for the page. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param id: The id for the", "Watermark text for the textbox. :type watermark: str \"\"\" _attribute_map = { 'contribution':", "{'key': 'sections', 'type': '[Section]'}, 'visible': {'key': 'visible', 'type': 'bool'} } def __init__(self, contribution=None,", "str :param description: :type description: str :param fields: :type fields: list of :class:`WorkItemBehaviorField", "\"\"\"ProcessModel. :param description: :type description: str :param name: :type name: str :param projects:", "{'key': 'id', 'type': 'str'}, 'inherited': {'key': 'inherited', 'type': 'bool'}, 'is_contribution': {'key': 'isContribution', 'type':", "{'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'read_only': {'key': 'readOnly', 'type':", "behavior_field_id: str :param id: :type id: str :param url: :type url: str \"\"\"", "layout. :type pages: list of :class:`Page <work-item-tracking.v4_0.models.Page>` :param system_controls: Headers controls of the", "__init__(self, contribution_id=None, height=None, inputs=None, show_on_deleted_work_item=None): super(WitContribution, self).__init__() self.contribution_id = contribution_id self.height = height", ":type description: str :param is_default: :type is_default: bool :param is_enabled: :type is_enabled: bool", "color: str :param description: :type description: str :param icon: :type icon: str :param", "'int'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, abstract=None, color=None, description=None, fields=None,", "= name self.overriden = overriden self.rank = rank self.url = url class WorkItemBehaviorField(Model):", "is_enabled: :type is_enabled: bool :param name: :type name: str \"\"\" _attribute_map = {", "contribution: Contribution for the group. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param controls: Controls to", ":type url: str \"\"\" _attribute_map = { 'behavior_field_id': {'key': 'behaviorFieldId', 'type': 'str'}, 'id':", "{ 'id': {'key': 'id', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def", "'str'}, 'locked': {'key': 'locked', 'type': 'bool'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key':", "name: str :param states: :type states: list of :class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param url: :type", "super(WorkItemStateResultModel, self).__init__() self.color = color self.hidden = hidden self.id = id self.name =", "of :class:`Control <work-item-tracking.v4_0.models.Control>` :param height: The height for the contribution. :type height: int", "\"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'name': {'key': 'name', 'type':", "A value indicating if the page should be hidden or not. :type visible:", "self).__init__() self.color = color self.hidden = hidden self.id = id self.name = name", "= order self.state_category = state_category self.url = url class WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior. :param behavior:", "'groups': {'key': 'groups', 'type': '[Group]'}, 'id': {'key': 'id', 'type': 'str'}, 'overridden': {'key': 'overridden',", ":type behaviors: list of :class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param class_: :type class_: object :param color:", "self.id = id self.inherits = inherits self.is_disabled = is_disabled self.layout = layout self.name", "self.overridden = overridden self.visible = visible class Page(Model): \"\"\"Page. :param contribution: Contribution for", "= height self.inputs = inputs self.show_on_deleted_work_item = show_on_deleted_work_item class WorkItemBehavior(Model): \"\"\"WorkItemBehavior. :param abstract:", ":param inherits: Parent WIT Id/Internal ReferenceName that it inherits from :type inherits: str", "'type': 'int'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, abstract=None, color=None, description=None,", "{'key': 'contributionId', 'type': 'str'}, 'height': {'key': 'height', 'type': 'int'}, 'inputs': {'key': 'inputs', 'type':", "class_: :type class_: object :param color: :type color: str :param description: :type description:", "the code is regenerated. # -------------------------------------------------------------------------------------------- from msrest.serialization import Model class Control(Model): \"\"\"Control.", "def __init__(self, description=None, name=None, parent_process_type_id=None, reference_name=None): super(CreateProcessModel, self).__init__() self.description = description self.name =", "read_only self.visible = visible self.watermark = watermark class CreateProcessModel(Model): \"\"\"CreateProcessModel. :param description: :type", "url=None): super(WorkItemStateResultModel, self).__init__() self.color = color self.hidden = hidden self.id = id self.name", "the section. :type order: int :param overridden: A value indicating whether this layout", ":type color: str :param hidden: :type hidden: bool :param id: :type id: str", "file, DO NOT EDIT # Changes may cause incorrect behavior and will be", "inputs: A dictionary holding key value pairs for contribution inputs. :type inputs: dict", "'type': 'bool'}, 'rank': {'key': 'rank', 'type': 'int'}, 'url': {'key': 'url', 'type': 'str'} }", "id self.is_identity = is_identity self.name = name self.type = type self.url = url", ":class:`Control <work-item-tracking.v4_0.models.Control>` \"\"\" _attribute_map = { 'extensions': {'key': 'extensions', 'type': '[Extension]'}, 'pages': {'key':", "'watermark': {'key': 'watermark', 'type': 'str'} } def __init__(self, contribution=None, control_type=None, height=None, id=None, inherited=None,", "value indicating if the group should be hidden or not. :type visible: bool", "is_default: bool :param url: :type url: str \"\"\" _attribute_map = { 'behavior': {'key':", "node has been overridden by a child layout. :type overridden: bool :param page_type:", "the control. :type metadata: str :param order: :type order: int :param overridden: A", "id: :type id: str :param name: :type name: str :param order: :type order:", "self).__init__() self.id = id class FieldModel(Model): \"\"\"FieldModel. :param description: :type description: str :param", "WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField. :param behavior_field_id: :type behavior_field_id: str :param id: :type id: str :param", "id: str :param overridden: A value indicating whether this layout node has been", "'name': {'key': 'name', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self,", "order: int :param state_category: :type state_category: str :param url: :type url: str \"\"\"", "the layout node. :type id: str :param overridden: A value indicating whether this", ":type description: str :param icon: :type icon: str :param id: :type id: str", "id self.inherits = inherits self.is_disabled = is_disabled self.layout = layout self.name = name", "str :param inherits: Parent WIT Id/Internal ReferenceName that it inherits from :type inherits:", "is_contribution=None, label=None, locked=None, order=None, overridden=None, page_type=None, sections=None, visible=None): super(Page, self).__init__() self.contribution = contribution", "name=None, projects=None, properties=None, reference_name=None, type_id=None): super(ProcessModel, self).__init__() self.description = description self.name = name", "self.is_contribution = is_contribution self.label = label self.locked = locked self.order = order self.overridden", ":param groups: :type groups: list of :class:`Group <work-item-tracking.v4_0.models.Group>` :param id: The id for", "condition_type: str :param field: :type field: str :param value: :type value: str \"\"\"", ":type url: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'id':", "object :param color: :type color: str :param description: :type description: str :param icon:", "'showOnDeletedWorkItem', 'type': 'bool'} } def __init__(self, contribution_id=None, height=None, inputs=None, show_on_deleted_work_item=None): super(WitContribution, self).__init__() self.contribution_id", "list of :class:`Control <work-item-tracking.v4_0.models.Control>` :param height: The height for the contribution. :type height:", "__init__(self, contribution=None, controls=None, height=None, id=None, inherited=None, is_contribution=None, label=None, order=None, overridden=None, visible=None): super(Group, self).__init__()", "behaviors: :type behaviors: list of :class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param class_: :type class_: object :param", "'[Control]'} } def __init__(self, extensions=None, pages=None, system_controls=None): super(FormLayout, self).__init__() self.extensions = extensions self.pages", "'label', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'},", "node. :type id: str :param overridden: A value indicating whether this layout node", "is_disabled: :type is_disabled: bool :param layout: :type layout: :class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>` :param name: :type", "'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'is_system': {'key': 'isSystem', 'type': 'bool'} } def __init__(self,", "value: :type value: str \"\"\" _attribute_map = { 'condition_type': {'key': 'conditionType', 'type': 'str'},", "extensions: Gets and sets extensions list :type extensions: list of :class:`Extension <work-item-tracking.v4_0.models.Extension>` :param", "Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in", "{ 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'control_type': {'key': 'controlType', 'type': 'str'}, 'height': {'key':", "user operations are permitted on this page and the contents of this page", "pages=None, system_controls=None): super(FormLayout, self).__init__() self.extensions = extensions self.pages = pages self.system_controls = system_controls", "} def __init__(self, id=None, url=None): super(WorkItemBehaviorReference, self).__init__() self.id = id self.url = url", ":param field: :type field: str :param value: :type value: str \"\"\" _attribute_map =", "A value indicating if the control is readonly. :type read_only: bool :param visible:", "textbox. :type watermark: str \"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'},", "{ 'description': {'key': 'description', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_identity': {'key':", "'bool'}, 'layout': {'key': 'layout', 'type': 'FormLayout'}, 'name': {'key': 'name', 'type': 'str'}, 'states': {'key':", "in the project root for license information. # -------------------------------------------------------------------------------------------- # Generated file, DO", "name=None): super(UpdateProcessModel, self).__init__() self.description = description self.is_default = is_default self.is_enabled = is_enabled self.name", "bool \"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'controls': {'key': 'controls',", "self.contribution = contribution self.id = id self.inherited = inherited self.is_contribution = is_contribution self.label", ":param metadata: Inner text of the control. :type metadata: str :param order: :type", "has been overridden by a child layout. :type overridden: bool :param page_type: The", "'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'}", "= url class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param color: :type color: str :param hidden: :type", ":param visible: A value indicating if the control should be hidden or not.", ":param id: The id for the layout node. :type id: str :param overridden:", "'{object}'}, 'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem', 'type': 'bool'} } def __init__(self, contribution_id=None, height=None, inputs=None, show_on_deleted_work_item=None):", "bool :param label: Label for the field :type label: str :param metadata: Inner", "'id': {'key': 'id', 'type': 'str'}, 'is_identity': {'key': 'isIdentity', 'type': 'bool'}, 'name': {'key': 'name',", "WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel. :param behaviors: :type behaviors: list of :class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param class_: :type", "'str'}, 'id': {'key': 'id', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def", "'url': {'key': 'url', 'type': 'str'} } def __init__(self, behavior=None, is_default=None, url=None): super(WorkItemTypeBehavior, self).__init__()", "'type': 'ProcessProperties'}, 'reference_name': {'key': 'referenceName', 'type': 'str'}, 'type_id': {'key': 'typeId', 'type': 'str'} }", "fields: :type fields: list of :class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param id: :type id: str :param", "super(FormLayout, self).__init__() self.extensions = extensions self.pages = pages self.system_controls = system_controls class Group(Model):", "'id': {'key': 'id', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'is_system': {'key': 'isSystem',", "\"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'controls': {'key': 'controls', 'type':", "html controls. :type height: int :param id: The id for the layout node.", ":type height: int :param id: The id for the layout node. :type id:", "int :param id: The id for the layout node. :type id: str :param", "conditions: list of :class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>` :param friendly_name: :type friendly_name: str :param id: :type", "self.id = id self.inherits = inherits self.name = name self.overriden = overriden self.rank", "metadata=None, order=None, overridden=None, read_only=None, visible=None, watermark=None): super(Control, self).__init__() self.contribution = contribution self.control_type =", "if the control is readonly. :type read_only: bool :param visible: A value indicating", ":class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>` :param properties: :type properties: :class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>` :param reference_name: :type reference_name: str", "\"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'is_default': {'key': 'isDefault', 'type':", "'icon', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'str'},", "'description': {'key': 'description', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'projects': {'key': 'projects',", "behavior_field_id: :type behavior_field_id: str :param id: :type id: str :param url: :type url:", "} def __init__(self, contribution=None, controls=None, height=None, id=None, inherited=None, is_contribution=None, label=None, order=None, overridden=None, visible=None):", "<work-item-tracking.v4_0.models.FormLayout>` :param name: :type name: str :param states: :type states: list of :class:`WorkItemStateResultModel", "bool :param id: :type id: str :param name: :type name: str :param order:", "list of :class:`Control <work-item-tracking.v4_0.models.Control>` \"\"\" _attribute_map = { 'extensions': {'key': 'extensions', 'type': '[Extension]'},", "the layout. :type system_controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` \"\"\" _attribute_map = { 'extensions':", "'bool'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'page_type': {'key':", ":type color: str :param description: :type description: str :param icon: :type icon: str", ":type version: str \"\"\" _attribute_map = { 'class_': {'key': 'class', 'type': 'object'}, 'is_default':", "= page_type self.sections = sections self.visible = visible class ProcessModel(Model): \"\"\"ProcessModel. :param description:", "<work-item-tracking.v4_0.models.RuleActionModel>` :param conditions: :type conditions: list of :class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>` :param friendly_name: :type friendly_name:", ":type locked: bool :param order: Order in which the page should appear in", "self.contribution = contribution self.controls = controls self.height = height self.id = id self.inherited", "contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param id: The id for the layout node. :type id:", "is_contribution: bool :param label: The label for the page. :type label: str :param", "str :param name: :type name: str :param order: :type order: int :param state_category:", "= action_type self.target_field = target_field self.value = value class RuleConditionModel(Model): \"\"\"RuleConditionModel. :param condition_type:", "'object'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'parent_process_type_id': {'key':", "'overridden', 'type': 'bool'}, 'read_only': {'key': 'readOnly', 'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'},", ":param class_: :type class_: object :param color: :type color: str :param description: :type", "'id', 'type': 'str'}, 'is_identity': {'key': 'isIdentity', 'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'},", "'type': 'str'} } def __init__(self, description=None, is_default=None, is_enabled=None, name=None): super(UpdateProcessModel, self).__init__() self.description =", "'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'url': {'key': 'url',", "str :param overridden: A value indicating whether this layout node has been overridden", "{'key': 'icon', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type':", "= { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'control_type': {'key': 'controlType', 'type': 'str'}, 'height':", "self.inherits = inherits self.name = name self.overriden = overriden self.rank = rank self.url", "deleted workItem. :type show_on_deleted_work_item: bool \"\"\" _attribute_map = { 'contribution_id': {'key': 'contributionId', 'type':", "= is_identity self.name = name self.type = type self.url = url class FieldRuleModel(Model):", "inherited: A value indicating whether this layout node has been inherited from a", "\"\"\" _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'url': {'key': 'url', 'type':", "\"\"\" _attribute_map = { 'contribution_id': {'key': 'contributionId', 'type': 'str'}, 'height': {'key': 'height', 'type':", "'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, description=None, id=None, name=None,", "target_field: str :param value: :type value: str \"\"\" _attribute_map = { 'action_type': {'key':", "color self.description = description self.fields = fields self.id = id self.inherits = inherits", "'type': 'str'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'reference_name': {'key': 'referenceName', 'type': 'str'} }", "self.behavior = behavior self.is_default = is_default self.url = url class WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel. :param", "{ 'id': {'key': 'id', 'type': 'str'} } def __init__(self, id=None): super(Extension, self).__init__() self.id", "'name', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, description=None, id=None,", "{'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'metadata': {'key': 'metadata', 'type':", "'type': 'str'} } def __init__(self, behavior_field_id=None, id=None, url=None): super(WorkItemBehaviorField, self).__init__() self.behavior_field_id = behavior_field_id", "def __init__(self, behaviors=None, class_=None, color=None, description=None, icon=None, id=None, inherits=None, is_disabled=None, layout=None, name=None, states=None,", "str \"\"\" _attribute_map = { 'action_type': {'key': 'actionType', 'type': 'str'}, 'target_field': {'key': 'targetField',", "'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'read_only':", "extensions list :type extensions: list of :class:`Extension <work-item-tracking.v4_0.models.Extension>` :param pages: Top level tabs", "= is_default self.is_enabled = is_enabled self.parent_process_type_id = parent_process_type_id self.version = version class ProjectReference(Model):", ":type description: str :param name: :type name: str :param projects: :type projects: list", "description self.icon = icon self.id = id self.inherits = inherits self.is_disabled = is_disabled", "{'key': 'name', 'type': 'str'} } def __init__(self, description=None, is_default=None, is_enabled=None, name=None): super(UpdateProcessModel, self).__init__()", "'WorkItemBehaviorReference'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'url': {'key': 'url', 'type': 'str'} } def", "should appear in the section. :type order: int :param overridden: A value indicating", "'WitContribution'}, 'controls': {'key': 'controls', 'type': '[Control]'}, 'height': {'key': 'height', 'type': 'int'}, 'id': {'key':", "_attribute_map = { 'behavior': {'key': 'behavior', 'type': 'WorkItemBehaviorReference'}, 'is_default': {'key': 'isDefault', 'type': 'bool'},", "actions=None, conditions=None, friendly_name=None, id=None, is_disabled=None, is_system=None): super(FieldRuleModel, self).__init__() self.actions = actions self.conditions =", ":type description: str :param name: :type name: str :param parent_process_type_id: :type parent_process_type_id: str", "pages self.system_controls = system_controls class Group(Model): \"\"\"Group. :param contribution: Contribution for the group.", "class Control(Model): \"\"\"Control. :param contribution: Contribution for the control. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>`", "from :type inherits: str :param is_disabled: :type is_disabled: bool :param layout: :type layout:", "height self.inputs = inputs self.show_on_deleted_work_item = show_on_deleted_work_item class WorkItemBehavior(Model): \"\"\"WorkItemBehavior. :param abstract: :type", "'isDefault', 'type': 'bool'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, behavior=None, is_default=None,", "'str'}, 'version': {'key': 'version', 'type': 'str'} } def __init__(self, class_=None, is_default=None, is_enabled=None, parent_process_type_id=None,", ":type parent_process_type_id: str :param reference_name: :type reference_name: str \"\"\" _attribute_map = { 'description':", ":type name: str :param states: :type states: list of :class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param url:", "the layout node is contribution are not. :type is_contribution: bool :param label: The", "_attribute_map = { 'behaviors': {'key': 'behaviors', 'type': '[WorkItemTypeBehavior]'}, 'class_': {'key': 'class', 'type': 'object'},", "bool \"\"\" _attribute_map = { 'groups': {'key': 'groups', 'type': '[Group]'}, 'id': {'key': 'id',", "id: :type id: str \"\"\" _attribute_map = { 'id': {'key': 'id', 'type': 'str'}", "Control(Model): \"\"\"Control. :param contribution: Contribution for the control. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param", "controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` :param height: The height for the contribution. :type", "'type': 'str'}, 'overridden': {'key': 'overridden', 'type': 'bool'} } def __init__(self, groups=None, id=None, overridden=None):", "value indicating whether any user operations are permitted on this page and the", "self.action_type = action_type self.target_field = target_field self.value = value class RuleConditionModel(Model): \"\"\"RuleConditionModel. :param", "self.height = height self.inputs = inputs self.show_on_deleted_work_item = show_on_deleted_work_item class WorkItemBehavior(Model): \"\"\"WorkItemBehavior. :param", "= { 'behavior': {'key': 'behavior', 'type': 'WorkItemBehaviorReference'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'url':", "overridden self.page_type = page_type self.sections = sections self.visible = visible class ProcessModel(Model): \"\"\"ProcessModel.", "str :param name: :type name: str :param url: :type url: str \"\"\" _attribute_map", "overriden=None, rank=None, url=None): super(WorkItemBehavior, self).__init__() self.abstract = abstract self.color = color self.description =", "-------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the", "'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_identity': {'key': 'isIdentity', 'type': 'bool'}, 'name': {'key':", "'type': 'str'}, 'locked': {'key': 'locked', 'type': 'bool'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden':", "<work-item-tracking.v4_0.models.Control>` :param height: The height for the contribution. :type height: int :param id:", "'actions': {'key': 'actions', 'type': '[RuleActionModel]'}, 'conditions': {'key': 'conditions', 'type': '[RuleConditionModel]'}, 'friendly_name': {'key': 'friendlyName',", "class_=None, color=None, description=None, icon=None, id=None, inherits=None, is_disabled=None, layout=None, name=None, states=None, url=None): super(WorkItemTypeModel, self).__init__()", "list of :class:`Section <work-item-tracking.v4_0.models.Section>` :param visible: A value indicating if the page should", "hidden or not. :type visible: bool \"\"\" _attribute_map = { 'contribution': {'key': 'contribution',", "The icon for the page. :type page_type: object :param sections: The sections of", "is_disabled=None, is_system=None): super(FieldRuleModel, self).__init__() self.actions = actions self.conditions = conditions self.friendly_name = friendly_name", "is readonly. :type read_only: bool :param visible: A value indicating if the control", "'str'}, 'name': {'key': 'name', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'state_category': {'key':", "visible class ProcessModel(Model): \"\"\"ProcessModel. :param description: :type description: str :param name: :type name:", "'metadata': {'key': 'metadata', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden',", "self.name = name self.projects = projects self.properties = properties self.reference_name = reference_name self.type_id", "name: str :param url: :type url: str \"\"\" _attribute_map = { 'description': {'key':", "which the page should appear in the layout. :type order: int :param overridden:", "page and the contents of this page :type locked: bool :param order: Order", ":param order: Order in which the page should appear in the layout. :type", "'type': 'int'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key': 'inherited', 'type': 'bool'}, 'is_contribution':", "__init__(self, description=None, is_default=None, is_enabled=None, name=None): super(UpdateProcessModel, self).__init__() self.description = description self.is_default = is_default", "self).__init__() self.condition_type = condition_type self.field = field self.value = value class Section(Model): \"\"\"Section.", ":type id: str :param inherits: Parent WIT Id/Internal ReferenceName that it inherits from", "metadata self.order = order self.overridden = overridden self.read_only = read_only self.visible = visible", "'[Control]'}, 'height': {'key': 'height', 'type': 'int'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key':", "= visible class Page(Model): \"\"\"Page. :param contribution: Contribution for the page. :type contribution:", "= condition_type self.field = field self.value = value class Section(Model): \"\"\"Section. :param groups:", "order self.state_category = state_category self.url = url class WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior. :param behavior: :type", "{'key': 'locked', 'type': 'bool'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type':", ":param icon: :type icon: str :param id: :type id: str :param inherits: Parent", "behavior_field_id self.id = id self.url = url class WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference. :param id: :type", "be hidden or not. :type visible: bool \"\"\" _attribute_map = { 'contribution': {'key':", "the control should be hidden or not. :type visible: bool :param watermark: Watermark", "\"\"\"FormLayout. :param extensions: Gets and sets extensions list :type extensions: list of :class:`Extension", "label=None, locked=None, order=None, overridden=None, page_type=None, sections=None, visible=None): super(Page, self).__init__() self.contribution = contribution self.id", "ProjectReference(Model): \"\"\"ProjectReference. :param description: :type description: str :param id: :type id: str :param", "self.id = id self.inherited = inherited self.is_contribution = is_contribution self.label = label self.order", "layout. :type order: int :param overridden: A value indicating whether this layout node", "is_enabled: :type is_enabled: bool :param parent_process_type_id: :type parent_process_type_id: str :param version: :type version:", "'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'read_only': {'key': 'readOnly', 'type': 'bool'}, 'visible': {'key':", "version: str \"\"\" _attribute_map = { 'class_': {'key': 'class', 'type': 'object'}, 'is_default': {'key':", "self.inputs = inputs self.show_on_deleted_work_item = show_on_deleted_work_item class WorkItemBehavior(Model): \"\"\"WorkItemBehavior. :param abstract: :type abstract:", "friendly_name: str :param id: :type id: str :param is_disabled: :type is_disabled: bool :param", "Controls to be put in the group. :type controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>`", "self.condition_type = condition_type self.field = field self.value = value class Section(Model): \"\"\"Section. :param", "'bool'}, 'visible': {'key': 'visible', 'type': 'bool'}, 'watermark': {'key': 'watermark', 'type': 'str'} } def", ":type show_on_deleted_work_item: bool \"\"\" _attribute_map = { 'contribution_id': {'key': 'contributionId', 'type': 'str'}, 'height':", ":type visible: bool \"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'controls':", "'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'locked': {'key': 'locked', 'type': 'bool'}, 'order': {'key':", "'name', 'type': 'str'} } def __init__(self, description=None, is_default=None, is_enabled=None, name=None): super(UpdateProcessModel, self).__init__() self.description", ":param description: :type description: str :param id: :type id: str :param is_identity: :type", "'color', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'icon': {'key': 'icon', 'type': 'str'},", "'type': 'str'} } def __init__(self, id=None, url=None): super(WorkItemBehaviorReference, self).__init__() self.id = id self.url", "= { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'controls': {'key': 'controls', 'type': '[Control]'}, 'height':", "= id self.overridden = overridden class UpdateProcessModel(Model): \"\"\"UpdateProcessModel. :param description: :type description: str", "'type': '[RuleActionModel]'}, 'conditions': {'key': 'conditions', 'type': '[RuleConditionModel]'}, 'friendly_name': {'key': 'friendlyName', 'type': 'str'}, 'id':", "overridden=None): super(Section, self).__init__() self.groups = groups self.id = id self.overridden = overridden class", ":type controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` :param height: The height for the contribution.", "id for the contribution. :type contribution_id: str :param height: The height for the", ":param action_type: :type action_type: str :param target_field: :type target_field: str :param value: :type", "regenerated. # -------------------------------------------------------------------------------------------- from msrest.serialization import Model class Control(Model): \"\"\"Control. :param contribution: Contribution", "is_enabled=None, parent_process_type_id=None, version=None): super(ProcessProperties, self).__init__() self.class_ = class_ self.is_default = is_default self.is_enabled =", "# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT", "inherits=None, name=None, overriden=None, rank=None, url=None): super(WorkItemBehavior, self).__init__() self.abstract = abstract self.color = color", "= name self.type = type self.url = url class FieldRuleModel(Model): \"\"\"FieldRuleModel. :param actions:", "\"\"\" _attribute_map = { 'action_type': {'key': 'actionType', 'type': 'str'}, 'target_field': {'key': 'targetField', 'type':", "label self.locked = locked self.order = order self.overridden = overridden self.page_type = page_type", "= value class Section(Model): \"\"\"Section. :param groups: :type groups: list of :class:`Group <work-item-tracking.v4_0.models.Group>`", "\"\"\" _attribute_map = { 'extensions': {'key': 'extensions', 'type': '[Extension]'}, 'pages': {'key': 'pages', 'type':", "inherits self.is_disabled = is_disabled self.layout = layout self.name = name self.states = states", "reference_name class Extension(Model): \"\"\"Extension. :param id: :type id: str \"\"\" _attribute_map = {", "has been overridden by a child layout. :type overridden: bool \"\"\" _attribute_map =", "object :param url: :type url: str \"\"\" _attribute_map = { 'description': {'key': 'description',", "{'key': 'abstract', 'type': 'bool'}, 'color': {'key': 'color', 'type': 'str'}, 'description': {'key': 'description', 'type':", "\"\"\"Page. :param contribution: Contribution for the page. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param id:", "str :param target_field: :type target_field: str :param value: :type value: str \"\"\" _attribute_map", "bool :param parent_process_type_id: :type parent_process_type_id: str :param version: :type version: str \"\"\" _attribute_map", "{'key': 'isDisabled', 'type': 'bool'}, 'layout': {'key': 'layout', 'type': 'FormLayout'}, 'name': {'key': 'name', 'type':", "should be hidden or not. :type visible: bool :param watermark: Watermark text for", ":class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>` :param friendly_name: :type friendly_name: str :param id: :type id: str :param", "are not. :type is_contribution: bool :param label: Label for the group. :type label:", "read_only=None, visible=None, watermark=None): super(Control, self).__init__() self.contribution = contribution self.control_type = control_type self.height =", "self.description = description self.id = id self.is_identity = is_identity self.name = name self.type", "action_type=None, target_field=None, value=None): super(RuleActionModel, self).__init__() self.action_type = action_type self.target_field = target_field self.value =", "'bool'}, 'is_contribution': {'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'metadata': {'key':", "{'key': 'systemControls', 'type': '[Control]'} } def __init__(self, extensions=None, pages=None, system_controls=None): super(FormLayout, self).__init__() self.extensions", "list of :class:`Group <work-item-tracking.v4_0.models.Group>` :param id: The id for the layout node. :type", ":type id: str \"\"\" _attribute_map = { 'id': {'key': 'id', 'type': 'str'} }", ":type class_: object :param is_default: :type is_default: bool :param is_enabled: :type is_enabled: bool", "in the layout. :type order: int :param overridden: A value indicating whether this", "str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'id': {'key': 'id',", "groups self.id = id self.overridden = overridden class UpdateProcessModel(Model): \"\"\"UpdateProcessModel. :param description: :type", "{'key': 'order', 'type': 'int'}, 'state_category': {'key': 'stateCategory', 'type': 'str'}, 'url': {'key': 'url', 'type':", "'control_type': {'key': 'controlType', 'type': 'str'}, 'height': {'key': 'height', 'type': 'int'}, 'id': {'key': 'id',", "url: :type url: str \"\"\" _attribute_map = { 'behaviors': {'key': 'behaviors', 'type': '[WorkItemTypeBehavior]'},", "'id', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, behavior_field_id=None, id=None,", "'str'}, 'name': {'key': 'name', 'type': 'str'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'reference_name': {'key':", "self.control_type = control_type self.height = height self.id = id self.inherited = inherited self.is_contribution", "\"\"\"UpdateProcessModel. :param description: :type description: str :param is_default: :type is_default: bool :param is_enabled:", "description: str :param is_default: :type is_default: bool :param is_enabled: :type is_enabled: bool :param", "'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'visible': {'key': 'visible',", "super(CreateProcessModel, self).__init__() self.description = description self.name = name self.parent_process_type_id = parent_process_type_id self.reference_name =", "{'key': 'description', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type':", "'overridden', 'type': 'bool'} } def __init__(self, groups=None, id=None, overridden=None): super(Section, self).__init__() self.groups =", "self.url = url class RuleActionModel(Model): \"\"\"RuleActionModel. :param action_type: :type action_type: str :param target_field:", "self.page_type = page_type self.sections = sections self.visible = visible class ProcessModel(Model): \"\"\"ProcessModel. :param", "'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'version': {'key': 'version',", "str \"\"\" _attribute_map = { 'behavior': {'key': 'behavior', 'type': 'WorkItemBehaviorReference'}, 'is_default': {'key': 'isDefault',", "is contribution are not. :type is_contribution: bool :param label: Label for the group.", ":param color: :type color: str :param description: :type description: str :param fields: :type", "the MIT License. See License.txt in the project root for license information. #", "The id for the contribution. :type contribution_id: str :param height: The height for", "self.id = id self.name = name self.url = url class RuleActionModel(Model): \"\"\"RuleActionModel. :param", "extensions: list of :class:`Extension <work-item-tracking.v4_0.models.Extension>` :param pages: Top level tabs of the layout.", "properties=None, reference_name=None, type_id=None): super(ProcessModel, self).__init__() self.description = description self.name = name self.projects =", "inherited self.is_contribution = is_contribution self.label = label self.locked = locked self.order = order", "node has been overridden by a child layout. :type overridden: bool \"\"\" _attribute_map", "'type': 'str'}, 'value': {'key': 'value', 'type': 'str'} } def __init__(self, action_type=None, target_field=None, value=None):", "{ 'color': {'key': 'color', 'type': 'str'}, 'hidden': {'key': 'hidden', 'type': 'bool'}, 'id': {'key':", ":type url: str \"\"\" _attribute_map = { 'color': {'key': 'color', 'type': 'str'}, 'hidden':", "'description', 'type': 'str'}, 'icon': {'key': 'icon', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'},", "# -------------------------------------------------------------------------------------------- from msrest.serialization import Model class Control(Model): \"\"\"Control. :param contribution: Contribution for", "'overridden', 'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'} } def __init__(self, contribution=None, controls=None,", "{ 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key':", "friendly_name: :type friendly_name: str :param id: :type id: str :param is_disabled: :type is_disabled:", "id self.inherited = inherited self.is_contribution = is_contribution self.label = label self.locked = locked", ":class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>` :param conditions: :type conditions: list of :class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>` :param friendly_name: :type", "value indicating whether this layout node has been overridden by a child layout.", "Model class Control(Model): \"\"\"Control. :param contribution: Contribution for the control. :type contribution: :class:`WitContribution", "section. :type order: int :param overridden: A value indicating whether this layout node", "str :param order: :type order: int :param state_category: :type state_category: str :param url:", "description: :type description: str :param name: :type name: str :param projects: :type projects:", "condition_type self.field = field self.value = value class Section(Model): \"\"\"Section. :param groups: :type", "'type': 'bool'} } def __init__(self, actions=None, conditions=None, friendly_name=None, id=None, is_disabled=None, is_system=None): super(FieldRuleModel, self).__init__()", "'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'controls': {'key': 'controls', 'type': '[Control]'}, 'height': {'key': 'height',", "'type': 'str'} } def __init__(self, color=None, hidden=None, id=None, name=None, order=None, state_category=None, url=None): super(WorkItemStateResultModel,", "properties self.reference_name = reference_name self.type_id = type_id class ProcessProperties(Model): \"\"\"ProcessProperties. :param class_: :type", "def __init__(self, id=None): super(Extension, self).__init__() self.id = id class FieldModel(Model): \"\"\"FieldModel. :param description:", "'behaviorFieldId', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'}", ":param url: :type url: str \"\"\" _attribute_map = { 'id': {'key': 'id', 'type':", "inherited: bool :param is_contribution: A value indicating if the layout node is contribution", ":param contribution: Contribution for the page. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param id: The", "page. :type label: str :param locked: A value indicating whether any user operations", "height=None, id=None, inherited=None, is_contribution=None, label=None, order=None, overridden=None, visible=None): super(Group, self).__init__() self.contribution = contribution", "} def __init__(self, condition_type=None, field=None, value=None): super(RuleConditionModel, self).__init__() self.condition_type = condition_type self.field =", "watermark class CreateProcessModel(Model): \"\"\"CreateProcessModel. :param description: :type description: str :param name: :type name:", ":type value: str \"\"\" _attribute_map = { 'condition_type': {'key': 'conditionType', 'type': 'str'}, 'field':", "'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, behavior_field_id=None, id=None, url=None): super(WorkItemBehaviorField,", "'layout', 'type': 'FormLayout'}, 'name': {'key': 'name', 'type': 'str'}, 'states': {'key': 'states', 'type': '[WorkItemStateResultModel]'},", "layout node has been overridden by a child layout. :type overridden: bool \"\"\"", "'str'}, 'inherits': {'key': 'inherits', 'type': 'WorkItemBehaviorReference'}, 'name': {'key': 'name', 'type': 'str'}, 'overriden': {'key':", "'[Group]'}, 'id': {'key': 'id', 'type': 'str'}, 'overridden': {'key': 'overridden', 'type': 'bool'} } def", "'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'control_type': {'key': 'controlType', 'type': 'str'}, 'height': {'key': 'height',", "'str'}, 'target_field': {'key': 'targetField', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'} } def", "'conditions': {'key': 'conditions', 'type': '[RuleConditionModel]'}, 'friendly_name': {'key': 'friendlyName', 'type': 'str'}, 'id': {'key': 'id',", "<work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param is_default: :type is_default: bool :param url: :type url: str \"\"\" _attribute_map", "str :param parent_process_type_id: :type parent_process_type_id: str :param reference_name: :type reference_name: str \"\"\" _attribute_map", "page_type=None, sections=None, visible=None): super(Page, self).__init__() self.contribution = contribution self.id = id self.inherited =", "bool :param watermark: Watermark text for the textbox. :type watermark: str \"\"\" _attribute_map", "sections=None, visible=None): super(Page, self).__init__() self.contribution = contribution self.id = id self.inherited = inherited", "{'key': 'class', 'type': 'object'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type':", "'type': 'str'}, 'target_field': {'key': 'targetField', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'} }", "field :type label: str :param metadata: Inner text of the control. :type metadata:", "{'key': 'parentProcessTypeId', 'type': 'str'}, 'reference_name': {'key': 'referenceName', 'type': 'str'} } def __init__(self, description=None,", "color=None, description=None, fields=None, id=None, inherits=None, name=None, overriden=None, rank=None, url=None): super(WorkItemBehavior, self).__init__() self.abstract =", "'type': '[Control]'}, 'height': {'key': 'height', 'type': 'int'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited':", "= behavior self.is_default = is_default self.url = url class WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel. :param behaviors:", "= description self.icon = icon self.id = id self.inherits = inherits self.is_disabled =", "= name self.projects = projects self.properties = properties self.reference_name = reference_name self.type_id =", "= { 'abstract': {'key': 'abstract', 'type': 'bool'}, 'color': {'key': 'color', 'type': 'str'}, 'description':", "is_contribution: bool :param label: Label for the field :type label: str :param metadata:", "The height for the contribution. :type height: int :param inputs: A dictionary holding", "parent_process_type_id: :type parent_process_type_id: str :param reference_name: :type reference_name: str \"\"\" _attribute_map = {", "class ProcessProperties(Model): \"\"\"ProcessProperties. :param class_: :type class_: object :param is_default: :type is_default: bool", "'contributionId', 'type': 'str'}, 'height': {'key': 'height', 'type': 'int'}, 'inputs': {'key': 'inputs', 'type': '{object}'},", "a child layout. :type overridden: bool :param page_type: The icon for the page.", "by a child layout. :type overridden: bool :param read_only: A value indicating if", "'type': 'str'} } def __init__(self, condition_type=None, field=None, value=None): super(RuleConditionModel, self).__init__() self.condition_type = condition_type", "'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'WorkItemBehaviorReference'}, 'name': {'key': 'name', 'type': 'str'},", "'height': {'key': 'height', 'type': 'int'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key': 'inherited',", "= inherits self.is_disabled = is_disabled self.layout = layout self.name = name self.states =", "= { 'id': {'key': 'id', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} }", "'visible', 'type': 'bool'} } def __init__(self, contribution=None, id=None, inherited=None, is_contribution=None, label=None, locked=None, order=None,", ":param condition_type: :type condition_type: str :param field: :type field: str :param value: :type", "the control is readonly. :type read_only: bool :param visible: A value indicating if", "__init__(self, behavior=None, is_default=None, url=None): super(WorkItemTypeBehavior, self).__init__() self.behavior = behavior self.is_default = is_default self.url", "id self.inherited = inherited self.is_contribution = is_contribution self.label = label self.metadata = metadata", "'ProcessProperties'}, 'reference_name': {'key': 'referenceName', 'type': 'str'}, 'type_id': {'key': 'typeId', 'type': 'str'} } def", "self.behaviors = behaviors self.class_ = class_ self.color = color self.description = description self.icon", "'WorkItemBehaviorReference'}, 'name': {'key': 'name', 'type': 'str'}, 'overriden': {'key': 'overriden', 'type': 'bool'}, 'rank': {'key':", "by a child layout. :type overridden: bool \"\"\" _attribute_map = { 'groups': {'key':", "= is_default self.url = url class WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel. :param behaviors: :type behaviors: list", "parent layout. This is expected to only be only set by the combiner.", "may cause incorrect behavior and will be lost if the code is regenerated.", "'type': 'bool'}, 'is_system': {'key': 'isSystem', 'type': 'bool'} } def __init__(self, actions=None, conditions=None, friendly_name=None,", "} def __init__(self, behavior=None, is_default=None, url=None): super(WorkItemTypeBehavior, self).__init__() self.behavior = behavior self.is_default =", "self.id = id self.name = name self.order = order self.state_category = state_category self.url", "str \"\"\" _attribute_map = { 'condition_type': {'key': 'conditionType', 'type': 'str'}, 'field': {'key': 'field',", "'url': {'key': 'url', 'type': 'str'} } def __init__(self, behavior_field_id=None, id=None, url=None): super(WorkItemBehaviorField, self).__init__()", "height self.id = id self.inherited = inherited self.is_contribution = is_contribution self.label = label", ":type action_type: str :param target_field: :type target_field: str :param value: :type value: str", "name self.order = order self.state_category = state_category self.url = url class WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior.", "self.state_category = state_category self.url = url class WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior. :param behavior: :type behavior:", "'[Extension]'}, 'pages': {'key': 'pages', 'type': '[Page]'}, 'system_controls': {'key': 'systemControls', 'type': '[Control]'} } def", "def __init__(self, contribution=None, controls=None, height=None, id=None, inherited=None, is_contribution=None, label=None, order=None, overridden=None, visible=None): super(Group,", "states: :type states: list of :class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param url: :type url: str \"\"\"", "self.description = description self.name = name self.parent_process_type_id = parent_process_type_id self.reference_name = reference_name class", "is_default: :type is_default: bool :param is_enabled: :type is_enabled: bool :param name: :type name:", "All rights reserved. # Licensed under the MIT License. See License.txt in the", "only set by the combiner. :type inherited: bool :param is_contribution: A value indicating", "description self.id = id self.name = name self.url = url class RuleActionModel(Model): \"\"\"RuleActionModel.", "_attribute_map = { 'class_': {'key': 'class', 'type': 'object'}, 'is_default': {'key': 'isDefault', 'type': 'bool'},", "is_identity: :type is_identity: bool :param name: :type name: str :param type: :type type:", "'name': {'key': 'name', 'type': 'str'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'reference_name': {'key': 'referenceName',", "self.fields = fields self.id = id self.inherits = inherits self.name = name self.overriden", "the group. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param controls: Controls to be put in", "icon: str :param id: :type id: str :param inherits: Parent WIT Id/Internal ReferenceName", "str :param id: :type id: str :param inherits: Parent WIT Id/Internal ReferenceName that", "self.field = field self.value = value class Section(Model): \"\"\"Section. :param groups: :type groups:", "of :class:`Section <work-item-tracking.v4_0.models.Section>` :param visible: A value indicating if the page should be", "'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'page_type': {'key': 'pageType', 'type': 'object'}, 'sections': {'key':", "'label', 'type': 'str'}, 'metadata': {'key': 'metadata', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'},", "= id self.url = url class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param color: :type color: str", "the textbox. :type watermark: str \"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type':", "'type': 'str'}, 'height': {'key': 'height', 'type': 'int'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited':", "'str'}, 'inherits': {'key': 'inherits', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'layout': {'key':", "self.value = value class Section(Model): \"\"\"Section. :param groups: :type groups: list of :class:`Group", "'extensions', 'type': '[Extension]'}, 'pages': {'key': 'pages', 'type': '[Page]'}, 'system_controls': {'key': 'systemControls', 'type': '[Control]'}", "A value indicating if the layout node is contribution are not. :type is_contribution:", "'projects': {'key': 'projects', 'type': '[ProjectReference]'}, 'properties': {'key': 'properties', 'type': 'ProcessProperties'}, 'reference_name': {'key': 'referenceName',", "{'key': 'friendlyName', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type':", "__init__(self, action_type=None, target_field=None, value=None): super(RuleActionModel, self).__init__() self.action_type = action_type self.target_field = target_field self.value", "node is contribution are not. :type is_contribution: bool :param label: Label for the", "'type': 'str'} } def __init__(self, description=None, name=None, projects=None, properties=None, reference_name=None, type_id=None): super(ProcessModel, self).__init__()", "__init__(self, id=None): super(Extension, self).__init__() self.id = id class FieldModel(Model): \"\"\"FieldModel. :param description: :type", "= is_disabled self.layout = layout self.name = name self.states = states self.url =", "super(FieldRuleModel, self).__init__() self.actions = actions self.conditions = conditions self.friendly_name = friendly_name self.id =", "the contribution should be show on deleted workItem. :type show_on_deleted_work_item: bool \"\"\" _attribute_map", "'actions', 'type': '[RuleActionModel]'}, 'conditions': {'key': 'conditions', 'type': '[RuleConditionModel]'}, 'friendly_name': {'key': 'friendlyName', 'type': 'str'},", "{'key': 'name', 'type': 'str'}, 'states': {'key': 'states', 'type': '[WorkItemStateResultModel]'}, 'url': {'key': 'url', 'type':", "self.description = description self.icon = icon self.id = id self.inherits = inherits self.is_disabled", ":param contribution: Contribution for the control. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param control_type: Type", "combiner. :type inherited: bool :param is_contribution: A value indicating if the layout node", "layout node is contribution are not. :type is_contribution: bool :param label: The label", ":class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param url: :type url: str \"\"\" _attribute_map = { 'behaviors': {'key':", "reference_name=None): super(CreateProcessModel, self).__init__() self.description = description self.name = name self.parent_process_type_id = parent_process_type_id self.reference_name", "self.projects = projects self.properties = properties self.reference_name = reference_name self.type_id = type_id class", "'rank': {'key': 'rank', 'type': 'int'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self,", "friendly_name self.id = id self.is_disabled = is_disabled self.is_system = is_system class FormLayout(Model): \"\"\"FormLayout.", "License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # Generated file,", "abstract self.color = color self.description = description self.fields = fields self.id = id", "Top level tabs of the layout. :type pages: list of :class:`Page <work-item-tracking.v4_0.models.Page>` :param", "sections: list of :class:`Section <work-item-tracking.v4_0.models.Section>` :param visible: A value indicating if the page", "<work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param url: :type url: str \"\"\" _attribute_map = { 'behaviors': {'key': 'behaviors',", ":param url: :type url: str \"\"\" _attribute_map = { 'behaviors': {'key': 'behaviors', 'type':", "'inputs', 'type': '{object}'}, 'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem', 'type': 'bool'} } def __init__(self, contribution_id=None, height=None,", "self).__init__() self.description = description self.id = id self.name = name self.url = url", "A value indicating if the layout node is contribution or not. :type is_contribution:", "'label': {'key': 'label', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden',", "{'key': 'color', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'fields': {'key': 'fields', 'type':", "_attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'},", "def __init__(self, color=None, hidden=None, id=None, name=None, order=None, state_category=None, url=None): super(WorkItemStateResultModel, self).__init__() self.color =", ":type page_type: object :param sections: The sections of the page. :type sections: list", "'is_contribution': {'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'order': {'key': 'order',", "overriden self.rank = rank self.url = url class WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField. :param behavior_field_id: :type", "name: :type name: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'},", "action_type self.target_field = target_field self.value = value class RuleConditionModel(Model): \"\"\"RuleConditionModel. :param condition_type: :type", "has been overridden by a child layout. :type overridden: bool :param read_only: A", "is_default=None, url=None): super(WorkItemTypeBehavior, self).__init__() self.behavior = behavior self.is_default = is_default self.url = url", "and the contents of this page :type locked: bool :param order: Order in", "= groups self.id = id self.overridden = overridden class UpdateProcessModel(Model): \"\"\"UpdateProcessModel. :param description:", "\"\"\" _attribute_map = { 'color': {'key': 'color', 'type': 'str'}, 'hidden': {'key': 'hidden', 'type':", "text of the control. :type metadata: str :param order: :type order: int :param", "id: The id for the layout node. :type id: str :param inherited: A", "url class WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference. :param id: :type id: str :param url: :type url:", "ProcessProperties(Model): \"\"\"ProcessProperties. :param class_: :type class_: object :param is_default: :type is_default: bool :param", ":param order: Order in which the group should appear in the section. :type", ":param url: :type url: str \"\"\" _attribute_map = { 'abstract': {'key': 'abstract', 'type':", "in which the page should appear in the layout. :type order: int :param", "Id/Internal ReferenceName that it inherits from :type inherits: str :param is_disabled: :type is_disabled:", "contents of this page :type locked: bool :param order: Order in which the", "'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'metadata': {'key': 'metadata', 'type': 'str'}, 'order': {'key':", "this page :type locked: bool :param order: Order in which the page should", "a parent layout. This is expected to only be only set by the", "inherits self.name = name self.overriden = overriden self.rank = rank self.url = url", ":param id: The id for the layout node. :type id: str :param inherited:", "str :param icon: :type icon: str :param id: :type id: str :param inherits:", "overridden: bool :param read_only: A value indicating if the control is readonly. :type", "system_controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` \"\"\" _attribute_map = { 'extensions': {'key': 'extensions', 'type':", "class_ self.is_default = is_default self.is_enabled = is_enabled self.parent_process_type_id = parent_process_type_id self.version = version", "self.rank = rank self.url = url class WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField. :param behavior_field_id: :type behavior_field_id:", ":param parent_process_type_id: :type parent_process_type_id: str :param version: :type version: str \"\"\" _attribute_map =", "overridden self.visible = visible class Page(Model): \"\"\"Page. :param contribution: Contribution for the page.", "self.label = label self.metadata = metadata self.order = order self.overridden = overridden self.read_only", "'str'} } def __init__(self, id=None): super(Extension, self).__init__() self.id = id class FieldModel(Model): \"\"\"FieldModel.", "'value': {'key': 'value', 'type': 'str'} } def __init__(self, condition_type=None, field=None, value=None): super(RuleConditionModel, self).__init__()", "NOT EDIT # Changes may cause incorrect behavior and will be lost if", "'type': 'bool'}, 'color': {'key': 'color', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'fields':", "self).__init__() self.extensions = extensions self.pages = pages self.system_controls = system_controls class Group(Model): \"\"\"Group.", "WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior. :param behavior: :type behavior: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param is_default: :type is_default: bool", "{'key': 'url', 'type': 'str'} } def __init__(self, behaviors=None, class_=None, color=None, description=None, icon=None, id=None,", "height: The height for the contribution. :type height: int :param id: The id", "layout. :type overridden: bool :param page_type: The icon for the page. :type page_type:", "str :param hidden: :type hidden: bool :param id: :type id: str :param name:", "License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- #", "{'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'WorkItemBehaviorReference'}, 'name': {'key': 'name', 'type':", "Label for the field :type label: str :param metadata: Inner text of the", "_attribute_map = { 'extensions': {'key': 'extensions', 'type': '[Extension]'}, 'pages': {'key': 'pages', 'type': '[Page]'},", "-------------------------------------------------------------------------------------------- from msrest.serialization import Model class Control(Model): \"\"\"Control. :param contribution: Contribution for the", "self.id = id self.url = url class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param color: :type color:", "icon for the page. :type page_type: object :param sections: The sections of the", ":type conditions: list of :class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>` :param friendly_name: :type friendly_name: str :param id:", ":type id: str :param is_disabled: :type is_disabled: bool :param is_system: :type is_system: bool", "{'key': 'rank', 'type': 'int'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, abstract=None,", ":param type_id: :type type_id: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type':", "show_on_deleted_work_item: bool \"\"\" _attribute_map = { 'contribution_id': {'key': 'contributionId', 'type': 'str'}, 'height': {'key':", ":type is_contribution: bool :param label: The label for the page. :type label: str", "holding key value pairs for contribution inputs. :type inputs: dict :param show_on_deleted_work_item: A", "is_enabled=None, name=None): super(UpdateProcessModel, self).__init__() self.description = description self.is_default = is_default self.is_enabled = is_enabled", "{'key': 'pages', 'type': '[Page]'}, 'system_controls': {'key': 'systemControls', 'type': '[Control]'} } def __init__(self, extensions=None,", "contribution: Contribution for the page. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param id: The id", "} def __init__(self, class_=None, is_default=None, is_enabled=None, parent_process_type_id=None, version=None): super(ProcessProperties, self).__init__() self.class_ = class_", "or not. :type is_contribution: bool :param label: Label for the field :type label:", "name: :type name: str :param url: :type url: str \"\"\" _attribute_map = {", "= name self.order = order self.state_category = state_category self.url = url class WorkItemTypeBehavior(Model):", "'contribution_id': {'key': 'contributionId', 'type': 'str'}, 'height': {'key': 'height', 'type': 'int'}, 'inputs': {'key': 'inputs',", ":param behavior_field_id: :type behavior_field_id: str :param id: :type id: str :param url: :type", "} def __init__(self, abstract=None, color=None, description=None, fields=None, id=None, inherits=None, name=None, overriden=None, rank=None, url=None):", "'locked', 'type': 'bool'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'},", "= watermark class CreateProcessModel(Model): \"\"\"CreateProcessModel. :param description: :type description: str :param name: :type", "= overridden self.page_type = page_type self.sections = sections self.visible = visible class ProcessModel(Model):", "if the contribution should be show on deleted workItem. :type show_on_deleted_work_item: bool \"\"\"", "'page_type': {'key': 'pageType', 'type': 'object'}, 'sections': {'key': 'sections', 'type': '[Section]'}, 'visible': {'key': 'visible',", "in the section. :type order: int :param overridden: A value indicating whether this", "overridden by a child layout. :type overridden: bool :param page_type: The icon for", "self.description = description self.name = name self.projects = projects self.properties = properties self.reference_name", "'type': 'str'}, 'type': {'key': 'type', 'type': 'object'}, 'url': {'key': 'url', 'type': 'str'} }", "Height of the control, for html controls. :type height: int :param id: The", "bool :param layout: :type layout: :class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>` :param name: :type name: str :param", "} def __init__(self, id=None): super(Extension, self).__init__() self.id = id class FieldModel(Model): \"\"\"FieldModel. :param", "if the page should be hidden or not. :type visible: bool \"\"\" _attribute_map", "behavior self.is_default = is_default self.url = url class WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel. :param behaviors: :type", ":param name: :type name: str :param projects: :type projects: list of :class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>`", ":type name: str :param parent_process_type_id: :type parent_process_type_id: str :param reference_name: :type reference_name: str", "\"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'id': {'key': 'id', 'type':", "tabs of the layout. :type pages: list of :class:`Page <work-item-tracking.v4_0.models.Page>` :param system_controls: Headers", "indicating if the group should be hidden or not. :type visible: bool \"\"\"", "is_default=None, is_enabled=None, parent_process_type_id=None, version=None): super(ProcessProperties, self).__init__() self.class_ = class_ self.is_default = is_default self.is_enabled", "expected to only be only set by the combiner. :type inherited: bool :param", "self).__init__() self.contribution = contribution self.control_type = control_type self.height = height self.id = id", "color: :type color: str :param hidden: :type hidden: bool :param id: :type id:", "'type': 'str'}, 'field': {'key': 'field', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'} }", "on deleted workItem. :type show_on_deleted_work_item: bool \"\"\" _attribute_map = { 'contribution_id': {'key': 'contributionId',", "'color': {'key': 'color', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'fields': {'key': 'fields',", "'overriden', 'type': 'bool'}, 'rank': {'key': 'rank', 'type': 'int'}, 'url': {'key': 'url', 'type': 'str'}", "hidden: :type hidden: bool :param id: :type id: str :param name: :type name:", "'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'} } def __init__(self, description=None, is_default=None, is_enabled=None,", "class RuleConditionModel(Model): \"\"\"RuleConditionModel. :param condition_type: :type condition_type: str :param field: :type field: str", "{'key': 'isEnabled', 'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'} } def __init__(self, description=None,", "str :param url: :type url: str \"\"\" _attribute_map = { 'color': {'key': 'color',", ":param layout: :type layout: :class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>` :param name: :type name: str :param states:", "description: str :param id: :type id: str :param name: :type name: str :param", "'description', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_identity': {'key': 'isIdentity', 'type': 'bool'},", "= show_on_deleted_work_item class WorkItemBehavior(Model): \"\"\"WorkItemBehavior. :param abstract: :type abstract: bool :param color: :type", "'str'}, 'reference_name': {'key': 'referenceName', 'type': 'str'} } def __init__(self, description=None, name=None, parent_process_type_id=None, reference_name=None):", "__init__(self, description=None, id=None, is_identity=None, name=None, type=None, url=None): super(FieldModel, self).__init__() self.description = description self.id", "= url class WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel. :param behaviors: :type behaviors: list of :class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>`", "= name self.url = url class RuleActionModel(Model): \"\"\"RuleActionModel. :param action_type: :type action_type: str", "super(Extension, self).__init__() self.id = id class FieldModel(Model): \"\"\"FieldModel. :param description: :type description: str", "the layout node. :type id: str :param inherited: A value indicating whether this", "list of :class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param class_: :type class_: object :param color: :type color:", ":param system_controls: Headers controls of the layout. :type system_controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>`", "abstract: bool :param color: :type color: str :param description: :type description: str :param", "self.inherited = inherited self.is_contribution = is_contribution self.label = label self.metadata = metadata self.order", "parent_process_type_id self.reference_name = reference_name class Extension(Model): \"\"\"Extension. :param id: :type id: str \"\"\"", "of :class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>` :param properties: :type properties: :class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>` :param reference_name: :type reference_name:", "{'key': 'contribution', 'type': 'WitContribution'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key': 'inherited', 'type':", "super(WitContribution, self).__init__() self.contribution_id = contribution_id self.height = height self.inputs = inputs self.show_on_deleted_work_item =", "height: Height of the control, for html controls. :type height: int :param id:", "'url', 'type': 'str'} } def __init__(self, color=None, hidden=None, id=None, name=None, order=None, state_category=None, url=None):", "'str'}, 'overridden': {'key': 'overridden', 'type': 'bool'} } def __init__(self, groups=None, id=None, overridden=None): super(Section,", "class WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior. :param behavior: :type behavior: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param is_default: :type is_default:", "{'key': 'url', 'type': 'str'} } def __init__(self, color=None, hidden=None, id=None, name=None, order=None, state_category=None,", ":type name: str :param order: :type order: int :param state_category: :type state_category: str", "str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'is_default': {'key': 'isDefault',", "'controls', 'type': '[Control]'}, 'height': {'key': 'height', 'type': 'int'}, 'id': {'key': 'id', 'type': 'str'},", "{'key': 'description', 'type': 'str'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type':", "color: :type color: str :param description: :type description: str :param icon: :type icon:", "\"\"\"WorkItemTypeBehavior. :param behavior: :type behavior: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param is_default: :type is_default: bool :param", "page :type locked: bool :param order: Order in which the page should appear", "the group should appear in the section. :type order: int :param overridden: A", "\"\"\"WorkItemBehaviorReference. :param id: :type id: str :param url: :type url: str \"\"\" _attribute_map", "is contribution or not. :type is_contribution: bool :param label: Label for the field", ":param watermark: Watermark text for the textbox. :type watermark: str \"\"\" _attribute_map =", "'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'reference_name':", "hidden or not. :type visible: bool :param watermark: Watermark text for the textbox.", "self.id = id self.inherited = inherited self.is_contribution = is_contribution self.label = label self.locked", "__init__(self, behaviors=None, class_=None, color=None, description=None, icon=None, id=None, inherits=None, is_disabled=None, layout=None, name=None, states=None, url=None):", ":type field: str :param value: :type value: str \"\"\" _attribute_map = { 'condition_type':", "reference_name self.type_id = type_id class ProcessProperties(Model): \"\"\"ProcessProperties. :param class_: :type class_: object :param", "'int'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key': 'inherited', 'type': 'bool'}, 'is_contribution': {'key':", "str :param is_disabled: :type is_disabled: bool :param is_system: :type is_system: bool \"\"\" _attribute_map", "'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, color=None, hidden=None, id=None, name=None,", "{ 'groups': {'key': 'groups', 'type': '[Group]'}, 'id': {'key': 'id', 'type': 'str'}, 'overridden': {'key':", "is_default: :type is_default: bool :param is_enabled: :type is_enabled: bool :param parent_process_type_id: :type parent_process_type_id:", ":param visible: A value indicating if the page should be hidden or not.", "'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'layout': {'key': 'layout', 'type': 'FormLayout'}, 'name': {'key':", "{'key': 'field', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'} } def __init__(self, condition_type=None,", "value indicating if the contribution should be show on deleted workItem. :type show_on_deleted_work_item:", "{'key': 'description', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type':", "{'key': 'visible', 'type': 'bool'} } def __init__(self, contribution=None, controls=None, height=None, id=None, inherited=None, is_contribution=None,", "'description': {'key': 'description', 'type': 'str'}, 'fields': {'key': 'fields', 'type': '[WorkItemBehaviorField]'}, 'id': {'key': 'id',", "str :param id: :type id: str :param url: :type url: str \"\"\" _attribute_map", "self.description = description self.is_default = is_default self.is_enabled = is_enabled self.name = name class", "behavior: :type behavior: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param is_default: :type is_default: bool :param url: :type", "'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'fields': {'key': 'fields', 'type': '[WorkItemBehaviorField]'}, 'id':", "list of :class:`Page <work-item-tracking.v4_0.models.Page>` :param system_controls: Headers controls of the layout. :type system_controls:", "'[WorkItemTypeBehavior]'}, 'class_': {'key': 'class', 'type': 'object'}, 'color': {'key': 'color', 'type': 'str'}, 'description': {'key':", "= id self.is_identity = is_identity self.name = name self.type = type self.url =", "self.name = name self.order = order self.state_category = state_category self.url = url class", "{ 'condition_type': {'key': 'conditionType', 'type': 'str'}, 'field': {'key': 'field', 'type': 'str'}, 'value': {'key':", "height: The height for the contribution. :type height: int :param inputs: A dictionary", "controls. :type height: int :param id: The id for the layout node. :type", "url=None): super(WorkItemBehaviorField, self).__init__() self.behavior_field_id = behavior_field_id self.id = id self.url = url class", "contribution_id: The id for the contribution. :type contribution_id: str :param height: The height", "{ 'class_': {'key': 'class', 'type': 'object'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key':", "\"\"\"Section. :param groups: :type groups: list of :class:`Group <work-item-tracking.v4_0.models.Group>` :param id: The id", "'isEnabled', 'type': 'bool'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'version': {'key': 'version', 'type': 'str'}", "self.name = name self.overriden = overriden self.rank = rank self.url = url class", "id=None, inherits=None, is_disabled=None, layout=None, name=None, states=None, url=None): super(WorkItemTypeModel, self).__init__() self.behaviors = behaviors self.class_", "indicating whether this layout node has been overridden by a child layout. :type", "'bool'} } def __init__(self, contribution=None, controls=None, height=None, id=None, inherited=None, is_contribution=None, label=None, order=None, overridden=None,", "id: The id for the layout node. :type id: str :param overridden: A", "A dictionary holding key value pairs for contribution inputs. :type inputs: dict :param", "the group. :type controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` :param height: The height for", "node has been inherited from a parent layout. This is expected to only", "'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'str'}, 'is_disabled':", "read_only: bool :param visible: A value indicating if the control should be hidden", "'type': 'str'}, 'hidden': {'key': 'hidden', 'type': 'bool'}, 'id': {'key': 'id', 'type': 'str'}, 'name':", "Licensed under the MIT License. See License.txt in the project root for license", ":param page_type: The icon for the page. :type page_type: object :param sections: The", ":param value: :type value: str \"\"\" _attribute_map = { 'condition_type': {'key': 'conditionType', 'type':", "Headers controls of the layout. :type system_controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` \"\"\" _attribute_map", "not. :type is_contribution: bool :param label: Label for the group. :type label: str", ":param height: The height for the contribution. :type height: int :param id: The", ":type class_: object :param color: :type color: str :param description: :type description: str", "'type': 'bool'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'version': {'key': 'version', 'type': 'str'} }", "'type': '[ProjectReference]'}, 'properties': {'key': 'properties', 'type': 'ProcessProperties'}, 'reference_name': {'key': 'referenceName', 'type': 'str'}, 'type_id':", "order self.overridden = overridden self.visible = visible class Page(Model): \"\"\"Page. :param contribution: Contribution", "{'key': 'targetField', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'} } def __init__(self, action_type=None,", "class FormLayout(Model): \"\"\"FormLayout. :param extensions: Gets and sets extensions list :type extensions: list", "Extension(Model): \"\"\"Extension. :param id: :type id: str \"\"\" _attribute_map = { 'id': {'key':", "{'key': 'referenceName', 'type': 'str'}, 'type_id': {'key': 'typeId', 'type': 'str'} } def __init__(self, description=None,", "value indicating if the control should be hidden or not. :type visible: bool", ":type inputs: dict :param show_on_deleted_work_item: A value indicating if the contribution should be", "__init__(self, extensions=None, pages=None, system_controls=None): super(FormLayout, self).__init__() self.extensions = extensions self.pages = pages self.system_controls", "type_id: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'name': {'key':", "parent_process_type_id: :type parent_process_type_id: str :param version: :type version: str \"\"\" _attribute_map = {", "of :class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param url: :type url: str \"\"\" _attribute_map = { 'behaviors':", "{'key': 'hidden', 'type': 'bool'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type':", "'bool'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, behavior=None, is_default=None, url=None): super(WorkItemTypeBehavior,", "self).__init__() self.actions = actions self.conditions = conditions self.friendly_name = friendly_name self.id = id", "height=None, inputs=None, show_on_deleted_work_item=None): super(WitContribution, self).__init__() self.contribution_id = contribution_id self.height = height self.inputs =", "action_type: :type action_type: str :param target_field: :type target_field: str :param value: :type value:", "= order self.overridden = overridden self.read_only = read_only self.visible = visible self.watermark =", "field self.value = value class Section(Model): \"\"\"Section. :param groups: :type groups: list of", "= sections self.visible = visible class ProcessModel(Model): \"\"\"ProcessModel. :param description: :type description: str", "show_on_deleted_work_item: A value indicating if the contribution should be show on deleted workItem.", "'url', 'type': 'str'} } def __init__(self, description=None, id=None, is_identity=None, name=None, type=None, url=None): super(FieldModel,", "'isIdentity', 'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'object'},", "self.inherits = inherits self.is_disabled = is_disabled self.layout = layout self.name = name self.states", "'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden':", "of :class:`Extension <work-item-tracking.v4_0.models.Extension>` :param pages: Top level tabs of the layout. :type pages:", "'label', 'type': 'str'}, 'locked': {'key': 'locked', 'type': 'bool'}, 'order': {'key': 'order', 'type': 'int'},", "'class', 'type': 'object'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'},", "'str'} } def __init__(self, description=None, name=None, projects=None, properties=None, reference_name=None, type_id=None): super(ProcessModel, self).__init__() self.description", "'type': 'str'} } def __init__(self, description=None, id=None, name=None, url=None): super(ProjectReference, self).__init__() self.description =", "rank: :type rank: int :param url: :type url: str \"\"\" _attribute_map = {", "'class_': {'key': 'class', 'type': 'object'}, 'color': {'key': 'color', 'type': 'str'}, 'description': {'key': 'description',", "the field :type label: str :param metadata: Inner text of the control. :type", "self.icon = icon self.id = id self.inherits = inherits self.is_disabled = is_disabled self.layout", "\"\"\"WorkItemStateResultModel. :param color: :type color: str :param hidden: :type hidden: bool :param id:", "dict :param show_on_deleted_work_item: A value indicating if the contribution should be show on", "self.overridden = overridden self.read_only = read_only self.visible = visible self.watermark = watermark class", "str :param height: The height for the contribution. :type height: int :param inputs:", "height: int :param id: The id for the layout node. :type id: str", "watermark=None): super(Control, self).__init__() self.contribution = contribution self.control_type = control_type self.height = height self.id", "<work-item-tracking.v4_0.models.WitContribution>` :param controls: Controls to be put in the group. :type controls: list", "'fields', 'type': '[WorkItemBehaviorField]'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'WorkItemBehaviorReference'},", "{'key': 'actions', 'type': '[RuleActionModel]'}, 'conditions': {'key': 'conditions', 'type': '[RuleConditionModel]'}, 'friendly_name': {'key': 'friendlyName', 'type':", "'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_identity': {'key': 'isIdentity', 'type': 'bool'}, 'name':", ":type pages: list of :class:`Page <work-item-tracking.v4_0.models.Page>` :param system_controls: Headers controls of the layout.", "} def __init__(self, contribution=None, control_type=None, height=None, id=None, inherited=None, is_contribution=None, label=None, metadata=None, order=None, overridden=None,", "WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param color: :type color: str :param hidden: :type hidden: bool :param", "bool :param label: The label for the page. :type label: str :param locked:", "name: :type name: str :param projects: :type projects: list of :class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>` :param", "__init__(self, description=None, id=None, name=None, url=None): super(ProjectReference, self).__init__() self.description = description self.id = id", ":param name: :type name: str :param url: :type url: str \"\"\" _attribute_map =", "'FormLayout'}, 'name': {'key': 'name', 'type': 'str'}, 'states': {'key': 'states', 'type': '[WorkItemStateResultModel]'}, 'url': {'key':", "url=None): super(WorkItemTypeModel, self).__init__() self.behaviors = behaviors self.class_ = class_ self.color = color self.description", ":class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param is_default: :type is_default: bool :param url: :type url: str \"\"\"", "A value indicating if the group should be hidden or not. :type visible:", "'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'locked': {'key': 'locked', 'type': 'bool'},", "is_system=None): super(FieldRuleModel, self).__init__() self.actions = actions self.conditions = conditions self.friendly_name = friendly_name self.id", "self).__init__() self.groups = groups self.id = id self.overridden = overridden class UpdateProcessModel(Model): \"\"\"UpdateProcessModel.", "__init__(self, behavior_field_id=None, id=None, url=None): super(WorkItemBehaviorField, self).__init__() self.behavior_field_id = behavior_field_id self.id = id self.url", ":type is_default: bool :param is_enabled: :type is_enabled: bool :param name: :type name: str", "self.id = id class FieldModel(Model): \"\"\"FieldModel. :param description: :type description: str :param id:", "is_default self.is_enabled = is_enabled self.parent_process_type_id = parent_process_type_id self.version = version class ProjectReference(Model): \"\"\"ProjectReference.", "order self.overridden = overridden self.page_type = page_type self.sections = sections self.visible = visible", "id=None, inherits=None, name=None, overriden=None, rank=None, url=None): super(WorkItemBehavior, self).__init__() self.abstract = abstract self.color =", "type_id class ProcessProperties(Model): \"\"\"ProcessProperties. :param class_: :type class_: object :param is_default: :type is_default:", "{'key': 'stateCategory', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, color=None,", "for the textbox. :type watermark: str \"\"\" _attribute_map = { 'contribution': {'key': 'contribution',", "Type of the control. :type control_type: str :param height: Height of the control,", "class_: object :param is_default: :type is_default: bool :param is_enabled: :type is_enabled: bool :param", "readonly. :type read_only: bool :param visible: A value indicating if the control should", "def __init__(self, groups=None, id=None, overridden=None): super(Section, self).__init__() self.groups = groups self.id = id", "is_contribution self.label = label self.metadata = metadata self.order = order self.overridden = overridden" ]
[ "from utils import LogMixin class Reponse(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def redis(self): \"\"\"", "= self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx in movies)) response = [] for movie in movies:", "@abc.abstractmethod def fetch(self, ids): \"\"\" hydrate relevant ids with data \"\"\" return class", "class ids with metadata, return redis pipeline that must be executed \"\"\" if", "obj: obj['year'] = int(obj['year']) response.append(obj) return response def movie_to_index(self, movies): return self.redis.mget(('index:movie:{}'.format(m) for", "movie in movies: values = self.redis.hmget('movie:{}'.format(movie), fields) obj = dict(zip(fields, values)) if 'genres'", "in kwargs.items(): setattr(self, key, value) def fetch(self, movies, fields=None, from_index=False): \"\"\" hydrates class", "fields=None, from_index=False): \"\"\" hydrates class ids with metadata, return redis pipeline that must", "import abc from utils import LogMixin class Reponse(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def", "super().__init__() for key, value in kwargs.items(): setattr(self, key, value) def fetch(self, movies, fields=None,", "import LogMixin class Reponse(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def redis(self): \"\"\" redis connection", "fields is None: fields = Movies.DEFAULT_FIELDS if from_index: movies = self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx", "abc from utils import LogMixin class Reponse(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def redis(self):", "be executed \"\"\" if fields is None: fields = Movies.DEFAULT_FIELDS if from_index: movies", "if fields is None: fields = Movies.DEFAULT_FIELDS if from_index: movies = self.redis.mget(('inverse:index:movie:{}'.format(idx) for", "values = self.redis.hmget('movie:{}'.format(movie), fields) obj = dict(zip(fields, values)) if 'genres' in obj: obj['genres']", "None: fields = Movies.DEFAULT_FIELDS if from_index: movies = self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx in movies))", "key, value) def fetch(self, movies, fields=None, from_index=False): \"\"\" hydrates class ids with metadata,", "value in kwargs.items(): setattr(self, key, value) def fetch(self, movies, fields=None, from_index=False): \"\"\" hydrates", "Movies(Reponse, LogMixin): DEFAULT_FIELDS = ['title', 'year', 'genres'] def __init__(self, **kwargs): super().__init__() for key,", "'genres' in obj: obj['genres'] = obj['genres'].split(',') if 'year' in obj: obj['year'] = int(obj['year'])", "<reponame>ziggyzacks/pyrecs import abc from utils import LogMixin class Reponse(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod", "redis(self): \"\"\" redis connection \"\"\" return @abc.abstractmethod def fetch(self, ids): \"\"\" hydrate relevant", "pipeline that must be executed \"\"\" if fields is None: fields = Movies.DEFAULT_FIELDS", "obj['genres'] = obj['genres'].split(',') if 'year' in obj: obj['year'] = int(obj['year']) response.append(obj) return response", "fetch(self, movies, fields=None, from_index=False): \"\"\" hydrates class ids with metadata, return redis pipeline", "from_index: movies = self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx in movies)) response = [] for movie", "= [] for movie in movies: values = self.redis.hmget('movie:{}'.format(movie), fields) obj = dict(zip(fields,", "ids with metadata, return redis pipeline that must be executed \"\"\" if fields", "with data \"\"\" return class Movies(Reponse, LogMixin): DEFAULT_FIELDS = ['title', 'year', 'genres'] def", "LogMixin): DEFAULT_FIELDS = ['title', 'year', 'genres'] def __init__(self, **kwargs): super().__init__() for key, value", "fields = Movies.DEFAULT_FIELDS if from_index: movies = self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx in movies)) response", "\"\"\" redis connection \"\"\" return @abc.abstractmethod def fetch(self, ids): \"\"\" hydrate relevant ids", "'year', 'genres'] def __init__(self, **kwargs): super().__init__() for key, value in kwargs.items(): setattr(self, key,", "__metaclass__ = abc.ABCMeta @abc.abstractmethod def redis(self): \"\"\" redis connection \"\"\" return @abc.abstractmethod def", "movies: values = self.redis.hmget('movie:{}'.format(movie), fields) obj = dict(zip(fields, values)) if 'genres' in obj:", "@abc.abstractmethod def redis(self): \"\"\" redis connection \"\"\" return @abc.abstractmethod def fetch(self, ids): \"\"\"", "obj: obj['genres'] = obj['genres'].split(',') if 'year' in obj: obj['year'] = int(obj['year']) response.append(obj) return", "hydrates class ids with metadata, return redis pipeline that must be executed \"\"\"", "__init__(self, **kwargs): super().__init__() for key, value in kwargs.items(): setattr(self, key, value) def fetch(self,", "return redis pipeline that must be executed \"\"\" if fields is None: fields", "movies)) response = [] for movie in movies: values = self.redis.hmget('movie:{}'.format(movie), fields) obj", "int(obj['year']) response.append(obj) return response def movie_to_index(self, movies): return self.redis.mget(('index:movie:{}'.format(m) for m in movies))", "= ['title', 'year', 'genres'] def __init__(self, **kwargs): super().__init__() for key, value in kwargs.items():", "values)) if 'genres' in obj: obj['genres'] = obj['genres'].split(',') if 'year' in obj: obj['year']", "ids with data \"\"\" return class Movies(Reponse, LogMixin): DEFAULT_FIELDS = ['title', 'year', 'genres']", "for idx in movies)) response = [] for movie in movies: values =", "idx in movies)) response = [] for movie in movies: values = self.redis.hmget('movie:{}'.format(movie),", "DEFAULT_FIELDS = ['title', 'year', 'genres'] def __init__(self, **kwargs): super().__init__() for key, value in", "\"\"\" return class Movies(Reponse, LogMixin): DEFAULT_FIELDS = ['title', 'year', 'genres'] def __init__(self, **kwargs):", "= self.redis.hmget('movie:{}'.format(movie), fields) obj = dict(zip(fields, values)) if 'genres' in obj: obj['genres'] =", "for movie in movies: values = self.redis.hmget('movie:{}'.format(movie), fields) obj = dict(zip(fields, values)) if", "self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx in movies)) response = [] for movie in movies: values", "in movies: values = self.redis.hmget('movie:{}'.format(movie), fields) obj = dict(zip(fields, values)) if 'genres' in", "relevant ids with data \"\"\" return class Movies(Reponse, LogMixin): DEFAULT_FIELDS = ['title', 'year',", "if from_index: movies = self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx in movies)) response = [] for", "'year' in obj: obj['year'] = int(obj['year']) response.append(obj) return response def movie_to_index(self, movies): return", "= obj['genres'].split(',') if 'year' in obj: obj['year'] = int(obj['year']) response.append(obj) return response def", "value) def fetch(self, movies, fields=None, from_index=False): \"\"\" hydrates class ids with metadata, return", "if 'genres' in obj: obj['genres'] = obj['genres'].split(',') if 'year' in obj: obj['year'] =", "def __init__(self, **kwargs): super().__init__() for key, value in kwargs.items(): setattr(self, key, value) def", "[] for movie in movies: values = self.redis.hmget('movie:{}'.format(movie), fields) obj = dict(zip(fields, values))", "class Reponse(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def redis(self): \"\"\" redis connection \"\"\" return", "fetch(self, ids): \"\"\" hydrate relevant ids with data \"\"\" return class Movies(Reponse, LogMixin):", "= dict(zip(fields, values)) if 'genres' in obj: obj['genres'] = obj['genres'].split(',') if 'year' in", "['title', 'year', 'genres'] def __init__(self, **kwargs): super().__init__() for key, value in kwargs.items(): setattr(self,", "setattr(self, key, value) def fetch(self, movies, fields=None, from_index=False): \"\"\" hydrates class ids with", "connection \"\"\" return @abc.abstractmethod def fetch(self, ids): \"\"\" hydrate relevant ids with data", "\"\"\" hydrates class ids with metadata, return redis pipeline that must be executed", "**kwargs): super().__init__() for key, value in kwargs.items(): setattr(self, key, value) def fetch(self, movies,", "redis pipeline that must be executed \"\"\" if fields is None: fields =", "return @abc.abstractmethod def fetch(self, ids): \"\"\" hydrate relevant ids with data \"\"\" return", "obj = dict(zip(fields, values)) if 'genres' in obj: obj['genres'] = obj['genres'].split(',') if 'year'", "dict(zip(fields, values)) if 'genres' in obj: obj['genres'] = obj['genres'].split(',') if 'year' in obj:", "metadata, return redis pipeline that must be executed \"\"\" if fields is None:", "movies = self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx in movies)) response = [] for movie in", "utils import LogMixin class Reponse(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def redis(self): \"\"\" redis", "must be executed \"\"\" if fields is None: fields = Movies.DEFAULT_FIELDS if from_index:", "self.redis.hmget('movie:{}'.format(movie), fields) obj = dict(zip(fields, values)) if 'genres' in obj: obj['genres'] = obj['genres'].split(',')", "\"\"\" if fields is None: fields = Movies.DEFAULT_FIELDS if from_index: movies = self.redis.mget(('inverse:index:movie:{}'.format(idx)", "class Movies(Reponse, LogMixin): DEFAULT_FIELDS = ['title', 'year', 'genres'] def __init__(self, **kwargs): super().__init__() for", "= Movies.DEFAULT_FIELDS if from_index: movies = self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx in movies)) response =", "key, value in kwargs.items(): setattr(self, key, value) def fetch(self, movies, fields=None, from_index=False): \"\"\"", "in obj: obj['genres'] = obj['genres'].split(',') if 'year' in obj: obj['year'] = int(obj['year']) response.append(obj)", "ids): \"\"\" hydrate relevant ids with data \"\"\" return class Movies(Reponse, LogMixin): DEFAULT_FIELDS", "\"\"\" return @abc.abstractmethod def fetch(self, ids): \"\"\" hydrate relevant ids with data \"\"\"", "that must be executed \"\"\" if fields is None: fields = Movies.DEFAULT_FIELDS if", "if 'year' in obj: obj['year'] = int(obj['year']) response.append(obj) return response def movie_to_index(self, movies):", "is None: fields = Movies.DEFAULT_FIELDS if from_index: movies = self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx in", "= int(obj['year']) response.append(obj) return response def movie_to_index(self, movies): return self.redis.mget(('index:movie:{}'.format(m) for m in", "def redis(self): \"\"\" redis connection \"\"\" return @abc.abstractmethod def fetch(self, ids): \"\"\" hydrate", "Movies.DEFAULT_FIELDS if from_index: movies = self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx in movies)) response = []", "executed \"\"\" if fields is None: fields = Movies.DEFAULT_FIELDS if from_index: movies =", "return class Movies(Reponse, LogMixin): DEFAULT_FIELDS = ['title', 'year', 'genres'] def __init__(self, **kwargs): super().__init__()", "obj['year'] = int(obj['year']) response.append(obj) return response def movie_to_index(self, movies): return self.redis.mget(('index:movie:{}'.format(m) for m", "hydrate relevant ids with data \"\"\" return class Movies(Reponse, LogMixin): DEFAULT_FIELDS = ['title',", "for key, value in kwargs.items(): setattr(self, key, value) def fetch(self, movies, fields=None, from_index=False):", "response = [] for movie in movies: values = self.redis.hmget('movie:{}'.format(movie), fields) obj =", "def fetch(self, movies, fields=None, from_index=False): \"\"\" hydrates class ids with metadata, return redis", "def fetch(self, ids): \"\"\" hydrate relevant ids with data \"\"\" return class Movies(Reponse,", "in movies)) response = [] for movie in movies: values = self.redis.hmget('movie:{}'.format(movie), fields)", "with metadata, return redis pipeline that must be executed \"\"\" if fields is", "abc.ABCMeta @abc.abstractmethod def redis(self): \"\"\" redis connection \"\"\" return @abc.abstractmethod def fetch(self, ids):", "'genres'] def __init__(self, **kwargs): super().__init__() for key, value in kwargs.items(): setattr(self, key, value)", "kwargs.items(): setattr(self, key, value) def fetch(self, movies, fields=None, from_index=False): \"\"\" hydrates class ids", "\"\"\" hydrate relevant ids with data \"\"\" return class Movies(Reponse, LogMixin): DEFAULT_FIELDS =", "obj['genres'].split(',') if 'year' in obj: obj['year'] = int(obj['year']) response.append(obj) return response def movie_to_index(self,", "fields) obj = dict(zip(fields, values)) if 'genres' in obj: obj['genres'] = obj['genres'].split(',') if", "redis connection \"\"\" return @abc.abstractmethod def fetch(self, ids): \"\"\" hydrate relevant ids with", "movies, fields=None, from_index=False): \"\"\" hydrates class ids with metadata, return redis pipeline that", "in obj: obj['year'] = int(obj['year']) response.append(obj) return response def movie_to_index(self, movies): return self.redis.mget(('index:movie:{}'.format(m)", "from_index=False): \"\"\" hydrates class ids with metadata, return redis pipeline that must be", "Reponse(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def redis(self): \"\"\" redis connection \"\"\" return @abc.abstractmethod", "LogMixin class Reponse(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def redis(self): \"\"\" redis connection \"\"\"", "data \"\"\" return class Movies(Reponse, LogMixin): DEFAULT_FIELDS = ['title', 'year', 'genres'] def __init__(self,", "= abc.ABCMeta @abc.abstractmethod def redis(self): \"\"\" redis connection \"\"\" return @abc.abstractmethod def fetch(self," ]
[ "# This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports = [name_pb], visibility = visibility,", "kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb = name", "name + \"_pb\" py_grpc_compile( name = name_pb, deps = deps, visibility = visibility,", ") native.py_library( name = name, srcs = [name_pb], deps = all_requirements, # fixme", "\"py_grpc_compile\") load(\"@grpc_py_deps//:requirements.bzl\", \"all_requirements\") def py_proto_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose =", "verbose, ) native.py_library( name = name, srcs = [name_pb], deps = all_requirements, #", "[name_pb], visibility = visibility, ) def py_grpc_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\")", "deps = all_requirements, # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports = [name_pb],", "py_grpc_compile( name = name_pb, deps = deps, visibility = visibility, verbose = verbose,", "= name, srcs = [name_pb], deps = all_requirements, # fixme don't need grpc", "= verbose, ) native.py_library( name = name, srcs = [name_pb], deps = all_requirements,", "= [name_pb], deps = all_requirements, # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports", "\"_pb\" py_grpc_compile( name = name_pb, deps = deps, visibility = visibility, verbose =", "[name_pb], deps = all_requirements, # fixme don't need grpc here # This magically", "name + \"_pb\" py_proto_compile( name = name_pb, deps = deps, visibility = visibility,", "= kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb = name + \"_pb\"", "= kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb =", "This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports = [name_pb], visibility = visibility, )", "= kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_proto_compile( name = name_pb, deps =", "= name + \"_pb\" py_grpc_compile( name = name_pb, deps = deps, visibility =", "all_requirements, # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports = [name_pb], visibility =", "= name_pb, deps = deps, visibility = visibility, verbose = verbose, ) native.py_library(", "native.py_library( name = name, srcs = [name_pb], deps = all_requirements, # This magically", "visibility = visibility, ) def py_grpc_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose", "py_grpc_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\")", "= kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_proto_compile( name =", "kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_grpc_compile( name = name_pb, deps = deps,", "kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_grpc_compile(", "kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_proto_compile(", "name_pb = name + \"_pb\" py_grpc_compile( name = name_pb, deps = deps, visibility", "name_pb = name + \"_pb\" py_proto_compile( name = name_pb, deps = deps, visibility", "visibility, ) def py_grpc_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\")", "imports = [name_pb], visibility = visibility, ) def py_grpc_library(**kwargs): name = kwargs.get(\"name\") deps", "= kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_grpc_compile( name =", "= name, srcs = [name_pb], deps = all_requirements, # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb}", ") native.py_library( name = name, srcs = [name_pb], deps = all_requirements, # This", "verbose = kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_proto_compile( name", "visibility = kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_proto_compile( name = name_pb, deps", "visibility = visibility, verbose = verbose, ) native.py_library( name = name, srcs =", "visibility = kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_grpc_compile( name = name_pb, deps", "= visibility, ) def py_grpc_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose =", "= [name_pb], deps = all_requirements, # fixme don't need grpc here # This", "def py_proto_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility =", "\"py_proto_compile\", \"py_grpc_compile\") load(\"@grpc_py_deps//:requirements.bzl\", \"all_requirements\") def py_proto_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose", "verbose = verbose, ) native.py_library( name = name, srcs = [name_pb], deps =", "to PYTHONPATH imports = [name_pb], visibility = visibility, ) def py_grpc_library(**kwargs): name =", "adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports = [name_pb], visibility = visibility, ) def py_grpc_library(**kwargs):", "kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_proto_compile( name = name_pb,", "= deps, visibility = visibility, verbose = verbose, ) native.py_library( name = name,", "[name_pb], deps = all_requirements, # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports =", "= name + \"_pb\" py_proto_compile( name = name_pb, deps = deps, visibility =", "deps = deps, visibility = visibility, verbose = verbose, ) native.py_library( name =", "# fixme don't need grpc here # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH", "deps, visibility = visibility, verbose = verbose, ) native.py_library( name = name, srcs", "+ \"_pb\" py_proto_compile( name = name_pb, deps = deps, visibility = visibility, verbose", "py_proto_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\")", "name_pb, deps = deps, visibility = visibility, verbose = verbose, ) native.py_library( name", "= [name_pb], visibility = visibility, ) def py_grpc_library(**kwargs): name = kwargs.get(\"name\") deps =", "= all_requirements, # fixme don't need grpc here # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb}", "REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports = [name_pb], visibility = visibility, ) def py_grpc_library(**kwargs): name", "name = name, srcs = [name_pb], deps = all_requirements, # fixme don't need", "visibility, verbose = verbose, ) native.py_library( name = name, srcs = [name_pb], deps", "verbose = kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_grpc_compile( name", "kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_grpc_compile( name = name_pb,", "load(\"//python:compile.bzl\", \"py_proto_compile\", \"py_grpc_compile\") load(\"@grpc_py_deps//:requirements.bzl\", \"all_requirements\") def py_proto_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\")", "py_proto_compile( name = name_pb, deps = deps, visibility = visibility, verbose = verbose,", "deps = kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb = name +", "need grpc here # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports = [name_pb],", "def py_grpc_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility =", "deps = all_requirements, # fixme don't need grpc here # This magically adds", "name = name_pb, deps = deps, visibility = visibility, verbose = verbose, )", "+ \"_pb\" py_grpc_compile( name = name_pb, deps = deps, visibility = visibility, verbose", "\"_pb\" py_proto_compile( name = name_pb, deps = deps, visibility = visibility, verbose =", "grpc here # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports = [name_pb], visibility", "= all_requirements, # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports = [name_pb], visibility", "load(\"@grpc_py_deps//:requirements.bzl\", \"all_requirements\") def py_proto_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\")", "name, srcs = [name_pb], deps = all_requirements, # fixme don't need grpc here", "name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb", "here # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports = [name_pb], visibility =", "= visibility, verbose = verbose, ) native.py_library( name = name, srcs = [name_pb],", "srcs = [name_pb], deps = all_requirements, # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH", "all_requirements, # fixme don't need grpc here # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to", "= kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_grpc_compile( name = name_pb, deps =", "<gh_stars>0 load(\"//python:compile.bzl\", \"py_proto_compile\", \"py_grpc_compile\") load(\"@grpc_py_deps//:requirements.bzl\", \"all_requirements\") def py_proto_library(**kwargs): name = kwargs.get(\"name\") deps =", "srcs = [name_pb], deps = all_requirements, # fixme don't need grpc here #", "PYTHONPATH imports = [name_pb], visibility = visibility, ) def py_grpc_library(**kwargs): name = kwargs.get(\"name\")", "kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_proto_compile( name = name_pb, deps = deps,", "fixme don't need grpc here # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports", "magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports = [name_pb], visibility = visibility, ) def", "name, srcs = [name_pb], deps = all_requirements, # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to", "\"all_requirements\") def py_proto_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility", ") def py_grpc_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility", "name = name, srcs = [name_pb], deps = all_requirements, # This magically adds", "native.py_library( name = name, srcs = [name_pb], deps = all_requirements, # fixme don't", "don't need grpc here # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports =" ]
[ "the copyright holders nor the names of its # contributors may be used", "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A", "machine: machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame() # Add all of the fields of the type", "ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT #", "# Copyright (c) 1999-2008 <NAME> and <NAME> # Copyright (c) 2009 The Hewlett-Packard", "# documentation and/or other materials provided with the distribution; # neither the name", "the above copyright # notice, this list of conditions and the following disclaimer;", "All rights reserved. # # Redistribution and use in source and binary forms,", "software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY", "# this software without specific prior written permission. # # THIS SOFTWARE IS", "\"external\" in self: return set() if parent: ident = \"%s_%s\" % (parent, self.type_ast.ident)", "Add all of the fields of the type to it for field in", "1999-2008 <NAME> and <NAME> # Copyright (c) 2009 The Hewlett-Packard Development Company #", "disclaimer; # redistributions in binary form must reproduce the above copyright # notice,", "def __init__(self, slicc, type_ast, pairs, field_asts): super(TypeDeclAST, self).__init__(slicc, pairs) self.type_ast = type_ast self.field_asts", "\"%s_%s\" % (parent, self.type_ast.ident) else: ident = self.type_ast.ident return set((\"%s.hh\" % ident, \"%s.cc\"", "redistributions of source code must retain the above copyright # notice, this list", "= self.type_ast.ident return set((\"%s.hh\" % ident, \"%s.cc\" % ident)) def generate(self): ident =", "conditions and the following disclaimer in the # documentation and/or other materials provided", "field_asts): super(TypeDeclAST, self).__init__(slicc, pairs) self.type_ast = type_ast self.field_asts = field_asts def __repr__(self): return", "ident = str(self.type_ast) machine = self.symtab.state_machine # Make the new type new_type =", "the new type new_type = Type(self.symtab, ident, self.location, self.pairs, self.state_machine) if machine: machine.addType(new_type)", "IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY", "self: return set() if parent: ident = \"%s_%s\" % (parent, self.type_ast.ident) else: ident", "this list of conditions and the following disclaimer; # redistributions in binary form", "PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR", "BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES", "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE", "str(self.type_ast) machine = self.symtab.state_machine # Make the new type new_type = Type(self.symtab, ident,", "notice, this list of conditions and the following disclaimer in the # documentation", "import DeclAST from slicc.symbols.Type import Type class TypeDeclAST(DeclAST): def __init__(self, slicc, type_ast, pairs,", "this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED", "TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR", "without # modification, are permitted provided that the following conditions are # met:", "all of the fields of the type to it for field in self.field_asts:", "% (self.type_ast) def files(self, parent=None): if \"external\" in self: return set() if parent:", "(c) 2009 The Hewlett-Packard Development Company # All rights reserved. # # Redistribution", "and/or other materials provided with the distribution; # neither the name of the", "ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED", "NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,", "with or without # modification, are permitted provided that the following conditions are", "def files(self, parent=None): if \"external\" in self: return set() if parent: ident =", "# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY #", "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED.", "self.state_machine) if machine: machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame() # Add all of the fields of", "BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN", "% ident, \"%s.cc\" % ident)) def generate(self): ident = str(self.type_ast) machine = self.symtab.state_machine", "# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #", "self.type_ast.ident) else: ident = self.type_ast.ident return set((\"%s.hh\" % ident, \"%s.cc\" % ident)) def", "from slicc.symbols.Type import Type class TypeDeclAST(DeclAST): def __init__(self, slicc, type_ast, pairs, field_asts): super(TypeDeclAST,", "endorse or promote products derived from # this software without specific prior written", "pairs, field_asts): super(TypeDeclAST, self).__init__(slicc, pairs) self.type_ast = type_ast self.field_asts = field_asts def __repr__(self):", "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER", "field_asts def __repr__(self): return \"[TypeDecl: %r]\" % (self.type_ast) def files(self, parent=None): if \"external\"", "if machine: machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame() # Add all of the fields of the", "__repr__(self): return \"[TypeDecl: %r]\" % (self.type_ast) def files(self, parent=None): if \"external\" in self:", "WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF", "DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT #", "NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR #", "rights reserved. # # Redistribution and use in source and binary forms, with", "OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER", "permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS", "OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE,", "THE POSSIBILITY OF SUCH DAMAGE. from slicc.ast.DeclAST import DeclAST from slicc.symbols.Type import Type", "THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF", "OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR", "or without # modification, are permitted provided that the following conditions are #", "are permitted provided that the following conditions are # met: redistributions of source", "# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, #", "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE)", "that the following conditions are # met: redistributions of source code must retain", "ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from slicc.ast.DeclAST import DeclAST from slicc.symbols.Type", "SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND", "Hewlett-Packard Development Company # All rights reserved. # # Redistribution and use in", "with the distribution; # neither the name of the copyright holders nor the", "SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,", "NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY", "COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,", "new_type = Type(self.symtab, ident, self.location, self.pairs, self.state_machine) if machine: machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame() #", "FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT", "without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE", "provided that the following conditions are # met: redistributions of source code must", "code must retain the above copyright # notice, this list of conditions and", "# notice, this list of conditions and the following disclaimer in the #", "ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT", "SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED", "Copyright (c) 1999-2008 <NAME> and <NAME> # Copyright (c) 2009 The Hewlett-Packard Development", "from slicc.ast.DeclAST import DeclAST from slicc.symbols.Type import Type class TypeDeclAST(DeclAST): def __init__(self, slicc,", "OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR", "= type_ast self.field_asts = field_asts def __repr__(self): return \"[TypeDecl: %r]\" % (self.type_ast) def", "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS", "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY", "list of conditions and the following disclaimer; # redistributions in binary form must", "machine = self.symtab.state_machine # Make the new type new_type = Type(self.symtab, ident, self.location,", "set() if parent: ident = \"%s_%s\" % (parent, self.type_ast.ident) else: ident = self.type_ast.ident", "THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from slicc.ast.DeclAST", "= str(self.type_ast) machine = self.symtab.state_machine # Make the new type new_type = Type(self.symtab,", "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY,", "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF", "AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT", "and use in source and binary forms, with or without # modification, are", "Development Company # All rights reserved. # # Redistribution and use in source", "THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED", "CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY", "EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES", "other materials provided with the distribution; # neither the name of the copyright", "this list of conditions and the following disclaimer in the # documentation and/or", "<NAME> # Copyright (c) 2009 The Hewlett-Packard Development Company # All rights reserved.", "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from slicc.ast.DeclAST import", "return set() if parent: ident = \"%s_%s\" % (parent, self.type_ast.ident) else: ident =", "distribution; # neither the name of the copyright holders nor the names of", "self.symtab.newSymbol(new_type) self.symtab.pushFrame() # Add all of the fields of the type to it", "pairs) self.type_ast = type_ast self.field_asts = field_asts def __repr__(self): return \"[TypeDecl: %r]\" %", "of its # contributors may be used to endorse or promote products derived", "its # contributors may be used to endorse or promote products derived from", "(INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS", "disclaimer in the # documentation and/or other materials provided with the distribution; #", "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA,", "OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE", "OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS", "notice, this list of conditions and the following disclaimer; # redistributions in binary", "WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING", "contributors may be used to endorse or promote products derived from # this", "IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from slicc.ast.DeclAST import DeclAST from", "must retain the above copyright # notice, this list of conditions and the", "ident = \"%s_%s\" % (parent, self.type_ast.ident) else: ident = self.type_ast.ident return set((\"%s.hh\" %", "# notice, this list of conditions and the following disclaimer; # redistributions in", "type_ast self.field_asts = field_asts def __repr__(self): return \"[TypeDecl: %r]\" % (self.type_ast) def files(self,", "% (parent, self.type_ast.ident) else: ident = self.type_ast.ident return set((\"%s.hh\" % ident, \"%s.cc\" %", "redistributions in binary form must reproduce the above copyright # notice, this list", "Redistribution and use in source and binary forms, with or without # modification,", "source and binary forms, with or without # modification, are permitted provided that", "above copyright # notice, this list of conditions and the following disclaimer in", "BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF", "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\"", "slicc.ast.DeclAST import DeclAST from slicc.symbols.Type import Type class TypeDeclAST(DeclAST): def __init__(self, slicc, type_ast,", "binary form must reproduce the above copyright # notice, this list of conditions", "(c) 1999-2008 <NAME> and <NAME> # Copyright (c) 2009 The Hewlett-Packard Development Company", "form must reproduce the above copyright # notice, this list of conditions and", "and the following disclaimer; # redistributions in binary form must reproduce the above", "<NAME> and <NAME> # Copyright (c) 2009 The Hewlett-Packard Development Company # All", "STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY", "slicc, type_ast, pairs, field_asts): super(TypeDeclAST, self).__init__(slicc, pairs) self.type_ast = type_ast self.field_asts = field_asts", "derived from # this software without specific prior written permission. # # THIS", "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN", "IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR", "= self.symtab.state_machine # Make the new type new_type = Type(self.symtab, ident, self.location, self.pairs,", "in self: return set() if parent: ident = \"%s_%s\" % (parent, self.type_ast.ident) else:", "# contributors may be used to endorse or promote products derived from #", "the above copyright # notice, this list of conditions and the following disclaimer", "PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS", "% ident)) def generate(self): ident = str(self.type_ast) machine = self.symtab.state_machine # Make the", "EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,", "import Type class TypeDeclAST(DeclAST): def __init__(self, slicc, type_ast, pairs, field_asts): super(TypeDeclAST, self).__init__(slicc, pairs)", "Copyright (c) 2009 The Hewlett-Packard Development Company # All rights reserved. # #", "generate(self): ident = str(self.type_ast) machine = self.symtab.state_machine # Make the new type new_type", "following disclaimer; # redistributions in binary form must reproduce the above copyright #", "and the following disclaimer in the # documentation and/or other materials provided with", "self.pairs, self.state_machine) if machine: machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame() # Add all of the fields", "forms, with or without # modification, are permitted provided that the following conditions", "of the fields of the type to it for field in self.field_asts: field.generate(new_type)", "are # met: redistributions of source code must retain the above copyright #", "source code must retain the above copyright # notice, this list of conditions", "FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT", "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR", "in source and binary forms, with or without # modification, are permitted provided", "type new_type = Type(self.symtab, ident, self.location, self.pairs, self.state_machine) if machine: machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame()", "provided with the distribution; # neither the name of the copyright holders nor", "IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF", "return \"[TypeDecl: %r]\" % (self.type_ast) def files(self, parent=None): if \"external\" in self: return", "class TypeDeclAST(DeclAST): def __init__(self, slicc, type_ast, pairs, field_asts): super(TypeDeclAST, self).__init__(slicc, pairs) self.type_ast =", "# # Redistribution and use in source and binary forms, with or without", "AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR", "SUCH DAMAGE. from slicc.ast.DeclAST import DeclAST from slicc.symbols.Type import Type class TypeDeclAST(DeclAST): def", "= field_asts def __repr__(self): return \"[TypeDecl: %r]\" % (self.type_ast) def files(self, parent=None): if", "OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER", "used to endorse or promote products derived from # this software without specific", "IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN", "BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR", "promote products derived from # this software without specific prior written permission. #", "COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, #", "prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS", "ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT", "return set((\"%s.hh\" % ident, \"%s.cc\" % ident)) def generate(self): ident = str(self.type_ast) machine", "the distribution; # neither the name of the copyright holders nor the names", "# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE", "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE #", "HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT", "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from", "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE", "if parent: ident = \"%s_%s\" % (parent, self.type_ast.ident) else: ident = self.type_ast.ident return", "following disclaimer in the # documentation and/or other materials provided with the distribution;", "self.type_ast.ident return set((\"%s.hh\" % ident, \"%s.cc\" % ident)) def generate(self): ident = str(self.type_ast)", "the fields of the type to it for field in self.field_asts: field.generate(new_type) self.symtab.popFrame()", "IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO,", "use in source and binary forms, with or without # modification, are permitted", "in binary form must reproduce the above copyright # notice, this list of", "OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF", "# All rights reserved. # # Redistribution and use in source and binary", "above copyright # notice, this list of conditions and the following disclaimer; #", "CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,", "machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame() # Add all of the fields of the type to", "to endorse or promote products derived from # this software without specific prior", "# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS", "ident, \"%s.cc\" % ident)) def generate(self): ident = str(self.type_ast) machine = self.symtab.state_machine #", "if \"external\" in self: return set() if parent: ident = \"%s_%s\" % (parent,", "of conditions and the following disclaimer; # redistributions in binary form must reproduce", "name of the copyright holders nor the names of its # contributors may", "# neither the name of the copyright holders nor the names of its", "# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL,", "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED", "copyright holders nor the names of its # contributors may be used to", "DeclAST from slicc.symbols.Type import Type class TypeDeclAST(DeclAST): def __init__(self, slicc, type_ast, pairs, field_asts):", "the following disclaimer; # redistributions in binary form must reproduce the above copyright", "ident)) def generate(self): ident = str(self.type_ast) machine = self.symtab.state_machine # Make the new", "new type new_type = Type(self.symtab, ident, self.location, self.pairs, self.state_machine) if machine: machine.addType(new_type) self.symtab.newSymbol(new_type)", "HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,", "holders nor the names of its # contributors may be used to endorse", "products derived from # this software without specific prior written permission. # #", "USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY", "# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING", "documentation and/or other materials provided with the distribution; # neither the name of", "# redistributions in binary form must reproduce the above copyright # notice, this", "from # this software without specific prior written permission. # # THIS SOFTWARE", "slicc.symbols.Type import Type class TypeDeclAST(DeclAST): def __init__(self, slicc, type_ast, pairs, field_asts): super(TypeDeclAST, self).__init__(slicc,", "Type(self.symtab, ident, self.location, self.pairs, self.state_machine) if machine: machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame() # Add all", "type_ast, pairs, field_asts): super(TypeDeclAST, self).__init__(slicc, pairs) self.type_ast = type_ast self.field_asts = field_asts def", "parent: ident = \"%s_%s\" % (parent, self.type_ast.ident) else: ident = self.type_ast.ident return set((\"%s.hh\"", "# Copyright (c) 2009 The Hewlett-Packard Development Company # All rights reserved. #", "LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND", "be used to endorse or promote products derived from # this software without", "conditions are # met: redistributions of source code must retain the above copyright", "OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO", "%r]\" % (self.type_ast) def files(self, parent=None): if \"external\" in self: return set() if", "USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH", "reproduce the above copyright # notice, this list of conditions and the following", "OF SUCH DAMAGE. from slicc.ast.DeclAST import DeclAST from slicc.symbols.Type import Type class TypeDeclAST(DeclAST):", "BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR", "OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS", "and binary forms, with or without # modification, are permitted provided that the", "names of its # contributors may be used to endorse or promote products", "AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL", "# Add all of the fields of the type to it for field", "the following conditions are # met: redistributions of source code must retain the", "POSSIBILITY OF SUCH DAMAGE. from slicc.ast.DeclAST import DeclAST from slicc.symbols.Type import Type class", "conditions and the following disclaimer; # redistributions in binary form must reproduce the", "neither the name of the copyright holders nor the names of its #", "IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY", "(self.type_ast) def files(self, parent=None): if \"external\" in self: return set() if parent: ident", "modification, are permitted provided that the following conditions are # met: redistributions of", "TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE", "of conditions and the following disclaimer in the # documentation and/or other materials", "WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND", "# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT #", "# met: redistributions of source code must retain the above copyright # notice,", "ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED", "ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN", "EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from slicc.ast.DeclAST import DeclAST", "OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR", "FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE", "INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT,", "\"[TypeDecl: %r]\" % (self.type_ast) def files(self, parent=None): if \"external\" in self: return set()", "CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT", "OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF", "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR", "OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF", "THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE", "# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT", "self.field_asts = field_asts def __repr__(self): return \"[TypeDecl: %r]\" % (self.type_ast) def files(self, parent=None):", "the following disclaimer in the # documentation and/or other materials provided with the", "must reproduce the above copyright # notice, this list of conditions and the", "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE", "TypeDeclAST(DeclAST): def __init__(self, slicc, type_ast, pairs, field_asts): super(TypeDeclAST, self).__init__(slicc, pairs) self.type_ast = type_ast", "DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE", "else: ident = self.type_ast.ident return set((\"%s.hh\" % ident, \"%s.cc\" % ident)) def generate(self):", "The Hewlett-Packard Development Company # All rights reserved. # # Redistribution and use", "PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS", "CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL", "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE", "DAMAGE. from slicc.ast.DeclAST import DeclAST from slicc.symbols.Type import Type class TypeDeclAST(DeclAST): def __init__(self,", "in the # documentation and/or other materials provided with the distribution; # neither", "set((\"%s.hh\" % ident, \"%s.cc\" % ident)) def generate(self): ident = str(self.type_ast) machine =", "# Make the new type new_type = Type(self.symtab, ident, self.location, self.pairs, self.state_machine) if", "permitted provided that the following conditions are # met: redistributions of source code", "the name of the copyright holders nor the names of its # contributors", "\"%s.cc\" % ident)) def generate(self): ident = str(self.type_ast) machine = self.symtab.state_machine # Make", "materials provided with the distribution; # neither the name of the copyright holders", "MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT", "parent=None): if \"external\" in self: return set() if parent: ident = \"%s_%s\" %", "= Type(self.symtab, ident, self.location, self.pairs, self.state_machine) if machine: machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame() # Add", "2009 The Hewlett-Packard Development Company # All rights reserved. # # Redistribution and", "list of conditions and the following disclaimer in the # documentation and/or other", "(parent, self.type_ast.ident) else: ident = self.type_ast.ident return set((\"%s.hh\" % ident, \"%s.cc\" % ident))", "the names of its # contributors may be used to endorse or promote", "retain the above copyright # notice, this list of conditions and the following", "super(TypeDeclAST, self).__init__(slicc, pairs) self.type_ast = type_ast self.field_asts = field_asts def __repr__(self): return \"[TypeDecl:", "the # documentation and/or other materials provided with the distribution; # neither the", "reserved. # # Redistribution and use in source and binary forms, with or", "# Redistribution and use in source and binary forms, with or without #", "self.symtab.pushFrame() # Add all of the fields of the type to it for", "def generate(self): ident = str(self.type_ast) machine = self.symtab.state_machine # Make the new type", "nor the names of its # contributors may be used to endorse or", "DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;", "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF", "__init__(self, slicc, type_ast, pairs, field_asts): super(TypeDeclAST, self).__init__(slicc, pairs) self.type_ast = type_ast self.field_asts =", "self.location, self.pairs, self.state_machine) if machine: machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame() # Add all of the", "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS;", "Make the new type new_type = Type(self.symtab, ident, self.location, self.pairs, self.state_machine) if machine:", "OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON", "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,", "self.symtab.state_machine # Make the new type new_type = Type(self.symtab, ident, self.location, self.pairs, self.state_machine)", "TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE", "files(self, parent=None): if \"external\" in self: return set() if parent: ident = \"%s_%s\"", "binary forms, with or without # modification, are permitted provided that the following", "of source code must retain the above copyright # notice, this list of", "following conditions are # met: redistributions of source code must retain the above", "OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY,", "def __repr__(self): return \"[TypeDecl: %r]\" % (self.type_ast) def files(self, parent=None): if \"external\" in", "may be used to endorse or promote products derived from # this software", "Company # All rights reserved. # # Redistribution and use in source and", "met: redistributions of source code must retain the above copyright # notice, this", "and <NAME> # Copyright (c) 2009 The Hewlett-Packard Development Company # All rights", "# modification, are permitted provided that the following conditions are # met: redistributions", "# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS #", "OF THE POSSIBILITY OF SUCH DAMAGE. from slicc.ast.DeclAST import DeclAST from slicc.symbols.Type import", "copyright # notice, this list of conditions and the following disclaimer; # redistributions", "THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,", "INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED", "Type class TypeDeclAST(DeclAST): def __init__(self, slicc, type_ast, pairs, field_asts): super(TypeDeclAST, self).__init__(slicc, pairs) self.type_ast", "= \"%s_%s\" % (parent, self.type_ast.ident) else: ident = self.type_ast.ident return set((\"%s.hh\" % ident,", "GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION)", "LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT", "OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY", "INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS", "self).__init__(slicc, pairs) self.type_ast = type_ast self.field_asts = field_asts def __repr__(self): return \"[TypeDecl: %r]\"", "self.type_ast = type_ast self.field_asts = field_asts def __repr__(self): return \"[TypeDecl: %r]\" % (self.type_ast)", "# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", "ident, self.location, self.pairs, self.state_machine) if machine: machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame() # Add all of", "of the copyright holders nor the names of its # contributors may be", "written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND", "copyright # notice, this list of conditions and the following disclaimer in the", "or promote products derived from # this software without specific prior written permission.", "INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO,", "specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT", "ident = self.type_ast.ident return set((\"%s.hh\" % ident, \"%s.cc\" % ident)) def generate(self): ident" ]